blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f581bada19f7323dbf5fddc2048c8dd31283f183 | 45de7b97cab6f8c9be0147acf3a330b01b1fb62a | /naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java | 76e1e8169a38cfe3c5e67b06f010bc3a6fef257e | [
"Apache-2.0"
] | permissive | chengchangan/nacos | 22fdfd0e7ace2028ba038902f2dea4b4583e6bae | 8da289fc2ea5c97e2c0af113acf4fa595d6844ea | refs/heads/main | 2023-04-16T08:44:33.486579 | 2021-04-23T09:50:58 | 2021-04-23T09:50:58 | 349,335,197 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 29,111 | java | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.controllers;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.api.naming.NamingResponseCode;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.auth.common.ActionTypes;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.healthcheck.RsInfo;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.SwitchEntry;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.push.ClientInfo;
import com.alibaba.nacos.naming.push.DataSource;
import com.alibaba.nacos.naming.push.PushService;
import com.alibaba.nacos.naming.web.CanDistro;
import com.alibaba.nacos.naming.web.DistroFilter;
import com.alibaba.nacos.naming.web.NamingResourceParser;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.util.VersionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 服务的注册 Server端处理器
*
*
* Instance operation controller.
*
* @author nkorange
*/
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance")
public class InstanceController {
@Autowired
private SwitchDomain switchDomain;
@Autowired
private PushService pushService;
@Autowired
private ServiceManager serviceManager;
private DataSource pushDataSource = new DataSource() {
@Override
public String getData(PushService.PushClient client) {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
try {
result = doSrvIpxt(client.getNamespaceId(), client.getServiceName(), client.getAgent(),
client.getClusters(), client.getSocketAddr().getAddress().getHostAddress(), 0,
StringUtils.EMPTY, false, StringUtils.EMPTY, StringUtils.EMPTY, false);
} catch (Exception e) {
Loggers.SRV_LOG.warn("PUSH-SERVICE: service is not modified", e);
}
// overdrive the cache millis to push mode
result.put("cacheMillis", switchDomain.getPushCacheMillis(client.getServiceName()));
return result.toString();
}
};
/**
* Register new instance.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during register
*/
@CanDistro
@PostMapping
@Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE)
public String register(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
// 从request中解析出 Instance
final Instance instance = parseInstance(request);
serviceManager.registerInstance(namespaceId, serviceName, instance);
return "ok";
}
/**
* Deregister instances.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during deregister
*/
@CanDistro
@DeleteMapping
@Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE)
public String deregister(HttpServletRequest request) throws Exception {
Instance instance = getIpAddress(request);
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) {
Loggers.SRV_LOG.warn("remove instance from non-exist service: {}", serviceName);
return "ok";
}
serviceManager.removeInstance(namespaceId, serviceName, instance.isEphemeral(), instance);
return "ok";
}
/**
* Update instance.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during update
*/
@CanDistro
@PutMapping
@Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE)
public String update(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
final Instance instance = parseInstance(request);
String agent = WebUtils.getUserAgent(request);
ClientInfo clientInfo = new ClientInfo(agent);
if (clientInfo.type == ClientInfo.ClientType.JAVA
&& clientInfo.version.compareTo(VersionUtil.parseVersion("1.0.0")) >= 0) {
serviceManager.updateInstance(namespaceId, serviceName, instance);
} else {
serviceManager.registerInstance(namespaceId, serviceName, instance);
}
return "ok";
}
/**
* Patch instance.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during patch
*/
@CanDistro
@PatchMapping
@Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE)
public String patch(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
String ip = WebUtils.required(request, "ip");
String port = WebUtils.required(request, "port");
String cluster = WebUtils.optional(request, CommonParams.CLUSTER_NAME, StringUtils.EMPTY);
if (StringUtils.isBlank(cluster)) {
cluster = WebUtils.optional(request, "cluster", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
}
Instance instance = serviceManager.getInstance(namespaceId, serviceName, cluster, ip, Integer.parseInt(port));
if (instance == null) {
throw new IllegalArgumentException("instance not found");
}
String metadata = WebUtils.optional(request, "metadata", StringUtils.EMPTY);
if (StringUtils.isNotBlank(metadata)) {
instance.setMetadata(UtilsAndCommons.parseMetadata(metadata));
}
String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
if (StringUtils.isNotBlank(app)) {
instance.setApp(app);
}
String weight = WebUtils.optional(request, "weight", StringUtils.EMPTY);
if (StringUtils.isNotBlank(weight)) {
instance.setWeight(Double.parseDouble(weight));
}
String healthy = WebUtils.optional(request, "healthy", StringUtils.EMPTY);
if (StringUtils.isNotBlank(healthy)) {
instance.setHealthy(BooleanUtils.toBoolean(healthy));
}
String enabledString = WebUtils.optional(request, "enabled", StringUtils.EMPTY);
if (StringUtils.isNotBlank(enabledString)) {
instance.setEnabled(BooleanUtils.toBoolean(enabledString));
}
instance.setLastBeat(System.currentTimeMillis());
instance.validate();
serviceManager.updateInstance(namespaceId, serviceName, instance);
return "ok";
}
/**
* Get all instance of input service.
*
* @param request http request
* @return list of instance
* @throws Exception any error during list
*/
@GetMapping("/list")
@Secured(parser = NamingResourceParser.class, action = ActionTypes.READ)
public ObjectNode list(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
String agent = WebUtils.getUserAgent(request);
String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY);
String clientIP = WebUtils.optional(request, "clientIP", StringUtils.EMPTY);
int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0"));
String env = WebUtils.optional(request, "env", StringUtils.EMPTY);
boolean isCheck = Boolean.parseBoolean(WebUtils.optional(request, "isCheck", "false"));
String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
String tenant = WebUtils.optional(request, "tid", StringUtils.EMPTY);
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false"));
return doSrvIpxt(namespaceId, serviceName, agent, clusters, clientIP, udpPort, env, isCheck, app, tenant,
healthyOnly);
}
/**
* Get detail information of specified instance.
*
* @param request http request
* @return detail information of instance
* @throws Exception any error during get
*/
@GetMapping
@Secured(parser = NamingResourceParser.class, action = ActionTypes.READ)
public ObjectNode detail(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
String cluster = WebUtils.optional(request, CommonParams.CLUSTER_NAME, UtilsAndCommons.DEFAULT_CLUSTER_NAME);
String ip = WebUtils.required(request, "ip");
int port = Integer.parseInt(WebUtils.required(request, "port"));
Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) {
throw new NacosException(NacosException.NOT_FOUND, "no service " + serviceName + " found!");
}
List<String> clusters = new ArrayList<>();
clusters.add(cluster);
List<Instance> ips = service.allIPs(clusters);
if (ips == null || ips.isEmpty()) {
throw new NacosException(NacosException.NOT_FOUND,
"no ips found for cluster " + cluster + " in service " + serviceName);
}
for (Instance instance : ips) {
if (instance.getIp().equals(ip) && instance.getPort() == port) {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.put("service", serviceName);
result.put("ip", ip);
result.put("port", port);
result.put("clusterName", cluster);
result.put("weight", instance.getWeight());
result.put("healthy", instance.isHealthy());
result.put("instanceId", instance.getInstanceId());
result.set("metadata", JacksonUtils.transferToJsonNode(instance.getMetadata()));
return result;
}
}
throw new NacosException(NacosException.NOT_FOUND, "no matched ip found!");
}
/**
* Create a beat for instance.
*
* @param request http request
* @return detail information of instance
* @throws Exception any error during handle
*/
@CanDistro
@PutMapping("/beat")
@Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE)
public ObjectNode beat(HttpServletRequest request) throws Exception {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.put(SwitchEntry.CLIENT_BEAT_INTERVAL, switchDomain.getClientBeatInterval());
String beat = WebUtils.optional(request, "beat", StringUtils.EMPTY);
RsInfo clientBeat = null;
if (StringUtils.isNotBlank(beat)) {
clientBeat = JacksonUtils.toObj(beat, RsInfo.class);
}
String clusterName = WebUtils
.optional(request, CommonParams.CLUSTER_NAME, UtilsAndCommons.DEFAULT_CLUSTER_NAME);
String ip = WebUtils.optional(request, "ip", StringUtils.EMPTY);
int port = Integer.parseInt(WebUtils.optional(request, "port", "0"));
if (clientBeat != null) {
if (StringUtils.isNotBlank(clientBeat.getCluster())) {
clusterName = clientBeat.getCluster();
} else {
// fix #2533
clientBeat.setCluster(clusterName);
}
ip = clientBeat.getIp();
port = clientBeat.getPort();
}
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
checkServiceNameFormat(serviceName);
Loggers.SRV_LOG.debug("[CLIENT-BEAT] full arguments: beat: {}, serviceName: {}", clientBeat, serviceName);
Instance instance = serviceManager.getInstance(namespaceId, serviceName, clusterName, ip, port);
if (instance == null) {
if (clientBeat == null) {
result.put(CommonParams.CODE, NamingResponseCode.RESOURCE_NOT_FOUND);
return result;
}
Loggers.SRV_LOG.warn("[CLIENT-BEAT] The instance has been removed for health mechanism, "
+ "perform data compensation operations, beat: {}, serviceName: {}", clientBeat, serviceName);
instance = new Instance();
instance.setPort(clientBeat.getPort());
instance.setIp(clientBeat.getIp());
instance.setWeight(clientBeat.getWeight());
instance.setMetadata(clientBeat.getMetadata());
instance.setClusterName(clusterName);
instance.setServiceName(serviceName);
instance.setInstanceId(instance.getInstanceId());
instance.setEphemeral(clientBeat.isEphemeral());
serviceManager.registerInstance(namespaceId, serviceName, instance);
}
Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) {
throw new NacosException(NacosException.SERVER_ERROR,
"service not found: " + serviceName + "@" + namespaceId);
}
if (clientBeat == null) {
clientBeat = new RsInfo();
clientBeat.setIp(ip);
clientBeat.setPort(port);
clientBeat.setCluster(clusterName);
}
service.processClientBeat(clientBeat);
result.put(CommonParams.CODE, NamingResponseCode.OK);
if (instance.containsMetadata(PreservedMetadataKeys.HEART_BEAT_INTERVAL)) {
result.put(SwitchEntry.CLIENT_BEAT_INTERVAL, instance.getInstanceHeartBeatInterval());
}
result.put(SwitchEntry.LIGHT_BEAT_ENABLED, switchDomain.isLightBeatEnabled());
return result;
}
/**
* List all instance with health status.
*
* @param key (namespace##)?serviceName
* @return list of instance
* @throws NacosException any error during handle
*/
@RequestMapping("/statuses")
public ObjectNode listWithHealthStatus(@RequestParam String key) throws NacosException {
String serviceName;
String namespaceId;
if (key.contains(UtilsAndCommons.NAMESPACE_SERVICE_CONNECTOR)) {
namespaceId = key.split(UtilsAndCommons.NAMESPACE_SERVICE_CONNECTOR)[0];
serviceName = key.split(UtilsAndCommons.NAMESPACE_SERVICE_CONNECTOR)[1];
} else {
namespaceId = Constants.DEFAULT_NAMESPACE_ID;
serviceName = key;
}
checkServiceNameFormat(serviceName);
Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) {
throw new NacosException(NacosException.NOT_FOUND, "service: " + serviceName + " not found.");
}
List<Instance> ips = service.allIPs();
ObjectNode result = JacksonUtils.createEmptyJsonNode();
ArrayNode ipArray = JacksonUtils.createEmptyArrayNode();
for (Instance ip : ips) {
ipArray.add(ip.toIpAddr() + "_" + ip.isHealthy());
}
result.replace("ips", ipArray);
return result;
}
/**
* check combineServiceName format. the serviceName can't be blank. some relational logic in {@link
* DistroFilter#doFilter}, it will handle combineServiceName in some case, you should know it.
* <pre>
* serviceName = "@@"; the length = 0; illegal
* serviceName = "group@@"; the length = 1; illegal
* serviceName = "@@serviceName"; the length = 2; legal
* serviceName = "group@@serviceName"; the length = 2; legal
* </pre>
*
* @param combineServiceName such as: groupName@@serviceName
*/
private void checkServiceNameFormat(String combineServiceName) {
String[] split = combineServiceName.split(Constants.SERVICE_INFO_SPLITER);
if (split.length <= 1) {
throw new IllegalArgumentException(
"Param 'serviceName' is illegal, it should be format as 'groupName@@serviceName");
}
}
private Instance parseInstance(HttpServletRequest request) throws Exception {
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
String app = WebUtils.optional(request, "app", "DEFAULT");
Instance instance = getIpAddress(request);
instance.setApp(app);
instance.setServiceName(serviceName);
// Generate simple instance id first. This value would be updated according to
// INSTANCE_ID_GENERATOR.
instance.setInstanceId(instance.generateInstanceId());
instance.setLastBeat(System.currentTimeMillis());
String metadata = WebUtils.optional(request, "metadata", StringUtils.EMPTY);
if (StringUtils.isNotEmpty(metadata)) {
instance.setMetadata(UtilsAndCommons.parseMetadata(metadata));
}
instance.validate();
return instance;
}
private Instance getIpAddress(HttpServletRequest request) {
final String ip = WebUtils.required(request, "ip");
final String port = WebUtils.required(request, "port");
String cluster = WebUtils.optional(request, CommonParams.CLUSTER_NAME, StringUtils.EMPTY);
if (StringUtils.isBlank(cluster)) {
cluster = WebUtils.optional(request, "cluster", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
}
String enabledString = WebUtils.optional(request, "enabled", StringUtils.EMPTY);
boolean enabled;
if (StringUtils.isBlank(enabledString)) {
enabled = BooleanUtils.toBoolean(WebUtils.optional(request, "enable", "true"));
} else {
enabled = BooleanUtils.toBoolean(enabledString);
}
boolean ephemeral = BooleanUtils.toBoolean(
WebUtils.optional(request, "ephemeral", String.valueOf(switchDomain.isDefaultInstanceEphemeral())));
String weight = WebUtils.optional(request, "weight", "1");
boolean healthy = BooleanUtils.toBoolean(WebUtils.optional(request, "healthy", "true"));
Instance instance = new Instance();
instance.setPort(Integer.parseInt(port));
instance.setIp(ip);
instance.setWeight(Double.parseDouble(weight));
instance.setClusterName(cluster);
instance.setHealthy(healthy);
instance.setEnabled(enabled);
instance.setEphemeral(ephemeral);
return instance;
}
private void checkIfDisabled(Service service) throws Exception {
if (!service.getEnabled()) {
throw new Exception("service is disabled now.");
}
}
/**
* Get service full information with instances.
*
* @param namespaceId namespace id
* @param serviceName service name
* @param agent agent infor string
* @param clusters cluster names
* @param clientIP client ip
* @param udpPort push udp port
* @param env env
* @param isCheck is check request
* @param app app name
* @param tid tenant
* @param healthyOnly whether only for healthy check
* @return service full information with instances
* @throws Exception any error during handle
*/
public ObjectNode doSrvIpxt(String namespaceId, String serviceName, String agent, String clusters, String clientIP,
int udpPort, String env, boolean isCheck, String app, String tid, boolean healthyOnly) throws Exception {
ClientInfo clientInfo = new ClientInfo(agent);
ObjectNode result = JacksonUtils.createEmptyJsonNode();
Service service = serviceManager.getService(namespaceId, serviceName);
long cacheMillis = switchDomain.getDefaultCacheMillis();
// now try to enable the push
try {
if (udpPort > 0 && pushService.canEnablePush(agent)) {
pushService
.addClient(namespaceId, serviceName, clusters, agent, new InetSocketAddress(clientIP, udpPort),
pushDataSource, tid, app);
cacheMillis = switchDomain.getPushCacheMillis(serviceName);
}
} catch (Exception e) {
Loggers.SRV_LOG
.error("[NACOS-API] failed to added push client {}, {}:{}", clientInfo, clientIP, udpPort, e);
cacheMillis = switchDomain.getDefaultCacheMillis();
}
if (service == null) {
if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG.debug("no instance to serve for service: {}", serviceName);
}
result.put("name", serviceName);
result.put("clusters", clusters);
result.put("cacheMillis", cacheMillis);
result.replace("hosts", JacksonUtils.createEmptyArrayNode());
return result;
}
checkIfDisabled(service);
List<Instance> srvedIPs;
srvedIPs = service.srvIPs(Arrays.asList(StringUtils.split(clusters, ",")));
// filter ips using selector:
if (service.getSelector() != null && StringUtils.isNotBlank(clientIP)) {
srvedIPs = service.getSelector().select(clientIP, srvedIPs);
}
if (CollectionUtils.isEmpty(srvedIPs)) {
if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG.debug("no instance to serve for service: {}", serviceName);
}
if (clientInfo.type == ClientInfo.ClientType.JAVA
&& clientInfo.version.compareTo(VersionUtil.parseVersion("1.0.0")) >= 0) {
result.put("dom", serviceName);
} else {
result.put("dom", NamingUtils.getServiceName(serviceName));
}
result.put("name", serviceName);
result.put("cacheMillis", cacheMillis);
result.put("lastRefTime", System.currentTimeMillis());
result.put("checksum", service.getChecksum());
result.put("useSpecifiedURL", false);
result.put("clusters", clusters);
result.put("env", env);
result.set("hosts", JacksonUtils.createEmptyArrayNode());
result.set("metadata", JacksonUtils.transferToJsonNode(service.getMetadata()));
return result;
}
Map<Boolean, List<Instance>> ipMap = new HashMap<>(2);
ipMap.put(Boolean.TRUE, new ArrayList<>());
ipMap.put(Boolean.FALSE, new ArrayList<>());
for (Instance ip : srvedIPs) {
ipMap.get(ip.isHealthy()).add(ip);
}
if (isCheck) {
result.put("reachProtectThreshold", false);
}
double threshold = service.getProtectThreshold();
if ((float) ipMap.get(Boolean.TRUE).size() / srvedIPs.size() <= threshold) {
Loggers.SRV_LOG.warn("protect threshold reached, return all ips, service: {}", serviceName);
if (isCheck) {
result.put("reachProtectThreshold", true);
}
ipMap.get(Boolean.TRUE).addAll(ipMap.get(Boolean.FALSE));
ipMap.get(Boolean.FALSE).clear();
}
if (isCheck) {
result.put("protectThreshold", service.getProtectThreshold());
result.put("reachLocalSiteCallThreshold", false);
return JacksonUtils.createEmptyJsonNode();
}
ArrayNode hosts = JacksonUtils.createEmptyArrayNode();
for (Map.Entry<Boolean, List<Instance>> entry : ipMap.entrySet()) {
List<Instance> ips = entry.getValue();
if (healthyOnly && !entry.getKey()) {
continue;
}
for (Instance instance : ips) {
// remove disabled instance:
if (!instance.isEnabled()) {
continue;
}
ObjectNode ipObj = JacksonUtils.createEmptyJsonNode();
ipObj.put("ip", instance.getIp());
ipObj.put("port", instance.getPort());
// deprecated since nacos 1.0.0:
ipObj.put("valid", entry.getKey());
ipObj.put("healthy", entry.getKey());
ipObj.put("marked", instance.isMarked());
ipObj.put("instanceId", instance.getInstanceId());
ipObj.set("metadata", JacksonUtils.transferToJsonNode(instance.getMetadata()));
ipObj.put("enabled", instance.isEnabled());
ipObj.put("weight", instance.getWeight());
ipObj.put("clusterName", instance.getClusterName());
if (clientInfo.type == ClientInfo.ClientType.JAVA
&& clientInfo.version.compareTo(VersionUtil.parseVersion("1.0.0")) >= 0) {
ipObj.put("serviceName", instance.getServiceName());
} else {
ipObj.put("serviceName", NamingUtils.getServiceName(instance.getServiceName()));
}
ipObj.put("ephemeral", instance.isEphemeral());
hosts.add(ipObj);
}
}
result.replace("hosts", hosts);
if (clientInfo.type == ClientInfo.ClientType.JAVA
&& clientInfo.version.compareTo(VersionUtil.parseVersion("1.0.0")) >= 0) {
result.put("dom", serviceName);
} else {
result.put("dom", NamingUtils.getServiceName(serviceName));
}
result.put("name", serviceName);
result.put("cacheMillis", cacheMillis);
result.put("lastRefTime", System.currentTimeMillis());
result.put("checksum", service.getChecksum());
result.put("useSpecifiedURL", false);
result.put("clusters", clusters);
result.put("env", env);
result.replace("metadata", JacksonUtils.transferToJsonNode(service.getMetadata()));
return result;
}
}
| [
"cheng.changan@eascs.com"
] | cheng.changan@eascs.com |
5cff87a374e119d19512d9ef87df0c371cee0f61 | e12f401c80470bf873718a53cf8d9a1c220f2553 | /src/test/java/pl/ciemic/spring5recipeapp/Spring5ReciepeAppApplicationTests.java | 136ef365346ada99e960afcb24721c81caa2eb3a | [] | no_license | ciemic/spring5-recipeapp | e2e48fc9a33d91ae6abca9b2d5d66a49a64dda48 | f06fc6f0b56a0e6cb40a410109d6cbd635aa4294 | refs/heads/master | 2020-03-31T17:38:32.933593 | 2018-10-22T11:24:50 | 2018-10-22T11:24:50 | 152,429,225 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 363 | java | package pl.ciemic.spring5recipeapp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Spring5ReciepeAppApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"michal.cieslar@gmail.com"
] | michal.cieslar@gmail.com |
8300e6000da4d0868e1e7180bb2b1256b3e7270c | 581bade295817a91f95993927d58ce698c141579 | /src/main/java/edu/uni/professionalcourses/controller/DisciplineCategoryController.java | 3c183715a4f26cf67d28d089e03b040a16a9c4fa | [] | no_license | codemky/uni | 23ff633d7db5321203335b5ba2ccd11f94b41100 | 42aa474c677de30645024b200d0e700b0a279e74 | refs/heads/master | 2022-11-26T01:36:27.125817 | 2019-06-27T15:31:36 | 2019-06-27T15:31:36 | 183,236,103 | 2 | 0 | null | 2022-11-16T11:43:58 | 2019-04-24T13:36:06 | Java | UTF-8 | Java | false | false | 7,538 | java | package edu.uni.professionalcourses.controller;
import com.github.pagehelper.PageInfo;
import edu.uni.bean.Result;
import edu.uni.bean.ResultType;
import edu.uni.professionalcourses.bean.DisciplineCategory;
import edu.uni.professionalcourses.service.DisciplineCategoryService;
import edu.uni.utils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**author:曹中耀
create:2019.5.1
modified:2019.5.11
功能: DisciplineCategoryController的增删查改
*/
@Api(description = "专业课程模块")
@Controller
@RequestMapping("json/professionalcourses")
public class DisciplineCategoryController {
@Autowired
private DisciplineCategoryService disciplineCategoryService;
@Autowired
private RedisCache cache;
/**
* 内部类,专门用来管理每个get方法所对应缓存的名称。
*/
static class CacheNameHelper{
//pc_DisciplineCategory_listAll
public static final String ListAll_CacheName = "pc_DisciplineCategory_listAll";
// pc_DisciplineCategory_{类别id}
public static final String Receive_CacheNamePrefix = "pc_DisciplineCategory_";
// pc_DisciplineCategory_list_{页码}
private static final String List_CacheNamePrefix = "pc_DisciplineCategory_list_";
}
//显示所有数据
@ApiOperation(value = "显示DisciplineCategory中所有信息",notes = "未测试")
@GetMapping("disciplineCategory/listAll")
public void listAll(HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
String json =cache.get(CacheNameHelper.ListAll_CacheName);
if(json==null){
// System.out.println("查询数据库");
List<DisciplineCategory> preCourses= disciplineCategoryService.selectAll();
json= Result.build(ResultType.Success).appendData("preCourse",preCourses).convertIntoJSON();
cache.set(CacheNameHelper.ListAll_CacheName,json);
}
response.getWriter().write(json);
}
/**
* 新增DisciplineCategory信息
* @param disciplineCategory
* @return
*/
@ApiOperation(value="新增先修课程信息", notes = "未测试")
@ApiImplicitParam(name="disciplineCategory",value ="学科门类实体类", required = true, dataType ="DisciplineCategory")
@PostMapping("DisciplineCategory")
@ResponseBody
public Result create(@RequestBody(required = false) DisciplineCategory disciplineCategory){
if(disciplineCategory!= null){
boolean success = disciplineCategoryService.insert(disciplineCategory);
if(success){
cache.deleteByPaterm(CacheNameHelper.List_CacheNamePrefix + "*");
cache.deleteByPaterm(CacheNameHelper.ListAll_CacheName );
cache.deleteByPaterm(CacheNameHelper.Receive_CacheNamePrefix + "*");
return Result.build(ResultType.Success);
}else{
return Result.build(ResultType.Failed);
}
}
return Result.build(ResultType.ParamError);
}
/**
* 根据id删除DisciplineCategory信息
* @param id
* @return
*/
@ApiOperation(value="根据id删除DisciplineCategory信息", notes="未测试")
@ApiImplicitParam(name = "id", value = "DisciplineCategory主id", required = true, dataType = "bigint", paramType = "path")
@DeleteMapping("/disciplineCategory/{id}")
@ResponseBody
public Result destroy(@PathVariable Long id){
boolean success = disciplineCategoryService.delete(id);
if(success){
// 清空相关缓存
cache.deleteByPaterm(CacheNameHelper.List_CacheNamePrefix + "*");
cache.deleteByPaterm(CacheNameHelper.ListAll_CacheName );
cache.deleteByPaterm(CacheNameHelper.Receive_CacheNamePrefix + id);
return Result.build(ResultType.Success);
}else{
return Result.build(ResultType.Failed);
}
}
/**
* 根据id更新DisciplineCategory信息
* @param disciplineCategory
* @return
*/
@ApiOperation(value="根据id更新DisciplineCategory信息", notes="未测试")
@ApiImplicitParam(name = "disciplineCategory", value = "DisciplineCategory实体",
required = true, dataType = "DisciplineCategory")
@PutMapping("/disciplineCategory")
@ResponseBody
public Result update(@RequestBody(required = false) DisciplineCategory disciplineCategory){
if(disciplineCategory != null && disciplineCategory.getId() != null){
boolean success = disciplineCategoryService.update(disciplineCategory);
if(success){
cache.delete(CacheNameHelper.Receive_CacheNamePrefix + disciplineCategory.getId());
cache.deleteByPaterm(CacheNameHelper.ListAll_CacheName );
return Result.build(ResultType.Success);
}else{
return Result.build(ResultType.Failed);
}
}
return Result.build(ResultType.ParamError);
}
/**
* 根据id查询DisciplineCategory信息
* @param id
* @param response
* @throws IOException
*/
@ApiOperation(value="根据id查询DisciplineCategory信息", notes="未测试")
@ApiImplicitParam(name = "id", value = "DisciplineCategory主id", required = false, dataType = "bigint", paramType = "path")
@GetMapping("/disciplineCategory{id}")
public void receive(@PathVariable Integer id, HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
String cacheName = CacheNameHelper.Receive_CacheNamePrefix + id;
String json = cache.get(cacheName);
if(json == null){
json = Result.build(ResultType.Success).appendData("disciplineCategory",
disciplineCategoryService.select(id)).convertIntoJSON();
cache.set(cacheName, json);
}
response.getWriter().write(json);
}
/**
* 根据页码分页查询所有该页码所有DisciplineCategory信息
* @param pageNum
* @param response
* @throws IOException
*/
@ApiOperation(value = "根据页码分页查询该页码所有DisciplineCategory信息", notes = "未测试")
@ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer", paramType = "path")
@GetMapping(value = "/disciplineCategory/list/{pageNum}")
public void list(
@PathVariable Integer pageNum ,
HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
String cacheName = CacheNameHelper.List_CacheNamePrefix + pageNum;
String json = cache.get(cacheName);
if(json == null){
PageInfo<DisciplineCategory> pageInfo = disciplineCategoryService.selectPage(pageNum);
json = Result.build(ResultType.Success).appendData("pageInfo", pageInfo).convertIntoJSON();
if(pageInfo != null) {
cache.set(cacheName, json);
}
}
response.getWriter().write(json);
}
}
| [
"384130332@qq.com"
] | 384130332@qq.com |
90cb1ab830c2bd237e2ee6bf98639c2bed9b5e65 | ffc345e5c5f19febd0ed98d42be78b1abb832cf4 | /sitestats/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/providers/ReportsDataProvider.java | d5a7e4458dbb0189526b3d87a437864e3e75ef44 | [
"ECL-2.0"
] | permissive | unixcrh/Fudan-Sakai | 50c89d41ee447f99d6347b14197ba701f6131a5f | 924b4c0b702ada7eba4e0efb8db99cb99ed47dce | refs/heads/master | 2020-12-24T17:54:54.747919 | 2012-04-13T14:53:40 | 2012-04-13T14:53:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,405 | java | /**
* $URL: https://source.sakaiproject.org/svn/sitestats/tags/sitestats-2.2.2/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/providers/ReportsDataProvider.java $
* $Id: ReportsDataProvider.java 78671 2010-06-21 15:20:56Z nuno@ufp.edu.pt $
*
* Copyright (c) 2006-2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.sitestats.tool.wicket.providers;
import java.io.Serializable;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.sakaiproject.sitestats.api.EventStat;
import org.sakaiproject.sitestats.api.PrefsData;
import org.sakaiproject.sitestats.api.ResourceStat;
import org.sakaiproject.sitestats.api.SitePresence;
import org.sakaiproject.sitestats.api.SiteVisits;
import org.sakaiproject.sitestats.api.Stat;
import org.sakaiproject.sitestats.api.StatsManager;
import org.sakaiproject.sitestats.api.event.EventRegistryService;
import org.sakaiproject.sitestats.api.report.Report;
import org.sakaiproject.sitestats.api.report.ReportDef;
import org.sakaiproject.sitestats.tool.facade.Locator;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
public class ReportsDataProvider extends SortableSearchableDataProvider {
private static final long serialVersionUID = 1L;
private static Log LOG = LogFactory.getLog(ReportsDataProvider.class);
public final static String COL_SITE = StatsManager.T_SITE;
public final static String COL_USERID = StatsManager.T_USER;
public final static String COL_USERNAME = "userName";
public final static String COL_EVENT = StatsManager.T_EVENT;
public final static String COL_TOOL = StatsManager.T_TOOL;
public final static String COL_RESOURCE = StatsManager.T_RESOURCE;
public final static String COL_ACTION = StatsManager.T_RESOURCE_ACTION;
public final static String COL_DATE = StatsManager.T_DATE;
public final static String COL_TOTAL = StatsManager.T_TOTAL;
public final static String COL_VISITS = StatsManager.T_VISITS;
public final static String COL_UNIQUEVISITS = StatsManager.T_UNIQUEVISITS;
public final static String COL_DURATION = StatsManager.T_DURATION;
private boolean log = true;
private PrefsData prefsData;
private ReportDef reportDef;
private Report report;
private int reportRowCount = -1;
public ReportsDataProvider(PrefsData prefsData, ReportDef reportDef) {
this(prefsData, reportDef, true);
}
public ReportsDataProvider(PrefsData prefsData, ReportDef reportDef, boolean log) {
InjectorHolder.getInjector().inject(this);
this.prefsData = prefsData;
this.setReportDef(reportDef);
this.log = log;
// set default sort
if(!reportDef.getReportParams().isHowSort() || reportDef.getReportParams().getHowSortBy() == null) {
setSort(COL_USERNAME, true);
}else{
setSort(reportDef.getReportParams().getHowSortBy(), reportDef.getReportParams().getHowSortAscending());
}
}
public void setReportDef(ReportDef reportDef) {
this.report = null;
this.reportRowCount = -1;
this.reportDef = reportDef;
}
public ReportDef getReportDef() {
return reportDef;
}
public Iterator iterator(int first, int count) {
int end = first + count;
end = end < size()? size() : end;
end = end < 0? getReport().getReportData().size() : end;
return getReport().getReportData().subList(first, end).iterator();
}
public Report getReport() {
if(report == null) {
report = Locator.getFacade().getReportManager().getReport(getReportDef(), prefsData.isListToolEventsOnlyAvailableInSite(), null, log);
if(log && report != null) {
LOG.info("Site statistics report generated: "+report.getReportDefinition().toString(false));
}
}
if(report != null) {
sortReport();
}
return report;
}
public IModel model(Object object) {
return new Model((Serializable) object);
}
public int size() {
if(reportRowCount == -1) {
reportRowCount = getReport().getReportData().size();
}
return reportRowCount;
}
public void sortReport() {
Collections.sort(report.getReportData(), getReportDataComparator(getSort().getProperty(), getSort().isAscending(), Locator.getFacade().getStatsManager(), Locator.getFacade().getEventRegistryService(), Locator.getFacade().getUserDirectoryService()));
}
public final Comparator<Stat> getReportDataComparator(final String fieldName, final boolean sortAscending,
final StatsManager SST_sm, final EventRegistryService SST_ers, final UserDirectoryService M_uds) {
return new Comparator<Stat>() {
private final transient Collator collator = Collator.getInstance();
public int compare(Stat r1, Stat r2) {
if(fieldName.equals(COL_SITE)){
String s1 = Locator.getFacade().getSiteService().getSiteDisplay(r1.getSiteId()).toLowerCase();
String s2 = Locator.getFacade().getSiteService().getSiteDisplay(r2.getSiteId()).toLowerCase();
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_USERID)){
String s1;
try{
s1 = M_uds.getUser(r1.getUserId()).getDisplayId();
}catch(UserNotDefinedException e){
s1 = "-";
}
String s2;
try{
s2 = M_uds.getUser(r2.getUserId()).getDisplayId();
}catch(UserNotDefinedException e){
s2 = "-";
}
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_USERNAME)){
String s1 = Locator.getFacade().getStatsManager().getUserNameForDisplay(r1.getUserId()).toLowerCase();
String s2 = Locator.getFacade().getStatsManager().getUserNameForDisplay(r2.getUserId()).toLowerCase();
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_EVENT)){
EventStat es1 = (EventStat) r1;
EventStat es2 = (EventStat) r2;
String s1 = SST_ers.getEventName(es1.getEventId()).toLowerCase();
String s2 = SST_ers.getEventName(es2.getEventId()).toLowerCase();
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_EVENT)){
EventStat es1 = (EventStat) r1;
EventStat es2 = (EventStat) r2;
String s1 = SST_ers.getToolName(es1.getToolId()).toLowerCase();
String s2 = SST_ers.getToolName(es2.getToolId()).toLowerCase();
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_RESOURCE)){
ResourceStat rs1 = (ResourceStat) r1;
ResourceStat rs2 = (ResourceStat) r2;
String s1 = SST_sm.getResourceName(rs1.getResourceRef()).toLowerCase();
String s2 = SST_sm.getResourceName(rs2.getResourceRef()).toLowerCase();
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_ACTION)){
ResourceStat rs1 = (ResourceStat) r1;
ResourceStat rs2 = (ResourceStat) r2;
String s1 = ((String) rs1.getResourceAction()).toLowerCase();
String s2 = ((String) rs2.getResourceAction()).toLowerCase();
int res = collator.compare(s1, s2);
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_DATE)){
int res = r1.getDate() != null ? r1.getDate().compareTo(r2.getDate()) : -1;
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_TOTAL)){
int res = Long.valueOf(r1.getCount()).compareTo(Long.valueOf(r2.getCount()));
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_VISITS)){
SiteVisits sv1 = (SiteVisits) r1;
SiteVisits sv2 = (SiteVisits) r2;
int res = Long.valueOf(sv1.getTotalVisits()).compareTo(Long.valueOf(sv2.getTotalVisits()));
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_UNIQUEVISITS)){
SiteVisits sv1 = (SiteVisits) r1;
SiteVisits sv2 = (SiteVisits) r2;
int res = Long.valueOf(sv1.getTotalUnique()).compareTo(Long.valueOf(sv2.getTotalUnique()));
if(sortAscending)
return res;
else return -res;
}else if(fieldName.equals(COL_DURATION)){
SitePresence sv1 = (SitePresence) r1;
SitePresence sv2 = (SitePresence) r2;
int res = Long.valueOf(sv1.getDuration()).compareTo(Long.valueOf(sv2.getDuration()));
if(sortAscending)
return res;
else return -res;
}
return 0;
}
};
}
}
| [
"gaojun@fudan.edu.cn"
] | gaojun@fudan.edu.cn |
9099edf608be12decfe7667cf5cbb0da21210e5a | b63cb2dcbf4655c51d87205ec9e97e97f212e954 | /asdf/src/inheritance/Ray.java | cd31950aa1271e6333f6999084e4d66baf6455cc | [] | no_license | daeheeryu/asdf | 1bba876e335368d2849b7cc5c5a5c7daf971cd78 | 0ccc0101871f99646ed27bb6c6bf7fc08897b844 | refs/heads/master | 2020-05-20T02:55:22.011658 | 2019-05-07T07:25:00 | 2019-05-07T07:25:00 | 185,343,724 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 60 | java | package inheritance;
public class Ray extends car{
}
| [
"kccistc@emb18"
] | kccistc@emb18 |
dcfb4b2325f28a08b2f942608d208ce18892ea37 | 978cbe0deaa37dbbf166d0938f919a89a097b189 | /call_center/src/test/java/com/negocio/call/ConsultasEmpleadosCallCenterTests.java | 8f497d65dc86547cfedf67ab839e65efc2646f43 | [] | no_license | haburitic/PruebaAlMundo | f2bf3e5e6fa4d5fb1ab4b366d3c5e964ff407a55 | 8cf8121f91bdc123250f3609d17850df4a146d44 | refs/heads/master | 2021-04-03T06:44:01.741268 | 2018-03-11T06:15:36 | 2018-03-11T06:15:36 | 124,723,632 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,999 | java | package com.negocio.call;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import com.negocio.controller.ConsultasEmpleadosController;
import com.negocio.dto.EmpleadoDto;
import com.negocio.entity.Empleado;
import com.negocio.impl.AsesorDisponibleImpl;
import com.negocio.repository.EmpleadoDao;
import com.negocio.util.CargosEmpleados;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConsultasEmpleadosCallCenterTests {
private
ConsultasEmpleadosController consultasEmpleadosController = new ConsultasEmpleadosController();
@Mock private EmpleadoDao empleadoDao;
@InjectMocks private AsesorDisponibleImpl asesorDisponibleImpl= new AsesorDisponibleImpl();
@Before
public void before() {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(consultasEmpleadosController, "asesorDisponibleImpl", asesorDisponibleImpl);
ReflectionTestUtils.setField(asesorDisponibleImpl, "empleadoDao", empleadoDao);
}
@Test
public void consultarListaVacia() {
Mockito.when(empleadoDao.findAll()).thenReturn(null);
List<EmpleadoDto> respuesta = consultasEmpleadosController.consultarEmpleados();
assertTrue(respuesta.isEmpty());
}
@Test
public void consultarListaCon1Empleado() {
Mockito.when(empleadoDao.findAll()).thenReturn(iterarListaEmpleados(1));
List<EmpleadoDto> respuesta = consultasEmpleadosController.consultarEmpleados();
assertEquals("0", respuesta.get(0).getNombre());
assertEquals("OP", respuesta.get(0).getCargo());
assertEquals(true, respuesta.get(0).isActivo());
}
@Test
public void consultarListaCon2Empleado() {
Mockito.when(empleadoDao.findAll()).thenReturn(iterarListaEmpleados(1));
List<EmpleadoDto> respuesta = consultasEmpleadosController.consultarEmpleados();
assertEquals("0", respuesta.get(0).getNombre());
assertEquals("OP", respuesta.get(0).getCargo());
assertEquals(true, respuesta.get(0).isActivo());
assertEquals("0", respuesta.get(1).getNombre());
assertEquals("SU", respuesta.get(1).getCargo());
assertEquals(true, respuesta.get(1).isActivo());
}
@Test
public void consultarListaCon3Emplados() {
Mockito.when(empleadoDao.findAll()).thenReturn(iterarListaEmpleados(1));
List<EmpleadoDto> respuesta = consultasEmpleadosController.consultarEmpleados();
assertEquals("0", respuesta.get(0).getNombre());
assertEquals("OP", respuesta.get(0).getCargo());
assertEquals(true, respuesta.get(0).isActivo());
assertEquals("0", respuesta.get(1).getNombre());
assertEquals("SU", respuesta.get(1).getCargo());
assertEquals(true, respuesta.get(1).isActivo());
assertEquals("0", respuesta.get(2).getNombre());
assertEquals("DI", respuesta.get(2).getCargo());
assertEquals(true, respuesta.get(2).isActivo());
}
public List<Empleado> iterarListaEmpleados(int cantidad){
List<Empleado> listaEmpleados= Collections.synchronizedList(new ArrayList<>());
iterartipoEmpleado(cantidad, listaEmpleados, CargosEmpleados.OPERADOR.getOperador());
iterartipoEmpleado(cantidad, listaEmpleados, CargosEmpleados.SUPERVISOR.getOperador());
iterartipoEmpleado(cantidad, listaEmpleados, CargosEmpleados.DIRECTOR.getOperador());
return listaEmpleados;
}
private void iterartipoEmpleado(int cantidad, List<Empleado> listaEmpleados, String tipo) {
for (int i = 0; i < cantidad; i++) {
Empleado lista = new Empleado();
lista.setActivo(true);
lista.setCargo(tipo);
lista.setNombre(String.valueOf(i));
listaEmpleados.add(lista);
}
}
}
| [
"haburitic@gmail.com"
] | haburitic@gmail.com |
dde13401364cd87c832cd556dae0ea9a595211b1 | 9e245cff68c16348cb365baa74f9871371a31966 | /QueryPhonesecWebservice/src/main/java/com/newlandframework/rpc/services/pojo/CostTime.java | 369ebe09d481b7a8d98a3e158c7293191c402f88 | [
"Apache-2.0"
] | permissive | zg666/QueryPhonesecWebservice | 185f43331b552a63feb3b02479dfc1d25605c3e4 | 436c9c8c593eb2e6ca563a8ff8e4a34c486af6b1 | refs/heads/master | 2021-01-23T09:41:09.535678 | 2017-09-06T10:01:56 | 2017-09-06T10:01:56 | 102,593,250 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,380 | java | /**
* Copyright (C) 2017 Newland Group Holding Limited
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.newlandframework.rpc.services.pojo;
import java.io.Serializable;
/**
* @author tangjie<https://github.com/tang-jie>
* @filename:CostTime.java
* @description:CostTime功能模块
* @blogs http://www.cnblogs.com/jietang/
* @since 2017/3/22
*/
public class CostTime implements Serializable {
public long elapse;
public String detail;
public long getElapse() {
return elapse;
}
public void setElapse(long elapse) {
this.elapse = elapse;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String toString() {
return "CostTime [elapse=" + elapse + ", detail=" + detail + "]";
}
}
| [
"1095710366@qq.com"
] | 1095710366@qq.com |
4fa17f2202208a96f174c18a65da3bd5f66cc183 | 6c533437ddba5db4a4a32ba8d9e3c839d21f71fa | /MyMovies/app/src/main/java/nanodegree/prips/com/mymovies/common/ToolbarBuilder.java | c3379fa0f90952dc97256e456708d713d3d51df3 | [] | no_license | prips/Nanodegree-AppPortFolio | a7762ac4e2ab3cb990bb70d1a3cf4c369f994731 | 9939f79cee167894428576f028e4919b530faaf6 | refs/heads/master | 2020-03-29T18:35:01.452616 | 2015-09-28T06:55:31 | 2015-09-28T06:55:31 | 41,108,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 775 | java | package nanodegree.prips.com.mymovies.common;
import android.content.Context;
import android.support.v7.widget.Toolbar;
/**
* Created by pseth on 9/10/15.
*/
public class ToolbarBuilder extends AbstractBuilder<Toolbar> {
private Context mContext;
public ToolbarBuilder(Context context) {
if (context == null) {
throw new IllegalArgumentException("context");
}
mContext = context;
}
public ToolbarBuilder buildWithTitle(String title) {
init();
mBuilt.setTitle(title);
return this;
}
@Override
protected Toolbar createInstance() {
return new Toolbar(mContext);
}
private interface IToolbarType {
int TOOLBAR_SHORT = 0;
int TOOLBAR_TALL = 1;
}
}
| [
"pseth@paypalcorp.com"
] | pseth@paypalcorp.com |
5bf3bfc7a9dff5367da1f072f4f1f8ace060c2e5 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/alibaba--druid/5dac70deb021b342f1e2cf3b858b6e34e8e9586c/before/OracleSelectJoin.java | 33ca42028797da17bc933f18f6383bb83bf5667a | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,553 | java | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.dialect.oracle.ast.stmt;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitor;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
public class OracleSelectJoin extends SQLJoinTableSource implements OracleSelectTableSource {
protected OracleSelectPivotBase pivot;
public OracleSelectJoin(String alias){
super(alias);
}
public OracleSelectJoin(){
}
public OracleSelectPivotBase getPivot() {
return pivot;
}
public void setPivot(OracleSelectPivotBase pivot) {
this.pivot = pivot;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
this.accept0((OracleASTVisitor) visitor);
}
protected void accept0(OracleASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, this.left);
acceptChild(visitor, this.right);
acceptChild(visitor, this.condition);
acceptChild(visitor, this.using);
acceptChild(visitor, this.flashback);
}
visitor.endVisit(this);
}
public void output(StringBuffer buf) {
this.left.output(buf);
buf.append(JoinType.toString(this.joinType));
this.right.output(buf);
if (this.condition != null) {
buf.append(" ON ");
this.condition.output(buf);
}
if (this.using.size() > 0) {
buf.append(" USING (");
int i = 0;
for (int size = this.using.size(); i < size; ++i) {
if (i != 0) {
buf.append(", ");
}
((SQLExpr) this.using.get(i)).output(buf);
}
buf.append(")");
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
OracleSelectJoin that = (OracleSelectJoin) o;
if (pivot != null ? !pivot.equals(that.pivot) : that.pivot != null) return false;
return flashback != null ? flashback.equals(that.flashback) : that.flashback == null;
}
@Override
public int hashCode() {
int result = pivot != null ? pivot.hashCode() : 0;
result = 31 * result + (flashback != null ? flashback.hashCode() : 0);
return result;
}
public String toString () {
return SQLUtils.toOracleString(this);
}
public SQLJoinTableSource clone() {
OracleSelectJoin x = new OracleSelectJoin();
cloneTo(x);
if (pivot != null) {
x.setPivot(pivot.clone());
}
if (flashback != null) {
x.setFlashback(flashback.clone());
}
return x;
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
ad5e9edd252dfe021a4d5fc1faf41163d2929273 | 0dc3633f6a8be05c362e594af416b5142218ff7d | /src/main/java/com/github/sindrebn/_3_fun_with_interfaces/ApiSender.java | d1624644fe63945298b0dcb8a87a146cdd5a0204 | [] | no_license | sindrebn/java8godis | e4e0388f340d296bff9046f9cf72b76a71284e52 | 16a54a15f9c6feb59d6d22da64f46fbee608b67e | refs/heads/master | 2020-07-24T06:29:43.439401 | 2019-09-11T14:13:02 | 2019-09-11T14:13:02 | 207,829,325 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 505 | java | package com.github.sindrebn._3_fun_with_interfaces;
public class ApiSender implements WithSenderId {
public final long senderId;
public final String apiKey;
public ApiSender(long senderId, String apiKey) {
this.senderId = senderId;
this.apiKey = apiKey;
}
@Override
public long getSenderId() {
return senderId;
}
@Override
public String toString() {
return "sender with ID '" + senderId + "' authenticated through the API";
}
}
| [
"sindre.nordbo@bekk.no"
] | sindre.nordbo@bekk.no |
1d9f882942f3d6517fa4a6674588ada5f64ebd0c | 350c9db526574b1583e65990611f3eeca256d633 | /hospital/src/main/java/com/solvd/treeset/TreeSetMain.java | 7f3b55f536368a56d4a84f5ade86233a2c5c96e2 | [] | no_license | CFacu/java-test-automation | 386657bb1e066bd3fa972139a142d99606133453 | bfd1ba7dbc4b5f8eb4542f8f574b5a26825c39c3 | refs/heads/master | 2022-11-27T01:59:25.918812 | 2020-03-10T04:53:40 | 2020-03-10T04:53:40 | 232,844,691 | 0 | 0 | null | 2022-11-16T00:41:33 | 2020-01-09T15:48:58 | Java | UTF-8 | Java | false | false | 637 | java | package com.solvd.treeset;
public class TreeSetMain {
public static void main(String[] args) {
MyTreeSet tree = new MyTreeSet();
tree.add(15);
tree.add(123);
tree.add(546);
tree.add(1);
tree.add(78);
tree.add(853);
System.out.println("InOrder TreeSet:");
tree.printInOrder(tree.getRoot());
System.out.println("PostOrder TreeSet:");
tree.printPostOrder(tree.getRoot());
System.out.println("Deleting info:");
tree.delete(123);
tree.delete(546);
tree.delete(1);
tree.printInOrder(tree.getRoot());
}
} | [
"c.facu98@gmail.com"
] | c.facu98@gmail.com |
dacd093ac95f2ae47e50dc0919d4c6cd51244f27 | b40988776a0f4765eee34071b9e45e0bedaac252 | /seed-mpp/src/main/java/com/jadyer/seed/mpp/mgr/user/UserInfoRepository.java | e7dceae5fa90aedcd0f42792bf79bb404d155302 | [
"Apache-2.0"
] | permissive | uestclife/seed | 8368e9a186b42462ea4d4c93405a54abc87830fc | 832120f9d0c5ecfc9692f419e8a5952620df38a4 | refs/heads/master | 2021-01-21T20:38:20.178152 | 2017-05-19T08:37:44 | 2017-05-19T08:37:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 596 | java | package com.jadyer.seed.mpp.mgr.user;
import com.jadyer.seed.comm.jpa.BaseRepository;
import com.jadyer.seed.mpp.mgr.user.model.UserInfo;
import org.springframework.data.jpa.repository.Query;
public interface UserInfoRepository extends BaseRepository<UserInfo, Long> {
@Query("FROM UserInfo WHERE username=?1 AND password=?2")
UserInfo findByUsernameAndPassword(String username, String password);
@Query("FROM UserInfo WHERE mptype=1 AND mpid=?1")
UserInfo findByWxid(String mpid);
@Query("FROM UserInfo WHERE mptype=2 AND mpid=?1")
UserInfo findByQqid(String mpid);
} | [
"jadyer@yeah.net"
] | jadyer@yeah.net |
76ac8625b2fd138096af5fed27faf8c290b1f84f | ddabf75eb7036338ad5375b88682474a12e213d9 | /src/paulpackage/Device.java | bed54a8f7c9da666a9821a91710c907fa932db71 | [] | no_license | shubhamvadhera/cap-nosql-aws | c607c8a17a99e6853fd764eb781dbbc1e3ac0923 | 23c34899eafeb2735075675c7d5bcbe54d194d55 | refs/heads/master | 2021-06-13T20:42:19.634258 | 2017-04-26T16:34:21 | 2017-04-26T16:34:21 | 56,011,872 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,945 | java | package paulpackage;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.BufferOverflowException;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.*;
/**
* Description of the Class
*
*@author Paul Nguyen
*@created April 24, 2003
*/
public class Device {
/**
* Description of the Field
*
*@since
*/
public final static int NUM_BLOCKS_PER_PAGE = 512; // 512 blocks per page
/**
* Description of the Field
*
*@since
*/
public final static int BLOCK_SIZE = 8 * 1024;// 8K blocks
/**
* Description of the Field
*
*@since
*/
public final static int PAGE_SIZE = BLOCK_SIZE * NUM_BLOCKS_PER_PAGE;
private final static boolean DEBUG = true;
private String filename;
private FileChannel filechannel;
private MappedByteBuffer bytebuffer;
/**
* Constructor for the Device object
*
*@param filename Description of Parameter
*@since
*/
public Device(String filename) {
this.filename = filename;
this.filechannel = null;
this.bytebuffer = null;
}
/**
* Gets the block attribute of the Device object
*
*@param block_number Description of Parameter
*@return The block value
*@since
*/
public ByteBuffer getBlock(int block_number) {
allocateByteBuffer();
int offset = BLOCK_SIZE * (block_number);
int limit = BLOCK_SIZE + offset;
if (DEBUG) {
System.out.println("Get Block Number: " + block_number);
System.out.println("Get Block Offset: " + offset);
System.out.println("Get BLock Limit: " + limit);
}
this.bytebuffer.position(offset).limit(limit);
ByteBuffer block = this.bytebuffer.slice();
return block;
}
/**
* Gets the page attribute of the Device object
*
*@param page_number Description of Parameter
*@return The page value
*@since
*/
public ByteBuffer getPage(int page_number) {
allocateByteBuffer(page_number);
int offset = PAGE_SIZE * (page_number);
offset += BLOCK_SIZE;
// for file header
int limit = offset + PAGE_SIZE;
if (DEBUG) {
System.out.println("Get Page Number: " + page_number);
System.out.println("Get Page Offset: " + offset);
System.out.println("Get Page Limit: " + limit);
}
this.bytebuffer.position(offset).limit(limit);
ByteBuffer page = this.bytebuffer.slice();
return page;
}
public ByteBuffer getLargePages(int page_number, int page_count) {
allocateByteBuffer(page_number);
int offset = PAGE_SIZE * (page_number);
int limit = offset + (PAGE_SIZE*page_count);
if (DEBUG) {
System.out.println("Get Large Page Start Page Number: " + page_number);
System.out.println("Get Large Page Offset: " + offset);
System.out.println("Get Large Page Limit: " + limit);
}
this.bytebuffer.position(offset).limit(limit);
ByteBuffer page = this.bytebuffer.slice();
return page;
}
/**
* Gets the channel attribute of the Device object
*
*@return The channel value
*@since
*/
public FileChannel getChannel() {
return filechannel;
}
/**
* Description of the Method
*
*@return Description of the Returned Value
*@since
*/
public boolean mount() {
try {
File filechk = new File(this.filename);
if (filechk.exists()) {
if (DEBUG) {
System.out.println(this.filename + " exists.");
}
RandomAccessFile thefile = new RandomAccessFile(this.filename, "rw");
this.filechannel = thefile.getChannel();
return false;
} else {
if (DEBUG) {
System.out.println(this.filename + " does not exist, creating...");
}
RandomAccessFile thefile = new RandomAccessFile(this.filename, "rw");
thefile.setLength(BLOCK_SIZE + PAGE_SIZE);
// one block header + initial page
this.filechannel = thefile.getChannel();
return true;
}
} catch (Exception e) {
System.out.println(e);
return false;
}
}
/**
* Description of the Method
*
*@since
*/
public void umount() {
if (this.bytebuffer != null) {
this.bytebuffer.force();
}
}
/**
* Description of the Method
*
*@since
*/
private void allocateByteBuffer() {
try {
if (DEBUG) {
System.out.println("File Channel Size: " + this.filechannel.size());
}
if (this.bytebuffer == null) {
this.bytebuffer = this.filechannel.map(
FileChannel.MapMode.READ_WRITE,
0,
this.filechannel.size()
);
this.bytebuffer.clear();
} else {
this.bytebuffer.clear();
}
} catch (Exception e) {
}
}
/**
* Description of the Method
*
*@param page_number Description of Parameter
*@since
*/
private void allocateByteBuffer(int page_number) {
int offset = PAGE_SIZE * (page_number) + BLOCK_SIZE ;
int limit = offset + PAGE_SIZE;
try {
if (DEBUG) {
System.out.println("File Channel Size: " + this.filechannel.size());
System.out.println("Page Request Size: " + limit );
}
// map to full file
if (this.bytebuffer == null) {
this.bytebuffer = this.filechannel.map(
FileChannel.MapMode.READ_WRITE,
0,
this.filechannel.size()
);
}
// todo, check for max extent limit and throw exception
// expand fize size to accomodate page expansion
if (limit > this.filechannel.size() ) {
this.bytebuffer = this.filechannel.map(
FileChannel.MapMode.READ_WRITE,
0,
limit
);
}
this.bytebuffer.clear();
} catch (Exception e) {
}
}
}
| [
"shubhamvadhera@gmail.com"
] | shubhamvadhera@gmail.com |
e097f3378ded757fa3fa1dd4f1bb1c67a3a10550 | 95201e4f586aa7a289ea55514e9e0449410f5839 | /AndroidProject/BookBarStatic/app/src/main/java/com/ssdut411/app/bookbarstatic/volley/VolleyManager.java | deccdf9ddcaa17a632e93c82938c16a0528ab415 | [] | no_license | yaohan/GoToSchool | 0dd6fa88acf60530bdd51a5e16399cadc821c53f | 950cf9ca723d0f072c409b7c0af1d455a6d9322c | refs/heads/master | 2021-01-09T09:24:23.930129 | 2017-09-19T02:14:24 | 2017-09-19T02:14:24 | 63,244,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,053 | java | package com.ssdut411.app.bookbarstatic.volley;
import android.content.Context;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.ssdut411.app.bookbarstatic.utils.L;
/**
* Created by yao_han on 2015/11/24.
*/
public class VolleyManager {
// 超时时间(毫秒)
private static final int TIME_OUT = 10 * 1000;
// 最大重连次数,1表示重连2次
private static final int MAX_RETRIES = 1;
private static RequestQueue requestQueue;
private static ImageLoader imageLoader;
private VolleyManager() {
}
/**
* 初始化
* <p/>
* 最好是在application的onCreate方法里面初始化
*
* @param context
*/
public static void init(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new BitmapCache(context));
}
/**
* 得到请求队列
*
* @return
*/
public static RequestQueue getRequestQueue() {
return requestQueue;
}
/**
* 得到ImageLoader
*
* @return
*/
public static ImageLoader getImageLoader() {
return imageLoader;
}
/**
* 添加一个请求到RequestQueue队列
*
* @param request
* @param tag
*/
public static <T> void addRequest(Request<T> request, Object tag) {
if (null != tag) {
request.setTag(tag);
}
// 设置超时时间10s,最大重连次数2次
request.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT, MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
L.i("requestQueue == null?" + (requestQueue == null));
requestQueue.add(request);
}
/**
* 取消RequestQueue队列的请求
*
* @param tag
*/
public static void cancelAll(Object tag) {
requestQueue.cancelAll(tag);
}
}
| [
"937860151@qq.com"
] | 937860151@qq.com |
20b80922847ddec605959bd0077cb3c535231615 | 1f189290f36a9445f2a50a98a9244ae23704addd | /recomendacionfc/src/main/java/com/isistan/lbsn/vencindario/NearestNUserNeighborhoodSplitDMByScoring.java | 0ae725b36b23ec89fc9a63c2c660f3871f02e61b | [] | no_license | carlosrios10/recomendacionjava | 3320c82814241a3d0a6dd64edce02e7c6f1103e8 | 81214ef05d93a601a72d883e5a74684847f32bfd | refs/heads/master | 2021-01-22T23:15:48.960520 | 2018-09-06T20:17:53 | 2018-09-06T20:17:53 | 31,434,723 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,054 | java | package com.isistan.lbsn.vencindario;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections.IteratorUtils;
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveArrayIterator;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.common.RefreshHelper;
import org.apache.mahout.cf.taste.impl.recommender.TopItems;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import com.isistan.lbsn.datamodels.DataModelByItemCategory;
import com.isistan.lbsn.datamodels.ItemModel;
import com.isistan.lbsn.entidades.Item;
import com.isistan.lbsn.scoring.Scoring;
public class NearestNUserNeighborhoodSplitDMByScoring implements UserNeighborhoodAux {
private final int n;
private final double minSimilarity;
private final double samplingRate;
private final RefreshHelper refreshHelper;
private final ItemModel itemModel;
private final UserSimilarity userSimilarity;
private final DataModelByItemCategory dataModel;
private int radio;
public NearestNUserNeighborhoodSplitDMByScoring(int n, Scoring userSimilarity,ItemModel itemModel,DataModelByItemCategory dataModel)
throws TasteException {
this(n, Double.NEGATIVE_INFINITY, userSimilarity, itemModel,dataModel, 1.0);
}
public NearestNUserNeighborhoodSplitDMByScoring(int n,double minSimilarity,Scoring userSimilarity,ItemModel itemModel,DataModelByItemCategory dataModel, double samplingRate)
throws TasteException {
this.userSimilarity = userSimilarity;
this.samplingRate = samplingRate;
this.itemModel = itemModel;
this.dataModel = dataModel;
Preconditions.checkArgument(n >= 1, "n must be at least 1");
int numItems = itemModel.getCantidadDeItems();
this.n = n > numItems ? numItems : n;
this.minSimilarity = minSimilarity;
this.refreshHelper = new RefreshHelper(null);
this.refreshHelper.addDependency(this.userSimilarity);
}
public void refresh(Collection<Refreshable> alreadyRefreshed) {
// TODO Auto-generated method stub
}
public long[] getUserNeighborhood(long userID) throws TasteException {
return null;
}
public long[] getUserNeighborhood(long userID, long itemID)
throws TasteException {
LongPrimitiveIterator userIDs = mergeUserIDs(itemID);
UserSimilarity userSimilarityImpl = this.userSimilarity;
TopItems.Estimator<Long> estimator = new Estimator(userSimilarityImpl, userID, minSimilarity);
return TopItems.getTopUsers(n, userIDs, null, estimator);
}
private LongPrimitiveArrayIterator mergeUserIDs(long itemID) throws TasteException{
Collection<Long> cateNivelTodas = new HashSet<Long>();
Item item = itemModel.getItem(itemID);
Collection<Long> coll = item.getCategoriaNivel1();
for (Iterator<Long> iterator = coll.iterator(); iterator.hasNext();) {
Long long1 = iterator.next();
LongPrimitiveIterator userIDs = this.dataModel.getUserIDs(long1);
cateNivelTodas.addAll(IteratorUtils.toList(userIDs));
}
long[] catArray = Longs.toArray(cateNivelTodas);
return new LongPrimitiveArrayIterator(catArray);
}
private static final class Estimator implements TopItems.Estimator<Long> {
private final UserSimilarity userSimilarityImpl;
private final long theUserID;
private final double minSim;
private Estimator(UserSimilarity userSimilarityImpl, long theUserID, double minSim) {
this.userSimilarityImpl = userSimilarityImpl;
this.theUserID = theUserID;
this.minSim = minSim;
}
public double estimate(Long userID) throws TasteException {
if (userID == theUserID) {
return Double.NaN;
}
double sim = userSimilarityImpl.userSimilarity(theUserID, userID);
return sim >= minSim ? sim : Double.NaN;
}
}
}
| [
"cm.rios.10@gmail.com"
] | cm.rios.10@gmail.com |
d27a2c3b16f20cffbcbf66a40d17211ade07e9f3 | 260cec5c5240eb2bd9b0a0e4442f4e04d079b96a | /Codeforces/src/petyaAndString/MyClass.java | 769f3bf808c458c64e88809cf9055ef364202838 | [] | no_license | Sumit-Anand3098/core_java | aea1107870cd2240664c21814e7974681392522a | d72047948102e831768c9149b2ac20a6483f99af | refs/heads/main | 2023-04-06T11:24:54.671083 | 2021-04-16T19:20:54 | 2021-04-16T19:20:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 864 | java | package petyaAndString;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String x=s.nextLine();
String y=s.nextLine();
String str1=x.toLowerCase();
String str2=y.toLowerCase();
String str3="abcdefghijklmnopqrstuvwxyz";
int sum1=0 , sum2=0;
for(int i=0;i<str1.length();i++) {
if(str1.charAt(i)==str2.charAt(i)) {
}
else {
for(int j=0;j<str3.length();j++) {
if(str3.charAt(j)==str1.charAt(i)) {
sum1+=j;
}
}
for(int j=0;j<str3.length();j++) {
if(str3.charAt(j)==str2.charAt(i)) {
sum2+=j;
}
}
break;
}
}
if(sum1<sum2) {
System.out.println("-1");
}
else if(sum1==sum2) {
System.out.println("0");
}
else if(sum1>sum2) {
System.out.println("1");
}
}
}
| [
"sumit@Blazee"
] | sumit@Blazee |
272533463b9e98804091be7b9389a6520a205c0e | 76e8173d3cbeb700a5c85072af3273973376b7d9 | /recycle_pad/src/com/recycle/pad/net/action/NextActionRcv.java | 6f90e5beca491ecd6881c327523366ddbfc48efb | [] | no_license | zhouyeliang/recycle | aae816e6d3871733f2dea3077f372befce6dbc9a | 5808ca7bbe47c5b163fd14b4d9ad80205d07de9f | refs/heads/master | 2020-07-02T09:55:34.648207 | 2016-09-21T02:27:46 | 2016-09-21T02:27:46 | 66,745,098 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 895 | java | package com.recycle.pad.net.action;
import org.json.JSONException;
import android.content.Context;
/**
* @author tao do next request if the last goes well consider extends
* {@link BareReceiver}
*/
public class NextActionRcv implements ActionReceiverImpl {
ActionReceiverImpl lastRcv;
ActionRequestImpl nextReq;
ActionReceiverImpl nextRcv;
public NextActionRcv(ActionReceiverImpl lastRcv, ActionRequestImpl nReq,
ActionReceiverImpl nRcv) {
super();
this.lastRcv = lastRcv;
this.nextReq = nReq;
this.nextRcv = nRcv;
}
@Override
public boolean response(String result) throws JSONException {
if (null != lastRcv && lastRcv.response(result)) {
ActionBuilder.getInstance().request(nextReq, nextRcv);
return true;
}
return false;
}
@Override
public Context getReceiverContext() {
return null == nextRcv ? null : nextRcv.getReceiverContext();
}
}
| [
"965660236@qq.com"
] | 965660236@qq.com |
5ffcf845a44104149fb6f8770d89fce6aa0bf957 | 1075e9cf51417a88414653b7731839c1b5c0a747 | /app/src/main/java/cn/estronger/bike/connect/Connect.java | 6d8e612ecc1644579b95346f9c94eab07dad14e6 | [] | no_license | Hollyxx/ViBlue | 08b5795ce1555b9b659d1f9401d00e2784aeddc1 | a48f4add23a20ccaf778ec419d0166cf7cad3909 | refs/heads/master | 2021-01-20T08:19:03.866155 | 2017-02-24T05:23:39 | 2017-02-24T05:23:39 | 90,128,844 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 29,005 | java | package cn.estronger.bike.connect;
import android.content.Context;
import cn.estronger.bike.constant.NetConstant;
import cn.estronger.bike.utils.JZLocationConverter;
import cn.estronger.bike.utils.MyHttpUtils;
import cn.estronger.bike.utils.PrefUtils;
import com.tools.SystemTools;
import org.xutils.common.util.MD5;
import java.util.HashMap;
/**
* Created by MrLv on 2016/12/14.
*/
public class Connect {
public static final int ZXING_CODE = 0;
public static final int OPEN_LOCK = 1;
public static final int SEND_REGISTER_CODE = 2;
public static final int REGISTER = 3;
public static final int LOGIN = 4;
public static final int DEPOSIT = 5;
public static final int SEACH = 6;
public static final int WX_PAY_CHARGE_DEPOSIT = 7;
public static final int ALIPAY_CHARGE_DEPOSIT = 8;
public static final int IDENTITY = 9;
public static final int BEEP_LOCK = 10;
public static final int CHARGING = 11;
public static final int PERM = 12;
public static final int GET_BICYCLE_LOCATION = 13;
public static final int SIGN_RECOMMEND = 14;
public static final int BOOK = 15;
public static final int GET_ORDER_INFO = 16;
public static final int CANCEL_ORDER = 17;
public static final int INFO = 18;
public static final int UPDATE_INFO = 19;
public static final int UPDATE_MODILE = 20;
public static final int GET_CREDIT_LOG_PB = 21;
public static final int GET_WALLET_INFO = 22;
public static final int GET_WALLET_DETAIL = 23;
public static final int GET_ORDERS = 24;
public static final int GET_ORDER_DETAIL = 25;
public static final int GET_MESSAGES = 26;
public static final int LOCK_POSITION = 27;
public static final int LOG_OUT = 28;
public static final int UPDATE_AVATAR = 28;
public static final int CURRENT = 29;
public static final int INDEX = 30;
public static final int REQUEST_PERMISSION_SETTING = 31;
public static final int CASH_APPLY = 32;
public static final int ADD_FAULT = 33;
public static final int ADD_ILLEGAL_PARKING = 34;
public static final int ADD_NORMAL_PARKING = 35;
public static final int CONTACT = 36;
public static final int VERSION = 37;
public static final int GET_EXPIRED_LIST = 38;
public static final int GET_COUPON_LIST = 39;
public static final int GET_ENCRYPT_CODE = 40;
/**
* 开锁指令
*
* @param device_id 设备ID
* @param callback 回调
*/
public static void openLock(Context context, String device_id, String lat, String lng, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("device_id", device_id);
map.put("lat", lat);
map.put("lng", lng);
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPost(context, OPEN_LOCK, NetConstant.OPEN_LOCK, map, callback);
}
/**
* 获取注册的验证码
*
* @param mobile 手机号
* @param callback 回调
*/
public static void getRegCode(Context context, String mobile, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("mobile", mobile);
MyHttpUtils.xutilsPost(context, SEND_REGISTER_CODE, NetConstant.SEND_REGISTER_CODE, map, callback);
}
/**
* 注册
*
* @param mobile 手机号
* @param code 验证码
* @param callback 回调
*/
public static void register(Context context, String mobile, String code, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("mobile", mobile);
map.put("code", code);
map.put("uuid", SystemTools.getPhoneId());
MyHttpUtils.xutilsPost(context, REGISTER, NetConstant.REGISTER, map, callback);
}
/**
* 登录
*
* @param context
* @param mobile
* @param code
* @param callback
*/
public static void login(Context context, String mobile, String code, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("mobile", mobile);
map.put("code", code);
map.put("uuid", SystemTools.getPhoneId());
MyHttpUtils.xutilsPost(context, LOGIN, NetConstant.LOGIN, map, callback);
}
/**
* 充值押金生成押金订单
*
* @param context
* @param callback
*/
public static void deposit(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPost(context, DEPOSIT, NetConstant.DEPOSIT, map, callback);
}
/**
* 微信支付
*
* @param context
* @param pdr_sn
* @param callback
*/
public static void wxPay(Context context, String pdr_sn, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("pdr_sn", pdr_sn);
MyHttpUtils.xutilsPost(context, WX_PAY_CHARGE_DEPOSIT, NetConstant.WX_PAY_CHARGE_DEPOSIT, map, callback);
}
/**
* 支付宝支付
*
* @param context
* @param pdr_sn
* @param callback
*/
public static void aliPay(Context context, String pdr_sn, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("pdr_sn", pdr_sn);
MyHttpUtils.xutilsPost(context, ALIPAY_CHARGE_DEPOSIT, NetConstant.ALIPAY_CHARGE_DEPOSIT, map, callback);
}
/**
* 实名认证
*
* @param context
* @param real_name 姓名
* @param identity 身份证
* @param callback
*/
public static void identity(Context context, String real_name, String identity, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("real_name", real_name);
map.put("identity", identity);
MyHttpUtils.xutilsPost(context, IDENTITY, NetConstant.IDENTITY, map, callback);
}
/**
* 寻车响铃
*
* @param context
* @param device_id
* @param callback
*/
public static void beepLock(Context context, String device_id, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("device_id", device_id);
MyHttpUtils.xutilsPostNoPb(BEEP_LOCK, NetConstant.BEEP_LOCK, map, callback);
}
/**
* 生成充值订单
*
* @param context
* @param amount 金额
* @param callback
*/
public static void charging(Context context, String amount, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("amount", amount);
MyHttpUtils.xutilsPostNoPb(CHARGING, NetConstant.CHARGING, map, callback);
}
/**
* 获取附近的车辆 marker
*
* @param lat 纬度
* @param lng 经度
* @param zoom 缩放级别
* @param type 单车类型 0全部 1单人 2双人 3家庭
* @param callback
*/
public static void getMarker(String lat, String lng, String zoom, String type, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
JZLocationConverter.LatLng latlng = JZLocationConverter.gcj02ToWgs84(new JZLocationConverter.LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
map.put("lat", latlng.getLatitude() + "");
map.put("lng", latlng.getLongitude() + "");
map.put("zoom", zoom);
map.put("type", type);
MyHttpUtils.xutilsPostNoPb(GET_BICYCLE_LOCATION, NetConstant.GET_BICYCLE_LOCATION, map, callback);
}
/**
* 获取当前订单
*
* @param context 上下文
* @param device_id 设备id
* @param order_sn 订单id
* @param callback 回调
*/
public static void currentOrder(Context context, String device_id, String order_sn, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("device_id", device_id);
map.put("order_sn", order_sn);
MyHttpUtils.xutilsPostNoPb(GET_ORDER_INFO, NetConstant.GET_ORDER_INFO, map, callback);
}
/**
* 获取当前订单
*
* @param context 上下文
* @param device_id 设备id
* @param order_sn 订单id
* @param callback 回调
*/
public static void currentOrderPb(Context context, String device_id, String order_sn, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("device_id", device_id);
map.put("order_sn", order_sn);
MyHttpUtils.xutilsPost(context, GET_ORDER_INFO, NetConstant.GET_ORDER_INFO, map, callback);
}
/**
* 推荐注册联系人
*
* @param context
* @param mobile 推荐人的手机号
* @param callback
*/
public static void recommend(Context context, String mobile, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("mobile", mobile);
MyHttpUtils.xutilsPost(context, SIGN_RECOMMEND, NetConstant.SIGN_RECOMMEND, map, callback);
}
/**
* 单车预约
*
* @param context
* @param lat
* @param lng
* @param bicycle_sn
* @param callback
*/
public static void book(Context context, String lat, String lng, String bicycle_sn, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
JZLocationConverter.LatLng latlng = JZLocationConverter.gcj02ToWgs84(new JZLocationConverter.LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("device_id", bicycle_sn);
map.put("lat", latlng.getLatitude() + "");
map.put("lng", latlng.getLongitude() + "");
MyHttpUtils.xutilsPost(context, BOOK, NetConstant.BOOK, map, callback);
}
/**
* 取消预约
*
* @param context
* @param order_sn
* @param callback
*/
public static void cancelBook(Context context, String order_sn, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("order_sn", order_sn);
MyHttpUtils.xutilsPost(context, CANCEL_ORDER, NetConstant.CANCEL_ORDER, map, callback);
}
/**
* 获取用户个人信息
*
* @param context
* @param callback
*/
public static void info(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPostNoPb(INFO, NetConstant.INFO, map, callback);
}
/**
* 修改个人信息
*
* @param context
* @param nickname
* @param callback
*/
public static void updateInfo(Context context, String nickname, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("nickname", nickname);
MyHttpUtils.xutilsPost(context, UPDATE_INFO, NetConstant.UPDATE_INFO, map, callback);
}
/**
* 更新手机号
*
* @param context
* @param mobile
* @param code
* @param real_name
* @param identification
* @param callback
*/
public static void updateModile(Context context, String mobile, String code, String real_name, String identification, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("mobile", mobile);
map.put("code", code);
map.put("real_name", real_name);
map.put("identification", identification);
MyHttpUtils.xutilsPost(context, UPDATE_MODILE, NetConstant.UPDATE_MODILE, map, callback);
}
/**
* 获取信用记录
*
* @param context
* @param page 页数
* @param callback
*/
public static void getCreditLogPb(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPost(context, GET_CREDIT_LOG_PB, NetConstant.GET_CREDIT_LOG, map, callback);
}
public static void getCreditLog(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPostNoPb(GET_CREDIT_LOG_PB, NetConstant.GET_CREDIT_LOG, map, callback);
}
/**
* 获取钱包信息
*
* @param context
* @param callback
*/
public static void getWalletInfo(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPost(context, GET_WALLET_INFO, NetConstant.GET_WALLET_INFO, map, callback);
}
/**
* 获取钱包明细
*
* @param context
* @param page
* @param callback
*/
public static void getWalletDetailPb(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPost(context, GET_WALLET_DETAIL, NetConstant.GET_WALLET_DETAIL, map, callback);
}
public static void getWalletDetail(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPostNoPb(GET_WALLET_DETAIL, NetConstant.GET_WALLET_DETAIL, map, callback);
}
/**
* 获取行程列表
*
* @param context
* @param page
* @param callback
*/
public static void getOrdersPb(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPost(context, GET_ORDERS, NetConstant.GET_ORDERS, map, callback);
}
public static void getOrders(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPostNoPb(GET_ORDERS, NetConstant.GET_ORDERS, map, callback);
}
/**
* 获取行程详情
*
* @param context
* @param order_id 订单id
* @param callback
*/
public static void getOrdersDetail(Context context, String order_id, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("order_id", order_id);
MyHttpUtils.xutilsPost(context, GET_ORDER_DETAIL, NetConstant.GET_ORDER_DETAIL, map, callback);
}
/**
* 获取消息列表
*
* @param context
* @param page
* @param callback
*/
public static void getMessagesPb(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPost(context, GET_MESSAGES, NetConstant.GET_MESSAGES, map, callback);
}
public static void getMessages(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPostNoPb(GET_MESSAGES, NetConstant.GET_MESSAGES, map, callback);
}
/**
* 查找锁位置
*
* @param context
* @param device_id 锁id
* @param callback
*/
public static void lockPosition(Context context, String device_id, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("device_id", device_id);
MyHttpUtils.xutilsPost(context, LOCK_POSITION, NetConstant.LOCK_POSITION, map, callback);
}
/**
* 退出登录
*
* @param context
* @param callback
*/
public static void logout(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPost(context, LOG_OUT, NetConstant.LOG_OUT, map, callback);
}
/**
* 更新个人头像
*
* @param context
* @param upfile
* @param callback
*/
public static void updateAvatar(Context context, String upfile, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPostUpload(context, UPDATE_AVATAR, NetConstant.UPDATE_AVATAR, map, "avatar", upfile, callback);
}
/**
* 获取当前订单
*
* @param context
* @param callback
*/
public static void current(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPostNoPb(CURRENT, NetConstant.CURRENT, map, callback);
}
/**
* 获取用户协议等链接地址
*
* @param context
* @param callback
*/
public static void index(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("language", "");
MyHttpUtils.xutilsPostNoPb(INDEX, NetConstant.INDEX, map, callback);
}
/**
* 退押金
*
* @param context
* @param callback
*/
public static void cashApply(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPost(context, CASH_APPLY, NetConstant.CASH_APPLY, map, callback);
}
/**
* 故障上报
*
* @param context
* @param lat 经度
* @param lng 维度
* @param fault_type 故障类型
* @param fault_content 故障内容
* @param upfile 文件名
* @param callback 回调
*/
public static void addFault(Context context, String lat, String lng, String bicycle_sn, String fault_type, String fault_content, String upfile, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("lat", lat);
map.put("lng", lng);
map.put("bicycle_sn", bicycle_sn);
map.put("fault_type", fault_type);
map.put("fault_content", fault_content);
if ("".equals(upfile)) {
MyHttpUtils.xutilsPost(context, ADD_FAULT, NetConstant.ADD_FAULT, map, callback);
} else {
MyHttpUtils.xutilsPostUpload(context, ADD_FAULT, NetConstant.ADD_FAULT, map, "fault_image", upfile, callback);
}
}
/**
* 违停举报
*
* @param context
* @param lat
* @param lng
* @param bicycle_sn
* @param content
* @param upfile
* @param callback
* @param type 默认违停1,其他为2
*/
public static void addIllegalParking(Context context, String lat, String lng, String bicycle_sn, String content, String upfile, String type,MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("lat", lat);
map.put("lng", lng);
map.put("bicycle_sn", bicycle_sn);
map.put("content", content);
map.put("type", type);
if ("".equals(upfile)) {
MyHttpUtils.xutilsPost(context, ADD_ILLEGAL_PARKING, NetConstant.ADD_ILLEGAL_PARKING, map, callback);
} else {
MyHttpUtils.xutilsPostUpload(context, ADD_ILLEGAL_PARKING, NetConstant.ADD_ILLEGAL_PARKING, map, "file_image", upfile, callback);
}
}
/**
* 停车拍照
* @param context
* @param lat
* @param lng
* @param bicycle_sn
* @param content
* @param upfile
* @param callback
*/
public static void addNormalParking(Context context, String lat, String lng, String bicycle_sn, String content, String upfile, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("lat", lat);
map.put("lng", lng);
map.put("bicycle_sn", bicycle_sn);
map.put("content", content);
MyHttpUtils.xutilsPostUpload(context, ADD_NORMAL_PARKING, NetConstant.ADD_NORMAL_PARKING, map, "parking_image", upfile, callback);
}
/**
* 获取联系方式
* @param context
* @param callback
*/
public static void getContact(Context context,MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
MyHttpUtils.xutilsPost(context, CONTACT, NetConstant.CONTACT, map, callback);
}
public static void getExpiredList(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPost(context, GET_EXPIRED_LIST, NetConstant.GET_EXPIRED_LIST, map, callback);
}
public static void getExpiredListNoPb(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPostNoPb(GET_EXPIRED_LIST, NetConstant.GET_EXPIRED_LIST, map, callback);
}
public static void getCouponList(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPost(context, GET_COUPON_LIST, NetConstant.GET_COUPON_LIST, map, callback);
}
/**
* 获取优惠券列表
* @param context
* @param page
* @param callback
*/
public static void getCouponListNoPb(Context context, String page, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
map.put("page", page);
MyHttpUtils.xutilsPostNoPb(GET_COUPON_LIST, NetConstant.GET_COUPON_LIST, map, callback);
}
public static void getEncryptCode(Context context, MyHttpUtils.MyHttpCallback callback) {
HashMap map = new HashMap<String, String>();
map.put("user_id", PrefUtils.getString(context, "user_id", "-1"));
map.put("sign", MD5.md5(PrefUtils.getString(context, "user_id", "-1") + SystemTools.getPhoneId()));
MyHttpUtils.xutilsPost(context,GET_ENCRYPT_CODE, NetConstant.GET_ENCRYPT_CODE, map, callback);
}
}
| [
"969538128@qq.com"
] | 969538128@qq.com |
321610729502b004fdbfe3e248ab153f27da4897 | 99027b80b0038545097cd3a1f33c7f27cdfc18eb | /src/ALG/字符串替换.java | 85a59a9db677576dc3a2f61b302441c4a8c7ea66 | [] | no_license | LanceShu/ALG | a6477c02b07014a26586de1841ff966b099d4741 | 40df97f3715986e751c6025b07cba7fc068e632c | refs/heads/master | 2021-09-12T08:19:34.448046 | 2018-04-15T15:28:08 | 2018-04-15T15:28:08 | 114,628,497 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,421 | java | package ALG;
public class 字符串替换 {
public static void main(String[] args) {
char[] string = "hello world".toCharArray();
System.out.println(string.length);
changeString(string,string.length);
}
public static void changeString(char[] string,int usedLength){
if(string == null || string.length < usedLength){
return;
}
int whiteCount = 0;
for(int i = 0;i<usedLength;i++){
if(string[i] == ' '){
whiteCount++;
}
}
int targetLength = whiteCount * 2 + usedLength;
int tmp = targetLength;
if(targetLength < usedLength){
return;
}
if(whiteCount == 0){
System.out.println(string);
return;
}
usedLength --;
targetLength --;
System.out.println("uselength:"+usedLength);
System.out.println("target:"+targetLength);
char[] chage = new char[targetLength+1];
while(usedLength >= 0 && usedLength <= targetLength){
if(string[usedLength] == ' '){
chage[targetLength--]='0';
chage[targetLength--]='2';
chage[targetLength--]='%';
}else{
chage[targetLength--]=string[usedLength];
}
usedLength --;
}
System.out.println(chage);
}
}
| [
"869924650@qq.com"
] | 869924650@qq.com |
40515728f878b708299221684079e774f4a423ed | 5e3346210bb39862cca389c734240a8eb96aa185 | /app/src/main/java/com/hetekivi/rasian/Data/RSS/FeedCollection.java | 60cf83a4c24e886d2ee6bf76ac49eec67103c45b | [
"Apache-2.0"
] | permissive | SanteriHetekivi/Rasian | 86d7c4c48bb1e308c0471d9b0044cdfd63fc1c4a | 6cf3b7ea4147182142971d59d93dd67a172598c1 | refs/heads/master | 2021-05-04T10:32:55.981622 | 2016-09-23T07:15:42 | 2016-09-23T07:15:42 | 55,347,532 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,008 | java | package com.hetekivi.rasian.Data.RSS;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import com.hetekivi.rasian.Activities.FeedsActivity;
import com.hetekivi.rasian.Activities.MainActivity;
import com.hetekivi.rasian.Data.Global;
import com.hetekivi.rasian.Interfaces.*;
import com.hetekivi.rasian.R;
import com.hetekivi.rasian.Receives.UpdateReceiver;
import com.hetekivi.rasian.Tasks.*;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.util.*;
import static com.hetekivi.rasian.Data.Global.*;
import static com.hetekivi.rasian.External.Tools.DownloadDirectory;
/**
* Created by Santeri Hetekivi on 26.3.2016.
*/
/**
* Class RSSCollection
* for storing and managing Feed feeds.
*/
public class FeedCollection implements Rowable, Storable, Updatable, Addable, Removable, JSON
{
/**
* Public static final values for class.
*/
private static final String TAG = "RSSCollection";
/**
* Constructor
*/
public FeedCollection()
{
this.Feeds = new LinkedHashMap<>();
}
public static final int DEFAULT_DELAY_HOURS = 24;
public static final int DEFAULT_ROW_LIMIT = 10;
public static final String DEFAULT_DOWNLOAD_DIR = DownloadDirectory();
/**
* Public static final keys for preferences.
*/
public static final String PREFERENCES_START = TAG+"_";
public static final String PREF_NEXT_UPDATE = PREFERENCES_START + "NextUpdate";
public static final String PREF_FEEDS = PREFERENCES_START + "Feeds";
public static final String PREF_DELAY_HOURS = PREFERENCES_START + "DelayHours";
public static final String PREF_DOWNLOAD_DIR = PREFERENCES_START + "DownloadDir";
public static final String PREF_ROW_LIMIT = PREFERENCES_START + "RowLimit";
/**
* Tag names for parsing.
* Must be lowercase.
*/
public static final String NAME_FEED = "feed";
public static final String NAME_NEXT_UPDATE = "next_update";
public static final String NAME_DELAY_HOURS = "delay_hours";
public static final String NAME_DOWNLOAD_DIR = "download_dir";
public static final String NAME_ROW_LIMIT = "row_limit";
/**
* Classes member variables.
*/
public DateTime NextUpdate = null;
private Map<String, Feed> Feeds = new HashMap<>();
private int delayHours = DEFAULT_DELAY_HOURS;
public File downloadDir = new File(DEFAULT_DOWNLOAD_DIR);
public List<Data> Rows = new LinkedList<>(); // List to store rows.
public int RowLimit = DEFAULT_ROW_LIMIT;
/**
* Function Feeds
* for getting all feeds.
* @return All added feeds.
*/
public Map<String,Feed> Feeds()
{
return this.Feeds;
}
/**
* Function Feed
* for getting feed that has given url.
* @param url Url that will be used for selecting fees.
* @return Feed that has given url.
*/
private Feed Feed(String url)
{
Feed feed = null;
if(this.Feeds().containsKey(url))
{
feed = this.Feeds().get(url);
}
return feed;
}
/**
* Function Feed
* for setting given feed to this collection.
* @param feed Feed to set.
*/
public boolean Feed(Feed feed)
{
if(feed.Url() != null && !feed.Url().isEmpty())
{
this.Feeds.put(feed.Url(), feed);
this.Rows = this.Rows();
return true;
}
return false;
}
/**
* Function removeFeed
* for removing feed by it's url.
* @param url Feed's url.
*/
private boolean removeFeed(String url)
{
if(this.Feeds().containsKey(url))
{
this.Feeds.remove(url);
return true;
}
else if(Check())
{
Log.e(TAG, "Removing feed with url: "+url+" failed!");
return false;
}
return false;
}
/**
* Function DelayHours
* for getting alarm's repeat delay in hours.
* @return Alarm's repeat delay in hours.
*/
public int DelayHours()
{
return this.delayHours;
}
/**
* Function DelayMillis
* for getting alarm's repeat delay in milliseconds.
* @return Alarm's repeat delay in milliseconds.
*/
public int DelayMillis()
{
return this.delayHours * 1000 * 60 * 60;
}
/**
* Function Rows
* for making and returning Data rows.
* @return List of rows as Data objects.
*/
@Override
public List<Data> Rows()
{
List<Data> rows = new LinkedList<>();
for (Feed feed : this.Feeds.values())
{
rows.addAll(feed.Rows());
}
Collections.sort(rows, Collections.reverseOrder());
final int limit = (rows.size() < Global.ROW_LIMIT() || Global.ROW_LIMIT() < 0 )?rows.size():Global.ROW_LIMIT();
this.Rows = rows.subList(0, limit);
return rows;
}
/**
* Function onRowsGotten
* is called when rows have been gotten.
* @param rows All rows.
*/
@Override
public void onRowsGotten(List<Data> rows) {
this.Rows = rows;
}
/**
* Function Load
* for loading data from preferences.
* @return Success of load.
*/
@Override
public boolean Load()
{
Boolean success = false;
if(Global.hasPreference())
{
success = true;
Set<String> urls = Preference.Get(PREF_FEEDS, new HashSet<String>());
boolean rssSuccess;
for (String url : urls) {
Feed rss = new Feed(url);
rssSuccess = rss.Load();
if(rssSuccess)
{
rssSuccess = rss.Update(false, false);
if(rssSuccess) this.Feed(rss);
}
success = rssSuccess && success;
}
this.delayHours = Preference.Get(PREF_DELAY_HOURS, DEFAULT_DELAY_HOURS);
if(Preference.Contains(PREF_NEXT_UPDATE))
{
this.NextUpdate = new DateTime(Preference.Get(PREF_NEXT_UPDATE, ""));
}
else this.setAlarm(this.delayHours);
this.downloadDir = new File(Preference.Get(PREF_DOWNLOAD_DIR, DEFAULT_DOWNLOAD_DIR));
this.RowLimit = Preference.Get(PREF_ROW_LIMIT, DEFAULT_ROW_LIMIT);
if(this.NextUpdate.isBefore(new DateTime()))
{
this.resetAlarm();
}
}
return success;
}
/**
* Function onLoadSuccess
* This gets called when loading has been done and was successful.
*/
@Override
public void onLoadSuccess() {
}
/**
* Function onLoadFailure
* This gets called when loading has been done and there were errors.
*/
@Override
public void onLoadFailure() {
}
/**
* Function Save
* for saving data to preferences.
* @return Success of save.
*/
@Override
public boolean Save()
{
Boolean success = false;
if(Global.hasPreference())
{
success = true;
Set<String> urls = new LinkedHashSet<>();
List<Feed> feeds = new LinkedList<>(this.Feeds.values());
for (Feed feed : feeds)
{
urls.add(feed.Url());
success = feed.Save() && success;
}
success = Preference.Set(PREF_FEEDS, urls) && success;
if(!Preference.Contains(PREF_DELAY_HOURS) || !Preference.Contains(PREF_NEXT_UPDATE)) setAlarm(delayHours);
success = Preference.Set(PREF_DELAY_HOURS, delayHours) && success;
if(this.NextUpdate != null) success = Preference.Set(PREF_NEXT_UPDATE, NextUpdate.toString()) && success;
success = Preference.Set(PREF_DOWNLOAD_DIR, this.downloadDir.getPath()) && success;
success = Preference.Set(PREF_ROW_LIMIT, this.RowLimit) && success;
}
return success;
}
/**
* Function onSaveSuccess
* This gets called when saving has been done and was successful.
*/
@Override
public void onSaveSuccess() {
Log.d(TAG, "SaveTask Success!");
}
/**
* Function onSaveFailure
* This gets called when saving has been done and there were errors.
*/
@Override
public void onSaveFailure() {
Log.e(TAG, "SaveTask Failed!");
}
/**
* Function Update
* for updating objects data.
* @param updateAll Does update go thought all.
* @param setAll Sets all and overwrites limits.
* @return Success of update.
*/
@Override
public boolean Update(boolean updateAll, boolean setAll)
{
Boolean success = true;
for (Feed feed : this.Feeds.values())
{
success = feed.Update(updateAll, setAll) && success;
}
List<Data> rows = this.Rows();
if(setAll) this.Rows = rows;
return success;
}
/**
* Function onUpdateSuccessful
* This gets called when update has been done and was successful.
*/
@Override
public void onUpdateSuccessful() {
new SaveTask(this).execute();
}
/**
* Function onUpdateFailed
* This gets called when update has been done and there were errors.
*/
@Override
public void onUpdateFailed() {
}
/**
* Function setAlarm
* for setting Alarm Manager to repeat
* by given hours.
* @param _delayHours Repeat hours.
*/
public void setAlarm(int _delayHours)
{
this.delayHours = _delayHours;
int millis = this.DelayMillis();
DateTime nextDate = new DateTime().plusMillis(millis);
this.SetAlarm(nextDate, millis);
}
/**
* Function SetAlarm
* for setting Alarm Manager repeating by
* given millis and starting with given DateTime.
* @param nextDate Next Alarm.
* @param repeatMillis Repeat space.
*/
private void SetAlarm(DateTime nextDate, long repeatMillis)
{
if(context != null && nextDate != null)
{
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(alarmMgr != null)
{
NextUpdate = null;
Intent intent = new Intent(context, UpdateReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.cancel(alarmIntent);
if(repeatMillis > 0)
{
long nextMillis = nextDate.getMillis();
alarmMgr.setRepeating(AlarmManager.RTC, nextMillis, repeatMillis, alarmIntent);
NextUpdate = nextDate;
}
}
}
}
/**
* Function resetAlarm
* for resetting alarm that has been gotten out of sync.
*/
public void resetAlarm()
{
DateTime nextDate = NextUpdate;
int repeatMillis = this.DelayMillis();
DateTime now = new DateTime();
if(nextDate != null)
{
while(nextDate.isBefore(now))
{
nextDate = nextDate.plusMillis(repeatMillis);
}
}
else
{
nextDate = now.plusMillis(repeatMillis);
}
this.SetAlarm(nextDate, repeatMillis);
}
/**
* Function Add
* for adding Feed object to collection.
* @param objectToAdd Feed object that will be added.
* @return Success of add.
*/
@Override
public boolean Add(Object objectToAdd)
{
boolean success = false;
if(objectToAdd != null && objectToAdd instanceof Feed)
{
Feed feed = (Feed) objectToAdd;
if(feed.Update(true, false))
{
success = this.Feed(feed);
}
if(success)
{
this.Rows();
}
}
return success;
}
/**
* Function onAddSuccess
* This gets called when adding has been done and was successful.
*/
@Override
public void onAddSuccess() {
new SaveTask(this).execute();
}
/**
* Function onAddFailure
* This gets called when adding has been done and there were errors.
*/
@Override
public void onAddFailure() {
}
/**
* Function Remove
* for removing data.
* @param objectToRemove Object that will be removed.
* @return Success of remove.
*/
@Override
public boolean Remove(Object objectToRemove)
{
boolean success = false;
if(objectToRemove != null && objectToRemove instanceof Feed)
{
Feed feed = (Feed) objectToRemove;
if(this.removeFeed(feed.Url()))
{
this.Rows();
if(this.Save())
{
success = true;
}
}
}
return success;
}
/**
* Function onRemoveSuccess
* This gets called when removing has been done and was successful.
*/
@Override
public void onRemoveSuccess() {
}
/**
* Function onRemoveFailure
* This gets called when removing has been done and there were errors.
*/
@Override
public void onRemoveFailure() {
}
/**
* Function toJSON
* for making object to JSONObject
* @return JSONObject that contains objects data.
*/
@Override
public JSONObject toJSON() {
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put(NAME_NEXT_UPDATE, this.NextUpdate.toString());
jsonObject.put(NAME_DELAY_HOURS, this.delayHours);
jsonObject.put(NAME_ROW_LIMIT, this.RowLimit);
jsonObject.put(NAME_DOWNLOAD_DIR, this.downloadDir.getPath());
if(this.Feeds != null)
{
JSONArray items = new JSONArray();
JSONObject item;
List<Feed> feeds = new LinkedList<>(this.Feeds.values());
for (Feed feed : feeds)
{
item = feed.toJSON();
if(item != null) items.put(item);
}
jsonObject.putOpt(NAME_FEED, items);
}
}
catch (Exception e)
{
Log.e(TAG, e.getLocalizedMessage());
jsonObject = null;
}
return jsonObject;
}
/**
* Function onToJSONSuccess
* This gets called when ToJSONTask has been done and was successful.
*/
@Override
public void onToJSONSuccess() {
Log.d(TAG, "ToJSONTask Success!");
}
/**
* Function onToJSONFailure
* This gets called when ToJSONTask has been done and there were failure.
*/
@Override
public void onToJSONFailure() {
Log.e(TAG, "ToJSONTask Failed!");
}
/**
* Function fromJSON
* for reading data from JSONObject to object.
* @param jsonObject JSONObject to read from.
* @return Success of read.
*/
@Override
public boolean fromJSON(JSONObject jsonObject) {
boolean success = false;
if(jsonObject != null) {
try {
success = true;
if(jsonObject.has(NAME_DELAY_HOURS)) this.delayHours = jsonObject.getInt(NAME_DELAY_HOURS);
if(jsonObject.has(NAME_NEXT_UPDATE))
{
this.NextUpdate = new DateTime(jsonObject.getString(NAME_NEXT_UPDATE));
this.resetAlarm();
}
if(jsonObject.has(NAME_DOWNLOAD_DIR)) this.downloadDir = new File(jsonObject.getString(NAME_DOWNLOAD_DIR));
if(jsonObject.has(NAME_ROW_LIMIT)) this.RowLimit = jsonObject.getInt(NAME_ROW_LIMIT);
if(jsonObject.has(NAME_FEED))
{
JSONArray items = jsonObject.getJSONArray(NAME_FEED);
if (items != null) {
this.Feeds = new LinkedHashMap<>();
boolean feedSuccess;
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
if (item != null) {
Feed feed = new Feed();
feedSuccess = feed.fromJSON(item);
if (feedSuccess) {
feedSuccess = this.Feed(feed);
}
success = feedSuccess && success;
}
}
}
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
success = false;
}
}
if(success) this.Rows();
return success;
}
/**
* Function onFromJSONSuccess
* This gets called when FromJSONTask has been done and was successful.
*/
@Override
public void onFromJSONSuccess() {
new SaveTask(this).execute();
Log.d(TAG, "FromJSONTask Success!");
}
/**
* Function onFromJSONFailure
* This gets called when FromJSONTask has been done and there were failure.
*/
@Override
public void onFromJSONFailure() {
new LoadTask(this).execute();
Log.e(TAG, "FromJSONTask Failed!");
}
}
| [
"santeri@hetekivi.com"
] | santeri@hetekivi.com |
1de18c839e62a422df9953ffe0d0d22345ce00cf | 0bdffa0eea83604ae36590f69f0e8c11a5b5eb46 | /TD6/src/td7/correct/Exo3_3_SimpleBuffer.java | e45e6d4219c25dd3544f067caa2b86696b37212c | [] | no_license | anaisfinzi/TDs_G6 | 42bf9b0c149142098e236743f8a02b24b709db3b | 93c9e4eb0668994d088085deea03badc15e6c119 | refs/heads/master | 2021-01-10T13:48:56.744795 | 2015-11-04T12:07:00 | 2015-11-04T12:07:00 | 43,372,053 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 957 | java | /**
*
*/
package td7.correct;
import java.util.concurrent.Semaphore;
/**
* @author fcamps
*
*/
public class Exo3_3_SimpleBuffer implements Exo3_1_Buffer {
private Object[] tampon;
private Semaphore vide = new Semaphore(1);
private Semaphore plein = new Semaphore(0);
/**
*
*/
public Exo3_3_SimpleBuffer()
{
tampon = new Object[1];
}
/**
*
*/
public void deposer(Object message)
{
try {
vide.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tampon[0] = message;
System.out.println("depose : " + tampon[0]);
plein.release();
}
/**
*
*/
public Object prelever()
{
try {
plein.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object message = tampon[0];
System.out.println("prelever : " + tampon[0]);
message = null;
vide.release();
return message;
}
}
| [
"anais.finzi@isae.fr"
] | anais.finzi@isae.fr |
98307676ea1b10aefd33df2edec78a5fa0ac5b8c | b0cfa54034448bda7402d280509918cbe261f801 | /project/project17/server/src/test/java/se/kth/id2203/simulation/broadcast/ScenarioClientBroadcastParent.java | 39a1cd59f31da8182e83a08865a534f52bd9c53f | [] | no_license | thorsteinnth/kth-v17p01-dsac | 8f3cc2461c980820eece2b94c48485855f68c9ef | 491664cc5830a2dd88d901be95cd876bbfb2fd22 | refs/heads/master | 2021-01-20T08:30:10.315904 | 2017-03-12T14:13:46 | 2017-03-12T14:13:46 | 81,357,776 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,637 | java | package se.kth.id2203.simulation.broadcast;
import se.kth.id2203.broadcast.beb.BestEffortBroadcast;
import se.kth.id2203.broadcast.beb.BestEffortBroadcastPort;
import se.kth.id2203.broadcast.rb.ReliableBroadcast;
import se.kth.id2203.broadcast.rb.ReliableBroadcastPort;
import se.sics.kompics.*;
import se.sics.kompics.network.Network;
import se.sics.kompics.timer.Timer;
public class ScenarioClientBroadcastParent extends ComponentDefinition
{
// NOTE: Have to have a parent component to connect the child components
Positive<Network> net = requires(Network.class);
Positive<Timer> timer = requires(Timer.class);
protected final Component beb = create(BestEffortBroadcast.class, Init.NONE);
protected final Component rb = create(ReliableBroadcast.class, Init.NONE);
public ScenarioClientBroadcastParent()
{
connect(net, beb.getNegative(Network.class), Channel.TWO_WAY);
connect(beb.getPositive(BestEffortBroadcastPort.class), rb.getNegative(BestEffortBroadcastPort.class), Channel.TWO_WAY);
Class<? extends ComponentDefinition> scenarioClientBroadcastClass = ScenarioClientBroadcast.class;
Component scenarioClientBroadcast = create(scenarioClientBroadcastClass, Init.NONE);
connect(net, scenarioClientBroadcast.getNegative(Network.class), Channel.TWO_WAY);
connect(beb.getPositive(BestEffortBroadcastPort.class), scenarioClientBroadcast.getNegative(BestEffortBroadcastPort.class), Channel.TWO_WAY);
connect(rb.getPositive(ReliableBroadcastPort.class), scenarioClientBroadcast.getNegative(ReliableBroadcastPort.class), Channel.TWO_WAY);
}
}
| [
"thorsteinnth@gmail.com"
] | thorsteinnth@gmail.com |
0836b4ea61fac38297ecdafb1f430b5d2a7e2b57 | fa2b1604326a9f8a7c5d0e59d3be482f4501670f | /architecture-system-ecology-order/order-types/src/main/java/cn/jdl/ecology/repository/Aggregate.java | deef442acc5fa28c345b66353c469397fe535533 | [] | no_license | zk555/architecture-system-ecology | 6ae2ddeaa540a81b325c91a3e7d05c46cae579d2 | 95c29ae86a5a1ab69868ed0e906c652b88f4f583 | refs/heads/master | 2023-08-30T11:52:44.546657 | 2023-08-16T07:25:13 | 2023-08-16T07:25:13 | 368,247,579 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 140 | java | package cn.jdl.ecology.repository;
// 聚合根的Marker接口
public interface Aggregate <ID extends Identifier> extends Entity<ID> {
}
| [
"zhaokai03@shizhuang-inc.com"
] | zhaokai03@shizhuang-inc.com |
ae423ac21f9b3e483396475a85eb41160ee8d8e1 | 7cedb4516e988b05780c9b4293aa5e8b088d0ae4 | /src/states/Classes/Playing.java | 772f3ff5d3c03b0f91004c39fd4946c597400add | [] | no_license | litterboks/SWP_UE8_Command | c54361b3216024d187fc1af41711c7a6d95e1bc2 | da8e91ee9fd2dbabc92aace412926b9e894fb6aa | refs/heads/master | 2021-01-20T11:20:22.583813 | 2016-06-02T00:05:26 | 2016-06-02T00:05:26 | 60,216,898 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 832 | java | package states.Classes;
public class Playing extends StateImpl {
ContextImpl context;
Playing(ContextImpl context) {
this.context = context;
}
@Override
public void install() {
System.out.print(context.getName() + " is already installed and running.\n\n");
}
@Override
public void uninstall() {
System.out.print("Please quit " + context.getName() + " before uninstalling.\n\n");
}
@Override
public void play() {
System.out.print("Currently playing " + context.getName() + "\n\n");
}
@Override
public void quit() {
System.out.print("Shutting down " + context.getName() + "\n\n");
context.changeState(new Installed(context));
}
@Override
public void update() {
System.out.print("Please quit " + context.getName() + " before updating.\n\n");
}
@Override
public int getId() {
return 2;
}
}
| [
"motch1391@gmail.com"
] | motch1391@gmail.com |
9f03afe82db8bd4976e9a5050bb1a0e043b7694d | e12363f31161c5c324970f0939e7eafef443ff02 | /hashed/src/java/models/User.java | 4acf85dbb1a4e3cc757f7eace5af9e66253330b8 | [] | no_license | ericong2012/pingrestsocial | ab341b41d3006a464ed8236ea97785966fc9f2b0 | 3942dcc51d483d7158a79bf394a520ad2b5a6b5d | refs/heads/master | 2021-01-20T01:38:17.950447 | 2015-09-16T04:37:45 | 2015-09-16T04:37:45 | 42,564,815 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,662 | java | package models;
import org.parse4j.ParseException;
import org.parse4j.ParseObject;
import org.parse4j.ParseQuery;
public class User {
private String userID;
private String objectID;
private String fullname;
private String username;
private String profilePicture;
private String email;
public User(String userID, String objectID, String fullname, String username, String profilePicture) {
this(userID, objectID, fullname, username, profilePicture, "");
}
public User(String userID, String objectID, String fullname, String username, String profilePicture, String email){
this.userID = userID;
this.objectID = objectID;
this.fullname = fullname;
this.username = username;
this.profilePicture = profilePicture;
this.email = email;
}
public User(String userID, String fullname) {
this.userID = userID;
this.fullname = fullname;
}
public String getUserID() {
return userID;
}
public String getObjectID() {
return objectID;
}
public String getFullName() {
return fullname;
}
public String getEmail() {
return email;
}
public String toString() {
return username + " , ";
}
public String getProfilePicture() {
return profilePicture;
}
public String getUsername() {
return username;
}
public void setEmail(String email){
this.email = email;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public void setUsername(String username) {
this.username = username;
}
public void setProfilePicture(String profilePicture) {
this.profilePicture = profilePicture;
}
public void save() throws ParseException {
ParseObject user = null;
if (objectID.equals("")){
user = new ParseObject("PhotoOwner");
} else {
ParseQuery<ParseObject> query = ParseQuery.getQuery("PhotoOwner");
query.whereEqualTo("objectId", objectID);
user = query.find().get(0);
}
user.put("userid", userID);
user.put("groupname", "");
user.put("username", username);
user.put("fullname", fullname);
user.put("profilepicture", profilePicture);
user.put("email", email);
user.save();
if (objectID.equals("")){
objectID = user.getObjectId();
}
}
}
| [
"eric.ong.2012@sis.smu.edu.sg"
] | eric.ong.2012@sis.smu.edu.sg |
2daaf01095a54b5d19dcd03c6e043da2eb65992a | 65fffe6d9ce0144c7f84e09ea96a0734966891df | /currency-exchange-service-basic-version/src/main/java/com/mirco/services/controllers/CurrencyExchangeController.java | 4b1d3e3feeb4ba4eef83a3de20bfbcecf04fa9a5 | [] | no_license | anilKumar-GitHub/micro-services-poc | 56f3224a0eb3bf484310321500da8107c53c972f | 19a233a863fcfb45c68c9a601f7fd4f09e8a0c16 | refs/heads/master | 2023-03-09T19:20:01.488173 | 2021-02-26T16:25:22 | 2021-02-26T16:25:22 | 342,628,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,088 | java | package com.mirco.services.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.mirco.services.beans.ExchangeValue;
import com.mirco.services.repositories.CurrencyExchangeRespository;
@RestController
public class CurrencyExchangeController {
@Autowired
private CurrencyExchangeRespository exchangeRepo;
@Autowired
Environment env;
@GetMapping("/currency-exchange/from/{from}/to/{to}")
public ExchangeValue retrieveExchangeValue
(@PathVariable String from, @PathVariable String to) throws Exception {
ExchangeValue exchangeValue = exchangeRepo.findByFromAndTo(from, to);
exchangeValue.setPort(Integer.parseInt(env.getProperty("server.port")));
return exchangeValue;
}
@GetMapping("/greeting")
public String greeting() {
return "Currency-Exchange :: Good Morning ! Have Nice Day...!";
}
}
| [
"anilkumar81593@gmail.com"
] | anilkumar81593@gmail.com |
5ac3d6a08068bfefa5c22cf5d5d8dde7a233d066 | 4e560543d60ea1be7f653e658b86e63909ca91da | /src/main/java/com/dev/foodreservation/database/WalletDAO.java | b65c724049ebc012ff08e0d3015b9f64ef2cdb0c | [] | no_license | bdb0y/FoodReservationSystem | 5632bc83df9ff0849351bc83a68745dcde122977 | 5cb3a3fcd55e6d2fe602b5c746e6cabe459d0a00 | refs/heads/master | 2022-11-29T20:44:45.056849 | 2020-08-09T22:11:33 | 2020-08-09T22:11:33 | 273,685,822 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,850 | java | package com.dev.foodreservation.database;
import com.dev.foodreservation.database.interfaces.IntWallet;
import com.dev.foodreservation.database.utilities.Executor;
import com.dev.foodreservation.database.utilities.Procedure;
import com.dev.foodreservation.objects.Wallet;
import com.dev.foodreservation.objects.WalletTransaction;
import com.github.mfathi91.time.PersianDate;
import java.sql.*;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
public class WalletDAO implements IntWallet {
private final Connection connection;
private final Statement statement;
private final Time time;
private final Date date;
public WalletDAO() throws SQLException {
connection = new DatabaseConnection().connect();
statement = connection.createStatement();
time = Time.valueOf(LocalTime.now());
date = Date.valueOf(PersianDate.now().toString());
}
@Override
public List<Wallet> get(long id) throws SQLException {
Procedure procedure = new Procedure("GetBalance");
procedure.addField("ri", id);
List<Wallet> wallets = new ArrayList<>();
ResultSet resultSet = new Executor(statement).Execute(procedure);
while (resultSet.next()) wallets.add(walletRSV(resultSet));
return wallets;
}
@Override
public boolean chargeUp(long id, double amount) throws SQLException {
return makeTransaction(id, amount);
}
@Override
public boolean makeTransaction(long id, double amount) throws SQLException {
Procedure procedure = new Procedure("MakeTransaction");
procedure.addField("rii", id);
procedure.addField("t", "'" + time + "'");
procedure.addField("d", "'" + date + "'");
procedure.addField("a", amount);
return new Executor(statement).ExecuteUpdate(procedure) > 0;
}
@Override
public List<WalletTransaction> getTransactions(long id) throws SQLException {
Procedure procedure = new Procedure("GetTransactions");
procedure.addField("ri", id);
List<WalletTransaction> transactions = new ArrayList<>();
ResultSet resultSet = new Executor(statement).Execute(procedure);
while (resultSet.next())
transactions.add(walletTransactionsRSV(resultSet));
return transactions;
}
private WalletTransaction
walletTransactionsRSV(ResultSet resultSet) throws SQLException {
return new WalletTransaction(
resultSet.getLong(1),
resultSet.getLong(2),
resultSet.getDate(3),
resultSet.getTime(4),
resultSet.getDouble(5)
);
}
private Wallet walletRSV(ResultSet set) throws SQLException {
return new Wallet(set.getLong(1),
set.getDouble("balance"));
}
} | [
"bandar3eda021@gmail.com"
] | bandar3eda021@gmail.com |
2bafb67b7e244b92379977e63761a1aa6fc45251 | 104cda8eafe0617e2a5fa1e2b9f242d78370521b | /aliyun-java-sdk-cdn/src/main/java/com/aliyuncs/cdn/model/v20180510/ListRealtimeLogDeliveryInfosResponse.java | be4d9f454aa08e34ba16074e1e30c0dce80d7c8b | [
"Apache-2.0"
] | permissive | SanthosheG/aliyun-openapi-java-sdk | 89f9b245c1bcdff8dac0866c36ff9a261aa40684 | 38a910b1a7f4bdb1b0dd29601a1450efb1220f79 | refs/heads/master | 2020-07-24T00:00:59.491294 | 2019-09-09T23:00:27 | 2019-09-11T04:29:56 | 207,744,099 | 2 | 0 | NOASSERTION | 2019-09-11T06:55:58 | 2019-09-11T06:55:58 | null | UTF-8 | Java | false | false | 2,104 | java | /*
* 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.aliyuncs.cdn.model.v20180510;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.cdn.transform.v20180510.ListRealtimeLogDeliveryInfosResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class ListRealtimeLogDeliveryInfosResponse extends AcsResponse {
private String requestId;
private List<RealtimeLogDeliveryInfos> content;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public List<RealtimeLogDeliveryInfos> getContent() {
return this.content;
}
public void setContent(List<RealtimeLogDeliveryInfos> content) {
this.content = content;
}
public static class RealtimeLogDeliveryInfos {
private String project;
private String logstore;
private String region;
public String getProject() {
return this.project;
}
public void setProject(String project) {
this.project = project;
}
public String getLogstore() {
return this.logstore;
}
public void setLogstore(String logstore) {
this.logstore = logstore;
}
public String getRegion() {
return this.region;
}
public void setRegion(String region) {
this.region = region;
}
}
@Override
public ListRealtimeLogDeliveryInfosResponse getInstance(UnmarshallerContext context) {
return ListRealtimeLogDeliveryInfosResponseUnmarshaller.unmarshall(this, context);
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
0912b0f8ac52ee3881b27e99eda939255b32e42b | 09d0ddd512472a10bab82c912b66cbb13113fcbf | /TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/Fernflower/src/main/java/org/telegram/ui/_$$Lambda$DialogsActivity$0CqBdEwjzLcyLDVjAtjOQrlvawc.java | a72e41f2e72a3098f71dcb2cee0a23e6be1f8245 | [] | no_license | sgros/activity_flow_plugin | bde2de3745d95e8097c053795c9e990c829a88f4 | 9e59f8b3adacf078946990db9c58f4965a5ccb48 | refs/heads/master | 2020-06-19T02:39:13.865609 | 2019-07-08T20:17:28 | 2019-07-08T20:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 599 | java | package org.telegram.ui;
import java.util.ArrayList;
// $FF: synthetic class
public final class _$$Lambda$DialogsActivity$0CqBdEwjzLcyLDVjAtjOQrlvawc implements Runnable {
// $FF: synthetic field
private final DialogsActivity f$0;
// $FF: synthetic field
private final ArrayList f$1;
// $FF: synthetic method
public _$$Lambda$DialogsActivity$0CqBdEwjzLcyLDVjAtjOQrlvawc(DialogsActivity var1, ArrayList var2) {
this.f$0 = var1;
this.f$1 = var2;
}
public final void run() {
this.f$0.lambda$perfromSelectedDialogsAction$9$DialogsActivity(this.f$1);
}
}
| [
"crash@home.home.hr"
] | crash@home.home.hr |
df6e77355c52d36504e0f313f99b99cc3c233978 | a13203165b1c59f1d28a5ce513718e557c0f6634 | /simpleautolayout/src/androidTest/java/com/hwq/device/simpleautolayout/ExampleInstrumentedTest.java | 577e3694bdd05b124098d49fa35240c40c69e7bf | [] | no_license | crystal82/DeviceCompatibilityCenter | ea5c000319593e410fcd9193fe013afbae92fb60 | 3005fa0e3df3f98be80ce9f7f5120fdb5c4e4a29 | refs/heads/master | 2020-05-16T16:01:02.463050 | 2019-04-24T04:45:17 | 2019-04-24T04:45:17 | 183,149,191 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 751 | java | package com.hwq.device.simpleautolayout;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.hwq.device.simpleautolayout.test", appContext.getPackageName());
}
}
| [
"hwq@meitu.com"
] | hwq@meitu.com |
d86ad17e2075a631d047c5ee12c925bcd62adab8 | 3641d13258a5ff7f0e587de9b88b38e87158dfb7 | /src/com/shoping/mall/study/okhttp/lib/L.java | 7c0f7c70ae6a36d3efea9a09bb49f2a2377cb2ac | [
"Apache-2.0"
] | permissive | ftc300/AndroidShoppingBase | 647b8170a5be9a49e96cc6642284d601f1b4303f | c7988d8b0ecc41b3aa49f96656e84212db3cfd0b | refs/heads/master | 2021-01-13T14:12:16.699377 | 2016-07-24T09:43:50 | 2016-07-24T09:43:50 | 72,843,272 | 0 | 1 | null | 2016-11-04T11:50:36 | 2016-11-04T11:50:36 | null | UTF-8 | Java | false | false | 294 | java | package com.shoping.mall.study.okhttp.lib;
import android.util.Log;
/**
* Created by zhy on 15/11/6.
*/
public class L
{
private static boolean debug = false;
public static void e(String msg)
{
if (debug)
{
Log.e("OkHttp", msg);
}
}
}
| [
"cqtddt@163.com"
] | cqtddt@163.com |
5ebe6340f552c9d741a79b6bc34e087f3d92d2d6 | adf477d3dc3a92334459dbc662d2edd2a8ca90b7 | /SmartHouse/SmartHouse.Android/obj/Debug/81/android/src/android/support/compat/R.java | 239c31dcf85708fad2628b907aeca147f8a3f885 | [] | no_license | tissaa2/SmartHouse | 575b6743b3115ace8624aae63bff45c596bb9cd2 | e2a698e1c43e3e20db925dbff68b6cd7ec723fb1 | refs/heads/master | 2022-12-19T20:22:32.162143 | 2021-09-25T23:14:44 | 2021-09-25T23:14:44 | 93,633,349 | 0 | 1 | null | 2022-12-08T02:15:19 | 2017-06-07T12:35:24 | Java | UTF-8 | Java | false | false | 7,264 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by
* Xamarin.Android from the resource data it found.
* It should not be modified by hand.
*/
package android.support.compat;
public final class R {
public static final class attr {
public static final int font = 0x7f030099;
public static final int fontProviderAuthority = 0x7f03009b;
public static final int fontProviderCerts = 0x7f03009c;
public static final int fontProviderFetchStrategy = 0x7f03009d;
public static final int fontProviderFetchTimeout = 0x7f03009e;
public static final int fontProviderPackage = 0x7f03009f;
public static final int fontProviderQuery = 0x7f0300a0;
public static final int fontStyle = 0x7f0300a1;
public static final int fontWeight = 0x7f0300a2;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f040000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f050050;
public static final int notification_icon_bg_color = 0x7f050051;
public static final int ripple_material_light = 0x7f05005c;
public static final int secondary_text_default_material_light = 0x7f05005e;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f06004d;
public static final int compat_button_inset_vertical_material = 0x7f06004e;
public static final int compat_button_padding_horizontal_material = 0x7f06004f;
public static final int compat_button_padding_vertical_material = 0x7f060050;
public static final int compat_control_corner_material = 0x7f060051;
public static final int notification_action_icon_size = 0x7f060087;
public static final int notification_action_text_size = 0x7f060088;
public static final int notification_big_circle_margin = 0x7f060089;
public static final int notification_content_margin_start = 0x7f06008a;
public static final int notification_large_icon_height = 0x7f06008b;
public static final int notification_large_icon_width = 0x7f06008c;
public static final int notification_main_column_padding_top = 0x7f06008d;
public static final int notification_media_narrow_margin = 0x7f06008e;
public static final int notification_right_icon_size = 0x7f06008f;
public static final int notification_right_side_padding_top = 0x7f060090;
public static final int notification_small_icon_background_padding = 0x7f060091;
public static final int notification_small_icon_size_as_large = 0x7f060092;
public static final int notification_subtext_size = 0x7f060093;
public static final int notification_top_pad = 0x7f060094;
public static final int notification_top_pad_large_text = 0x7f060095;
}
public static final class drawable {
public static final int notification_action_background = 0x7f070079;
public static final int notification_bg = 0x7f07007a;
public static final int notification_bg_low = 0x7f07007b;
public static final int notification_bg_low_normal = 0x7f07007c;
public static final int notification_bg_low_pressed = 0x7f07007d;
public static final int notification_bg_normal = 0x7f07007e;
public static final int notification_bg_normal_pressed = 0x7f07007f;
public static final int notification_icon_background = 0x7f070080;
public static final int notification_template_icon_bg = 0x7f070081;
public static final int notification_template_icon_low_bg = 0x7f070082;
public static final int notification_tile_bg = 0x7f070083;
public static final int notify_panel_notification_icon_bg = 0x7f070084;
}
public static final class id {
public static final int action_container = 0x7f08000e;
public static final int action_divider = 0x7f080010;
public static final int action_image = 0x7f080011;
public static final int action_text = 0x7f080017;
public static final int actions = 0x7f080018;
public static final int async = 0x7f08001e;
public static final int blocking = 0x7f080021;
public static final int chronometer = 0x7f08002b;
public static final int forever = 0x7f08004a;
public static final int icon = 0x7f08004e;
public static final int icon_group = 0x7f08004f;
public static final int info = 0x7f080052;
public static final int italic = 0x7f080053;
public static final int line1 = 0x7f080057;
public static final int line3 = 0x7f080058;
public static final int normal = 0x7f080068;
public static final int notification_background = 0x7f080069;
public static final int notification_main_column = 0x7f08006a;
public static final int notification_main_column_container = 0x7f08006b;
public static final int right_icon = 0x7f080074;
public static final int right_side = 0x7f080075;
public static final int tag_transition_group = 0x7f08009f;
public static final int text = 0x7f0800a0;
public static final int text2 = 0x7f0800a1;
public static final int time = 0x7f0800a7;
public static final int title = 0x7f0800a8;
}
public static final class integer {
public static final int status_bar_notification_info_maxnum = 0x7f090009;
}
public static final class layout {
public static final int notification_action = 0x7f0a002a;
public static final int notification_action_tombstone = 0x7f0a002b;
public static final int notification_template_custom_big = 0x7f0a0032;
public static final int notification_template_icon_group = 0x7f0a0033;
public static final int notification_template_part_chronometer = 0x7f0a0037;
public static final int notification_template_part_time = 0x7f0a0038;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0c0026;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0d00fb;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0d00fc;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0d00fe;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0d0101;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0d0103;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0d0179;
public static final int Widget_Compat_NotificationActionText = 0x7f0d017a;
}
public static final class styleable {
public static final int[] FontFamily = new int[] { 0x7f03009b, 0x7f03009c, 0x7f03009d, 0x7f03009e, 0x7f03009f, 0x7f0300a0 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = new int[] { 0x01010532, 0x01010533, 0x0101053f, 0x7f030099, 0x7f0300a1, 0x7f0300a2 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
}
}
| [
"etiainen@rambler.ru"
] | etiainen@rambler.ru |
d0b11cb4a201dd784417672919d7d2f0cba64d3a | 6cb7cda430f2f054ecc4c4b35affb8418571e992 | /app/src/main/java/com/example/flower/http/RetrofitClient.java | cc5b01879080637adf80cf84fc69e0b768958a00 | [] | no_license | shenbengit/Flower | 6496152cbc8544591ba198154f8ce28586079998 | a5f95e2e6f4815bf512e665059de677a136a5d08 | refs/heads/master | 2021-06-20T23:28:05.595667 | 2021-06-09T01:50:12 | 2021-06-09T01:50:12 | 209,932,245 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,013 | java | package com.example.flower.http;
import android.text.TextUtils;
import com.example.flower.constant.Constant;
import com.example.flower.util.LogUtil;
import com.example.flower.util.RxUtil;
import com.example.flower.util.SystemUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @author ShenBen
* @date 2019/8/21 9:21
* @email 714081644@qq.com
*/
public class RetrofitClient {
private static final long DEFAULT_MILLISECONDS = 60000; //默认的超时时间
private static long REFRESH_TIME = 300; //回调刷新时间(单位ms)
private Retrofit mRetrofit;
private ApiService mService;
private static final class Holder {
private static final RetrofitClient INSTANCE = new RetrofitClient();
}
public static RetrofitClient getInstance() {
return Holder.INSTANCE;
}
private RetrofitClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> LogUtil.i(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(interceptor);
builder.addInterceptor(chain -> {
//设置公共请求头
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "application/json;charset=UTF-8")
.addHeader("Accept", "application/json;charset=UTF-8")
.addHeader("client-channel", "qqmark")
.addHeader("client-platform", SystemUtil.getSystemVersion())
.addHeader("client-terminal", SystemUtil.getSystemModel())
.addHeader("client-unique", "")
.addHeader("client-version", "7.5.2")
.build();
return chain.proceed(request);
});
builder.readTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
builder.writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
builder.connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
OkHttpClient client = builder.build();
Gson gson = new GsonBuilder().serializeNulls().create();
Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(Constant.BASE_URL);
mRetrofit = retrofitBuilder.build();
mService = mRetrofit.create(ApiService.class);
}
public ApiService getApiService() {
return mService;
}
public void setBaseUrl(String baseUrl) {
if (!TextUtils.isEmpty(baseUrl)) {
mRetrofit = mRetrofit.newBuilder().baseUrl(baseUrl).build();
mService = mRetrofit.create(ApiService.class);
}
}
public void dowdloadPicture(String url, String path, String fileName) {
getApiService().downloadFile(url)
.compose(RxUtil.io_io())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
| [
"71081644@qq.com"
] | 71081644@qq.com |
5546a89287168563dcfce6252e751cf7a36a6da2 | a8cbaf170fd1620c4b98c49ee300eca4cc9d9a59 | /src/main/java/ClassLoaderGenericLab2.java | a76fc44070c1df7175c6af7a23339373ec3c5cb7 | [] | no_license | KozinOleg97/ClassLoader_Lab | a295dd24ce6c7e03974b2036b7a637dfb325540f | 2a5b8aec647e2d201f4c6650d10c1406307ec056 | refs/heads/master | 2020-07-30T11:27:31.138295 | 2019-12-23T10:40:11 | 2019-12-23T10:40:11 | 210,214,185 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | public class ClassLoaderGenericLab2 {
Class doLabInterface(String strValue, Integer intValue) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
System.out.println("-------------- GenericLoader -------------");
MyClassLoader loader = new MyClassLoader();
Class myClassGeneric = loader.findClass("MyClassGeneric");
IMyGenericClass instance = (IMyGenericClass) myClassGeneric.newInstance();
instance.setA(strValue);
System.out.println(instance.getA());
instance.setA(intValue);
System.out.println(instance.getA());
return myClassGeneric;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
8e9ce238e8360dad801d3250967af31cf4c1d480 | 649c9cec3de73f10b1f4e933cae9ffa2f18cf3e3 | /src/main/java/com/yangrun/web/SeckillController.java | 34ba5e4f7c9f801137db64a635ed990eac6d8960 | [] | no_license | lyhq/seckill | 076c25250b5e9ba9e3838e34b07dd78f66ecbbb5 | e7acb142947e639cd4e59446bad0bbc47bf38cc8 | refs/heads/master | 2020-03-23T07:19:01.551015 | 2018-08-24T07:11:58 | 2018-08-24T07:11:58 | 141,263,009 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,021 | java | package com.yangrun.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.yangrun.dto.Exposer;
import com.yangrun.dto.SeckillExecution;
import com.yangrun.dto.SeckillResult;
import com.yangrun.entity.Seckill;
import com.yangrun.enums.SeckillStatEnum;
import com.yangrun.exception.RepeatKillException;
import com.yangrun.exception.SeckillCloseException;
import com.yangrun.service.SeckillService;
import java.util.Date;
import java.util.List;
/**
* Created by yangrun on 11:34 2017/12/1
*/
@Controller
@RequestMapping("/seckill") //url:模块/资源/{id}/细分
public class SeckillController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private SeckillService seckillService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) {
//获取列表页
List<Seckill> list = seckillService.getSeckillList();
//list.jsp+model = ModelAndView
model.addAttribute("list", list);
return "list";//WEB-INF/jsp/"list".jsp
}
@RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET)
public String detail(@PathVariable("seckillId") Long seckillId, Model model) {
if (seckillId == null) {
return "redirect:/seckill/list";
}
Seckill seckill = seckillService.getById(seckillId);
if (seckill == null) {
return "forward:/seckill/list";
}
model.addAttribute("seckill", seckill);
return "detail";
}
//ajax json
@RequestMapping(value = "/{seckillId}/exposer", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public SeckillResult<Exposer> exposer(@PathVariable("seckillId") Long seckillId) {
SeckillResult<Exposer> result;
try {
Exposer exposer = seckillService.exportSeckillUrl(seckillId);
result = new SeckillResult<Exposer>(true, exposer);
} catch (Exception e) {
logger.error(e.getMessage(), e);
result = new SeckillResult<Exposer>(false, e.getMessage());
}
return result;
}
@RequestMapping(value = "/{seckillId}/{md5}/execution", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId, @PathVariable("md5") String md5, @CookieValue(value = "killPhone", required = false) Long phone) {
if (phone == null) {
return new SeckillResult<SeckillExecution>(false, "用户未注册");
}
try {
//通过存储过程调用
SeckillExecution execution = seckillService.executeSeckillProcedure(seckillId, phone, md5);
return new SeckillResult<SeckillExecution>(true, execution);
} catch (RepeatKillException e) {
SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.REPEAT_KILL);
return new SeckillResult<SeckillExecution>(false, execution);
} catch (SeckillCloseException e) {
SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.END);
return new SeckillResult<SeckillExecution>(false, execution);
} catch (Exception e) {
logger.error(e.getMessage(), e);
SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);
return new SeckillResult<SeckillExecution>(false, execution);
}
}
@RequestMapping(value = "/time/now", method = RequestMethod.GET)
@ResponseBody
public SeckillResult<Long> time() {
Date now = new Date();
return new SeckillResult<Long>(true, now.getTime());
}
}
| [
"947167863@qq.com"
] | 947167863@qq.com |
128951d5b09a7fdc6158b3e4091c53dc4f433f0e | f65ac7c3ebebb9cda346722074d1c24fc1a7c483 | /src/scripts/java/xfp/java/scripts/PartialL2s.java | b61e4bcb1b8a141d464c9c3fbf9d0a18f040048a | [
"Apache-2.0"
] | permissive | palisades-lakes/xfp | 4500b36759712ceabca4b8d52bbdac83b9f8118f | db12850463cd2033c9814f38e26a820fa8f58bb2 | refs/heads/master | 2021-11-18T21:33:18.138991 | 2021-10-01T18:05:47 | 2021-10-01T18:05:47 | 171,350,634 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,304 | java | package xfp.java.scripts;
import org.apache.commons.rng.UniformRandomProvider;
import xfp.java.accumulators.Accumulator;
import xfp.java.accumulators.BigFloatAccumulator;
import xfp.java.numbers.Doubles;
import xfp.java.prng.Generator;
import xfp.java.prng.PRNG;
/** Benchmark partial l2 norms
*
* <pre>
* jy --source 12 src/scripts/java/xfp/java/scripts/PartialL2s.java
* </pre>
* @author palisades dot lakes at gmail dot com
* @version 2019-07-25
*/
@SuppressWarnings("unchecked")
public final class PartialL2s {
public static final void main (final String[] args) {
//Debug.DEBUG=false;
final int n = (8*1024*1024) - 1;
final int trys = 1 * 1024;
final UniformRandomProvider urp =
PRNG.well44497b("seeds/Well44497b-2019-01-09.txt");
final int emax = Doubles.deMax(n)/2;
final Generator g = Doubles.finiteGenerator(n,urp,emax);
final Accumulator a = BigFloatAccumulator.make();
assert a.isExact();
for (int i=0;i<trys;i++) {
//Debug.println();
//Debug.println(g.name());
final double[] x = (double[]) g.next();
final double[] z = a.partialL2s(x);
assert ! Double.isNaN(z[n-1]);} }
//--------------------------------------------------------------
}
//--------------------------------------------------------------
| [
"palisades.lakes@gmail.com"
] | palisades.lakes@gmail.com |
fad557fc7dd67731a58299d5d2abbd9ed0da85e1 | 94eb55bb0d954da8ae3dae65c6d0bcb268e4521e | /array-sort/src/main/java/com/example/Sort0100SelectionSort.java | 6811301f65233463ab4d908b871e024d7641cba5 | [] | no_license | 0xAlbertChen/java-data-structures-and-algorithms | 329731b99bbfa5ae2b972c13245ffef3ddcb91c7 | 93fc96245cfa54c389859a286e9087bbb4b3f30f | refs/heads/master | 2022-11-30T08:13:08.420424 | 2020-04-21T12:39:30 | 2020-04-21T12:39:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 808 | java | package com.example;
import java.util.Arrays;
import java.util.Random;
import static com.example.Swap.swap;
import static com.example.TestHelper.generate;
import static com.example.TestHelper.print;
public class Sort0100SelectionSort {
public static void sort(int[] arrays) {
int length = arrays.length;
for (int i = 0; i < length; i++) {
int minIndex = i;
for (int j = i; j < length; j++) {
if (arrays[j] < arrays[minIndex]) {
minIndex = j;
}
}
swap(arrays, i, minIndex);
TestHelper.print(arrays);
}
}
public static void main(String[] args) {
int[] ints = generate(10);
print(ints);
sort(ints);
print(ints);
}
}
| [
"xy83918@163.com"
] | xy83918@163.com |
47029c7aacc018cd97a1132e6494a4e9a95f9720 | d7be0cf96dae35a98dc1643011e025a28e3c92bd | /QZAdminServer/src/main/java/com/web/filter/ContextInitListener.java | e8f73391e4919630bf3c07006cc3d15cfd0ccd76 | [] | no_license | liaohanjie/QZStore | 8ab5827138266dc88179ee2cfb94c98d391c39be | 698d1e7d8386bca3b15fd4b3ea3020e5b9cc3c43 | refs/heads/master | 2021-01-10T18:35:14.604327 | 2016-05-31T05:17:50 | 2016-05-31T05:17:50 | 59,005,984 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,480 | java | package com.web.filter;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.cache.GameErrorCache;
import com.cache.GamePartnerCache;
import com.cache.GameServerCache;
import com.cache.SysJurisdictionCache;
import com.cache.SysMenuCache;
import com.cache.SysRequestCache;
import com.cache.SysUserCache;
import com.db.util.ConnUtil;
import com.game.action.EActionPool;
import com.game.constant.GameConstant;
import com.ks.access.DBBeanRowMapperManager;
public class ContextInitListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0){
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent event){
PropertyConfigurator.configure("conf/admin_log4j.properties");
Logger logger = Logger.getLogger(this.getClass().getSimpleName());
logger.info("init start...");
ConnUtil.init("conf/db_config.properties");
GameErrorCache.init("conf/error_lang.properties");
GameConstant.init("conf/server_config.properties");
try{
DBBeanRowMapperManager.init(null, "com.ks.table");
}catch(Exception e){
e.printStackTrace();
}
EActionPool.init();
SysMenuCache.load();
SysUserCache.load();
SysRequestCache.load();
SysJurisdictionCache.load();
GameServerCache.load();
GamePartnerCache.load();
logger.info("init is end!!!!");
}
}
| [
"liaohanjie1314@126.com"
] | liaohanjie1314@126.com |
7df9915fda39092004d00460cb309995e6b09bf0 | 6a7c4e586ea998ac3f037df4f37e3176e77febb2 | /src/com/sanguine/crm/model/clsRegionMasterModel_ID.java | bed65751ec92be2750dab989883f15fede82e998 | [] | no_license | puneteamsangsoftwares/SanguineERP | ef635a953b7f2ad24e7c53d28472f9b09ccce1cb | 9c603a4591d165e6975931f53847aa4a97a0a504 | refs/heads/master | 2022-12-25T05:02:27.601147 | 2021-01-12T13:18:11 | 2021-01-12T13:18:11 | 215,270,060 | 0 | 1 | null | 2019-10-15T10:54:03 | 2019-10-15T10:22:47 | Java | UTF-8 | Java | false | false | 840 | java | package com.sanguine.crm.model;
import java.io.Serializable;
import javax.persistence.Embeddable;
@SuppressWarnings("serial")
@Embeddable
public class clsRegionMasterModel_ID implements Serializable {
private String strRegionCode;
private String strClientCode;
public clsRegionMasterModel_ID() {
}
public clsRegionMasterModel_ID(String strCategoryCode, String strClientCode) {
this.strRegionCode = strCategoryCode;
this.strClientCode = strClientCode;
}
public String getStrClientCode() {
return strClientCode;
}
public void setStrClientCode(String strClientCode) {
this.strClientCode = strClientCode;
}
public String getStrRegionCode() {
return strRegionCode;
}
public void setStrRegionCode(String strRegionCode) {
this.strRegionCode = strRegionCode;
}
}
| [
"vinayakborwal95@gmail.com"
] | vinayakborwal95@gmail.com |
4e1deb33c76dab292413b8f2a25c1a247e34bfaf | 1d647e76ac2d834ce35eb20e0c2fb483c2f89650 | /at.o2xfs.xfs/src/at/o2xfs/xfs/siu/SIUIndicatorsStatus.java | 5f7c66f53283c82a15f23a0d586f04470ea42f29 | [
"BSD-2-Clause"
] | permissive | smshen/O2Xfs | 48c9dc7585546bc0628c5285495c5ecdb3f190e0 | 80b617741187d42b256618c67ddaba3484566f0a | refs/heads/master | 2021-01-21T09:14:06.745488 | 2014-03-09T12:57:25 | 2014-03-09T12:57:25 | 19,926,885 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,207 | java | /*
* Copyright (c) 2014, Andreas Fagschlunger. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package at.o2xfs.xfs.siu;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import at.o2xfs.xfs.XfsConstant;
import at.o2xfs.xfs.util.XfsConstants;
public class SIUIndicatorsStatus {
private final int[] indicators;
public SIUIndicatorsStatus(final int[] indicators) {
if (indicators == null) {
throw new IllegalArgumentException("indicators must not be null");
} else if (indicators.length != SIUConstant.INDICATORS_SIZE) {
throw new IllegalArgumentException("indicators.length != "
+ SIUConstant.INDICATORS_SIZE);
}
this.indicators = indicators;
}
private <E extends Enum<E> & XfsConstant> E getState(
final SIUIndicator indicator, final Class<E> type) {
final int value = indicators[(int) indicator.getValue()];
return XfsConstants.valueOf(value, type);
}
private <E extends Enum<E> & XfsConstant> Set<E> getStates(
final SIUIndicator indicator, final Class<E> type) {
final int value = indicators[(int) indicator.getValue()];
return XfsConstants.of(value, type);
}
public SIUOpenClosedIndicatorState getOpenClosedIndicatorState() {
return getState(SIUIndicator.OPENCLOSE,
SIUOpenClosedIndicatorState.class);
}
public SIUFasciaLightState getFasciaLightState() {
return getState(SIUIndicator.FASCIALIGHT, SIUFasciaLightState.class);
}
public Set<SIUAudioIndicatorState> getAudioIndicatorStates() {
return getStates(SIUIndicator.AUDIO, SIUAudioIndicatorState.class);
}
public SIUInternalHeatingState getInternalHeatingState() {
return getState(SIUIndicator.HEATING, SIUInternalHeatingState.class);
}
public SIUConsumerDisplayBacklightState getConsumerDisplayBacklightState() {
return getState(SIUIndicator.CONSUMER_DISPLAY_BACKLIGHT,
SIUConsumerDisplayBacklightState.class);
}
public SIUSignageDisplayState getSignageDisplayState() {
return getState(SIUIndicator.SIGNAGEDISPLAY,
SIUSignageDisplayState.class);
}
public Map<SIULamp, Boolean> getTransactionIndicatorsStates() {
final Map<SIULamp, Boolean> states = new HashMap<SIULamp, Boolean>();
final int value = indicators[(int) SIUIndicator.TRANSINDICATOR
.getValue()];
for (final SIULamp lamp : SIULamp.values()) {
boolean turnedOn = false;
if ((value & lamp.getValue()) == lamp.getValue()) {
turnedOn = true;
}
states.put(lamp, Boolean.valueOf(turnedOn));
}
return states;
}
public Map<SIUGeneralPurposeOutputPort, Boolean> getGeneralPurposeOutputPortsStates() {
final Map<SIUGeneralPurposeOutputPort, Boolean> portsStates = new HashMap<SIUGeneralPurposeOutputPort, Boolean>();
final int value = indicators[(int) SIUIndicator.GENERALOUTPUTPORT
.getValue()];
for (final SIUGeneralPurposeOutputPort port : SIUGeneralPurposeOutputPort
.values()) {
boolean turnedOn = false;
if ((value & port.getValue()) == port.getValue()) {
turnedOn = true;
}
portsStates.put(port, Boolean.valueOf(turnedOn));
}
return portsStates;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("openClosedIndicatorState",
getOpenClosedIndicatorState())
.append("fasciaLightState", getFasciaLightState())
.append("audioIndicatorStates", getAudioIndicatorStates())
.append("internalHeatingState", getInternalHeatingState())
.append("consumerDisplayBacklightState",
getConsumerDisplayBacklightState())
.append("signageDisplayState", getSignageDisplayState())
.append("transactionIndicatorsStates",
getTransactionIndicatorsStates())
.append("generalPurposeOutputPortsStates",
getGeneralPurposeOutputPortsStates()).toString();
}
} | [
"andreas.fagschlunger@reflex.at"
] | andreas.fagschlunger@reflex.at |
25e2ddad52ca75c258b96f3ed48d0fbf5ea8cbd4 | 8adc4e0536ebf07054ba0acdbf0b2c2b987c267a | /xmy/.svn/pristine/77/77bfcd75ad68a3228fd210ff3e1844de2d9fbeb8.svn-base | 28fa0abd756ec39751bdec4ca088ef9a29b86322 | [] | no_license | haifeiforwork/xmy | f53c9e5f8d345326e69780c9ae6d7cf44e951016 | abcf424be427168f9a9dac12a04f5a46224211ab | refs/heads/master | 2020-05-03T02:05:40.499935 | 2018-03-06T09:21:15 | 2018-03-06T09:21:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 715 | package com.zfj.xmy.common.service;
import com.zfj.xmy.common.persistence.pojo.app.CommonActivityGoodsOutDto;
import com.zfj.xmy.common.persistence.pojo.app.CommonActvivtyGoodsInDto;
/**
* @Title: CommonActivityService.java
* @Package com.zfj.xmy.common.service
* @Description:
* @author hexw
* @date 2017年12月8日 下午1:49:22
*/
public interface CommonActivityService {
/**
* 查询活动商品公共信息 (买即赠活动,专题促销,限时限量活动)
* @param inDto
* @return
* @return CommonActivityGoodsOutDto
* Date:2017年12月8日 下午3:11:10
* @author hexw
*/
CommonActivityGoodsOutDto getActivityGoodsDto(CommonActvivtyGoodsInDto inDto);
}
| [
"359479295@qq.com"
] | 359479295@qq.com | |
478e9e7cb4a3885ea81023b9b34ffcc59267b3bc | 609b4d88b1fb1ea7cd43f035ad36c540ea43d879 | /src/com/epam/task5/entity/MusicCard.java | 41312508399110d06c322f84fe7ea52215220a75 | [] | no_license | nd524s/Parser_XML | 2dc967817faa5e6616941e28069f718ae08176a0 | df33ce5ce43e461ecda430d4191d2b4661e679f6 | refs/heads/master | 2021-01-10T07:01:07.662136 | 2016-03-16T08:13:33 | 2016-03-16T08:13:33 | 54,012,857 | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 766 | java | package com.epam.task5.entity;
import javax.xml.bind.annotation.*;
/**
* Created by Никита on 29.12.2015.
*/
public class MusicCard extends Card {
private Author author = new Author();
private String song;
public MusicCard() {
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
@Override
public String toString() {
String s = super.toString();
return "MusicCard{" + s +
"author=" + author.toString() +
", song='" + song + '\'' +
'}';
}
}
| [
"nicitosovich@mail.ru"
] | nicitosovich@mail.ru |
bb7a956cfd4cb09369d924df597151ba40499bdf | 30f1ba2594748473e450786123a7306e53d12182 | /src/OfficceHours_03_30_2021/CreateEmail.java | 1e1f4eba7463f93b86f0a47ecd33211bc45ee1ba | [] | no_license | ramilazimov/untitled1 | 8266fe7ddfdf1966ef983453250edcfa05f02725 | 6bbae18f1fc219a7d6065f54b05488b62f8fd73c | refs/heads/master | 2023-06-03T06:48:30.066329 | 2021-06-23T02:04:20 | 2021-06-23T02:04:20 | 374,245,765 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 679 | java | package OfficceHours_03_30_2021;
import java.util.Scanner;
public class CreateEmail {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two words");
String wordOne = input.nextLine();
String wordTwo = input.nextLine();
String email = "";
if(wordOne.length() >= 6 && wordTwo.length() >= 6) {
email = wordOne.substring(0,4);
email += wordTwo.substring(wordTwo.length()-3); // Secret
email += "@cybertek.com";
System.out.println(email);
} else {
System.out.println("Invalid data");
}
}
}
| [
"79541318+ramilazimov@users.noreply.github.com"
] | 79541318+ramilazimov@users.noreply.github.com |
078d4d20da441261238c514f9fc0045a51720827 | 40283394023f6beb7043895319d23c14a03eb776 | /src/com/company/Role.java | 40402c3dafcf67cf9e43de334642424d45abeb69 | [] | no_license | fornacis-202/mafia | f2ffdd98d0ac40a944beacc594489a69d8003ce8 | e6c8c19284c5904287f1b0897cab01b16fed5a40 | refs/heads/master | 2023-05-21T09:23:55.078176 | 2021-06-13T07:33:40 | 2021-06-13T07:33:40 | 374,082,680 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 588 | java | package com.company;
/**
* The enum Role.
*/
public enum Role {
/**
* God father role.
*/
GOD_FATHER,
/**
* Doctor lecter role.
*/
DOCTOR_LECTER,
/**
* Mafia role.
*/
MAFIA,
/**
* Doctor role.
*/
DOCTOR,
/**
* Detective role.
*/
DETECTIVE,
/**
* Sniper role.
*/
SNIPER,
/**
* Mayor role.
*/
MAYOR,
/**
* Psychologist role.
*/
PSYCHOLOGIST,
/**
* Armored role.
*/
ARMORED,
/**
* Citizen role.
*/
CITIZEN
}
| [
"[fornacis.wro@gmail.com]"
] | [fornacis.wro@gmail.com] |
68613e31dd0ed3ce6e909111596e011a6d10d8f2 | 1cf6d4d2ab5aaeb7b493f0d6e0b57338482d916f | /app/src/main/java/me/test/catsanddogs/repository/DataRepositoryImplementation.java | 71cffac91e9de769613b385145452018d58d407b | [] | no_license | Syjgin/CatsAndDogs | 8e885e8209742438dbfaeeeba9afd9915abab55d | b0f11c4a6c468410e768d4e1f6d96ab76a0ddeab | refs/heads/master | 2020-04-20T03:31:05.700352 | 2019-02-01T06:02:54 | 2019-02-01T06:02:54 | 168,600,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,806 | java | package me.test.catsanddogs.repository;
import javax.inject.Inject;
import me.test.catsanddogs.constants.Constants;
import me.test.catsanddogs.di.Resolver;
import me.test.catsanddogs.mvp.model.ApiResponse;
import me.test.catsanddogs.services.ApiService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DataRepositoryImplementation implements DataRepository {
@Inject
ApiService service;
public DataRepositoryImplementation () {
Resolver.getApiComponent().inject(this);
}
@Override
public void getCat(final RepositoryCallback callback) {
try {
service.getResponse(Constants.Cat).enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
callback.onLoad(response.body());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
callback.onLoad(null);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void getDog(final RepositoryCallback callback) {
try {
service.getResponse(Constants.Dog).enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
callback.onLoad(response.body());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
callback.onLoad(null);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"gruz103@gmail.com"
] | gruz103@gmail.com |
ea1c4385475e625ee233c624503ea8986700b811 | 2b38f588d9c90d34c4c559333c30baf1397f230d | /app/src/main/java/com/example/pc/test2/MainActivity.java | e3798ec1207821275408e0f27aef1f28babf78ef | [] | no_license | dkdlzk456/Test2 | e6fc6163a6b4a7e9400b352ea641c8f91eff7af8 | e3f58a975e1cd4fff2fee3b694f9e3ebef5fdd20 | refs/heads/master | 2020-04-10T15:30:44.794770 | 2018-12-10T03:35:15 | 2018-12-10T03:35:15 | 159,750,331 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,243 | java | package com.example.pc.test2;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends FragmentActivity {
RadioGroup radioGourp1;
RadioGroup radioGourp2;
Button matchButton;
EditText myMoth;
EditText myDay;
int i;
String memo;
String memo1;
int Moth;
int Day;
int j;
int h;
private AdView mAdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
matchButton = findViewById(R.id.matchButton);
matchButton.setOnClickListener(matchListener);
ImageButton imageButton2 = findViewById(R.id.dilogButton2);
imageButton2.setOnClickListener(imageButtonListener2);
ImageButton imageButton = findViewById(R.id.dilogButton);
imageButton.setOnClickListener(imageButtonListener);
// Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
View.OnClickListener imageButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), dilogActivity.class);
startActivity(intent);
}
};
View.OnClickListener imageButtonListener2 = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), dilog2Activity.class);
startActivity(intent);
}
};
View.OnClickListener matchListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
int myGender = j;
int myBlood = i;
int myBlood2 = h;
myMoth = findViewById(R.id.myMoth);
myDay = findViewById(R.id.myDay);
radioGourp1 = findViewById(R.id.radioGourp1);
radioGourp2 = findViewById(R.id.radioGourp2);
memo = myMoth.getText().toString();
memo1 = myDay.getText().toString();
try {
Moth = Integer.valueOf(memo);
Day = Integer.valueOf(memo1);
int myHoro = findHoro(Moth, Day);
int matchGender = matchGender(myGender);
int matchBlood = matchBlood(myBlood);
final int matchHoro = matchHoro(myHoro);
int mathBlood2 = mathBlood2(myBlood2);
int matchHoro2 = matchHoro2(myHoro);
int matchHoro3 = matchHoro3(myHoro);
if(Moth != 0 && Moth <= 12 && Moth > 0 ) {
if(Day > 0 && Day !=0 && Day <= 31) {
if(i >=0 && i < 4 || h >= 0 && h < 4) {
final Intent intent = new Intent(getBaseContext(), CharListActivity.class);
intent.putExtra("matchGender", matchGender);
intent.putExtra("matchBlood", matchBlood);
intent.putExtra("mathBlood2", mathBlood2);
intent.putExtra("matchHoro", matchHoro);
intent.putExtra("matchHoro2",matchHoro2);
intent.putExtra("matchHoro3",matchHoro3);
startActivity(intent);
Handler delayHandler = new Handler();
delayHandler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("matchHoro", String.valueOf(matchHoro));
}
}, 3000);
}
else
Toast.makeText(getBaseContext(), "입력이 잘못 되었습니다.",Toast.LENGTH_LONG).show();
} else
Toast.makeText(getBaseContext(), "입력이 잘못 되었습니다.",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "입력이 잘못 되었습니다.", Toast.LENGTH_LONG).show();
}
}
};
public int matchGender(int gender) {
if (radioGourp1.getCheckedRadioButtonId() == R.id.genderMan) {
j = G.WOMAN;
return j;
} else j = G.MAN;
return j;
}
// 혈액형 두번째 비교
public int mathBlood2(int blood2) {
if (radioGourp1.getCheckedRadioButtonId() == R.id.genderMan) {
if (radioGourp2.getCheckedRadioButtonId() == R.id.Abutton) {
h = G.A;
return h;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Bbutton) {
h = G.O;
return h;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Obutton) {
h = G.B;
return h;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.ABbutton) {
h = G.B;
return h;
}
} else if (radioGourp1.getCheckedRadioButtonId() == R.id.genderWomun) {
if (radioGourp2.getCheckedRadioButtonId() == R.id.Abutton) {
h = G.A;
return h;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Bbutton) {
h = G.O;
return h;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Obutton) {
h = G.B;
return h;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.ABbutton) {
h = G.B;
return h;
}
}
return 0;
}
//혈액형 첫번째 비교
public int matchBlood(int blood) {
if (radioGourp1.getCheckedRadioButtonId() == R.id.genderMan) {
if (radioGourp2.getCheckedRadioButtonId() == R.id.Abutton) {
i = G.O;
return i;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Bbutton) {
i = G.AB;
return i;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Obutton) {
i = G.A;
return i;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.ABbutton) {
i = G.AB;
return i;
}
} else if (radioGourp1.getCheckedRadioButtonId() == R.id.genderWomun) {
if (radioGourp2.getCheckedRadioButtonId() == R.id.Abutton) {
i = G.O;
return i;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Bbutton) {
i = G.AB;
return i;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.Obutton) {
i = G.A;
return i;
} else if (radioGourp2.getCheckedRadioButtonId() == R.id.ABbutton) {
i = G.AB;
return i;
}
}
return 0;
}
public int dayTo(int month, int day) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return month * 31 + day;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return month * 30 + day;
} else
return month * 28 + day;
}
// 생일로 별자리 찾기
public int findHoro(int month, int day) {
final int my = dayTo(month, day);
if (dayTo(12, 23) <= my || dayTo(1, 20) >= my) {
return G.CAPRICORN;
} else if (dayTo(1, 21) >= my && dayTo(2, 19) >= my) {
return G.AQUARIUS;
} else if (dayTo(2, 20) <= my && my <= dayTo(3, 20)) {
return G.PISCES;
} else if (dayTo(3, 21) <= my && my <= dayTo(4, 20)) {
return G.ARIES;
} else if (dayTo(4, 21) <= my && my <= dayTo(5, 21)) {
return G.TAURUS;
} else if (dayTo(5, 22) <= my && my <= dayTo(6, 21)) {
return G.GEMINI;
} else if (dayTo(6, 22) <= my && my <= dayTo(7, 23)) {
return G.CANCER;
} else if (dayTo(7, 24) <= my && my <= dayTo(8, 23)) {
return G.LEO;
} else if (dayTo(8, 24) <= my && my <= dayTo(9, 23)) {
return G.VIRGO;
} else if (dayTo(9, 24) <= my && my <= dayTo(10, 23)) {
return G.LIBRA;
} else if (dayTo(10, 24) <= my && my <= dayTo(11, 22)) {
return G.SCORPIO;
} else if (dayTo(11, 23) <= my && my <= dayTo(12, 22)) {
return G.SAGITTARIUS;
} else return 0;
}
// 별자리로 길한 궁합 찾기 첫번째 비교
public int matchHoro(int horoscope) {
switch (horoscope) {
case G.CAPRICORN:
return G.VIRGO;
case G.AQUARIUS:
return G.GEMINI;
case G.PISCES:
return G.CANCER;
case G.ARIES:
return G.LEO;
case G.TAURUS:
return G.CAPRICORN;
case G.GEMINI:
return G.AQUARIUS;
case G.CANCER:
return G.PISCES;
case G.LEO:
return G.ARIES;
case G.VIRGO:
return G.TAURUS;
case G.LIBRA:
return G.AQUARIUS;
case G.SCORPIO:
return G.PISCES;
case G.SAGITTARIUS:
return G.LEO;
}
return 0;
}
// 별자리로 길한 궁합 찾기 두번째 비교
public int matchHoro2(int horoscope) {
switch (horoscope) {
case G.CAPRICORN:
return G.TAURUS;
case G.AQUARIUS:
return G.AQUARIUS;
case G.PISCES:
return G.SCORPIO;
case G.ARIES:
return G.SAGITTARIUS;
case G.TAURUS:
return G.VIRGO;
case G.GEMINI:
return G.LIBRA;
case G.CANCER:
return G.SCORPIO;
case G.LEO:
return G.SAGITTARIUS;
case G.VIRGO:
return G.CAPRICORN;
case G.LIBRA:
return G.GEMINI;
case G.SCORPIO:
return G.CANCER;
case G.SAGITTARIUS:
return G.ARIES;
}
return 0;
}
// 별자리로 길한 궁합 찾기 세번째 비교
public int matchHoro3(int horoscope) {
switch (horoscope) {
case G.CAPRICORN:
return G.CAPRICORN;
case G.AQUARIUS:
return G.LIBRA;
case G.PISCES:
return G.PISCES;
case G.ARIES:
return G.LEO;
case G.TAURUS:
return G.TAURUS;
case G.GEMINI:
return G.GEMINI;
case G.CANCER:
return G.CANCER;
case G.LEO:
return G.LEO;
case G.VIRGO:
return G.VIRGO;
case G.LIBRA:
return G.LIBRA;
case G.SCORPIO:
return G.SCORPIO;
case G.SAGITTARIUS:
return G.SAGITTARIUS;
}
return 0;
}
} | [
"43297784+dkdlzk456@users.noreply.github.com"
] | 43297784+dkdlzk456@users.noreply.github.com |
0f6110115dbd46a8d5b808cac0c9b8a9fca7afc7 | 35cb217925ce499a0908327449819ccc8ce59c02 | /src/main/java/me/lemire/integercompression/benchmarktools/BenchmarkCSV.java | 3115f0afbb46ebb57c18272b46ae1d3984478b25 | [
"Apache-2.0",
"GPL-1.0-or-later"
] | permissive | lemire/JavaFastPFOR | 89ff698fa85dd4125fad0b6a2e80237723a7efad | 0ecdda9e431da96d044b5773ec13eee9f4e9d2ed | refs/heads/master | 2023-09-06T06:44:58.762886 | 2023-07-13T18:32:23 | 2023-07-13T18:32:23 | 4,931,095 | 396 | 64 | Apache-2.0 | 2022-11-30T10:32:17 | 2012-07-06T21:05:45 | Java | UTF-8 | Java | false | false | 16,610 | java | package me.lemire.integercompression.benchmarktools;
import me.lemire.integercompression.*;
import me.lemire.integercompression.differential.IntegratedBinaryPacking;
import me.lemire.integercompression.differential.IntegratedByteIntegerCODEC;
import me.lemire.integercompression.differential.IntegratedComposition;
import me.lemire.integercompression.differential.IntegratedIntegerCODEC;
import me.lemire.integercompression.differential.IntegratedVariableByte;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
/**
* This will run benchmarks using a set of posting lists stored as CSV files.
*
* @author lemire
*
*/
public class BenchmarkCSV {
static IntegratedIntegerCODEC codecs[] = {
new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()) };
static IntegratedByteIntegerCODEC bcodecs[] = { new IntegratedVariableByte() };
static IntegerCODEC regcodecs[] = {
new Composition(new FastPFOR128(), new VariableByte()),
new Composition(new FastPFOR(), new VariableByte()),
new Composition(new BinaryPacking(), new VariableByte()) };
static ByteIntegerCODEC regbcodecs[] = { new VariableByte() };
private static ArrayList<int[]> loadIntegers(final String filename, final Format f)
throws IOException {
int misparsed = 0;
if (f == Format.ONEARRAYPERLINE) {
ArrayList<int[]> answer = new ArrayList<int[]>();
BufferedReader br = new BufferedReader(new FileReader(
filename));
String s;
while ((s = br.readLine()) != null) {
String[] numbers = s.split("[,;;]"); // that's
// slow
int[] a = new int[numbers.length];
for (int k = 0; k < numbers.length; ++k) {
try {
a[k] = Integer
.parseInt(numbers[k]
.trim());
} catch (java.lang.NumberFormatException nfe) {
if (misparsed == 0)
System.err.println(nfe);
++misparsed;
}
}
answer.add(a);
}
if (misparsed > 0)
System.out.println("Failed to parse "
+ misparsed + " entries");
br.close();
return answer;
} else if (f == Format.ONEARRAYPERFILE) {
ArrayList<Integer> answer = new ArrayList<Integer>();
BufferedReader br = new BufferedReader(new FileReader(
filename));
String s;
while ((s = br.readLine()) != null) {
String[] numbers = s.split("[,;;]");// that's
// slow
for (int k = 0; k < numbers.length; ++k) {
try {
answer.add(Integer
.parseInt(numbers[k]
.trim()));
} catch (java.lang.NumberFormatException nfe) {
if (misparsed == 0)
System.err.println(nfe);
++misparsed;
}
}
}
int[] actualanswer = new int[answer.size()];
for (int i = 0; i < answer.size(); ++i)
actualanswer[i] = answer.get(i);
ArrayList<int[]> wrap = new ArrayList<int[]>();
wrap.add(actualanswer);
if (misparsed > 0)
System.out.println("Failed to parse "
+ misparsed + " entries");
br.close();
return wrap;
} else {
ArrayList<Integer> answer = new ArrayList<Integer>();
BufferedReader br = new BufferedReader(new FileReader(
filename));
String s;
while ((s = br.readLine()) != null) {
try {
answer.add(Integer.parseInt(s.trim()));
} catch (java.lang.NumberFormatException nfe) {
if (misparsed == 0)
System.err.println(nfe);
++misparsed;
}
}
int[] actualanswer = new int[answer.size()];
for (int i = 0; i < answer.size(); ++i)
actualanswer[i] = answer.get(i);
ArrayList<int[]> wrap = new ArrayList<int[]>();
wrap.add(actualanswer);
if (misparsed > 0)
System.out.println("Failed to parse "
+ misparsed + " entries");
br.close();
return wrap;
}
}
private enum Format {
ONEARRAYPERLINE, ONEARRAYPERFILE, ONEINTPERLINE
}
private enum CompressionMode {
AS_IS, DELTA
}
/**
* @param args command-line arguments
* @throws IOException when some IO error occurs
*/
public static void main(final String[] args) throws IOException {
Format myformat = Format.ONEARRAYPERLINE;
CompressionMode cm = CompressionMode.DELTA;
ArrayList<String> files = new ArrayList<String>();
for (String s : args) {
if (s.startsWith("-")) {// it is a flag
if (s.equals("--onearrayperfile"))
myformat = Format.ONEARRAYPERFILE;
else if (s.equals("--nodelta"))
cm = CompressionMode.AS_IS;
else if (s.equals("--oneintperline"))
myformat = Format.ONEINTPERLINE;
else
throw new RuntimeException(
"I don't understand: " + s);
} else {// it is a filename
files.add(s);
}
}
if (myformat == Format.ONEARRAYPERFILE)
System.out.println("Treating each file as one array.");
else if (myformat == Format.ONEARRAYPERLINE)
System.out
.println("Each line of each file is an array: use --onearrayperfile or --oneintperline to change.");
else if (myformat == Format.ONEINTPERLINE)
System.out
.println("Treating each file as one array, with one integer per line.");
if (cm == CompressionMode.AS_IS)
System.out
.println("Compressing the integers 'as is' (no differential coding)");
else
System.out
.println("Using differential coding (arrays will be sorted): use --nodelta to prevent sorting");
ArrayList<int[]> data = new ArrayList<int[]>();
for (String fn : files)
for (int[] x : loadIntegers(fn, myformat))
data.add(x);
System.out.println("Loaded " + data.size() + " array(s)");
if (cm == CompressionMode.DELTA) {
System.out
.println("Sorting the arrray(s) because you are using differential coding");
for (int[] x : data)
Arrays.sort(x);
}
bench(data, cm, false);
bench(data, cm, false);
bench(data, cm, true);
bytebench(data, cm, false);
bytebench(data, cm, false);
bytebench(data, cm, true);
}
private static void bench(ArrayList<int[]> postings, CompressionMode cm,
boolean verbose) {
int maxlength = 0;
for (int[] x : postings)
if (maxlength < x.length)
maxlength = x.length;
if (verbose)
System.out.println("Max array length: " + maxlength);
int[] compbuffer = new int[2 * maxlength + 1024];
int[] decompbuffer = new int[maxlength];
if (verbose)
System.out.println("Scheme -- bits/int -- speed (mis)");
for (IntegerCODEC c : (cm == CompressionMode.DELTA ? codecs
: regcodecs)) {
long bef = 0;
long aft = 0;
long decomptime = 0;
long volumein = 0;
long volumeout = 0;
int[][] compdata = new int[postings.size()][];
for (int k = 0; k < postings.size(); ++k) {
int[] in = postings.get(k);
IntWrapper inpos = new IntWrapper(0);
IntWrapper outpos = new IntWrapper(0);
c.compress(in, inpos, in.length, compbuffer,
outpos);
int clength = outpos.get();
inpos = new IntWrapper(0);
outpos = new IntWrapper(0);
c.uncompress(compbuffer, inpos, clength,
decompbuffer, outpos);
volumein += in.length;
volumeout += clength;
if (outpos.get() != in.length)
throw new RuntimeException("bug");
for (int z = 0; z < in.length; ++z)
if (in[z] != decompbuffer[z])
throw new RuntimeException(
"bug");
compdata[k] = Arrays
.copyOf(compbuffer, clength);
}
bef = System.nanoTime();
for (int[] cin : compdata) {
IntWrapper inpos = new IntWrapper(0);
IntWrapper outpos = new IntWrapper(0);
c.uncompress(cin, inpos, cin.length,
decompbuffer, outpos);
if (inpos.get() != cin.length)
throw new RuntimeException("bug");
}
aft = System.nanoTime();
decomptime += (aft - bef);
double bitsPerInt = volumeout * 32.0 / volumein;
double decompressSpeed = volumein * 1000.0
/ (decomptime);
if (verbose)
System.out.println(c.toString()
+ "\t"
+ String.format("\t%1$.2f\t%2$.2f",
bitsPerInt, decompressSpeed));
}
}
private static void bytebench(ArrayList<int[]> postings,
CompressionMode cm, boolean verbose) {
int maxlength = 0;
for (int[] x : postings)
if (maxlength < x.length)
maxlength = x.length;
if (verbose)
System.out.println("Max array length: " + maxlength);
byte[] compbuffer = new byte[6 * (maxlength + 1024)];
int[] decompbuffer = new int[maxlength];
if (verbose)
System.out.println("Scheme -- bits/int -- speed (mis)");
for (ByteIntegerCODEC c : (cm == CompressionMode.DELTA ? bcodecs
: regbcodecs)) {
long bef = 0;
long aft = 0;
long decomptime = 0;
long volumein = 0;
long volumeout = 0;
byte[][] compdata = new byte[postings.size()][];
for (int k = 0; k < postings.size(); ++k) {
int[] in = postings.get(k);
IntWrapper inpos = new IntWrapper(0);
IntWrapper outpos = new IntWrapper(0);
c.compress(in, inpos, in.length, compbuffer,
outpos);
int clength = outpos.get();
inpos = new IntWrapper(0);
outpos = new IntWrapper(0);
c.uncompress(compbuffer, inpos, clength,
decompbuffer, outpos);
volumein += in.length;
volumeout += clength;
if (outpos.get() != in.length)
throw new RuntimeException("bug");
for (int z = 0; z < in.length; ++z)
if (in[z] != decompbuffer[z])
throw new RuntimeException(
"bug");
compdata[k] = Arrays
.copyOf(compbuffer, clength);
}
bef = System.nanoTime();
for (byte[] cin : compdata) {
IntWrapper inpos = new IntWrapper(0);
IntWrapper outpos = new IntWrapper(0);
c.uncompress(cin, inpos, cin.length,
decompbuffer, outpos);
if (inpos.get() != cin.length)
throw new RuntimeException("bug");
}
aft = System.nanoTime();
decomptime += (aft - bef);
double bitsPerInt = volumeout * 8.0 / volumein;
double decompressSpeed = volumein * 1000.0
/ (decomptime);
if (verbose)
System.out.println(c.toString()
+ "\t"
+ String.format("\t%1$.2f\t%2$.2f",
bitsPerInt, decompressSpeed));
}
}
}
| [
"lemire@gmail.com"
] | lemire@gmail.com |
a0021eac52b0df48dc69e4f2d559d663339a35f4 | 1506ae5c46a08f0d6dcd122251aeb3a3a149c8fb | /app/src/main/java/com/whoami/gcxhzz/until/BaseUtils.java | 7ce19cf916b7f9707da7e3afa7f7e914d36903dd | [] | no_license | newPersonKing/gcxhzz | b416e1d82a546a69146ebabaee3bd1876bc6b56c | 07d825efe05d63264908c7dae392bcb923733461 | refs/heads/master | 2020-04-22T19:18:48.522149 | 2019-08-30T00:41:16 | 2019-08-30T00:41:16 | 170,604,135 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,575 | java | package com.whoami.gcxhzz.until;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;
import com.google.gson.Gson;
import com.whoami.gcxhzz.activity.LoginActivity;
/**
* Created by algorithm
*/
public class BaseUtils {
private static Context sContext;
private static Gson gson;
private BaseUtils() {
throw new UnsupportedOperationException("u can't instantiate m3...");
}
/**
* Application 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
sContext = context.getApplicationContext();
gson = new Gson();
}
/**
* @return ApplicationContext
*/
public static synchronized Context getContext() {
if (sContext != null)
return sContext;
throw new NullPointerException("u should init first");
}
public static Gson getGson(){
if(!ObjectUtils.isNull(gson)){
return gson;
}
throw new NullPointerException("gson init error");
}
private static int screenWidth = 0;
private static int screenHeight = 0;
public static int dpToPx(int dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
public static int getScreenHeight(Context c) {
if (screenHeight == 0) {
WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenHeight = size.y;
}
return screenHeight;
}
public static int getScreenWidth(Context c) {
// DisplayMetrics dm = new DisplayMetrics(); 第二种方式
if (screenWidth == 0) {
WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
}
return screenWidth;
}
public static boolean isAndroid5() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
public static void gotoLogin(){
Intent intent=new Intent(sContext, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sContext.startActivity(intent);
}
}
| [
"guoyong@emcc.net.com"
] | guoyong@emcc.net.com |
806543128215247e9e7002c4210649d75344b59b | 76875917925793ea446a1b1536606633a3272653 | /evo-netty-all/src/main/java/com/tazine/evo/socket/netty/client/ClientChannelHandler.java | 69eb6e17b8f3ca27510b1711d82a32ec23db0d72 | [
"MIT"
] | permissive | BookFrank/EVO-World | 01555355c434fac65406e158ffa5f7aebf3ff7dc | 3d27ae414f0281668024838a4c64db4bdd4a6377 | refs/heads/master | 2022-06-22T05:56:43.648597 | 2020-05-05T15:44:32 | 2020-05-05T15:44:32 | 147,456,884 | 1 | 1 | MIT | 2022-06-21T02:58:35 | 2018-09-05T03:54:10 | Java | UTF-8 | Java | false | false | 854 | java | package com.tazine.evo.socket.netty.client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* TestClientHandler
*
* @author frank
* @date 2018/11/05
*/
public class ClientChannelHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
System.out.println("Server say : " + msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client channel is active");
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client channel inactive");
super.channelInactive(ctx);
}
}
| [
"bookfrank@foxmail.com"
] | bookfrank@foxmail.com |
c2d2462471773120f4c500d9812dab21a06f3dd1 | 9e5f38c4cf33672edb3fea65edb2135cf4705bd1 | /app/src/main/java/com/criddam/covid_19criddam/model/Post.java | 564925b00e5d04e872fa0c15d8c6afdd857f505f | [] | no_license | mrbell78/Covid19 | 1490eeab2bab1c0327b57a2426d05283a13388ab | 69bcd80812e19b71d615370989b27bc8744bd3f0 | refs/heads/master | 2021-05-25T17:42:36.508203 | 2020-05-31T02:24:46 | 2020-05-31T02:24:46 | 253,851,311 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,374 | java | package com.criddam.covid_19criddam.model;
import com.google.gson.annotations.SerializedName;
import retrofit2.http.Field;
public class Post {
String usertype;
String fullname;
String mobile;
String email;
@SerializedName("body")
String what_u_need;
String how_soon_do_u_need_it;
String password;
String hospital;
String location;
public Post() {
}
public Post(String usertype, String fullname, String mobile, String email, String what_u_need, String how_soon_do_u_need_it, String password, String hospital, String location) {
this.usertype = usertype;
this.fullname = fullname;
this.mobile = mobile;
this.email = email;
this.what_u_need = what_u_need;
this.how_soon_do_u_need_it = how_soon_do_u_need_it;
this.password = password;
this.hospital = hospital;
this.location = location;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWhat_u_need() {
return what_u_need;
}
public void setWhat_u_need(String what_u_need) {
this.what_u_need = what_u_need;
}
public String getHow_soon_do_u_need_it() {
return how_soon_do_u_need_it;
}
public void setHow_soon_do_u_need_it(String how_soon_do_u_need_it) {
this.how_soon_do_u_need_it = how_soon_do_u_need_it;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHospital() {
return hospital;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
| [
"mrbell12131103078@gmail.com"
] | mrbell12131103078@gmail.com |
2c1529b3a2d55e269d8193b4ac99913c43d92435 | 151d96522f7bed06863dddaad51f9fecfdf56d6f | /CliGest/src/ao/co/cligest/dao/TriagemDAO.java | c66f71d69506846ae284c7b1cb0d56a0bc5148d7 | [] | no_license | neblue47/cligest | 0c44452f33fc64d36de739541ca8680314c7ddb0 | 09648d95bddb83fbe9e83cf3f8168b78d4b1e6b7 | refs/heads/master | 2020-03-16T01:46:02.903337 | 2018-09-21T12:56:07 | 2018-09-21T12:56:07 | 132,448,018 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 52,914 | java | package ao.co.cligest.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.sql.Date;
import java.util.List;
import ao.co.cligest.entidades.*;
public class TriagemDAO {
private Connection con ;
//Esta lista serve para visualizar os pacientes
public List<Paciente> buscarpacienteFacturado(){
List <Paciente> lista = new ArrayList<Paciente>();
String sql = "SELECT * FROM vwpacientesparatriar";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Paciente fun = new Paciente();
fun.setId_entidade(rs.getInt("FK_consulta_marcada"));
fun.setNumero_processo(rs.getString("numero_processo"));
fun.setNome(rs.getString("paciente"));
fun.setServico(rs.getString("servico"));
fun.setId_servico(rs.getInt("id_servico"));
fun.setFK_doutor(rs.getInt("fk_doutor"));
fun.setFK_paciente(rs.getInt("FK_paciente"));
fun.setNome_doutor(rs.getString("medico"));
fun.setPreco(rs.getDouble("preco"));;
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_consulta"));
fun.setData_do_agendamento(data);
fun.setId_confirmada(rs.getInt("id_consulta_confirmada"));
fun.setHora(rs.getTime("Hora_Consulta"));
lista.add(fun);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
}
finally{
try{
con.close();
}catch(Throwable e){
System.out.println("Erro ao fechar as conexão");
e.printStackTrace();
}
}
return lista;
}
public List <Triagem> PacienteVisualizar ()
{
List <Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM vwconsultaconfirmada LIMIT 0,10";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem fun = new Triagem();
fun.setId_cons_conf(rs.getInt("id_consulta_confirmada"));
fun.setNumero_processo(rs.getString("numero_processo"));
fun.setNome(rs.getString("nome"));
fun.setNomem(rs.getString("nome_meio"));
fun.setApelido(rs.getString("ultimo_nome"));
fun.setServico(rs.getString("servico"));
lista.add(fun);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
// Esta lista serve para pesquisar os pacientes
public List <Funcionario> pesquisarNomePaciente (String nome)
{
List <Funcionario> lista = new ArrayList<Funcionario>();
String sql = "SELECT * FROM vwentidadecidadaocomofuncionario WHERE NOME LIKE ?";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setString(1, nome);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Funcionario fun = new Funcionario();
fun.setId(rs.getInt("ID_ENTIDADE"));
fun.setNome(rs.getString("NOME"));
fun.setNomem(rs.getString("NOME_MEIO"));
fun.setApelido(rs.getString("ULTIMO_NOME"));
fun.setNomeEsp(rs.getString("ESPECIALIDADE"));
lista.add(fun);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
// Este metodo serve para inserir os dados no banco
public int InserirDadosPaciente(Triagem fun)
{
int ultimoCod = 0;
String sql = "INSERT INTO TBLTRIAGEM(FK_consulta_confirmada,"
+ "FK_paciente, "
+ "FK_funcionario, "
+ "FK_estado_paciente, "
+ "FK_servico, "
+ "temperatura, "
+ "pulso, "
+ "respiracao,"
+ "tensao_sistolica,"
+ "tensao_diastolica,"
+ "peso,"
+ "data,"
+ "imc,"
+ "altura,"
+ "diagnostico_preliminar, hora_registo)" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
con = Conexao.getConexao();
PreparedStatement triagPac = con.prepareStatement(sql);
triagPac.setInt(1, fun.getId_cons_conf());
triagPac.setInt(2, fun.getFK_paciente());
triagPac.setInt(3, fun.getFk_funcionario());
triagPac.setInt(4, fun.getFK_estado_do_paciente());
triagPac.setInt(5, fun.getId_servico());
triagPac.setString(6, fun.getTemperatura());
triagPac.setString(7, fun.getPulso());
triagPac.setString(8, fun.getRespiracao());
triagPac.setString(9, fun.getTensao_sistolica());
triagPac.setString(10, fun.getTensao_diastolica());
triagPac.setDouble(11, fun.getPeso());
triagPac.setDate(12, data_registo());
triagPac.setDouble(13, fun.getImc());
triagPac.setDouble(14,fun.getAltura());
triagPac.setString(15, fun.getDiagnostico_preliminar());
triagPac.setString(16, new Formatando().horaAtual());
triagPac.execute();
ResultSet rs = triagPac.executeQuery("SELECT LAST_INSERT_ID()");
if(rs.next()){
ultimoCod = rs.getInt(1);
}
triagPac.close();
System.out.println("Cadastro de Sucesso....TBLTRIAGEM");
}catch(SQLException e){
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return ultimoCod;
}
public int buscarEstPac (String num)
{
int fk_estado=0;
String sql = "SELECT * FROM tblestadodopaciente where estado_do_paciente LIKE ?";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setString(1, num);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
fk_estado= rs.getInt("id_estado_do_paciente");
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return fk_estado;
}
public Triagem sinais(int cod){
Triagem pac = null;
String sql = "SELECT * FROM vwsinais where fk_paciente = ? order by FK_consulta_confirmada desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setAltura_s(rs.getString("altura"));
pac.setPeso(rs.getDouble("peso"));
pac.setImc(rs.getDouble("imc"));
pac.setValor_tmp(rs.getString("temperatura"));
pac.setValor_pulso(rs.getString("pulso"));
pac.setValor_tns(rs.getString("tensao"));
pac.setValor_resp(rs.getString("respiracao"));
pac.setEstado(rs.getString("estado_do_paciente"));
pac.setDescricao(rs.getString("diagnostico_preliminar"));
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public Triagem sinais(int cod,java.sql.Date data)
{
Triagem pac = null;
String sql = "SELECT * FROM vwsinais where fk_paciente = ? and data = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setAltura(rs.getDouble("altura"));
pac.setPeso(rs.getDouble("peso"));
pac.setImc(rs.getDouble("imc"));
pac.setValor_tmp(rs.getString("temperatura"));
pac.setValor_pulso(rs.getString("pulso"));
pac.setValor_tns(rs.getString("tensao"));
pac.setValor_resp(rs.getString("respiracao"));
pac.setEstado(rs.getString("estado_do_paciente"));
pac.setDescricao(rs.getString("diagnostico_preliminar"));
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public List<Triagem> diagnosticoDatas(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwdiagnosticados where fk_paciente = ? group by (data_daconsulta) order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome_enfermeiro"));
// pac.setNomem(rs.getString("nome_meio"));
// pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
er.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> consultasDatas(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwsinais where fk_paciente = ? group by (data) order by data desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome_enfermeiro"));
// pac.setNomem(rs.getString("nome_meio"));
// pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> receituarioDatas(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwreceituario where fk_paciente = ? group by (data_daconsulta) order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> receituarioVW(int cod,int fkcons)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwreceituario where fk_paciente = ? and id_consulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setInt(2, fkcons);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setId_consulta(rs.getInt("id_consulta"));
pac.setFarmaco(rs.getString("nome_comercial"));
pac.setVidAd(rs.getString("viaadministrar"));
pac.setQuantidade(rs.getInt("quantidade"));
pac.setDosagem(rs.getString("dosagem"));
pac.setPossologia(rs.getString("possologia"));
pac.setId_recetuario(rs.getInt("id_receituario"));
pac.setDescricao(rs.getString("observacao"));
pac.setFk_farmaco(rs.getInt("FK_farmaco"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public Triagem receituario_views(int cod, java.sql.Date data)
{
Triagem pac = null;
//Triagem pac = null;
String sql = "SELECT * FROM vwreceituario where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setFarmaco(rs.getString("nome_comercial"));
pac.setVidAd(rs.getString("viaadministrar"));
pac.setQuantidade(rs.getInt("quantidade"));
pac.setDosagem(rs.getString("dosagem"));
pac.setPosologia(rs.getString("possologia"));
pac.setDescricao(rs.getString("observacao"));
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public List <Triagem> receituario_viewss(int cod, java.sql.Date data)
{
List <Triagem> lista = new ArrayList<Triagem>();
Triagem pac = null;
//Triagem pac = null;
String sql = "SELECT * FROM vwreceituario where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
pac = new Triagem();
pac.setFarmaco(rs.getString("nome_comercial"));
pac.setVidAd(rs.getString("viaadministrar"));
pac.setQuantidade(rs.getInt("quantidade"));
pac.setDosagem(rs.getString("dosagem"));
pac.setPosologia(rs.getString("possologia"));
pac.setDescricao(rs.getString("observacao"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> ExamesClinicoDatas(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwexamesclinicosdatas where fk_paciente = ? group by (id_consulta) order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> TratamentoDatas(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwtratamentosrecomendas where fk_paciente = ? group by data_daconsulta order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
pac.setTratamento(rs.getString("descricao_tratamento"));
pac.setRecomendacao(rs.getString("descricao_recomendacao"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> ExamesClinicoDatas(int cod,java.sql.Date data)
{
List<Triagem> lista = new ArrayList<Triagem>();
Triagem pac = null;
String sql = "SELECT * FROM vwexamesclinicosdatas where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
pac = new Triagem();
pac.setAnalise(rs.getString("analise_clinica"));
pac.setPreco(rs.getDouble("preco"));
pac.setDescricao(rs.getString("observacao"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> exameClinico_views(int cod,java.sql.Date data)
{
List<Triagem> lista = new ArrayList<Triagem>();
Triagem pac = null;
String sql = "SELECT * FROM vwexamesclinicosdatas where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
pac = new Triagem();
pac.setAnalise(rs.getString("analise_clinica"));
pac.setPreco(rs.getDouble("preco"));
pac.setDescricao(rs.getString("observacao"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> ExamesClinicoDatasViews(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
Triagem pac = null;
String sql = "SELECT * FROM vwexamesclinicosdatas where fk_paciente = ? and data_daconsulta = curdate() order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
pac = new Triagem();
pac.setId_consulta(rs.getInt("id_consulta"));
pac.setAnalise(rs.getString("analise_clinica"));
pac.setPreco(rs.getDouble("preco"));
pac.setDescricao(rs.getString("observacao"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> consultasAntecedentes(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwantecedentes where fk_paciente = ? order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setNomem(rs.getString("nome_meio"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){System.out.println(er); }
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public Triagem antecedentes_views(int cod,java.sql.Date data)
{
Triagem pac = null;
String sql = "SELECT * FROM vwantecedentes where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setDescricao(rs.getString("obs_antecedentepessoal"));
pac.setTransfusao(rs.getInt("transfusao"));
pac.setCardiopatia(rs.getInt("cardiopatia"));
pac.setOsteoporose(rs.getInt("osteoporose"));
pac.setTuberculose(rs.getInt("tuberculose"));
pac.setAcidente(rs.getInt("acidente"));
pac.setTabagismo(rs.getInt("tabagismo"));
pac.setDiabete(rs.getInt("diabete"));
pac.setCirurgia(rs.getInt("cirurgia"));
pac.setHta(rs.getInt("hta"));
pac.setAvc(rs.getInt("avc"));
pac.setDoenca_renal_cronica(rs.getInt("doenca_renal_cronica"));
pac.setEndocrinas_metabolica(rs.getInt("endocrinas_metabolica"));
pac.setEtilismo(rs.getInt("etilismo"));
pac.setAlergia(rs.getInt("alergia"));
pac.setAnemia(rs.getInt("anemia"));
pac.setDrogas(rs.getInt("drogas"));
pac.setVirose(rs.getInt("virose"));
pac.setCancro(rs.getInt("cancro"));
pac.setDts(rs.getInt("dts"));
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public Triagem antecedentes_views(int cod)
{
Triagem pac = null;
String sql = "SELECT * FROM vwantecedentes where fk_paciente = ? ";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setDescricao(rs.getString("obs_antecedentepessoal"));
pac.setTransfusao(rs.getInt("transfusao"));
pac.setCardiopatia(rs.getInt("cardiopatia"));
pac.setOsteoporose(rs.getInt("osteoporose"));
pac.setTuberculose(rs.getInt("tuberculose"));
pac.setAcidente(rs.getInt("acidente"));
pac.setTabagismo(rs.getInt("tabagismo"));
pac.setDiabete(rs.getInt("diabete"));
pac.setCirurgia(rs.getInt("cirurgia"));
pac.setHta(rs.getInt("hta"));
pac.setAvc(rs.getInt("avc"));
pac.setDoenca_renal_cronica(rs.getInt("doenca_renal_cronica"));
pac.setEndocrinas_metabolica(rs.getInt("endocrinas_metabolica"));
pac.setEtilismo(rs.getInt("etilismo"));
pac.setAlergia(rs.getInt("alergia"));
pac.setAnemia(rs.getInt("anemia"));
pac.setDrogas(rs.getInt("drogas"));
pac.setVirose(rs.getInt("virose"));
pac.setCancro(rs.getInt("cancro"));
pac.setDts(rs.getInt("dts"));
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public List<Triagem> diagnosticados_views(int cod,java.sql.Date data)
{
List<Triagem> lista = new ArrayList<Triagem>();
Triagem pac = null;
String sql = "SELECT * FROM vwdiagnosticados where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
pac = new Triagem();
pac.setAnalise(rs.getString("diagnostico_cid"));
pac.setFk_cid(rs.getString("cod_cid"));
// pac.setPreco(rs.getDouble("preco"));
pac.setDescricao(rs.getString("obs_diagnostico"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> diagnosticados_views(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM vwdiagnosticados where fk_paciente = ? and data_daconsulta = CURDATE() ";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setDescricao(rs.getString("diagnostico_cid"));
pac.setFk_cid(rs.getString("cod_cid"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> diagnosticados_dia(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM vwdiagnosticados where id_consulta = ? and data_daconsulta = CURDATE() order by data_daconsulta desc ";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setDescricao(rs.getString("diagnostico_cid"));
pac.setFk_cid(rs.getString("cod_cid"));
pac.setDiagnostico_preliminar(rs.getString("obs_diagnostico"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public Triagem diagnosticados_doc(int cod)
{
Triagem pac = new Triagem();
String sql = "SELECT * FROM vwdiagnosticados where fk_paciente = ? and data_daconsulta = CURDATE()";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac.setId_consulta(rs.getInt("id_consulta"));
pac.setFK_doutor(rs.getInt("fk_medico"));
pac.setFK_paciente(rs.getInt("fk_paciente"));
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public Triagem exam_fisicos_views(int cod,java.sql.Date data)
{
Triagem pac = null;
String sql = "SELECT * FROM vwexamesfisicos where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setExa_cabeca(rs.getString("cabeca"));
pac.setExa_abdomen(rs.getString("abdomen"));
pac.setExa_membInf(rs.getString("mebro_inferior"));
pac.setExa_membSup(rs.getString("membro_superior"));
pac.setExa_pescoco(rs.getString("pescoco"));
pac.setExa_torax(rs.getString("torax"));
pac.setExa_urinario(rs.getString("genito_urinario"));
pac.setObjectivo_geral(rs.getString("objectivo_geral"));
pac.setSistema_nervoso(rs.getString("sistema_nervoso"));
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public Triagem tratamentos_views(int cod,java.sql.Date data)
{
Triagem pac = null;
String sql = "SELECT * FROM vwtratamentosrecomendas where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setTratamento(rs.getString("descricao_tratamento"));
pac.setRecomendacao(rs.getString("descricao_recomendacao"));
}
preparador.close();
}
catch(SQLException er){
System.out.println("Eror aqui: "+er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public List<Triagem> consultasDatasQH(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwqueixashistoricos where fk_paciente = ? order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
pac.setDescricao(rs.getString("descricao"));
pac.setHistorial(rs.getString("historico_dadoenca"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> consultasDatasEF(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwexamesfisicos where fk_paciente = ? order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
pac.setExa_cabeca(rs.getString("cabeca"));
pac.setExa_membSup(rs.getString("membro_superior"));
pac.setExa_membInf(rs.getString("mebro_inferior"));
pac.setExa_abdomen(rs.getString("abdomen"));
pac.setExa_pescoco(rs.getString("pescoco"));
pac.setExa_torax(rs.getString("torax"));
pac.setExa_urinario(rs.getString("genito_urinario"));
pac.setObjectivo_geral(rs.getString("objectivo_geral"));
pac.setSistema_nervoso(rs.getString("sistema_nervoso"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> consultasHipot(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwhipoteses where fk_paciente = ? group by (data_daconsulta) order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setNome(rs.getString("nome"));
pac.setApelido(rs.getString("ultimo_nome"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data_daconsulta"));
pac.setData(data);
pac.setFK_paciente(rs.getInt("fk_paciente"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> consultasHipots(int cod)
{
List<Triagem> lista = new ArrayList<Triagem>();
//Triagem pac = null;
String sql = "SELECT * FROM vwhipotesecids where fk_paciente = ? and data_daconsulta = curdate() order by data_daconsulta desc";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem pac = new Triagem();
pac.setDescricao(rs.getString("obs_hipotese"));
pac.setFk_cid(rs.getString("cid"));
pac.setDiagnostico_preliminar(rs.getString("descricao_cid"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public Triagem consultasHipot_views(int cod,java.sql.Date data)
{
Triagem pac = null;
//Triagem pac = null;
String sql = "SELECT * FROM vwhipotesecids where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setDescricao(rs.getString("obs_hipotese"));
pac.setFk_cid(rs.getString("cid"));
pac.setDiagnostico_preliminar(rs.getString("descricao_cid"));
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public List <Triagem> consultasHipot_viewss(int cod,java.sql.Date data)
{
List <Triagem> lista = new ArrayList<Triagem>();
Triagem pac = null;
//Triagem pac = null;
String sql = "SELECT * FROM vwhipotesecids where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
pac = new Triagem();
pac.setDescricao(rs.getString("obs_hipotese"));
pac.setFk_cid(rs.getString("cid"));
pac.setDiagnostico_preliminar(rs.getString("descricao_cid"));
lista.add(pac);
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public Triagem consultasDatasQH_views(int cod,java.sql.Date data)
{
Triagem pac = null;
//Triagem pac = null;
String sql = "SELECT * FROM vwinformtodasconsultaspacientes where fk_paciente = ? and data_daconsulta = ?";
try
{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, cod);
preparador.setDate(2, data);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
pac = new Triagem();
pac.setQueixa(rs.getString("queixa_principal"));
pac.setHistorial(rs.getString("historico_doenca"));
}
preparador.close();
}
catch(SQLException er){
System.out.println(er);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return pac;
}
public List <Triagem> VisualizarEstado()
{
List <Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM TBLESTADODOPACIENTE";
try{
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet ag = preparador.executeQuery();
while(ag.next())
{
Triagem fun = new Triagem();
fun.setFK_estado_do_paciente(ag.getInt("id_estado_do_paciente"));
fun.setNome_estado_do_paciente(ag.getString("estado_do_paciente"));
lista.add(fun);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public Triagem edit_triagem(String ed)
{
Triagem tr = null;
String sql = "SELECT * FROM vwpacientetriado_nd WHERE id_triagem = ?";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setString(1, ed);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
tr=new Triagem();
tr.setNome_estado_do_paciente(rs.getString("estado_do_paciente"));
tr.setFk_temperatura(rs.getInt("FK_temperatura"));
tr.setValor_tmp(rs.getString("temperatura"));
tr.setFk_pulso(rs.getInt("FK_pulso"));
tr.setValor_pulso(rs.getString("pulso"));
tr.setFk_respiracao(rs.getInt("FK_respiracao"));
tr.setValor_resp(rs.getString("respiracao"));
tr.setFK_tensao_sistolica(rs.getInt("FK_ta_sistolica"));
tr.setFK_tensao_diastolica(rs.getInt("FK_ta_diastolica"));
tr.setValor_tns(rs.getString("tensao_arterial"));
tr.setPeso(rs.getDouble("peso"));
tr.setDiagnostico_preliminar(rs.getString("diagnostico_preliminar"));
tr.setAltura_s(rs.getString("altura"));
tr.setImc(rs.getDouble("imc"));
tr.setFK_paciente(rs.getInt("fk_paciente"));
tr.setId_servico(rs.getInt("fk_servico"));
tr.setFK_doutor(rs.getInt("fk_doutor"));
tr.setFk_consulta_confirmada(rs.getInt("fk_consulta_confirmada"));
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return tr;
}
public void alt_triagem(Triagem fun)
{
String sql = "UPDATE TBLTRIAGEM SET FK_estado_paciente =?, FK_temperatura=?, FK_pulso=?, FK_respiracao=?, FK_tensao_sistolica=?, FK_tensao_diastolica=?, peso=?, altura =?, " +
"diagnostico_preliminar=?, hora_registo = ? WHERE id_triagem=?";
try {
con = Conexao.getConexao();
PreparedStatement tr = con.prepareStatement(sql);
tr.setInt(1, fun.getFK_estado_do_paciente());
tr.setDouble(2, fun.getFk_temperatura());
tr.setDouble(3, fun.getFk_pulso());
tr.setDouble(4, fun.getFk_respiracao());
tr.setInt(5, fun.getFK_tensao_sistolica());
tr.setInt(6, fun.getFK_tensao_diastolica());
tr.setDouble(7, fun.getPeso());
tr.setDouble(8, fun.getAltura());
tr.setString(9, fun.getDiagnostico_preliminar());
tr.setString(10, new Formatando().horaAtual());
tr.setInt(11, fun.getId_triagem());
tr.execute();
tr.close();
System.out.println("Alteracao com sucesso...TBLAGENDA");
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
}
public void salvar(Triagem trg)
{
if(trg.getId_triagem()!=0)
{
alt_triagem(trg);
}
else
{
InserirDadosPaciente(trg);
}
}
public boolean getConsulta(int cod)
{
Triagem fun = new Triagem();
String sql = "SELECT * FROM vwpacientetriado where fk_paciente like ?";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
fun.setFK_paciente(rs.getInt("fk_paciente"));
fun.setId_servico(rs.getInt("id_servico"));
fun.setFk_consulta_confirmada(rs.getInt("fk_consulta_confirmada"));
}
sql = "insert into tblconsulta (data_daconsulta,hora_daconsulta,fk_medico,fk_paciente,fk_servico)";
preparador = con.prepareStatement(sql);
preparador.setTime(1, null);
preparador.setTime(2, null);
preparador.setInt(3,0);
preparador.setInt(4, fun.getFK_paciente());
preparador.setInt(5, fun.getId_servico());
boolean passou = preparador.execute();
preparador.close();
return passou;
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return false;
}
public List <Triagem> PacConfirmado ()
{
List <Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM vwpacientetriado_nd where data = curdate() order by hora_registo asc ";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem fun = new Triagem();
fun.setNumero_processo(rs.getString("numeroProcesso"));
fun.setId_triagem(rs.getInt("id_triagem"));
fun.setNome(rs.getString("nome"));
fun.setNomem(rs.getString("nome_meio"));
fun.setApelido(rs.getString("ultimo_nome"));
fun.setServico(rs.getString("descricao"));
fun.setFK_paciente(rs.getInt("fk_paciente"));
fun.setId_servico(rs.getInt("fk_servico"));
fun.setFK_doutor(rs.getInt("FK_doutor"));
fun.setNome_doutor(rs.getString("nomecompleto"));
fun.setFk_consulta_confirmada(rs.getInt("fk_consulta_confirmada"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("data"));
fun.setData(data);
fun.setHoraConsulta(rs.getString("hora_registo"));
lista.add(fun);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
public List<Triagem> buscaGruposAnalise ()
{
List<Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM tblgrupodeanalises";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet rs = preparador.executeQuery();
while (rs.next()) {
Triagem t = new Triagem();
t.setId_grupoanalise(rs.getInt("id_grupo_analises_clinicas"));
t.setGrupoanalise(rs.getString("grupo_danalise"));
lista.add(t);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException ef) {
System.out.println("Erro finalizar: " + ef);
}
}
return lista;
}
public List<Triagem> buscaAnalises (int fkgrupo)
{
List<Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM vwexameslaboratoriais where id_grupo_analises_clinicas = ?";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, fkgrupo);
ResultSet rs = preparador.executeQuery();
while (rs.next()) {
Triagem t = new Triagem();
t.setId_analise(rs.getInt("id_servicodeanalise_clinica"));
t.setAnalise(rs.getString("analise_clinica"));
t.setGrupoanalise(rs.getString("grupo_danalise"));
t.setDisponibilidade(rs.getInt("disponibilidade"));
lista.add(t);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException ef) {
System.out.println("Erro finalizar: " + ef);
}
}
return lista;
}
public Triagem buscaAnalisesPorId (int id_analise)
{
Triagem t = null;
String sql = "SELECT * FROM vwexameslaboratoriais where id_servicodeanalise_clinica = ?";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, id_analise);
ResultSet rs = preparador.executeQuery();
if(rs.next())
{
t = new Triagem();
t.setId_analise(rs.getInt("id_servicodeanalise_clinica"));
t.setAnalise(rs.getString("analise_clinica"));
t.setGrupoanalise(rs.getString("grupo_danalise"));
t.setPreco(rs.getDouble("preco"));
}
preparador.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return t;
}
public List<Triagem> buscaAnalises ()
{
List<Triagem> lista = new ArrayList<Triagem>();
String sql = "SELECT * FROM vwexameslaboratoriais group by (grupo_danalise)";
try {
con = Conexao.getConexao();
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet rs = preparador.executeQuery();
while(rs.next())
{
Triagem t = new Triagem();
t.setId_analise(rs.getInt("id_servicodeanalise_clinica"));
t.setAnalise(rs.getString("analise_clinica"));
t.setGrupoanalise(rs.getString("grupo_danalise"));
t.setDisponibilidade(rs.getInt("disponibilidade"));
lista.add(t);
}
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
con.close();
}
catch(SQLException ef){
System.out.println("Erro finalizar: "+ef);
}
}
return lista;
}
//INSERIR DATA AUTOMM�TICA
public java.sql.Date data_registo()
{
java.sql.Date dt_registo = null;
Calendar c = Calendar.getInstance(); // Cria um objeto para armazenar a data atual
c.setTime(new java.util.Date()); // pega a data atual do sistema
int diaAtual = c.get(Calendar.DAY_OF_MONTH); // DIA
int mesAtual = c.get(Calendar.MONTH)+1; // MES
int anoAtual = c.get(Calendar.YEAR); // ANO
String hoje = anoAtual+"/"+mesAtual+"/"+diaAtual;
DateFormat formate = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date a;
try {
a = (java.util.Date) formate.parse(hoje);
dt_registo = new java.sql.Date(a.getTime());
} catch (ParseException e) { }
return dt_registo;
}
}
| [
"nelson.joao@APV-DSV28.pq3s.local"
] | nelson.joao@APV-DSV28.pq3s.local |
1bfc360e1c401e2d3dcd0283f2909c5ab1e9a113 | 4a6855c34f2224d876d27783b10cb4047027bb25 | /kodilla-spring/src/test/java/com/kodilla/spring/calculator/CalculatorTestSuite.java | a06aa25dcd20d10427aa54657ee34c119562496d | [] | no_license | szpila127/sebastian-inglot-kodilla-java | 12e75164f5748a4ecbd66959302a4d457461a3b4 | 58391b4236a961bf1d7e7c27b1428abe47635acd | refs/heads/master | 2020-05-31T18:57:46.095544 | 2020-05-13T21:55:23 | 2020-05-13T21:55:23 | 190,446,297 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,076 | java | package com.kodilla.spring.calculator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CalculatorTestSuite {
@Test
public void testCalculations() {
//Given
ApplicationContext context = new AnnotationConfigApplicationContext("com.kodilla.spring");
Calculator calculator = context.getBean(Calculator.class);
//When
double add = calculator.add(2, 3);
double sub = calculator.sub(10, 3);
double mul = calculator.mul(2, 3);
double div = calculator.div(27, 3);
//Then
Assert.assertEquals(5, add, 0.01);
Assert.assertEquals(7, sub, 0.01);
Assert.assertEquals(6, mul, 0.01);
Assert.assertEquals(9, div, 0.01);
}
}
| [
"inglot.seb@gmail.com"
] | inglot.seb@gmail.com |
36ea5b1f97732943c206dc63900e2c35e98d3b1b | 4b85afbe3798d53dae1332926a0a9b9bcb11d9c2 | /ProjectPhase/week-00/day-02/src/main/java/com/greenfox/springadv/repository/UserRepository.java | 4a8a280eead737f2cb600ce6e340f5fb4afa25f0 | [] | no_license | green-fox-academy/adeakgabi | dd96d95085d1867b241ff6d10059a6e9f016dcec | d78cff9092581bb5c70e594e2d33106a4c3b368d | refs/heads/master | 2020-04-17T00:39:12.988246 | 2019-07-28T17:25:42 | 2019-07-28T17:25:42 | 166,057,445 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 319 | java | package com.greenfox.springadv.repository;
import com.greenfox.springadv.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
User findUserByUserName (String name);
}
| [
"adeakgabi@gmail.com"
] | adeakgabi@gmail.com |
df0744d447f750fae7e886f6b034fc96b03aeb38 | d8b2d99ee338fcafa96534c49142820e84414c12 | /src/main/java/hudson/plugins/ws_cleanup/WsCleanupMatrixAggregator.java | 3f54520d9492c7b1e4040bd706bdf5a042a644b1 | [
"MIT"
] | permissive | hudson3-plugins/ws-cleanup-plugin | 61a082e88fc5c10af083e69a5a99af6cb8d433f5 | 15469641633fb77ce34e222bab971b37348ff31c | refs/heads/master | 2021-01-22T03:05:18.523562 | 2013-02-18T01:02:44 | 2013-02-18T01:02:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,298 | java | package hudson.plugins.ws_cleanup;
import hudson.FilePath;
import hudson.Launcher;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.BuildListener;
import hudson.model.Result;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WsCleanupMatrixAggregator extends MatrixAggregator {
private final List<Pattern> patterns;
private final boolean deleteDirs;
private final boolean skipWhenFailed;
private final boolean notFailBuild;
public WsCleanupMatrixAggregator(MatrixBuild build, Launcher launcher, BuildListener listener, List<Pattern> patterns,
boolean deleteDirs, boolean skipWhenFailed, boolean notFailBuid) {
super(build, launcher, listener);
this.patterns = patterns;
this.deleteDirs = deleteDirs;
this.skipWhenFailed = skipWhenFailed;
this.notFailBuild = notFailBuid;
}
public boolean endBuild() throws InterruptedException, IOException {
return doWorkspaceCleanup();
}
private boolean doWorkspaceCleanup() throws IOException, InterruptedException {
listener.getLogger().append("\nDeleting matrix project workspace... \n");
//TODO do we want to keep keep child workpsaces if run on the same machine? Make it optional?
/*
VirtualChannel vch = build.getWorkspace().getChannel();
String parentPath = build.getWorkspace().absolutize().toString();
Set<String> filter = new HashSet<String>();
for(MatrixRun run : build.getRuns()) {
if(vch != run.getWorkspace().getChannel())
continue;
String childPath = run.getWorkspace().absolutize().toString();
if(childPath.indexOf(parentPath) == 0) {
if(!parentPath.endsWith(File.separator))
parentPath = parentPath + File.separator;
String relativePath = childPath.substring(parentPath.length());
int firstDirIndex = relativePath.indexOf(File.separator);
String childDir = relativePath.substring(0,firstDirIndex);
//TODO add ./childDir ?
filter.add(childDir);
}
}
if(patterns == null) {
patterns = new LinkedList<Pattern>();
}
for(String excludeDir : filter)
patterns.add(new Pattern(excludeDir, PatternType.EXCLUDE));
*/
FilePath workspace = build.getWorkspace();
try {
if (workspace == null || !workspace.exists())
return true;
if ( this.skipWhenFailed && build.getResult().isWorseOrEqualTo(Result.FAILURE)) {
listener.getLogger().append("skipped for failed build\n\n");
return true;
}
if (patterns == null || patterns.isEmpty()) {
workspace.deleteRecursive();
} else {
workspace.act(new Cleanup(patterns,deleteDirs));
}
listener.getLogger().append("done\n\n");
} catch (Exception ex) {
Logger.getLogger(WsCleanupMatrixAggregator.class.getName()).log(Level.SEVERE, null, ex);
if(notFailBuild) {
listener.getLogger().append("Cannot delete workspace: " + ex.getCause() + "\n");
listener.getLogger().append("Option not to fail the build is turned on, so let's continue\n");
return true;
}
return false;
}
return true;
}
}
| [
"bobfoster@gmail.com"
] | bobfoster@gmail.com |
b05c657a3bd2e27ad7418c5a744e6a590583d828 | 8e9d1cab0acf9146ace0ea0fb073678a301046d1 | /src/test/java/com/hystrix/configutator/HystrixConfigurationDynamicUpdateTest.java | 3461b334c3e7f9f1b5c26d15584e65cf51761d06 | [
"Apache-2.0"
] | permissive | phaneesh/hystrix-configurator | a2260f754a590e97399cdf3f7bc5ef0b93f755ce | 5e44c9cced02fae1c5e65eb49c77107e0007ab0a | refs/heads/master | 2023-05-26T20:42:34.557259 | 2023-05-24T11:06:05 | 2023-05-24T11:06:05 | 52,278,663 | 4 | 5 | null | 2023-09-14T05:59:30 | 2016-02-22T14:22:30 | Java | UTF-8 | Java | false | false | 3,139 | java | package com.hystrix.configutator;
import com.hystrix.configurator.config.CircuitBreakerConfig;
import com.hystrix.configurator.config.CommandThreadPoolConfig;
import com.hystrix.configurator.config.HystrixCommandConfig;
import com.hystrix.configurator.config.HystrixConfig;
import com.hystrix.configurator.config.HystrixDefaultConfig;
import com.hystrix.configurator.config.MetricsConfig;
import com.hystrix.configurator.core.BaseCommand;
import com.hystrix.configurator.core.HystrixConfigurationFactory;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
@Slf4j
public class HystrixConfigurationDynamicUpdateTest {
@Before
public void setup() {
HystrixConfigurationFactory.init(
HystrixConfig.builder()
.defaultConfig(new HystrixDefaultConfig())
.commands(Collections.singletonList(HystrixCommandConfig.builder().name("test").build()))
.build());
}
private void changeTimeoutAndTest(String commandName) throws ExecutionException, InterruptedException {
HystrixCommandConfig commandConfig = HystrixCommandConfig.builder()
.name("TestCommand")
.semaphoreIsolation(false)
.threadPool(CommandThreadPoolConfig.builder().timeout(4000).build())
.metrics(MetricsConfig.builder().build())
.circuitBreaker(CircuitBreakerConfig.builder().build())
.fallbackEnabled(false)
.build();
SimpleTestCommand command111 = new SimpleTestCommand(commandConfig);
String result1 = command111.queue().get();
Assert.assertTrue(result1.equals("Simple Test"));
}
@Test
public void dynamicConfig() throws ExecutionException, InterruptedException {
try {
HystrixCommandConfig commandConfig = HystrixCommandConfig.builder()
.name("TestCommand")
.semaphoreIsolation(false)
.threadPool(CommandThreadPoolConfig.builder().timeout(1000).build())
.metrics(MetricsConfig.builder().build())
.circuitBreaker(CircuitBreakerConfig.builder().build())
.fallbackEnabled(false)
.build();
SimpleTestCommand command3 = new SimpleTestCommand(commandConfig);
String result = command3.queue().get();
Assert.assertTrue(result.equals("Simple Test"));
} catch (Exception e) {
changeTimeoutAndTest("TestCommand");
}
}
public static class SimpleTestCommand extends BaseCommand<String> {
HystrixCommandConfig commandConfig;
public SimpleTestCommand(HystrixCommandConfig commandConfig) {
super("TestCommand", commandConfig);
}
@Override
protected String run() throws InterruptedException {
Thread.sleep(2000);
return "Simple Test";
}
}
}
| [
"pranav.thakare@phonepe.com"
] | pranav.thakare@phonepe.com |
0272ddb49e11dd230a836a11a6ae9c1e623bf77b | 775e0f2be382eba67f6493e3171a666c0debbab7 | /src/org/college/fully/CollegeStaff.java | 86b1cb039ebeab8f0ac75560fc07e8e1528ff3b4 | [] | no_license | Hussain2917/Java-Programs | f68d199255b93b663f8cb620403318959cbe80ce | 646f07c64f422acc747f5b4f95bc6797b06c5955 | refs/heads/master | 2023-02-01T08:56:29.084271 | 2020-12-18T13:02:06 | 2020-12-18T13:02:06 | 322,257,103 | 0 | 0 | null | 2020-12-18T13:02:07 | 2020-12-17T10:17:53 | Java | UTF-8 | Java | false | false | 101 | java | package org.college.fully;
public interface CollegeStaff {
void staffName();
void staffId();
}
| [
"shaja3105@gmail.com"
] | shaja3105@gmail.com |
c47d9b7aeab860f1e58667a4a54badb4e8151e83 | e2b76028d32ab571a6aff42e6351670ca297defb | /HotelBookingSystem_Android/app/src/main/java/com/example/hotelbookingsystem/adminViewGuestManager.java | 56b02515938e4875341091f55705d27c0a52459b | [] | no_license | Sanjay-hangari/Software_Engineering_Hotel_Management_Android_Entire_project | 8b91cc9bf0e3f17a0f4f4d7e7c8ed8291faf6d00 | d3ce65db5137468ac1d63d28a5b831a56a348ac3 | refs/heads/master | 2023-06-28T19:39:12.828459 | 2021-08-02T16:30:34 | 2021-08-02T16:30:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,487 | java | package com.example.hotelbookingsystem;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class adminViewGuestManager extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String SHARED_PREF_NAME = "mypref";
Button admin_modifyGM,admin_deleteGM,home,logout;
EditText admin_userGM,admin_roleGM,admin_lastGM,admin_firstGM,admin_pwdGM,admin_staddrGM,admin_cityGM,admin_stateGM,admin_zipGM,admin_emailGM,admin_phone;
TextView admin_title;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_view_guest_manager);
sharedpreferences = getSharedPreferences(SHARED_PREF_NAME,MODE_PRIVATE);
final String keyUserName = sharedpreferences.getString(MyAdapter.KEY_un,"");
admin_userGM = findViewById(R.id.admin_userGM);
admin_roleGM = findViewById(R.id.admin_roleGM);
admin_firstGM = findViewById(R.id.admin_firstGM);
admin_lastGM = findViewById(R.id.admin_lastGM);
admin_pwdGM = findViewById(R.id.admin_pwdGM);
admin_staddrGM = findViewById(R.id.admin_staddrGM);
admin_cityGM = findViewById(R.id.admin_cityGM);
admin_stateGM = findViewById(R.id.admin_stateGM);
admin_zipGM = findViewById(R.id.admin_zipGM);
admin_emailGM = findViewById(R.id.admin_emailGM);
admin_phone = findViewById(R.id.admin_phoneGM);
admin_title = findViewById(R.id.admin_viewTextGM);
admin_modifyGM = findViewById(R.id.admin_modifyGM);
admin_deleteGM = findViewById(R.id.admin_deleteGM);
home = findViewById(R.id.adminViewHome);
logout = findViewById(R.id.adminViewLogout);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(adminViewGuestManager.this,adminHomeScreen.class));
}
});
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(adminViewGuestManager.this,MainActivity.class));
}
});
DBManager dbManager = new DBManager(adminViewGuestManager.this);
Profile profile = dbManager.adminViewUser(keyUserName);
admin_userGM.setText(profile.getUsername());
admin_pwdGM.setText(profile.getPassword());
admin_firstGM.setText(profile.getFirstName());
admin_lastGM.setText(profile.getLastName());
admin_staddrGM.setText(profile.getStreetAddress());
admin_cityGM.setText(profile.getCity());
admin_stateGM.setText(profile.getState());
admin_zipGM.setText(profile.getZipCode());
admin_emailGM.setText(profile.getEmail());
admin_phone.setText(profile.getPhone());
admin_roleGM.setText(profile.getRole());
admin_userGM.setFocusable(false);
admin_pwdGM.setFocusable(false);
admin_firstGM.setFocusable(false);
admin_lastGM.setFocusable(false);
admin_staddrGM.setFocusable(false);
admin_stateGM.setFocusable(false);
admin_cityGM.setFocusable(false);
admin_zipGM.setFocusable(false);
admin_emailGM.setFocusable(false);
admin_phone.setFocusable(false);
admin_roleGM.setFocusable(false);
admin_modifyGM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
admin_firstGM.setFocusableInTouchMode(true);
admin_lastGM.setFocusableInTouchMode(true);
admin_staddrGM.setFocusableInTouchMode(true);
admin_stateGM.setFocusableInTouchMode(true);
admin_cityGM.setFocusableInTouchMode(true);
admin_zipGM.setFocusableInTouchMode(true);
admin_emailGM.setFocusableInTouchMode(true);
admin_phone.setFocusableInTouchMode(true);
admin_title.setText("Modify Selected Guest/Manager Screen");
admin_deleteGM.setVisibility(View.GONE);
admin_modifyGM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Have to save those details in DataBase
admin_deleteGM.setVisibility(View.VISIBLE);
DBManager dbManager = new DBManager(adminViewGuestManager.this);
Profile profile = new Profile(admin_userGM.getText().toString(),admin_pwdGM.getText().toString(),admin_roleGM.getText().toString(),
admin_lastGM.getText().toString(),admin_firstGM.getText().toString(),admin_staddrGM.getText().toString(),admin_cityGM.getText().toString(),
admin_stateGM.getText().toString(),admin_zipGM.getText().toString(),admin_emailGM.getText().toString(),admin_phone.getText().toString());
final boolean updateResult = dbManager.adminUpdateProfile(profile,keyUserName);
AlertDialog.Builder builder = new AlertDialog.Builder(adminViewGuestManager.this);
builder.setTitle("Confirm");
builder.setMessage("Are you sure?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
if(updateResult)
{
startActivity(new Intent(adminViewGuestManager.this,adminViewGuestManager.class));
}
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
//Redirect to View Profile page with updated information showing on the screen
}
});
}
});
admin_deleteGM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(adminViewGuestManager.this);
builder.setTitle("Confirm");
builder.setMessage("Are you sure?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
DBManager dbManager = new DBManager(adminViewGuestManager.this);
final boolean res = dbManager.deleteUser(keyUserName);
if(res)
{
startActivity(new Intent(adminViewGuestManager.this,searchGusetManager.class));
}
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
| [
"bhat_aparna1@yahoo.co.in"
] | bhat_aparna1@yahoo.co.in |
cd3b0afac0e11db51b140b3196ecebcc7075a5de | 65b97231f8d73de8a6910fda4e9c70953c859f02 | /src/test/java/li/chee/vertx/flow/BusMessage.java | 2c02226d9e784196c580fd09cd1df1f90d4b8fd1 | [
"Apache-2.0"
] | permissive | kevbob1/vertx-redisques | cf5c190bb4900fa9d4a121bbf076fcbc902ec75c | d322b47a321f050200ef5cfd30010bd1fc783842 | refs/heads/master | 2021-01-15T19:05:04.920071 | 2013-03-10T21:43:43 | 2013-03-10T21:43:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 575 | java | package li.chee.vertx.flow;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
/**
* A base class for event bus message sending steps.
*
* @author Laurent Bovet <laurent.bovet@windmaster.ch>
*/
public abstract class BusMessage<T> extends ResultHandlingStep<Message<T>> {
protected EventBus eb;
protected String address;
protected T body;
public BusMessage<T> send(EventBus eb, String address, T body) {
this.address = address;
this.body = body;
this.eb = eb;
return this;
}
} | [
"laurent.bovet@windmaster.ch"
] | laurent.bovet@windmaster.ch |
5c17a2d52279da5549839764d4352cc826909c40 | f0ef2371f992e4981290e057d523c17e0e10ac13 | /app/src/main/java/com/appname/weare/app514/utils/CacheUtils.java | 00d5d464ed228bc54bde4768b50fe5b79697c62c | [] | no_license | sunjulei/A514 | f99c2db05342628f4b8b0831deb11d84eed45024 | 69c66a78be3f8cf2fd7ed89476fc68c70b50bd9f | refs/heads/master | 2020-08-03T06:42:45.296459 | 2019-10-11T02:01:04 | 2019-10-11T02:01:04 | 211,657,672 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 900 | java | package com.appname.weare.app514.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* 缓存工具类
*/
public class CacheUtils {
/**
* 得到保存的String类型的数据
*
* @param mContext
* @param key
* @return
*/
public static String getString(Context mContext, String key) {
String result = "";
SharedPreferences sp = mContext.getSharedPreferences("Aff", Context.MODE_PRIVATE);
result = sp.getString(key, "");
return result;
}
/**
* 保存String类型的数据
*
* @param mContext
* @param key
* @param value
*/
public static void saveString(Context mContext, String key, String value) {
SharedPreferences sp = mContext.getSharedPreferences("Aff", Context.MODE_PRIVATE);
sp.edit().putString(key, value).commit();
}
}
| [
"s8265606"
] | s8265606 |
5fea238d4764bbf18624852278f08e370b0ba6d0 | 4fb3c6c46bafbb6775147235f65af3f1ff44494c | /app/src/main/java/com/abhijeet/kisanhubassignment/views/MainActivity.java | 884dde90e1ab9af2d9f3cee74a61724221cd9b61 | [] | no_license | abhijeetvader9287/kisanhubassignment | 499af886cec1fd8c8c2a403f8b7548a3dba6da70 | 3f8977857d124ccd75bc1191b2c4f624b2547fc8 | refs/heads/master | 2020-04-08T07:10:38.823419 | 2018-12-07T11:42:47 | 2018-12-07T11:42:47 | 159,129,792 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,315 | java | package com.abhijeet.kisanhubassignment.views;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.abhijeet.kisanhubassignment.R;
import com.abhijeet.kisanhubassignment.Utilities.Utilities;
import com.abhijeet.kisanhubassignment.adapters.WeatherExpandableListAdapter;
import com.abhijeet.kisanhubassignment.data.Resource;
import com.abhijeet.kisanhubassignment.data.Status;
import com.abhijeet.kisanhubassignment.data.WeatherRepository;
import com.abhijeet.kisanhubassignment.data.local.WeatherDatabase;
import com.abhijeet.kisanhubassignment.data.model.WeatherModel;
import com.abhijeet.kisanhubassignment.viewmodel.WeatherViewModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
/**
* The type Main activity.
*/
public class MainActivity extends AppCompatActivity {
/**
* The Expandable list view.
*/
ExpandableListView expandableListView;
/**
* The Progress bar.
*/
ProgressBar progressBar;
/**
* The Toolbar.
*/
Toolbar toolbar;
/**
* The Metric spinner.
*/
Spinner metricSpinner;
/**
* The Location spinner.
*/
Spinner locationSpinner;
/**
* The Years list.
*/
List<Integer> yearsList;
/**
* The Weather model list.
*/
Map<Integer, List<WeatherModel>> weatherModelList;
/**
* The Weather expandable list adapter.
*/
WeatherExpandableListAdapter weatherExpandableListAdapter;
/**
* The Weather database.
*/
WeatherDatabase weatherDatabase;
/**
* The Weather repository.
*/
WeatherRepository weatherRepository;
/**
* The Weather view model.
*/
WeatherViewModel weatherViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandableListView);
progressBar = findViewById(R.id.progressBar);
toolbar = findViewById(R.id.toolbar);
metricSpinner = findViewById(R.id.metricSpinner);
locationSpinner = findViewById(R.id.locationSpinner);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
setUpDB_API();
}
/**
* Sets up db api.
*/
void setUpDB_API() {
weatherDatabase = WeatherDatabase.getAppDatabase(this);
weatherRepository = new WeatherRepository(weatherDatabase
.resultDao(), Utilities.isNetworkConnected(MainActivity.this));
weatherViewModel = new WeatherViewModel(weatherRepository);
ArrayAdapter locationSpinneradapter = ArrayAdapter.createFromResource(MainActivity.this
, R.array.locations, R.layout.spinner_item);
locationSpinneradapter.setDropDownViewResource(R.layout.spinner_list_item);
locationSpinner.setAdapter(locationSpinneradapter);
ArrayAdapter metricSpinneradapter = ArrayAdapter.createFromResource(MainActivity.this
, R.array.metrics, R.layout.spinner_item);
metricSpinneradapter.setDropDownViewResource(R.layout.spinner_list_item);
metricSpinner.setAdapter(metricSpinneradapter);
locationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
getData();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
metricSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
getData();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
/**
* Gets data.
*/
void getData() {
yearsList = new ArrayList<>();
weatherModelList = new HashMap<>();
weatherExpandableListAdapter = new WeatherExpandableListAdapter(MainActivity.this, yearsList, weatherModelList);
expandableListView.setAdapter(weatherExpandableListAdapter);
weatherRepository = new WeatherRepository(weatherDatabase
.resultDao(), Utilities.isNetworkConnected(MainActivity.this));
weatherViewModel = new WeatherViewModel(weatherRepository);
String metric = metricSpinner.getSelectedItem().toString();
String location = locationSpinner.getSelectedItem().toString();
weatherViewModel.getWeather(metric, location)
.observe(this, new Observer<Resource<List<WeatherModel>>>() {
@Override
public void onChanged(@Nullable final Resource<List<WeatherModel>> listResource) {
if (listResource.status == Status.SUCCESS) {
if (listResource.data.size() > 0) {
if (!Utilities.isNetworkConnected(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Offline data displayed.Please check your network connection.", Toast.LENGTH_LONG).show();
}
weatherViewModel.getYears().observe(MainActivity.this, new Observer<List<Integer>>() {
@Override
public void onChanged(@Nullable List<Integer> integers) {
for (int i = 0; i < integers.size(); i++) {
List<WeatherModel> weatherModelList_temp = new ArrayList<>();
for (int j = 0; j < listResource.data.size(); j++) {
if (integers.get(i).equals(listResource.data.get(j).getYear())) {
weatherModelList_temp.add(listResource.data.get(j));
weatherModelList.put(integers.get(i), weatherModelList_temp);
}
}
weatherExpandableListAdapter = new WeatherExpandableListAdapter(MainActivity.this, integers, weatherModelList);
expandableListView.setAdapter(weatherExpandableListAdapter);
}
}
});
} else {
if (!Utilities.isNetworkConnected(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Please check your network connection.", Toast.LENGTH_LONG).show();
}
}
progressBar.setVisibility(View.GONE);
}
if (listResource.status == Status.ERROR) {
progressBar.setVisibility(View.GONE);
}
if (listResource.status == Status.LOADING) {
progressBar.setVisibility(View.VISIBLE);
}
}
}
);
}
@Override
protected void onResume() {
super.onResume();
getData();
}
}
| [
"a.vader@innopix.solutions"
] | a.vader@innopix.solutions |
6bd6fcbd8b214ce38a83546cf2a1d55191658970 | 44fd4f847a99488ffcb7f886ce947402c12d67fb | /src/main/java/co/utb/softeng/moviesapp/controllers/MoviesController.java | 5a44544062ee920d846186087f2d8e5adf2611ac | [] | no_license | JuanMantilla/SpringMovieApp | 247537f6355b4e18fac8fefcb44d3ddbe2022be3 | 0c15f80e0f2761a8b52ebb16dfbe22c19bcb6ef9 | refs/heads/master | 2016-08-12T19:49:14.566380 | 2015-09-26T03:50:14 | 2015-09-26T03:50:14 | 43,187,552 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,261 | java | /*
* 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 co.utb.softeng.moviesapp.controllers;
import co.utb.softeng.moviesapp.entities.Movie;
import co.utb.softeng.moviesapp.services.MovieService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author William
*/
@Controller
@RequestMapping("/movie")
public class MoviesController {
@Autowired
MovieService movieService;
@RequestMapping(value={"/",""}, method = RequestMethod.GET)
public @ResponseBody List<Movie> getAllMovies() {
return movieService.getAllMovies();
}
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public @ResponseBody Movie getMovieById(@PathVariable Long id) {
return movieService.getMovieById(id);
}
@RequestMapping(value = "/by-name/{name}", method = RequestMethod.GET)
public @ResponseBody Movie getMovieByName(@PathVariable String name) {
return movieService.getMovieByName(name);
}
@RequestMapping(value = "/", method = RequestMethod.PUT)
public @ResponseBody Movie createMovie(@RequestBody Movie movie) {
movieService.saveOrUpdateMovie(movie);
return movie;
}
@RequestMapping(value = "/",method = RequestMethod.POST)
public @ResponseBody Movie updateMovie(@RequestBody Movie movie) {
movieService.saveOrUpdateMovie(movie);
return movie;
}
@RequestMapping(value = "/",method = RequestMethod.DELETE)
public @ResponseBody Movie deleteMovie(@RequestBody Movie movie) {
movieService.deleteMovie(movie.getId());
return movie;
}
}
| [
"jsman@DESKTOP-U5FV9KS.home"
] | jsman@DESKTOP-U5FV9KS.home |
b57d4a6944cf8d5510bccbd0ae9253ac9b9fe72d | 234499eb92966fb2cccc93bab4e5e09c15aa725e | /src/main/java/com/yoxiang/multi_thread_programming/chapter01/stop_thread/RunTest3.java | ff5aeaaca7716ef041c84162cd9e554bb224a14d | [] | no_license | RiversLau/concurrent-study | b8d7dbf0599a9eae6ffb31c175001c29669d60bb | c43a763bd2098e431ad7e9b4789889eb1cdd0419 | refs/heads/master | 2021-09-14T09:38:43.815287 | 2018-05-11T12:46:02 | 2018-05-11T12:46:02 | 115,006,276 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 384 | java | package com.yoxiang.multi_thread_programming.chapter01.stop_thread;
/**
* Author: Rivers
* Date: 2017/12/26 06:53
*/
public class RunTest3 {
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("是否停止1 = " + Thread.interrupted());
System.out.println("是否停止2 = " + Thread.interrupted());
}
}
| [
"zhaoxiang0805@hotmail.com"
] | zhaoxiang0805@hotmail.com |
6d604dd86336a92cece8dffd58af0a3f91ca4390 | d5245b6b2c439ec36910c252fb5dcc08343b2a69 | /Max Flow Algorithm/src/com/company/MaxFlow.java | 0acdfd5371efa302b13b60f9e6d801dd5351b19e | [
"Apache-2.0"
] | permissive | Aarthif-Nawaz/Max-Flow-Algorithm | 9eed094f4b57117ca6fb2f9ab03cb51316a05c52 | 345d61a88f6eb2344d60cfc6fa3f4593cab43d17 | refs/heads/master | 2022-06-12T19:15:07.244930 | 2020-05-08T17:13:34 | 2020-05-08T17:13:34 | 262,382,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,782 | java | // Package Name
package com.company;
// Imports
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
// Class MaxFlow
@SuppressWarnings("ALL")
public class MaxFlow {
// Instance Variables
private boolean[] marked; // if a node is visited set it to true
private Link[] linkTo; // Get all the links that has an augmenting path from source to sink
private long MaxFlow; // Get the max flow
// Get the maxflow
public MaxFlow(FlowNetwork flowNetwork, Node source, Node sink) {
// Check if this method return true
while (hasAugmentingPath(flowNetwork, source, sink)) {
String s = "";
long bottleNeck = Long.MAX_VALUE / 2; // Setting the bottleneck for this with the highest value possible
for (Node n = sink; n != source; n = linkTo[n.getId()].getOtherNode(n)) { // Run for loop from sink to source till all the edges in the linkto list are got
bottleNeck = Math.min(bottleNeck, linkTo[n.getId()].getResidualCapacity(n)); // Replace the value to the minimum value, note bottleneck value gets updated after each iteration
}
for (Node n = sink; n != source; n = linkTo[n.getId()].getOtherNode(n)) { // Run the for loop from sin to source again in order to add the residual flows to the original graph with bottleneck value, because there the same augmenting path applies to the original flownetwork
linkTo[n.getId()].addResidualFlow(n, bottleNeck); // Add the values to the linkto edges with the residual flow got from the bottleneck and update the original graph
s += linkTo[n.getId()].getTargetNode().getName() + " " + linkTo[n.getId()].getFromNode().getName() + " ";
//System.out.print(linkTo[n.getId()].getTargetNode().getName()+"--> "+linkTo[n.getId()].getFromNode().getName()+" ");
//System.out.println();
}
StringBuilder alphabet = new StringBuilder();
ArrayList<String> all = new ArrayList<>();
for (char alpha : s.toCharArray()) {
if (Character.toString(alpha).equals(" ")) {
all.add(alphabet.toString());
alphabet = new StringBuilder();
}
alphabet.append((alpha));
}
//reverse(all,all.size());
Collections.reverse(all);
for (String h : all) {
System.out.print(h + "->");
}
s = "";
System.out.println();
System.out.println("There is an Augmenting path ");
System.out.println("Maximum Flow that can go through the augmenting path is " + bottleNeck);
MaxFlow += bottleNeck;
}
}
// Return the maxflow
public long getMaxFlow() {
return MaxFlow;
}
// Find the maxflow using the Incut method
public boolean isInCut(int index) {
return marked[index];
}
// Check if there is an augmenting path
private boolean hasAugmentingPath(FlowNetwork flowNetwork, Node a, Node b) {
linkTo = new Link[flowNetwork.getNumOfNodes()]; // Initialize link to variable with the number of nodes from the graph
marked = new boolean[flowNetwork.getNumOfNodes()]; // Initialize marked variable with the number of nodes from the graph
// for bfs algorithm we use the queue data structure to add them
Queue<Node> queue = new LinkedList<>();
((LinkedList<Node>) queue).add(a); // Add the source node to the queue
marked[a.getId()] = true; //mark the value of the source node as true
// While the queue is not empty
while (!queue.isEmpty()) {
Node n = queue.remove(); // Take out the first node from the queue
for (Link l : flowNetwork.getAdjacencyList(n)) { // Get all the links for this source node
Node other = l.getOtherNode(n); // Get the other node , in this case the target node because wwe are getting it from the source node
if (l.getResidualCapacity(other) > 0) { // If the capacity is greater than 0
if (!marked[other.getId()]) { //If that node is not visited
linkTo[other.getId()] = l; // store the index of it as 1
marked[other.getId()] = true; // mark the nodes as visited
((LinkedList<Node>) queue).add(other); // add that node to queue
}
}
}
}
return marked[b.getId()]; // If the queue is empty then return the sink node
}
}
| [
"noreply@github.com"
] | noreply@github.com |
806ae92138009231d1491c73890c5d2952da1184 | 99b85c60dd690de4d5e4ddf0286707ad22a57227 | /ShoppingWeb/src/Org/Shopping/Model/ViewCartPo.java | 6c8ea6b392a640ebe15cb6f9f1f06f018d7c7544 | [] | no_license | DostylcWu/SSM | 8a202bb9b10d7c1be0c2b88f640ab1002d783e22 | fd265ad2691d15cc037b62818036c47072911e79 | refs/heads/master | 2020-03-24T02:54:49.772090 | 2018-08-01T05:56:28 | 2018-08-01T05:56:28 | 142,395,610 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,476 | java | package Org.Shopping.Model;
public class ViewCartPo {
private int uid;
private int gid;
private int amount;
private String gname;
private String gpic;
private double price;
private String tname;
public ViewCartPo() {
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getGid() {
return gid;
}
public void setGid(int gid) {
this.gid = gid;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public String getGpic() {
return gpic;
}
public void setGpic(String gpic) {
this.gpic = gpic;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public ViewCartPo(int uid, int gid, int amount, String gname, String gpic, double price, String tname) {
this.uid = uid;
this.gid = gid;
this.amount = amount;
this.gname = gname;
this.gpic = gpic;
this.price = price;
this.tname = tname;
}
}
| [
"mac@DamondeMacBook-Pro.local"
] | mac@DamondeMacBook-Pro.local |
dceafe55a2a5d7dbf3866f81d9b330995a568709 | 9254e7279570ac8ef687c416a79bb472146e9b35 | /sofa-20190815/src/main/java/com/aliyun/sofa20190815/models/CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse.java | 079b54d9c76dd5c9bd362cc3edad85f6b713878d | [
"Apache-2.0"
] | permissive | lquterqtd/alibabacloud-java-sdk | 3eaa17276dd28004dae6f87e763e13eb90c30032 | 3e5dca8c36398469e10cdaaa34c314ae0bb640b4 | refs/heads/master | 2023-08-12T13:56:26.379027 | 2021-10-19T07:22:15 | 2021-10-19T07:22:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,440 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sofa20190815.models;
import com.aliyun.tea.*;
public class CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse extends TeaModel {
@NameInMap("headers")
@Validation(required = true)
public java.util.Map<String, String> headers;
@NameInMap("body")
@Validation(required = true)
public CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponseBody body;
public static CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse build(java.util.Map<String, ?> map) throws Exception {
CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse self = new CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse();
return TeaModel.build(map, self);
}
public CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse setHeaders(java.util.Map<String, String> headers) {
this.headers = headers;
return this;
}
public java.util.Map<String, String> getHeaders() {
return this.headers;
}
public CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponse setBody(CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponseBody body) {
this.body = body;
return this;
}
public CancelLinkeantcodeAntcodeUserpersonalaccesstokensidrevokeResponseBody getBody() {
return this.body;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
ef12a8be5c240174f771a2369ca712459258d2ed | 34dd8020306df19560372f779535471f2c6b3368 | /src/main/java/com/pp/inception/service/connection/mongodbconnectionService.java | a0b1c95b6ac9d304472537cb765947b96ebe3967 | [] | no_license | pierrepetru/inception | 4d908c741e4f0294ac37a745d0dbb40e3f60360f | 0f8dbdbd97a740cb59561e5360c677b881ea6529 | refs/heads/master | 2021-01-10T05:34:20.839595 | 2016-03-09T16:10:48 | 2016-03-09T16:10:48 | 53,149,715 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,732 | java | package com.pp.inception.service.connection;
import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.pp.inception.model.sql.Column;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.stereotype.Service;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
/**
* Created by pdinulescu on 3/8/2016.
*/
@Service("mongodbConnectionService")
public class MongodbConnectionService implements ConnectionService {
public static final String DB_NAME = "test";
public static final String PERSON_COLLECTION = "restaurants";
public static final String MONGO_HOST = "localhost";
public static final int MONGO_PORT = 27017;
@Override
public String connecte(){
String result = "";
System.out.println("----------------------------------------");
Mongo mongo = null;
try {
mongo = new Mongo(MONGO_HOST, MONGO_PORT);
// MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
// mongoOps.findOne() ;
// MongoDatabase db = mongo.getDatabase("test");
System.out.println("********************Connection Mongo***********************");
DB db = mongo.getDB("test");
Set<String> collections = db.getCollectionNames();
for (String collectionName : collections) {
System.out.println(collectionName);
result +=" " + collectionName ;
}
DBCollection coll = db.getCollection("restaurants");
// DBObject doc = coll.findOne();
DBObject myDoc = coll.findOne();
result += " " + myDoc.toString() ;
System.out.println(myDoc);
mongo.close();
} catch (MongoException e) {
e.printStackTrace();
}
return result ;
}
@Override
public List<String> getAllTables() throws SQLException, ClassNotFoundException {
return null;
}
@Override
public List<Column> getStructureTable(String name) {
return null;
}
@Override
public List getDataColumnTable(String name, String fieldName, int page, int size) {
return null;
}
@Override
public List<String> getAllViews() {
return null;
}
@Override
public List<Column> getStructureViews(String name) {
return null;
}
@Override
public List getDataColumnView(String name, String fieldName, int page, int size) {
return null;
}
}
| [
"pierre.dinulescu@gmail.com"
] | pierre.dinulescu@gmail.com |
625894ae1cd57c5ff5f6168739d6c22299ff53fc | aa65ba75852735fadd7c113d32527b257f3afb6f | /components/identity/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/processors/LogoutRequestProcessor.java | 01d26415fb3bb91e328b2055503580c3b58ec4d7 | [] | no_license | Cloudxtreme/platform-3 | 0f2853c44604a07380de86abaad695b8744f990b | 28e34d628dd4c5990b16604a5ec9aeb23be177ae | refs/heads/master | 2021-05-29T14:40:32.621959 | 2012-12-03T12:15:43 | 2012-12-03T12:15:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,568 | java | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.sso.saml.processors;
import org.apache.axis2.AxisFault;
import org.apache.axis2.clustering.state.Replicator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opensaml.saml2.core.LogoutRequest;
import org.opensaml.saml2.core.LogoutResponse;
import org.opensaml.saml2.core.NameID;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO;
import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants;
import org.wso2.carbon.identity.sso.saml.builders.SingleLogoutMessageBuilder;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOReqValidationResponseDTO;
import org.wso2.carbon.identity.sso.saml.dto.SingleLogoutRequestDTO;
import org.wso2.carbon.identity.sso.saml.session.SSOSessionCommand;
import org.wso2.carbon.identity.sso.saml.session.SSOSessionPersistenceManager;
import org.wso2.carbon.identity.sso.saml.session.SessionInfoData;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.Map;
public class LogoutRequestProcessor {
private static Log log = LogFactory.getLog(LogoutRequestProcessor.class);
public SAMLSSOReqValidationResponseDTO process(LogoutRequest logoutRequest, String sessionId) throws IdentityException {
try {
SAMLSSOReqValidationResponseDTO reqValidationResponseDTO = new SAMLSSOReqValidationResponseDTO();
reqValidationResponseDTO.setLogOutReq(true);
String subject = null;
//Only if the logout request is received.
if (logoutRequest != null) {
if (logoutRequest.getIssuer() == null) {
String message = "Issuer should be mentioned in the Logout Request";
log.error(message);
return buildErrorResponse(logoutRequest.getID(), SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, message);
}
// TODO : Check for BaseID and EncryptedID as well.
if (logoutRequest.getNameID() != null) {
NameID nameID = logoutRequest.getNameID();
subject = nameID.getValue();
} else {
String message = "Subject Name should be specified in the Logout Request";
log.error(message);
return buildErrorResponse(logoutRequest.getID(), SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, message);
}
if (logoutRequest.getSessionIndexes() == null) {
String message = "At least one Session Index should be present in the Logout Request";
log.error(message);
return buildErrorResponse(logoutRequest.getID(), SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, message);
}
}
//Get the sessions from the SessionPersistenceManager and prepare the logout responses
SSOSessionPersistenceManager ssoSessionPersistenceManager = SSOSessionPersistenceManager.getPersistenceManager();
SessionInfoData sessionInfoData = ssoSessionPersistenceManager.getSessionInfo(sessionId);
if (sessionInfoData == null) {
String message = "No Established Sessions corresponding to Session Indexes provided.";
log.error(message);
return buildErrorResponse(logoutRequest.getID(), SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR,
message);
}
subject = sessionInfoData.getSubject();
String issuer = logoutRequest.getIssuer().getValue();
Map<String, SAMLSSOServiceProviderDO> sessionsList = sessionInfoData.getServiceProviderList();
SAMLSSOServiceProviderDO logoutReqIssuer = sessionsList.get(issuer);
// validate the signature, if it is set.
if(logoutReqIssuer.getCertAlias() != null){
boolean isSignatureValid = SAMLSSOUtil.validateAssertionSignature(logoutRequest, logoutReqIssuer.getCertAlias(),
MultitenantUtils.getTenantDomain(subject));
if (!isSignatureValid) {
String message = "The signature contained in the Assertion is not valid.";
log.error(message);
return buildErrorResponse(logoutRequest.getID(), SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR,
message);
}
}
SingleLogoutMessageBuilder logoutMsgBuilder = new SingleLogoutMessageBuilder();
Map<String, String> rpSessionsList = sessionInfoData.getRPSessionsList();
SingleLogoutRequestDTO[] singleLogoutReqDTOs = new SingleLogoutRequestDTO[sessionsList.size()-1];
LogoutRequest logoutReq = logoutMsgBuilder.buildLogoutRequest(subject, sessionId,
SAMLSSOConstants.SingleLogoutCodes.LOGOUT_USER);
String logoutReqString = SAMLSSOUtil.encode(SAMLSSOUtil.marshall(logoutReq));
int index = 0;
for (String key : sessionsList.keySet()) {
if (!key.equals(issuer)) {
SingleLogoutRequestDTO logoutReqDTO = new SingleLogoutRequestDTO();
logoutReqDTO.setAssertionConsumerURL(sessionsList.get(key).getLogoutURL());
if (sessionsList.get(key).getLogoutURL() == null ||
sessionsList.get(key).getLogoutURL().length() == 0) {
logoutReqDTO.setAssertionConsumerURL(sessionsList.get(key).getAssertionConsumerUrl());
}
logoutReqDTO.setLogoutResponse(logoutReqString);
logoutReqDTO.setRpSessionId(rpSessionsList.get(key));
singleLogoutReqDTOs[index] = logoutReqDTO;
index ++;
}
else {
reqValidationResponseDTO.setIssuer(sessionsList.get(key).getIssuer());
reqValidationResponseDTO.setAssertionConsumerURL(sessionsList.get(key).getAssertionConsumerUrl());
if(sessionsList.get(key).getLogoutURL() != null && sessionsList.get(key).getLogoutURL().length() > 0){
reqValidationResponseDTO.setAssertionConsumerURL(sessionsList.get(key).getLogoutURL());
}
}
}
reqValidationResponseDTO.setLogoutRespDTO(singleLogoutReqDTOs);
if (logoutRequest != null) {
LogoutResponse logoutResponse = logoutMsgBuilder.buildLogoutResponse(logoutRequest.getID(),
SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null);
reqValidationResponseDTO.setLogoutResponse(SAMLSSOUtil.encode(SAMLSSOUtil.marshall(logoutResponse)));
reqValidationResponseDTO.setValid(true);
}
ssoSessionPersistenceManager.removeSession(sessionId, issuer);
replicateSessionInfo(sessionId, issuer);
return reqValidationResponseDTO;
} catch (Exception e) {
log.error("Error Processing the Logout Request", e);
throw new IdentityException("Error Processing the Logout Request", e);
}
}
private SAMLSSOReqValidationResponseDTO buildErrorResponse(String id, String status, String statMsg) throws Exception {
SAMLSSOReqValidationResponseDTO reqValidationResponseDTO = new SAMLSSOReqValidationResponseDTO();
LogoutResponse logoutResp = new SingleLogoutMessageBuilder().buildLogoutResponse(id, status, statMsg);
reqValidationResponseDTO.setLogOutReq(true);
reqValidationResponseDTO.setValid(false);
reqValidationResponseDTO.setResponse(SAMLSSOUtil.encode(SAMLSSOUtil.marshall(logoutResp)));
return reqValidationResponseDTO;
}
private void replicateSessionInfo(String sessionID, String issuer) {
SSOSessionCommand sessionCommand = new SSOSessionCommand();
sessionCommand.setSsoTokenID(sessionID);
sessionCommand.setIssuer(issuer);
sessionCommand.setSignOut(true);
try {
if (log.isDebugEnabled()) {
log.info("Starting to replicate sign-out session Info for TokenID : " + sessionID);
}
Replicator.replicateState(sessionCommand,
SAMLSSOUtil.getConfigCtxService().getServerConfigContext().getAxisConfiguration());
if (log.isDebugEnabled()) {
log.info("Completed replicating sign-out Session Info for TokenID : " + sessionID);
}
} catch (AxisFault axisFault) {
log.error("Error when replicating the sign-out session info within the cluster", axisFault);
}
}
}
| [
"denis@a5903396-d722-0410-b921-86c7d4935375"
] | denis@a5903396-d722-0410-b921-86c7d4935375 |
83a98ccb7e402ca68e0b540dd324c0484bfdf04c | 8279abf9ffc9556e4946f57b40d03fef270aa344 | /client/src/main/java/com/client/register/RegisterController.java | 15ab1a8a9915ffbd3960438cfbeb463df303bb50 | [] | no_license | rask0ne/Chat-With-Rooms | caddf4e7c0da6ef6d8d67cbc6276952c9862fca9 | a52a66cf227125a6bef98d430bdb4fa14d318200 | refs/heads/master | 2021-01-21T12:21:01.369999 | 2017-05-19T09:57:28 | 2017-05-19T09:57:28 | 91,791,364 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,111 | java | package com.client.register;
import com.client.chatwindow.ChatController;
import com.client.chatwindow.Listener;
import com.client.login.LoginController;
import com.client.login.MainLauncher;
import com.client.util.ResizeHelper;
import com.messages.Message;
import com.messages.MessageType;
import com.messages.Status;
import com.messages.User;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;
import java.util.ResourceBundle;
import static java.lang.Thread.sleep;
/**
* Created by rask on 06.05.2017.
*/
public class RegisterController implements Initializable {
@FXML private ImageView Defaultview;
@FXML private ImageView Lucikview;
@FXML private ImageView Druzhkoview;
@FXML public TextField emailTextfield;
@FXML public PasswordField passwordTextField;
@FXML private TextField usernameTextfield;
@FXML private ChoiceBox imagePicker;
@FXML private Label selectedPicture;
public static ChatController con;
@FXML private BorderPane borderPane;
@FXML public Label msgLabelField;
private double xOffset;
private double yOffset;
private Scene scene;
private Socket socket;
private static ObjectOutputStream oos;
private InputStream is;
private ObjectInputStream input;
private OutputStream outputStream;
private static RegisterController instance;
public RegisterController() {
instance = this;
}
public static RegisterController getInstance() {
return instance;
}
public void showScene() throws IOException {
Platform.runLater(() -> {
Stage stage = (Stage) emailTextfield.getScene().getWindow();
stage.setResizable(true);
stage.setWidth(1040);
stage.setHeight(620);
stage.setOnCloseRequest((WindowEvent e) -> {
Platform.exit();
System.exit(0);
});
stage.setScene(this.scene);
stage.setMinWidth(800);
stage.setMinHeight(300);
ResizeHelper.addResizeListener(stage);
stage.centerOnScreen();
con.setUsernameLabel(usernameTextfield.getText());
con.setImageLabel(selectedPicture.getText());
});
}
@Override
public void initialize(URL location, ResourceBundle resources) {
imagePicker.getSelectionModel().selectFirst();
selectedPicture.textProperty().bind(imagePicker.getSelectionModel().selectedItemProperty());
selectedPicture.setVisible(false);
/* Drag and Drop */
borderPane.setOnMousePressed(event -> {
xOffset = MainLauncher.getPrimaryStage().getX() - event.getScreenX();
yOffset = MainLauncher.getPrimaryStage().getY() - event.getScreenY();
borderPane.setCursor(Cursor.CLOSED_HAND);
});
borderPane.setOnMouseDragged(event -> {
MainLauncher.getPrimaryStage().setX(event.getScreenX() + xOffset);
MainLauncher.getPrimaryStage().setY(event.getScreenY() + yOffset);
});
borderPane.setOnMouseReleased(event -> {
borderPane.setCursor(Cursor.DEFAULT);
});
imagePicker.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> selected, String oldPicture, String newPicture) {
if (oldPicture != null) {
switch (oldPicture) {
case "Default":
Defaultview.setVisible(false);
break;
case "Druzhko":
Druzhkoview.setVisible(false);
break;
case "Lucik":
Lucikview.setVisible(false);
break;
}
}
if (newPicture != null) {
switch (newPicture) {
case "Default":
Defaultview.setVisible(true);
break;
case "Druzhko":
Druzhkoview.setVisible(true);
break;
case "Lucik":
Lucikview.setVisible(true);
break;
}
}
}
});
int numberOfSquares = 30;
while (numberOfSquares > 0){
generateAnimation();
numberOfSquares--;
}
}
/* This method is used to generate the animation on the login window, It will generate random ints to determine
* the size, speed, starting points and direction of each square.
*/
public void generateAnimation(){
Random rand = new Random();
int sizeOfSqaure = rand.nextInt(50) + 1;
int speedOfSqaure = rand.nextInt(10) + 5;
int startXPoint = rand.nextInt(420);
int startYPoint = rand.nextInt(350);
int direction = rand.nextInt(5) + 1;
KeyValue moveXAxis = null;
KeyValue moveYAxis = null;
Rectangle r1 = null;
switch (direction){
case 1 :
// MOVE LEFT TO RIGHT
r1 = new Rectangle(0,startYPoint,sizeOfSqaure,sizeOfSqaure);
moveXAxis = new KeyValue(r1.xProperty(), 350 - sizeOfSqaure);
break;
case 2 :
// MOVE TOP TO BOTTOM
r1 = new Rectangle(startXPoint,0,sizeOfSqaure,sizeOfSqaure);
moveYAxis = new KeyValue(r1.yProperty(), 420 - sizeOfSqaure);
break;
case 3 :
// MOVE LEFT TO RIGHT, TOP TO BOTTOM
r1 = new Rectangle(startXPoint,0,sizeOfSqaure,sizeOfSqaure);
moveXAxis = new KeyValue(r1.xProperty(), 350 - sizeOfSqaure);
moveYAxis = new KeyValue(r1.yProperty(), 420 - sizeOfSqaure);
break;
case 4 :
// MOVE BOTTOM TO TOP
r1 = new Rectangle(startXPoint,420-sizeOfSqaure ,sizeOfSqaure,sizeOfSqaure);
moveYAxis = new KeyValue(r1.xProperty(), 0);
break;
case 5 :
// MOVE RIGHT TO LEFT
r1 = new Rectangle(420-sizeOfSqaure,startYPoint,sizeOfSqaure,sizeOfSqaure);
moveXAxis = new KeyValue(r1.xProperty(), 0);
break;
case 6 :
//MOVE RIGHT TO LEFT, BOTTOM TO TOP
r1 = new Rectangle(startXPoint,0,sizeOfSqaure,sizeOfSqaure);
moveXAxis = new KeyValue(r1.xProperty(), 350 - sizeOfSqaure);
moveYAxis = new KeyValue(r1.yProperty(), 420 - sizeOfSqaure);
break;
default:
System.out.println("default");
}
r1.setFill(Color.web("#F89406"));
r1.setOpacity(0.1);
KeyFrame keyFrame = new KeyFrame(Duration.millis(speedOfSqaure * 1000), moveXAxis, moveYAxis);
Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
timeline.getKeyFrames().add(keyFrame);
timeline.play();
borderPane.getChildren().add(borderPane.getChildren().size()-1,r1);
}
/* Terminates Application */
public void closeSystem(ActionEvent actionEvent){
/*Platform.exit();
System.exit(0);*/
((Node)(actionEvent.getSource())).getScene().getWindow().hide();
}
public void minimizeWindow(){
MainLauncher.getPrimaryStage().setIconified(true);
}
/* This displays an alert message to the user */
public void showErrorDialog(String message) {
Platform.runLater(()-> {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning!");
alert.setHeaderText(message);
alert.setContentText("Please check for firewall issues and check if the server is running.");
alert.showAndWait();
});
}
public void registerButtonAction(ActionEvent actionEvent) throws IOException, ClassNotFoundException, SQLException, InterruptedException {
socket = new Socket(InetAddress.getLocalHost(), 9001);
outputStream = socket.getOutputStream();
oos = new ObjectOutputStream(outputStream);
is = socket.getInputStream();
input = new ObjectInputStream(is);
Message createMessage = new Message();
createMessage.setName(usernameTextfield.getText());
createMessage.setType(MessageType.REGISTER);
createMessage.setEmail(emailTextfield.getText());
createMessage.setPassword(passwordTextField.getText());
oos.writeObject(createMessage);
oos.flush();
sleep(1000);
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/slack?autoReconnect=true&useSSL=false", "root", "root");
Statement stmt = (Statement) con.createStatement();
String query = "SELECT username, email FROM user;";
stmt.executeQuery(query);
ResultSet rs = stmt.getResultSet();
boolean check = true;
while (rs.next()) {
String DBusername = rs.getString("username");
String DBemail = rs.getString("email");
if (createMessage.getName().equals(DBusername) || createMessage.getEmail().equals(DBemail)) {
check = false;
break;
}
}
con.close();
if(check == false)
msgLabelField.setText("Username or Password already exist");
else{
((Node)(actionEvent.getSource())).getScene().getWindow().hide();
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
0ff60a3732702c1e0af1405172af1ba3ccb2d4b0 | 827d130ef49b595400b5f522c4fde8ea71cc97bc | /src/main/java/co/java/entity/Token.java | a4846979dad1d7ca2bf29ec7d167707d04c5565b | [] | no_license | Angela2400/ExamenFinal-1151628 | 4583ec59f530b593286c042b2e10ee3ed7decde5 | 3a64512ebf23461d29c683a5bebc9e024e3f335d | refs/heads/main | 2023-05-24T05:26:50.109295 | 2021-06-17T13:51:49 | 2021-06-17T13:51:49 | 377,661,338 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,532 | java | package co.java.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Token {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
@Column
String host;
@Column
String userdb;
@Column
String pass;
@Column
String db;
@Column
String token;
@Column
Integer port;
@ManyToOne
@JoinColumn(name = "user", referencedColumnName = "user")
Usuario user;
@Column
Integer state;
@ManyToOne
@JoinColumn(name = "type", referencedColumnName = "type")
TipoDB type;
public Token(String host, String userdb, String pass, String db, String token, Integer port, Usuario user,
Integer state, TipoDB type) {
super();
this.host = host;
this.userdb = userdb;
this.pass = pass;
this.db = db;
this.token = token;
this.port = port;
this.user = user;
this.state = state;
this.type = type;
}
public Token(Integer id, String host, String userdb, String pass, String db, String token, Integer port,
Usuario user, Integer state, TipoDB type) {
super();
this.id = id;
this.host = host;
this.userdb = userdb;
this.pass = pass;
this.db = db;
this.token = token;
this.port = port;
this.user = user;
this.state = state;
this.type = type;
}
public Token() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUserdb() {
return userdb;
}
public void setUserdb(String userdb) {
this.userdb = userdb;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getDb() {
return db;
}
public void setDb(String db) {
this.db = db;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Usuario getUser() {
return user;
}
public void setUser(Usuario user) {
this.user = user;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public TipoDB getType() {
return type;
}
public void setType(TipoDB type) {
this.type = type;
}
}
| [
"angelamildredacro@ufps.edu.co"
] | angelamildredacro@ufps.edu.co |
fd75c25e00d4e2394d6b40bb1c27666e07e99683 | a575a700b36dc9aec5da137470f05014f335d2fd | /gmall0624-manage-service/src/main/java/com/atguigu/gmall0624/manage/mapper/SpuImageMapper.java | 7c703d5edcd54de1554103b61ac5fe540726c26f | [] | no_license | jixiangyang1994/gmall0624 | 64e622be62a3943e30220e88f67a20c61e27b6ef | 0711ce5acd0b3ce84ce8187a2cd037e8522a80da | refs/heads/master | 2022-09-25T19:26:58.618218 | 2019-12-09T10:42:05 | 2019-12-09T10:42:05 | 225,773,393 | 1 | 0 | null | 2022-09-01T23:17:00 | 2019-12-04T03:45:15 | Java | UTF-8 | Java | false | false | 192 | java | package com.atguigu.gmall0624.manage.mapper;
import com.atguigu.gmall0624.bean.SpuImage;
import tk.mybatis.mapper.common.Mapper;
public interface SpuImageMapper extends Mapper<SpuImage> {
}
| [
"1191338935@qq.com"
] | 1191338935@qq.com |
5a7a277b66be35737c0bfe556c9f16f5a71bafe4 | af9d82a9eaf1a29a49c6a2193e9003624d4c04fe | /src/main/java/org/bluesoft/app/ws/exceptions/CouldNotUpdateRecordException.java | b2a7e4afcd83466d882a9cab36e0e3d8e4d549ca | [] | no_license | jstolorz/java-rest-app | 1d14e9b666a1f2db87e311363da76383cc8857bf | c414e259bf81f57c1e1b09c2d3120ce15fb4801d | refs/heads/master | 2020-03-22T11:37:44.073517 | 2018-07-26T13:07:09 | 2018-07-26T13:07:09 | 139,983,479 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 276 | java | package org.bluesoft.app.ws.exceptions;
public class CouldNotUpdateRecordException extends RuntimeException {
private static final long serialVersionUID = 5575907345216881334L;
public CouldNotUpdateRecordException(String message) {
super(message);
}
}
| [
"Jmnz1234"
] | Jmnz1234 |
cb15eff3df2ee9a213b0c0aadfa7e2632111eb0d | cc333bbb75078d5d92b2c4e9b34a0601acef13eb | /spring-aop-first/src/main/java/com/hjp/spring/aop/first/HelloWorldImpl2.java | 81027f9a4b1b8c20d3cddff272a9a93bcb5b7bd7 | [] | no_license | huangjianpin/spring-aop-demo | 6d7307dd4e6c56e194b794977dc8dc30f03d4368 | ac56ef44471a9e6cb04512075c2fb36c95710188 | refs/heads/master | 2021-08-23T15:24:18.001481 | 2017-12-05T11:56:19 | 2017-12-05T11:56:19 | 113,175,607 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 296 | java | package com.hjp.spring.aop.first;
public class HelloWorldImpl2 implements HelloWorld{
public void printHelloWorld(){
System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
}
public void doPrint(){
System.out.println("Enter HelloWorldImpl2.doPrint()");
return ;
}
}
| [
"hardon123a@163.com"
] | hardon123a@163.com |
3c7fc240ad24efe3f3b17ccf412f530389c59339 | 3e8cddebda843b848ae717317798e207494ae5d3 | /src/main/java/org/schoolzilla/homework/CsvProcessor.java | 1e63ff3f8429067ece9062f82ec0a536d09d017e | [] | no_license | lengebretsen/szhomework | f9c5578a07b24b0160b4d68aab5f1c62f4ab595c | 99e41f4d6811fdd410eb0f16130ae51838e00008 | refs/heads/master | 2020-03-26T14:41:06.311289 | 2014-07-02T17:58:31 | 2014-07-02T17:58:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,354 | java | package org.schoolzilla.homework;
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Wrapper class around opencsv CSVReader that handles csv files with column headers
* in the first row.
*
* @see http://opencsv.sourceforge.net/
*
* Created by lloydengebretsen on 6/28/14.
*/
public class CsvProcessor {
private String inputFile;
private CSVReader reader;
private String[] headerRow;
/**
* Constructor takes in String location of the input CSV file. Also reads off the first
* row of the file (column headers) of the file and stores it as a String[] for later
* reference.
*
* @param inputFile String location of input CSV file
* @throws IOException
*/
public CsvProcessor(String inputFile) throws IOException {
this.inputFile = inputFile;
reader = new CSVReader(new FileReader(inputFile));
headerRow = readLine();
}
/**
* Reads the next line from the CSV file and returns it as a String[]
* @return String[] with values from the next row in the CSV file or null if EoF
* has been reached
* @throws IOException
*/
public String[] readLine() throws IOException {
return reader.readNext();
}
public String[] getHeaderRow(){
return headerRow;
}
}
| [
"ldengebretsen@gmail.com"
] | ldengebretsen@gmail.com |
2ad08627c8479df463d15bf4d6200fc77cfd3549 | 05c6ae6a8d41b191afb7ff5bb507ecec2774698f | /lesson_8/app/src/main/java/com/kalashnyk/denys/gmapsapp/domain/AllPinsViewModel.java | 60b8a0fe90e18b9b651c8ee70c29c0baff5095af | [] | no_license | dan1603/ITVDN | 9106b534847d466af747dca4ca38aeb089a551e3 | af767e4aca74a29bbde36619d9fde566a471a71e | refs/heads/master | 2020-06-29T23:44:20.536187 | 2019-08-05T13:25:20 | 2019-08-05T13:25:20 | 182,649,020 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,097 | java | package com.kalashnyk.denys.gmapsapp.domain;
import android.annotation.SuppressLint;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.util.Log;
import com.kalashnyk.denys.gmapsapp.presentation.widget.SingleLiveEvent;
import com.kalashnyk.denys.gmapsapp.repository.AppRepository;
import com.kalashnyk.denys.gmapsapp.repository.database.entity.PinEntity;
import java.util.List;
public class AllPinsViewModel extends BaseViewModel {
private AppRepository mRepository;
private SingleLiveEvent<List<PinEntity>> liveDataItems = new SingleLiveEvent<>();
public AllPinsViewModel(Application application, AppRepository repository) {
super(application);
mRepository = repository;
}
@SuppressLint("CheckResult")
public void getAllItems() {
mRepository.getAllPins().subscribe(list -> liveDataItems.setValue(list), throwable -> {
Log.d("CheckId" , "throwable - " + throwable.getMessage());
});
}
public LiveData<List<PinEntity>> getLiveDataItems() {
return liveDataItems;
}
}
| [
"kalashnyk.denys@gmail.com"
] | kalashnyk.denys@gmail.com |
9994a0bde591e2ff625231c4f877b1923f0504cf | c3d3282e8667b8869c4b4322c93151a499aea048 | /ssm-practice02/src/main/java/cn/itcast/dao/AccountDao.java | 6495f26504e709f43946051e4119e6cf5fa1c07b | [] | no_license | chenxiaowai/project01 | 2d6c47027ba225a34a561c8ed6bdfcf88841b34b | 284c9aa4c32a6437784b3127d45740a7f80750fe | refs/heads/master | 2022-12-20T22:26:45.823600 | 2019-06-24T12:15:48 | 2019-06-24T12:15:48 | 193,496,370 | 0 | 0 | null | 2022-12-16T04:25:21 | 2019-06-24T11:56:25 | Java | UTF-8 | Java | false | false | 542 | java | package cn.itcast.dao;
import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 持久层接口
*/
@Repository("accountDao")
public interface AccountDao {
// 查询所有账户
@Select("select * from account")
List<Account> findAll();
// 保存帐户信息
@Insert("insert into account (name,money) values (#{name},#{money})")
void saveAccount(Account account);
}
| [
"zhangsan@itcast.cn"
] | zhangsan@itcast.cn |
01ba861380340f9dca688f58758dfa8ad4eecf97 | aa1e6fb49207ef7d3d7cc00b688fdb28895c6956 | /P15009900/src/main/java/com/erim/sz/common/bean/TexiDriveBean.java | 228b1fa2a84dbb9ed2110265073ce44b54dfcfb2 | [] | no_license | zhanght86/erim | f76fec9267200c6951a0a8c1fb3f723de88a039c | 504d81bb4926e496c11a34641dcc67150e78dadc | refs/heads/master | 2021-05-15T17:10:07.801083 | 2016-12-02T09:35:07 | 2016-12-02T09:35:07 | 107,489,023 | 1 | 0 | null | 2017-10-19T02:37:10 | 2017-10-19T02:37:10 | null | UTF-8 | Java | false | false | 7,039 | java | package com.erim.sz.common.bean;
import com.erim.core.bean.BaseBean;
/**
* @描述: 自驾管理
*
* @作者: 陈鹏
* @创建时间: 2015年7月10日 下午9:46:06
*/
public class TexiDriveBean extends BaseBean {
/**
* @Fields serialVersionUID : 序列化
*/
private static final long serialVersionUID = 1L;
private Integer id;
// 产品ID
private Integer tdlId;
// 自驾类型 01:全天 02:半天
private String zjlType;
// 用车城市
private String zjlProvince;
// 用车城市
private String zjlCity;
// 可否异地还车
private String zjlPlaceCar;
/**
* 半天
*/
//半天限时
private String zjlHfLimit;
//半天限公里
private String zjlHfLimitKm;
//半天的取车地点
private String zjlHfTakePlace;
//半天取车地址
private String zjlHfTakeAddress;
//半天的还车地点
private String zjlHfBackPlace;
//半天还车地址
private String zjlHfBackAddress;
//半天的费用说明
private String zjlHfCostShow;
//半天取车还车须知
private String zjlHfBackNotice;
//半天违章须知
private String zjlHfBreachNotice;
//半天保险说明
private String zjlHfInsuranceNotice;
//半天更改/取消订单说明
private String zjlHfUpdateNotice;
//特别备注
private String zjlHfSpecialNote;
/**
* 全天
*/
//全天限时长
private String zjlDay;
//全天限公里
private String zjlLimit;
//全天取车地点
private String ZjlTakePlace;
//全天取车地址
private String zjlTakeAddress;
//全天还车地点
private String zjlBackPlace;
//全天还车地址
private String zjlBackAddress;
//全天费用说明
private String zjlCostShow;
//全天取还须知
private String zjlBackShow;
//全天违章须知
private String zjlBreachNotice;
//全天保险说明
private String zjlInsuranceNotice;
//全天更改取消订单说明
private String zjlUpdateNotice;
//全天特别备注
private String zjlSpecialNotice;
/**
* 暂未使用字段
*/
//自驾半天
private String zjlHalfDay;
//自驾全天
private String zjlAllDay;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTdlId() {
return tdlId;
}
public void setTdlId(Integer tdlId) {
this.tdlId = tdlId;
}
public String getZjlType() {
return zjlType;
}
public void setZjlType(String zjlType) {
this.zjlType = zjlType;
}
public String getZjlProvince() {
return zjlProvince;
}
public void setZjlProvince(String zjlProvince) {
this.zjlProvince = zjlProvince;
}
public String getZjlCity() {
return zjlCity;
}
public void setZjlCity(String zjlCity) {
this.zjlCity = zjlCity;
}
public String getZjlPlaceCar() {
return zjlPlaceCar;
}
public void setZjlPlaceCar(String zjlPlaceCar) {
this.zjlPlaceCar = zjlPlaceCar;
}
public String getZjlHfLimit() {
return zjlHfLimit;
}
public void setZjlHfLimit(String zjlHfLimit) {
this.zjlHfLimit = zjlHfLimit;
}
public String getZjlHfLimitKm() {
return zjlHfLimitKm;
}
public void setZjlHfLimitKm(String zjlHfLimitKm) {
this.zjlHfLimitKm = zjlHfLimitKm;
}
public String getZjlHfTakePlace() {
return zjlHfTakePlace;
}
public void setZjlHfTakePlace(String zjlHfTakePlace) {
this.zjlHfTakePlace = zjlHfTakePlace;
}
public String getZjlHfTakeAddress() {
return zjlHfTakeAddress;
}
public void setZjlHfTakeAddress(String zjlHfTakeAddress) {
this.zjlHfTakeAddress = zjlHfTakeAddress;
}
public String getZjlHfBackPlace() {
return zjlHfBackPlace;
}
public void setZjlHfBackPlace(String zjlHfBackPlace) {
this.zjlHfBackPlace = zjlHfBackPlace;
}
public String getZjlHfBackAddress() {
return zjlHfBackAddress;
}
public void setZjlHfBackAddress(String zjlHfBackAddress) {
this.zjlHfBackAddress = zjlHfBackAddress;
}
public String getZjlHfCostShow() {
return zjlHfCostShow;
}
public void setZjlHfCostShow(String zjlHfCostShow) {
this.zjlHfCostShow = zjlHfCostShow;
}
public String getZjlHfBackNotice() {
return zjlHfBackNotice;
}
public void setZjlHfBackNotice(String zjlHfBackNotice) {
this.zjlHfBackNotice = zjlHfBackNotice;
}
public String getZjlHfBreachNotice() {
return zjlHfBreachNotice;
}
public void setZjlHfBreachNotice(String zjlHfBreachNotice) {
this.zjlHfBreachNotice = zjlHfBreachNotice;
}
public String getZjlHfInsuranceNotice() {
return zjlHfInsuranceNotice;
}
public void setZjlHfInsuranceNotice(String zjlHfInsuranceNotice) {
this.zjlHfInsuranceNotice = zjlHfInsuranceNotice;
}
public String getZjlHfUpdateNotice() {
return zjlHfUpdateNotice;
}
public void setZjlHfUpdateNotice(String zjlHfUpdateNotice) {
this.zjlHfUpdateNotice = zjlHfUpdateNotice;
}
public String getZjlHfSpecialNote() {
return zjlHfSpecialNote;
}
public void setZjlHfSpecialNote(String zjlHfSpecialNote) {
this.zjlHfSpecialNote = zjlHfSpecialNote;
}
public String getZjlLimit() {
return zjlLimit;
}
public void setZjlLimit(String zjlLimit) {
this.zjlLimit = zjlLimit;
}
public String getZjlTakePlace() {
return ZjlTakePlace;
}
public void setZjlTakePlace(String zjlTakePlace) {
ZjlTakePlace = zjlTakePlace;
}
public String getZjlTakeAddress() {
return zjlTakeAddress;
}
public void setZjlTakeAddress(String zjlTakeAddress) {
this.zjlTakeAddress = zjlTakeAddress;
}
public String getZjlBackPlace() {
return zjlBackPlace;
}
public void setZjlBackPlace(String zjlBackPlace) {
this.zjlBackPlace = zjlBackPlace;
}
public String getZjlBackAddress() {
return zjlBackAddress;
}
public void setZjlBackAddress(String zjlBackAddress) {
this.zjlBackAddress = zjlBackAddress;
}
public String getZjlCostShow() {
return zjlCostShow;
}
public void setZjlCostShow(String zjlCostShow) {
this.zjlCostShow = zjlCostShow;
}
public String getZjlBackShow() {
return zjlBackShow;
}
public void setZjlBackShow(String zjlBackShow) {
this.zjlBackShow = zjlBackShow;
}
public String getZjlBreachNotice() {
return zjlBreachNotice;
}
public void setZjlBreachNotice(String zjlBreachNotice) {
this.zjlBreachNotice = zjlBreachNotice;
}
public String getZjlInsuranceNotice() {
return zjlInsuranceNotice;
}
public void setZjlInsuranceNotice(String zjlInsuranceNotice) {
this.zjlInsuranceNotice = zjlInsuranceNotice;
}
public String getZjlUpdateNotice() {
return zjlUpdateNotice;
}
public void setZjlUpdateNotice(String zjlUpdateNotice) {
this.zjlUpdateNotice = zjlUpdateNotice;
}
public String getZjlSpecialNotice() {
return zjlSpecialNotice;
}
public void setZjlSpecialNotice(String zjlSpecialNotice) {
this.zjlSpecialNotice = zjlSpecialNotice;
}
public String getZjlHalfDay() {
return zjlHalfDay;
}
public void setZjlHalfDay(String zjlHalfDay) {
this.zjlHalfDay = zjlHalfDay;
}
public String getZjlAllDay() {
return zjlAllDay;
}
public void setZjlAllDay(String zjlAllDay) {
this.zjlAllDay = zjlAllDay;
}
public String getZjlDay() {
return zjlDay;
}
public void setZjlDay(String zjlDay) {
this.zjlDay = zjlDay;
}
}
| [
"libra0920@qq.com"
] | libra0920@qq.com |
d8bb8b06db58823c80e0a2ec3bbb23b537500a93 | fc160694094b89ab09e5c9a0f03db80437eabc93 | /java-speech/samples/snippets/generated/com/google/cloud/speech/v1p1beta1/adaptation/updatephraseset/SyncUpdatePhraseSet.java | a478d865ee765030fdbd43359b36a6a18492921b | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | googleapis/google-cloud-java | 4f4d97a145e0310db142ecbc3340ce3a2a444e5e | 6e23c3a406e19af410a1a1dd0d0487329875040e | refs/heads/main | 2023-09-04T09:09:02.481897 | 2023-08-31T20:45:11 | 2023-08-31T20:45:11 | 26,181,278 | 1,122 | 685 | Apache-2.0 | 2023-09-13T21:21:23 | 2014-11-04T17:57:16 | Java | UTF-8 | Java | false | false | 1,991 | java | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.google.cloud.speech.v1p1beta1.samples;
// [START speech_v1p1beta1_generated_Adaptation_UpdatePhraseSet_sync]
import com.google.cloud.speech.v1p1beta1.AdaptationClient;
import com.google.cloud.speech.v1p1beta1.PhraseSet;
import com.google.cloud.speech.v1p1beta1.UpdatePhraseSetRequest;
import com.google.protobuf.FieldMask;
public class SyncUpdatePhraseSet {
public static void main(String[] args) throws Exception {
syncUpdatePhraseSet();
}
public static void syncUpdatePhraseSet() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (AdaptationClient adaptationClient = AdaptationClient.create()) {
UpdatePhraseSetRequest request =
UpdatePhraseSetRequest.newBuilder()
.setPhraseSet(PhraseSet.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
PhraseSet response = adaptationClient.updatePhraseSet(request);
}
}
}
// [END speech_v1p1beta1_generated_Adaptation_UpdatePhraseSet_sync]
| [
"noreply@github.com"
] | noreply@github.com |
c4f81129e7360125c5996ed8a6e8f8411db71748 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_a62a6bf165d13fef3a42ab555f286023a0292ef8/DynamicService/2_a62a6bf165d13fef3a42ab555f286023a0292ef8_DynamicService_s.java | bdab3e2b3c4250049f193054a431283da9172b15 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 9,819 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.il;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.dom.NamespaceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.bpel.pmapi.ProcessInfoCustomizer;
import org.apache.xmlbeans.XmlObject;
import org.w3c.dom.Node;
/**
* Dynamic invocation handler for XML-based service; uses RPC message format conventions to dispatch
* invocation based on top-level element name (e.g. method name) and sub-elements (e.g. parameters).
*/
public class DynamicService<T> {
private final Log __log = LogFactory.getLog(getClass());
static final OMFactory OM = OMAbstractFactory.getOMFactory();
T _service;
Class<T> _clazz;
@SuppressWarnings("unchecked")
public DynamicService(T service) {
_clazz = (Class<T>) service.getClass();
_service = service;
}
public OMElement invoke(String operation, OMElement payload) {
if (__log.isDebugEnabled())
__log.debug("Invoke: operation "+operation+" on "+_clazz + ":\n" + payload);
String methodName = operation;
try {
Method invokedMethod = findMethod(methodName);
Object[] params = extractParams(invokedMethod, payload);
Object result = invokedMethod.invoke(_service, params);
OMElement response = null;
if (result != null) {
if (__log.isDebugEnabled())
__log.debug("Invoke: operation "+operation+" on "+_clazz + ":\n" + payload + "\nOM:" + OM + " namespace:" + payload.getNamespace());
response = OM.createOMElement(new QName((payload.getNamespace() == null ? "" : payload.getNamespace().getNamespaceURI()), methodName+"Response"));
OMElement parts = convertToOM(result);
parts = stripNamespace(parts);
response.addChild(parts);
}
if (__log.isDebugEnabled()) {
__log.debug("Response: operation "+operation+" on "+_clazz + ":\n" + response);
}
return response;
} catch (IllegalAccessException e) {
throw new RuntimeException("Couldn't invoke method named " + methodName + " in management interface!", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Invocation of method " + methodName + " in management interface failed: " + e.getTargetException().getMessage(), e.getTargetException());
}
}
@SuppressWarnings("unchecked")
private Object[] extractParams(Method method, OMElement omElmt) {
Class<?>[] paramTypes = method.getParameterTypes();
Object[] params = new Object[method.getParameterTypes().length];
Iterator<OMElement> omChildren = (Iterator<OMElement>) omElmt.getChildElements();
int paramIdx = 0;
for (Class<?> paramClass : paramTypes) {
OMElement omchild = (OMElement) omChildren.next();
if (__log.isDebugEnabled()) {
__log.debug("Extracting param " + paramClass + " from " + omchild);
}
params[paramIdx++] = convertFromOM(paramClass, omchild);
}
return params;
}
@SuppressWarnings("unchecked")
private static Object convertFromOM(Class<?> clazz, OMElement elmt) {
// Here comes the nasty code...
if (elmt == null || elmt.getText().length() == 0 && !elmt.getChildElements().hasNext())
return null;
else if (clazz.equals(String.class)) {
return elmt.getText();
} else if (clazz.equals(Boolean.class) || clazz.equals(Boolean.TYPE)) {
return (elmt.getText().equals("true") || elmt.getText().equals("yes")) ? Boolean.TRUE : Boolean.FALSE;
} else if (clazz.equals(QName.class)) {
// The getTextAsQName is buggy, it sometimes return the full text without extracting namespace
return OMUtils.getTextAsQName(elmt);
} else if (clazz.equals(ProcessInfoCustomizer.class)) {
return new ProcessInfoCustomizer(elmt.getText());
} else if (Node.class.isAssignableFrom(clazz)) {
return OMUtils.toDOM(elmt.getFirstElement());
} else if (clazz.equals(Long.TYPE) || clazz.equals(Long.class)) {
return Long.parseLong(elmt.getText());
} else if (clazz.equals(Integer.TYPE) || clazz.equals(Integer.class)) {
return Integer.parseInt(elmt.getText());
} else if (clazz.isArray()) {
ArrayList<Object> alist = new ArrayList<Object>();
Iterator<OMElement> children = elmt.getChildElements();
Class<?> targetClazz = clazz.getComponentType();
while (children.hasNext())
alist.add(parseType(targetClazz, ((OMElement)children.next()).getText()));
return alist.toArray((Object[]) Array.newInstance(targetClazz, alist.size()));
} else if (XmlObject.class.isAssignableFrom(clazz)) {
try {
Class beanFactory = clazz.forName(clazz.getCanonicalName() + "$Factory");
elmt.setNamespace(new NamespaceImpl(""));
elmt.setLocalName("xml-fragment");
return beanFactory.getMethod("parse", XMLStreamReader.class)
.invoke(null, elmt.getXMLStreamReaderWithoutCaching());
} catch (ClassNotFoundException e) {
throw new RuntimeException("Couldn't find class " + clazz.getCanonicalName() + ".Factory to instantiate xml bean", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Couldn't access class " + clazz.getCanonicalName() + ".Factory to instantiate xml bean", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Couldn't access xml bean parse method on class " + clazz.getCanonicalName() + ".Factory " +
"to instantiate xml bean", e);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Couldn't find xml bean parse method on class " + clazz.getCanonicalName() + ".Factory " +
"to instantiate xml bean", e);
}
} else throw new RuntimeException("Couldn't use element " + elmt + " to obtain a management method parameter.");
}
@SuppressWarnings("unchecked")
private static OMElement convertToOM(Object obj) {
if (obj instanceof XmlObject) {
try {
return new StAXOMBuilder(((XmlObject)obj).newInputStream()).getDocumentElement();
} catch (XMLStreamException e) {
throw new RuntimeException("Couldn't serialize result to an outgoing messages.", e);
}
} else if (obj instanceof List) {
OMElement listElmt = OM.createOMElement("list", null);
for (Object stuff : ((List) obj)) {
OMElement stuffElmt = OM.createOMElement("element", null);
stuffElmt.setText(stuff.toString());
listElmt.addChild(stuffElmt);
}
return listElmt;
} else throw new RuntimeException("Couldn't convert object " + obj + " into a response element.");
}
@SuppressWarnings("unchecked")
private static OMElement stripNamespace(OMElement element) {
OMElement parent = OM.createOMElement(new QName("", element.getLocalName()));
Iterator<OMElement> iter = (Iterator<OMElement>) element.getChildElements();
while (iter.hasNext()) {
OMElement child = iter.next();
child = child.cloneOMElement();
parent.addChild(child);
}
return parent;
}
private Method findMethod(String methodName) {
for (Method method : _clazz.getMethods()) {
if (method.getName().equals(methodName)) return method;
}
throw new RuntimeException("Couldn't find any method named " + methodName + " in interface " + _clazz.getName());
}
private static Object parseType(Class<?> clazz, String str) {
if (clazz.equals(Integer.class)) return Integer.valueOf(str);
if (clazz.equals(Float.class)) return Integer.valueOf(str);
if (clazz.equals(String.class)) return str;
return null;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
b5bf2467973253421834efafe6963873a3d3d4f8 | a37e46f95f5406d1d7dcd063519891a5c012e416 | /CellType.java | c19e11d8a8977e48c99d3e84a9160fcaccb2570c | [] | no_license | maguiremarion/JavaSnakeGame | ddf4c946861b4029d31f6e1f2ad907de06e12a5c | 9fcbf99958108d959754d078b5215eb215a97353 | refs/heads/master | 2020-09-26T08:21:41.621623 | 2019-12-06T00:46:40 | 2019-12-06T00:46:40 | 226,215,390 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 364 | java | /**CellType.java
*@author Maguire Marion
*@version 1.0
This program defines the possible
types of cells
*/
/** Defines options a what a type of cell a cell is
For example, a cell can be set to CellType.empty
to denote it's empty or CellType.food to denote it's
full of food */
public enum CellType {
empty,
food,
snake_node;
} | [
"noreply@github.com"
] | noreply@github.com |
8acc982f40b85cbee85c80e928f14f13c3641e7a | e199cfa5d09dbf6b1334b8580265c6c9af30e8f0 | /CS481_ControllerTests/src/edu/ycp/cs481/srdesign/LoginControllerTest.java | 1777f622a9ed0ebe5e975d1eea602c018faee3ad | [] | no_license | Thon9/CS481_SeniorDesignProject | f1cb6cebc7b64bd27da23c38bc337299a675ff50 | 1ee0978db3dc96e689a18fce496b4de8f0e3490f | refs/heads/master | 2020-06-30T01:12:14.108349 | 2015-05-05T16:25:20 | 2015-05-05T16:25:20 | 23,677,296 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 71 | java | package edu.ycp.cs481.srdesign;
public class LoginControllerTest {
}
| [
"aoduyebo@ycp.edu"
] | aoduyebo@ycp.edu |
afc7fedc5a76f35385fe2f65f3a50da95fdab927 | 53efcbcb8210a01c3a57cdc2784926ebc22d6412 | /src/main/java/br/com/fieesq/model54330/FieEsq35304.java | e0abeec369b6450527a3e7f545ddaae819c03896 | [] | no_license | fie23777/frontCercamento | d57846ac985f4023a8104a0872ca4a226509bbf2 | 6282f842544ab4ea332fe7802d08cf4e352f0ae3 | refs/heads/master | 2021-04-27T17:29:56.793349 | 2018-02-21T10:32:23 | 2018-02-21T10:32:23 | 122,322,301 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 768 | java | package br.com.fieesq.model54330;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
@Entity
public class FieEsq35304 {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String numEsq35304;
@Transient
private String esqParam;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumEsq35304() {
return numEsq35304;
}
public void setNumEsq35304(String numEsq35304) {
this.numEsq35304 = numEsq35304;
}
public String getEsqParam() {
return esqParam;
}
public void setEsqParam(String esqParam) {
this.esqParam = esqParam;
}
}
| [
"fie2377@gmail.com"
] | fie2377@gmail.com |
56251460d1914a59b303c03c8130a30129d45fe4 | b910cd743677560f31f4d6b03fe17df8d0d14139 | /app/src/main/java/com/alcove/partners/siyu/busFare.java | f396eb3722c7591126b10a6c648fe36ba58db2f2 | [] | no_license | manohar-poduri/SiYuVizag | fa3bd1e1231a1af085b052b7e290986cad3bd17d | 4151f683eef6e1f38e29925e0b6e8a5a4027263e | refs/heads/master | 2023-02-17T14:20:12.065407 | 2021-01-20T14:39:24 | 2021-01-20T14:39:24 | 331,333,986 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,351 | java | /*
Updated by Sirisha Balireddy on 20-05-2019 - SiYuVizag 1.1
*/
package com.alcove.partners.siyu;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class busFare extends second implements AdapterView.OnItemClickListener {
//Take in the values in form of strings
private String[] from = {"Jagadamba to R.K.Beach ", "Jagadamba to Madhurawada", "Jagadamba to Maddilapalem", "Jagadamba to MVP", "Jagadamba to Complex", "Jagadamba to Seethammadara",
"Jagadamba to Kailasagiri", "Jagadamba to Submarine", "Jagadamba to ChinnaWaltair", "Jagadamba to PeddaWaltair",
"Jagadamba to Rushikonda", "Jagadamba to Vuda Park", "Jagadamba to Zoo", "Jagadamba to Simhachalam", "Jagadamba to Gajuwaka",
"Jagadamba to Akkayapalem", "Jagadamba to Kancharapalem", "R.K.Beach to Madhurawada", "R.K.Beach to Maddilapalem", "R.K.Beach to MVP", "R.K.Beach to Complex", "R.K.Beach to Seethammadara",
"R.K.Beach to Kailasagiri", "R.K.Beach to Submarine", "R.K.Beach to ChinnaWaltair", "R.K.Beach to PeddaWaltair",
"R.K.Beach to Rushikonda", "R.K.Beach to Vuda Park", "R.K.Beach to Zoo", "R.K.Beach to Simhachalam", "R.K.Beach to Gajuwaka",
"R.K.Beach to Akkayapalem", "R.K.Beach to Kancharapalem", "Madhurawada to Maddilapalem", "Madhurawada to MVP", "Madhurawada to Complex", "Madhurawada to Seethammadara",
"Madhurawada to Kailasagiri", "Madhurawada to Submarine", "Madhurawada to ChinnaWaltair", "Madhurawada to PeddaWaltair",
"Madhurawada to Rushikonda", "Madhurawada to Vuda Park", "Madhurawada to Zoo", "Madhurawada to Simhachalam", "Madhurawada to Gajuwaka",
"Madhurawada to Akkayapalem", "Madhurawada to Kancharapalem", "Maddilapalem to MVP", "Maddilapalem to Complex", "Maddilapalem to Seethammadara",
"Maddilapalem to Kailasagiri", "Maddilapalem to Submarine", "Maddilapalem to ChinnaWaltair", "Maddilapalem to PeddaWaltair",
"Maddilapalem to Rushikonda", "Maddilapalem to Vuda Park", "Maddilapalem to Zoo", "Maddilapalem to Simhachalam", "Maddilapalem to Gajuwaka",
"Maddilapalem to Akkayapalem", "Maddilapalem to Kancharapalem", "MVP to Complex", "MVP to Seethammadara", "MVP to Kailasagiri", "MVP to Submarine", "MVP to ChinnaWaltair", "MVP to PeddaWaltair", "MVP to Rushikonda", "MVP to Vuda Park", "MVP to Zoo", "MVP to Simhachalam", "MVP to Gajuwaka", "MVP to Akkayapalem", "MVP to Kancharapalem", "Complex to Seethammadara", "Complex to Kailasagiri", "Complex to Submarine", "Complex to ChinnaWaltair", "Complex to PeddaWaltair",
"Complex to Rushikonda", "Complex to Vuda Park", "Complex to Zoo", "Complex to Simhachalam", "Complex to Gajuwaka", "Complex to Akkayapalem", "Complex to Kancharapalem", "Seethammadara to Kailasagiri", "Seethammadara to Submarine", "Seethammadara to ChinnaWaltair", "Seethammadara to PeddaWaltair",
"Seethammadara to Rushikonda", "Seethammadara to Vuda Park", "Seethammadara to Zoo", "Seethammadara to Simhachalam", "Seethammadara to Gajuwaka",
"Seethammadara to Akkayapalem", "Seethammadara to Kancharapalem", "Kailasagiri to Submarine", "Kailasagiri to ChinnaWaltair", "Kailasagiri to PeddaWaltair",
"Kailasagiri to Rushikonda", "Kailasagiri to Vuda Park", "Kailasagiri to Zoo", "Kailasagiri to Simhachalam", "Kailasagiri to Gajuwaka",
"Kailasagiri to Akkayapalem", "Kailasagiri to Kancharapalem", "Submarine to ChinnaWaltair", "Submarine to PeddaWaltair",
"Submarine to Rushikonda", "Submarine to Vuda Park", "Submarine to Zoo", "Submarine to Simhachalam", "Submarine to Gajuwaka",
"Submarine to Akkayapalem", "Submarine to Kancharapalem", "ChinnaWaltair to PeddaWaltair",
"ChinnaWaltair to Rushikonda", "ChinnaWaltair to Vuda Park", "ChinnaWaltair to Zoo", "ChinnaWaltair to Simhachalam", "ChinnaWaltair to Gajuwaka",
"ChinnaWaltair to Akkayapalem", "ChinnaWaltair to Kancharapalem", "PeddaWaltair to Rushikonda", "PeddaWaltair to Vuda Park", "PeddaWaltair to Zoo", "PeddaWaltair to Simhachalam", "PeddaWaltair to Gajuwaka",
"PeddaWaltair to Akkayapalem", "PeddaWaltair to Kancharapalem", "Rushikonda to Vuda Park", "Rushikonda to Zoo", "Rushikonda to Simhachalam", "Rushikonda to Gajuwaka",
"Rushikonda to Akkayapalem", "Rushikonda to Kancharapalem", "Vuda Park to Zoo", "Vuda Park to Simhachalam", "Vuda Park to Gajuwaka",
"Vuda Park to Akkayapalem", "Vuda Park to Kancharapalem", "ZOO to Simhachalam", "ZOO to Gajuwaka",
"ZOO to Akkayapalem", "ZOO to Kancharapalem", "Simhachalam to Gajuwaka", "Simhachalam to Akkayapalem", "Simhachalam to Kancharapalem", "Gajuwaka to Akkayapalem", "Gajuwaka to Kancharapalem", "Akkayapalem to Kancharapalem",
"ZillaParishad to R.K.Beach ", "ZillaParishad to Madhurawada", "ZillaParishad to Maddilapalem", "ZillaParishad to MVP", "ZillaParishad to Complex", "ZillaParishad to Seethammadara",
"ZillaParishad to Kailasagiri", "ZillaParishad to Submarine", "ZillaParishad to ChinnaWaltair", "ZillaParishad to PeddaWaltair",
"ZillaParishad to Rushikonda", "ZillaParishad to Vuda Park", "ZillaParishad to Zoo", "ZillaParishad to Simhachalam", "ZillaParishad to Gajuwaka",
"ZillaParishad to Akkayapalem", "ZillaParishad to Kancharapalem",
};
private ArrayList<String> listItem =new ArrayList<String>();
private ListView list;
private ImageView home;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadLocale();
setContentView(R.layout.activity_bus_fare);
home = findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), second.class));
}
});
//Adding elements to the arraylist
listItem = new ArrayList<>();
for(int i=0;i<from.length;i++)
{
listItem.add(from[i]);
}
//sorting the arraylist and the array
Collections.sort(listItem);
Arrays.sort(from);
list = (ListView) findViewById(R.id.lv5);
list.setOnItemClickListener(this);
//Setting the arraylist to listview
ArrayAdapter<String> ad = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
list.setAdapter(ad);
}
//function to goback to previous page or activity
public void gotoPrevious(View view){
finish();
}
/*
deals with action to be done after clicking an item in listview
*/
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent i1=new Intent(busFare.this,fares.class);
i1.putExtra("address",from[i].toString());
startActivity(i1);
}
} | [
"poduri.manohar46@gmal.com"
] | poduri.manohar46@gmal.com |
b64940d6fd710ad51031ed261f57e0662d83f90e | f662526b79170f8eeee8a78840dd454b1ea8048c | /ci$d.java | 16ae6588c94d62278c4e41e1f44d28a63135a0a9 | [] | no_license | jason920612/Minecraft | 5d3cd1eb90726efda60a61e8ff9e057059f9a484 | 5bd5fb4dac36e23a2c16576118da15c4890a2dff | refs/heads/master | 2023-01-12T17:04:25.208957 | 2020-11-26T08:51:21 | 2020-11-26T08:51:21 | 316,170,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 530 | java | import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.function.Supplier;
interface d {
ho a(ho paramho) throws CommandSyntaxException;
ho a(ho paramho, Supplier<ho> paramSupplier) throws CommandSyntaxException;
ho a();
void a(ho paramho1, ho paramho2) throws CommandSyntaxException;
void b(ho paramho) throws CommandSyntaxException;
}
/* Location: F:\dw\server.jar!\ci$d.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | [
"jasonya2206@gmail.com"
] | jasonya2206@gmail.com |
0bb95a170c8f17aa53deae962506b90ab62cfea2 | 7dd2de1fc260c1c570140efb0afdd119226b2e1e | /packages/internal/multiLayerPerceptrons/src/main/java/weka/classifiers/functions/activation/ApproximateSigmoid.java | 65b6f8618ede19cddad8e9e2f0b166c1378cfe9b | [] | no_license | Waikato/weka-3.8 | 489f7f6feb505c7f77d8a5f151e9b7b201938fb4 | 04804ccd6dff03534cbf3f2a71a35c73eef24fe8 | refs/heads/master | 2022-08-16T10:09:53.720693 | 2022-08-10T01:25:51 | 2022-08-10T01:25:51 | 135,419,657 | 198 | 144 | null | 2022-07-06T20:07:39 | 2018-05-30T09:25:20 | Java | UTF-8 | Java | false | false | 1,976 | java | /*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* ApproximateSigmoid.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.functions.activation;
/**
* <!-- globalinfo-start -->
* Computes approximate (fast) version of sigmoid activation function f(x) = 1 / (1 + e^(-x))
* <br><br>
* <!-- globalinfo-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 10949 $
*/
public class ApproximateSigmoid implements ActivationFunction {
/**
* Returns info for this class.
*/
public String globalInfo() {
return "Computes approximate (fast) version of sigmoid activation function f(x) = 1 / (1 + e^(-x))";
}
/**
* Computes approximate sigmoid function. Derivative is stored in d at position index if argument d != null.
*/
public double activation(double x, double[] d, int index) {
// Compute approximate sigmoid
double y = 1.0 + (-x) / 4096.0;
x = y * y;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
double output = 1.0 / (1.0 + x);
// Compute derivative if desired
if (d != null) {
d[index] = output * (1.0 - output) / y;
}
return output;
}
}
| [
"mhall@e0a1b77d-ad91-4216-81b1-defd5f83fa92"
] | mhall@e0a1b77d-ad91-4216-81b1-defd5f83fa92 |
549f41b389338d6bb6f8574ffae9efabd86ccd56 | 383d87a2843d091efd6d25d83ac665ed9e8a69f1 | /snaker-core/src/main/java/org/snaker/engine/core/OrderService.java | efcc0fe11e560998c48739ffbb57aa54930e4b5b | [
"Apache-2.0"
] | permissive | ocoer/snakerflow | 21846b9543ca3931968c67e749ad61d22790fc34 | df54476e078c185e0979d8fb966f2eac1ef45038 | refs/heads/master | 2021-06-01T15:50:00.827550 | 2015-11-13T07:11:45 | 2015-11-13T07:11:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,341 | java | /* Copyright 2013-2015 www.snakerflow.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.snaker.engine.core;
import java.util.List;
import java.util.Map;
import org.snaker.engine.Completion;
import org.snaker.engine.IOrderService;
import org.snaker.engine.SnakerEngine;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.*;
import org.snaker.engine.entity.Process;
import org.snaker.engine.entity.var.Variable;
import org.snaker.engine.helper.AssertHelper;
import org.snaker.engine.helper.DateHelper;
import org.snaker.engine.helper.StringHelper;
import org.snaker.engine.model.ProcessModel;
/**
* 流程实例业务类
* @author yuqs
* @since 1.0
*/
public class OrderService extends AccessService implements IOrderService {
/**
* 创建活动实例
* @see org.snaker.engine.core.OrderService#createOrder(Process, String, Map, String, String)
*/
public Order createOrder(Process process, String operator, Map<String, Object> args) {
return createOrder(process, operator, args, null, null);
}
/**
* 创建活动实例
*/
public Order createOrder(Process process, String operator, Map<String, Object> args,
String parentId, String parentNodeName) {
Order order = new Order();
order.setId(StringHelper.getPrimaryKey());
order.setParentId(parentId);
order.setParentNodeName(parentNodeName);
order.setCreateTime(DateHelper.getTime());
order.setLastUpdateTime(order.getCreateTime());
order.setCreator(operator);
order.setLastUpdator(order.getCreator());
order.setProcessId(process.getId());
ProcessModel model = process.getModel();
if(model != null && args != null) {
if(StringHelper.isNotEmpty(model.getExpireTime())) {
String expireTime = DateHelper.parseTime(args.get(model.getExpireTime()));
order.setExpireTime(expireTime);
}
String orderNo = (String)args.get(SnakerEngine.ID);
if(StringHelper.isNotEmpty(orderNo)) {
order.setOrderNo(orderNo);
} else {
order.setOrderNo(model.getGenerator().generate(model));
}
}
order.createVariables(args);
saveOrder(order);
return order;
}
/**
* 创建实例的抄送
*/
public void createCCOrder(String orderId, String creator, String... actorIds) {
for(String actorId : actorIds) {
CCOrder ccorder = new CCOrder();
ccorder.setOrderId(orderId);
ccorder.setActorId(actorId);
ccorder.setCreator(creator);
ccorder.setStatus(STATE_ACTIVE);
ccorder.setCreateTime(DateHelper.getTime());
access().saveCCOrder(ccorder);
}
}
/**
* 流程实例数据会保存至活动实例表、历史实例表
*/
public void saveOrder(Order order) {
HistoryOrder history = new HistoryOrder(order);
history.setOrderState(STATE_ACTIVE);
access().saveOrder(order);
access().saveHistory(history);
}
/**
* 更新活动实例的last_Updator、last_Update_Time、expire_Time、version
*/
public void updateOrder(Order order) {
access().updateOrder(order);
}
/**
* 更新抄送记录状态为已阅
*/
public void updateCCStatus(String orderId, String... actorIds) {
List<CCOrder> ccorders = access().getCCOrder(orderId, actorIds);
AssertHelper.notNull(ccorders);
for(CCOrder ccorder : ccorders) {
ccorder.setStatus(STATE_FINISH);
ccorder.setFinishTime(DateHelper.getTime());
access().updateCCOrder(ccorder);
}
}
/**
* 删除指定的抄送记录
*/
public void deleteCCOrder(String orderId, String actorId) {
List<CCOrder> ccorders = access().getCCOrder(orderId, actorId);
AssertHelper.notNull(ccorders);
for(CCOrder ccorder : ccorders) {
access().deleteCCOrder(ccorder);
}
}
/**
* 删除活动流程实例数据,更新历史流程实例的状态、结束时间
*/
public void complete(String orderId) {
Order order = access().getOrder(orderId);
HistoryOrder history = access().getHistOrder(orderId);
history.setOrderState(STATE_FINISH);
history.setEndTime(DateHelper.getTime());
access().updateHistory(history);
access().deleteOrder(order);
getCompletion().complete(history);
}
/**
* 强制中止流程实例
* @see org.snaker.engine.core.OrderService#terminate(String, String)
*/
public void terminate(String orderId) {
terminate(orderId, null);
}
/**
* 强制中止活动实例,并强制完成活动任务
*/
public void terminate(String orderId, String operator) {
SnakerEngine engine = ServiceContext.getEngine();
List<Task> tasks = engine
.query()
.getActiveTasks(new QueryFilter().setOrderId(orderId));
for(Task task : tasks) {
engine.task().complete(task.getId(), operator);
}
Order order = access().getOrder(orderId);
HistoryOrder history = new HistoryOrder(order);
history.setOrderState(STATE_TERMINATION);
history.setEndTime(DateHelper.getTime());
access().updateHistory(history);
access().deleteOrder(order);
getCompletion().complete(history);
}
/**
* 激活已完成的历史流程实例
* @param orderId 实例id
* @return 活动实例对象
*/
public Order resume(String orderId) {
HistoryOrder historyOrder = access().getHistOrder(orderId);
Order order = historyOrder.undo();
access().saveOrder(order);
historyOrder.setOrderState(STATE_ACTIVE);
access().updateHistory(historyOrder);
SnakerEngine engine = ServiceContext.getEngine();
List<HistoryTask> histTasks = access().getHistoryTasks(null,
new QueryFilter().setOrderId(orderId));
if(histTasks != null && !histTasks.isEmpty()) {
HistoryTask histTask = histTasks.get(0);
engine.task().resume(histTask.getId(), histTask.getOperator());
}
return order;
}
/**
* 级联删除指定流程实例的所有数据:
* 1.wf_order,wf_hist_order
* 2.wf_task,wf_hist_task
* 3.wf_task_actor,wf_hist_task_actor
* 4.wf_cc_order
* @param id 实例id
*/
public void cascadeRemove(String id) {
HistoryOrder historyOrder = access().getHistOrder(id);
AssertHelper.notNull(historyOrder);
List<Task> activeTasks = access().getActiveTasks(null, new QueryFilter().setOrderId(id));
List<HistoryTask> historyTasks = access().getHistoryTasks(null, new QueryFilter().setOrderId(id));
for(Task task : activeTasks) {
access().deleteTask(task);
}
for(HistoryTask historyTask : historyTasks) {
access().deleteHistoryTask(historyTask);
}
List<CCOrder> ccOrders = access().getCCOrder(id);
for(CCOrder ccOrder : ccOrders) {
access().deleteCCOrder(ccOrder);
}
Order order = access().getOrder(id);
access().deleteHistoryOrder(historyOrder);
if(order != null) {
access().deleteOrder(order);
}
}
}
| [
"snakerflow@163.com"
] | snakerflow@163.com |
f1110e01f2cceb4cba11e636b1a2168832fdd9ba | 6482753b5eb6357e7fe70e3057195e91682db323 | /io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java | d70e7454c35d4a897d59b04d974059344e108844 | [] | no_license | TheShermanTanker/Server-1.16.3 | 45cf9996afa4cd4d8963f8fd0588ae4ee9dca93c | 48cc08cb94c3094ebddb6ccfb4ea25538492bebf | refs/heads/master | 2022-12-19T02:20:01.786819 | 2020-09-18T21:29:40 | 2020-09-18T21:29:40 | 296,730,962 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,689 | java | package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelFuture;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
public class WebSocketServerHandshakerFactory {
private final String webSocketURL;
private final String subprotocols;
private final boolean allowExtensions;
private final int maxFramePayloadLength;
private final boolean allowMaskMismatch;
public WebSocketServerHandshakerFactory(final String webSocketURL, final String subprotocols, final boolean allowExtensions) {
this(webSocketURL, subprotocols, allowExtensions, 65536);
}
public WebSocketServerHandshakerFactory(final String webSocketURL, final String subprotocols, final boolean allowExtensions, final int maxFramePayloadLength) {
this(webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, false);
}
public WebSocketServerHandshakerFactory(final String webSocketURL, final String subprotocols, final boolean allowExtensions, final int maxFramePayloadLength, final boolean allowMaskMismatch) {
this.webSocketURL = webSocketURL;
this.subprotocols = subprotocols;
this.allowExtensions = allowExtensions;
this.maxFramePayloadLength = maxFramePayloadLength;
this.allowMaskMismatch = allowMaskMismatch;
}
public WebSocketServerHandshaker newHandshaker(final HttpRequest req) {
final CharSequence version = (CharSequence)req.headers().get((CharSequence)HttpHeaderNames.SEC_WEBSOCKET_VERSION);
if (version == null) {
return new WebSocketServerHandshaker00(this.webSocketURL, this.subprotocols, this.maxFramePayloadLength);
}
if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) {
return new WebSocketServerHandshaker13(this.webSocketURL, this.subprotocols, this.allowExtensions, this.maxFramePayloadLength, this.allowMaskMismatch);
}
if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) {
return new WebSocketServerHandshaker08(this.webSocketURL, this.subprotocols, this.allowExtensions, this.maxFramePayloadLength, this.allowMaskMismatch);
}
if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) {
return new WebSocketServerHandshaker07(this.webSocketURL, this.subprotocols, this.allowExtensions, this.maxFramePayloadLength, this.allowMaskMismatch);
}
return null;
}
@Deprecated
public static void sendUnsupportedWebSocketVersionResponse(final Channel channel) {
sendUnsupportedVersionResponse(channel);
}
public static ChannelFuture sendUnsupportedVersionResponse(final Channel channel) {
return sendUnsupportedVersionResponse(channel, channel.newPromise());
}
public static ChannelFuture sendUnsupportedVersionResponse(final Channel channel, final ChannelPromise promise) {
final HttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UPGRADE_REQUIRED);
res.headers().set((CharSequence)HttpHeaderNames.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue());
HttpUtil.setContentLength(res, 0L);
return channel.writeAndFlush(res, promise);
}
}
| [
"tanksherman27@gmail.com"
] | tanksherman27@gmail.com |
50a600ba1e22d1ead25393777018effb32d8ba11 | 945856661a4b3c072b4cebab10ea359f5558fdc2 | /src/main/java/com/fishercoder/solutions/LongestConsecutiveSequence.java | 65982fae89c35274869fada4b1526c2e1c616313 | [
"Apache-2.0"
] | permissive | udayinfy/Leetcode | 8a6c7c44d4f4f640b121586b547b22d7f278c493 | cba27f192c604872758ae08058d3c25ad2717e9d | refs/heads/master | 2021-01-01T18:43:55.713474 | 2017-07-26T05:02:15 | 2017-07-26T05:02:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,113 | java | package com.fishercoder.solutions;
import java.util.*;
/**
* Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
*/
public class LongestConsecutiveSequence {
//inspired by this solution: https://discuss.leetcode.com/topic/29286/my-java-solution-using-unionfound
public int longestConsecutive(int[] nums) {
Map<Integer, Integer> map = new HashMap();//<value, index>
UnionFind uf = new UnionFind(nums);
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])) continue;
map.put(nums[i], i);
if(map.containsKey(nums[i]-1)){
uf.union(i, map.get(nums[i]-1));//note: we want to union this index and nums[i]-1's root index which we can get from the map
}
if(map.containsKey(nums[i]+1)){
uf.union(i, map.get(nums[i]+1));
}
}
return uf.maxUnion();
}
class UnionFind{
int[] ids;
public UnionFind(int[] nums){
ids = new int[nums.length];
for(int i = 0; i < nums.length; i++) ids[i] = i;
}
public void union(int i, int j){
int x = find(ids, i);
int y = find(ids, j);
ids[x] = y;
}
public int find(int[] ids, int i){
while(i != ids[i]){
ids[i] = ids[ids[i]];
i = ids[i];
}
return i;
}
public boolean connected(int i, int j){
return find(ids, i) == find(ids, j);
}
public int maxUnion(){//this is O(n)
int max = 0;
int[] count = new int[ids.length];
for(int i = 0; i < ids.length; i++){
count[find(ids, i)]++;
max = max < count[find(ids, i)] ? count[find(ids, i)] : max;
}
return max;
}
}
class Solution_using_HashSet{
//inspired by this solution: https://discuss.leetcode.com/topic/25493/simple-fast-java-solution-using-set
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0) return 0;
Set<Integer> set = new HashSet();
for(int i : nums) set.add(i);
int max = 1;
for(int num : nums){
if(set.remove(num)){
int val = num;
int count = 1;
while(set.remove(val-1)) val--;//we find all numbers that are smaller than num and remove them from the set
count += num - val;
val = num;
while(set.remove(val+1)) val++;//then we find all numbers that are bigger than num and also remove them from the set
count += val - num;
max = Math.max(max, count);
}
}
return max;
}
}
}
| [
"stevesun@coupang.com"
] | stevesun@coupang.com |
257bd3a10f7797f7bbb5f970c2c4f69427680f27 | 56b07d4a869e0ad42f6c53924e59f837d19a5de8 | /core/framework/src/main/java/org/phoebus/framework/macros/Macros.java | 660019ba90ac7110287dad0e6fe628502a746abf | [] | no_license | lemrose/phoebus | 517075dc6b62177f1e5f1a48a5d9f7f778e8abfb | f42312b95580d4547abcae1e8f540250666e68ba | refs/heads/master | 2020-05-19T10:24:07.879622 | 2019-05-03T15:47:38 | 2019-05-03T15:47:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,406 | java | /*******************************************************************************
* Copyright (c) 2015-2018 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.phoebus.framework.macros;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/** Macro information
*
* <p>Holds macros and their value
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class Macros implements MacroValueProvider
{
// Using linked map for predictable order.
//
// Example, a tool that tries to first "save" a current macro value in another macro,
// then set it to a new value like this depends on the order of macros:
// SAVE = $(M), M = "new value"
//
// (At the same time, getNames() always sorts alphabetically, so does order still matter?)
//
// SYNC on access
private final Map<String, String> macros = new LinkedHashMap<>();
public final static Pattern MACRO_NAME_PATTERN = Pattern.compile("[A-Za-z][A-Za-z0-9_.\\-\\[\\]]*");
/** Check macro name
*
* <p>Permitted macro names are a subset of valid XML names:
* <ul>
* <li>Must start with character
* <li>May then contain characters or numbers
* <li>May also contain underscores
* <li>This check also permits brackets and dots
* for path-type properties like "traces[1].name"
* </ul>
* @param name Macro name to check
* @return Error message or <code>null</code> if name is valid
*/
public static String checkMacroName(final String name)
{
// Could use one big reg.ex. but try to provide error message for each case.
if (name == null || name.isEmpty())
return "Empty macro name";
if (name.indexOf('$') >= 0)
return "Macro name '" + name + "' contains recursive macro";
if (! MACRO_NAME_PATTERN.matcher(name).matches())
return "Invalid macro name '" + name + "': Must start with character, then contain characters, numbers or underscores";
if (name.toLowerCase().startsWith("xml"))
return "Invalid macro name '" + name + "': Must not start with 'XML' or 'xml'";
return null;
}
/** Parse macro information from "macro1=value1, macro2=value2" type text
*
* <p>Format:
* Macro name as described in {{@link #checkMacroName(String)},
* followed by '=' and value.
* Surrounding spaces are removed, and comma separates subsequent macro and value:
* <pre> M1 = Value1 , M2 = Value2 </pre>
*
* <p>Value must be enclosed in '"' quotes if it contains surrounding spaces or comma:
* <pre> MSG = "This is a message with comma, quoted!" , M2 = Value2 </pre>
*
* To include quotes in the value, the value must be quoted and the embedded quotes
* escaped:
* <pre> MSG = "This is a \"Message\""</pre>
*
* @param names_and_values
* @throws Exception
*/
public static Macros fromSimpleSpec(final String names_and_values) throws Exception
{
final Macros macros = new Macros();
final int len = names_and_values.length();
int pos = 0;
while (pos < len)
{
// Locate next '=' in name = value
final int sep = names_and_values.indexOf('=', pos);
if (sep < 0)
break;
// Fetch name
String name = names_and_values.substring(pos, sep).trim();
String error = checkMacroName(name);
if (error != null)
throw new Exception("Error parsing '" + names_and_values + "': " + error);
// Fetch value
String value = null;
pos = sep + 1;
int end = pos;
// Locate end, either a ',' or via quoted text
while (true)
{
if (end >= len)
{
value = names_and_values.substring(pos, end).trim();
break;
}
char c = names_and_values.charAt(end);
if (c == ',')
{
value = names_and_values.substring(pos, end).trim();
++end;
break;
}
if (c == '"')
{
// Locate end of quoted text, skipping escaped quotes
int close = end+1;
while (close < len)
{
if (names_and_values.charAt(close) == '"' &&
names_and_values.charAt(close-1) != '\\')
{
value = names_and_values.substring(end+1, close).replace("\\", "");
// Advance to ',' or end
end = close+1;
while (end < len &&
(names_and_values.charAt(end) == ' ' ||
names_and_values.charAt(end) == ','))
++end;
break;
}
++close;
}
break;
}
++end;
}
if (value == null)
throw new Exception("Error parsing '" + names_and_values + "': Missing value");
macros.add(name, value);
pos = end;
}
return macros;
}
/** Create empty macro map */
public Macros()
{
}
/** Create copy of existing macros
* @param other The source macros to be copied.
*/
public Macros(final Macros other)
{
if (other != null)
synchronized (other.macros)
{
synchronized (macros)
{
macros.putAll(other.macros);
}
}
}
/** @return Are the macros empty? */
public boolean isEmpty()
{
synchronized (macros)
{
return macros.isEmpty();
}
}
/** Merge two macro maps
*
* <p>Optimized for cases where <code>base</code> or <code>addition</code> are empty,
* but will never _change_ any macros.
* If a merge is necessary, it returns a new <code>Macros</code> instance.
*
* @param base Base macros
* @param addition Additional macros that may override 'base'
* @return Merged macros
*/
public static Macros merge(final Macros base, final Macros addition)
{
// Optimize if one is empty
if (addition == null || addition.isEmpty())
return base;
if (base == null || base.isEmpty())
return addition;
// Construct new macros
final Macros merged = new Macros();
synchronized (base.macros)
{
merged.macros.putAll(base.macros);
}
synchronized (addition.macros)
{
merged.macros.putAll(addition.macros);
}
return merged;
}
/** Add a macro
* @param name Name of the macro
* @param value Value of the macro
* @throws IllegalArgumentException for illegal macro name
* @see #checkMacroName(String)
*/
public void add(final String name, final String value)
{
final String error = checkMacroName(name);
if (error != null)
throw new IllegalArgumentException(error);
synchronized (macros)
{
macros.put(name, value);
}
}
/** @return Macro names, sorted alphabetically */
public Collection<String> getNames()
{
final List<String> names;
synchronized (macros)
{
names = new ArrayList<>(macros.keySet());
}
Collections.sort(names);
return names;
}
/** Perform given action for each name/value (names are not sorted)
* @param action Invoked with each name/value
*/
public void forEach(final BiConsumer<String, String> action)
{
synchronized (macros)
{
macros.forEach(action);
}
}
/** Expand values of all macros
* @param input Value provider, usually from the 'parent' widget
* @throws Exception on error
*/
public void expandValues(final MacroValueProvider input) throws Exception
{
synchronized (macros)
{
for (String name : macros.keySet())
{
final String orig = macros.get(name);
final String expanded = MacroHandler.replace(input, orig);
if (! expanded.equals(orig))
macros.put(name, expanded);
}
}
}
/** {@inheritDoc} */
@Override
public String getValue(final String name)
{
synchronized (macros)
{
return macros.get(name);
}
}
// Hash based on content
@Override
public int hashCode()
{
synchronized (macros)
{
return macros.hashCode();
}
}
// Compare based on content
@Override
public boolean equals(final Object obj)
{
if (! (obj instanceof Macros))
return false;
final Macros other = (Macros) obj;
synchronized (other.macros)
{
synchronized (macros)
{
return other.macros.equals(macros);
}
}
}
/** @return String representation for debugging */
@Override
public String toString()
{
synchronized (macros)
{
return "[" + getNames().stream()
.map((macro) -> macro + " = '" + macros.get(macro) + "'")
.collect(Collectors.joining(", ")) +
"]";
}
}
}
| [
"kay.kasemir@gmail.com"
] | kay.kasemir@gmail.com |
141b7376802141c1e6620707b4a0357e5338c5c2 | 5b5deea6fa7bffcd478aa715969a008a108ee749 | /app/src/main/java/com/vector/say_it/requestHandlerCallback.java | d59726f5e3a45f67ea8a83c9f5eda266b3e5effd | [
"MIT"
] | permissive | Vector26/Vector26-SAY-IT | 78a52dbbaa8e09e1c3d66a1bd5e09cfb550643d3 | df6eba2ed2152e0204d63f14aeda61ffaec8f7a8 | refs/heads/master | 2023-04-12T05:07:15.881071 | 2021-05-13T07:50:09 | 2021-05-13T07:50:09 | 364,874,810 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | package com.vector.say_it;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
public interface requestHandlerCallback {
void callback(JSONObject response);
void callback(JSONArray response);
void callbackError(VolleyError e);
}
| [
"mrdev2604@gmail.com"
] | mrdev2604@gmail.com |
0754d84943774f59acdaa1a8d0c9afeddfc06fd1 | f4bd39738bb9b4132a91789d24a12f06ec7b1479 | /SpringBoot2.0+SpringDataJPA/src/main/java/com/jane/service/impl/UserServiceImpl.java | a191c7e0fbdb1590c09375dd90e9f8ebcc1897ae | [] | no_license | 1290962959/SpringBoot | a1a449fd1cae5f684f49e1280338f061f004a1db | 1e0735589def6d65956df4c1a0acb610899a9d2a | refs/heads/master | 2021-02-17T13:53:54.140626 | 2019-12-27T08:49:39 | 2019-12-27T08:49:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 636 | java | package com.jane.service.impl;
import com.jane.dao.UserRepository;
import com.jane.service.UserServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
/**
* Created by Janus on 2018/9/10.
*/
@Service
public class UserServiceImpl implements UserServcie{
@Autowired
UserRepository userRepository;
@Transactional
public int updateEmailById(Integer id, String email) {
System.out.println("进入Service方法。。。");
int i = userRepository.updateEmailById(id, email);
return i;
}
}
| [
"1274654983@qq.com"
] | 1274654983@qq.com |
13360c8ee1181e2fd25fd2299324f31b749334dd | 88663377073ea05b80bf03dc14209de4dbe98a35 | /Remember4Ever/src/net/CharList.java | a4a329e0c3270dc41837791b9052dbd30870d3bb | [] | no_license | Nitrogen-Dioxide/NitroDioxide | 550e9dde09e6f23a629a4863bb7b8e4cd49935d5 | 90be6cdfe9b28b14494d5f7b69c1ffb27e52666b | refs/heads/master | 2016-09-05T14:51:04.367119 | 2015-09-18T14:51:45 | 2015-09-18T14:51:45 | 40,451,217 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 230 | java | package net;
public class CharList {
public static void main(String[] args) {
// TODO Auto-generated method stub
char c;
for(int x = 0; x <= 127; x++){
c = (char) x;
System.out.println(x + " = " + c);
}
}
}
| [
"nitrogen.dioxide99@gmail.com"
] | nitrogen.dioxide99@gmail.com |
f2b3de749c35550c3d1faa1bf94f87e52eb6cc23 | 6d0b9c96b7824610d59047e3b3651147ea5cedc3 | /Projet_DevOO_2013/exemple/src/bibliothequesTiers/ExampleFileFilter.java | 32c088900517f37292a89561b0c37ff487403057 | [] | no_license | ilerviraragavane/DevooProject | 31b7310960a41db124fde0fa2ab492b07a31c46b | 00b015d70a2253b8f5c9813e096c50cab8e7f136 | refs/heads/master | 2021-01-19T15:34:51.892548 | 2014-11-30T15:38:05 | 2014-11-30T15:38:05 | 27,340,745 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,611 | java | package bibliothequesTiers;
/*
* @(#)ExampleFileFilter.java 1.16 04/07/26
*
* Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* @(#)ExampleFileFilter.java 1.16 04/07/26
*/
import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.filechooser.*;
/**
* A convenience implementation of FileFilter that filters out
* all files except for those type extensions that it knows about.
*
* Extensions are of the type ".foo", which is typically found on
* Windows and Unix boxes, but not on Macinthosh. Case is ignored.
*
* Example - create a new filter that filerts out all files
* but gif and jpg image files:
*
* JFileChooser chooser = new JFileChooser();
* ExampleFileFilter filter = new ExampleFileFilter(
* new String{"gif", "jpg"}, "JPEG & GIF Images")
* chooser.addChoosableFileFilter(filter);
* chooser.showOpenDialog(this);
*
* @version 1.16 07/26/04
* @author Jeff Dinkins
*/
public class ExampleFileFilter extends FileFilter {
private static String TYPE_UNKNOWN = "Type Unknown";
private static String HIDDEN_FILE = "Hidden File";
private Hashtable filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
/**
* Creates a file filter. If no filters are added, then all
* files are accepted.
*
* @see #addExtension
*/
public ExampleFileFilter() {
this.filters = new Hashtable();
}
/**
* Creates a file filter that accepts files with the given extension.
* Example: new ExampleFileFilter("jpg");
*
* @see #addExtension
*/
public ExampleFileFilter(String extension) {
this(extension,null);
}
/**
* Creates a file filter that accepts the given file type.
* Example: new ExampleFileFilter("jpg", "JPEG Image Images");
*
* Note that the "." before the extension is not needed. If
* provided, it will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String extension, String description) {
this();
if(extension!=null) addExtension(extension);
if(description!=null) setDescription(description);
}
/**
* Creates a file filter from the given string array.
* Example: new ExampleFileFilter(String {"gif", "jpg"});
*
* Note that the "." before the extension is not needed adn
* will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String[] filters) {
this(filters, null);
}
/**
* Creates a file filter from the given string array and description.
* Example: new ExampleFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
*
* Note that the "." before the extension is not needed and will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String[] filters, String description) {
this();
for (int i = 0; i < filters.length; i++) {
// add filters one by one
addExtension(filters[i]);
}
if(description!=null) setDescription(description);
}
/**
* Return true if this file should be shown in the directory pane,
* false if it shouldn't.
*
* Files that begin with "." are ignored.
*
* @see #getExtension
* @see FileFilter#accepts
*/
public boolean accept(File f) {
if(f != null) {
if(f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if(extension != null && filters.get(getExtension(f)) != null) {
return true;
};
}
return false;
}
/**
* Return the extension portion of the file's name .
*
* @see #getExtension
* @see FileFilter#accept
*/
public String getExtension(File f) {
if(f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
return filename.substring(i+1).toLowerCase();
};
}
return null;
}
/**
* Adds a filetype "dot" extension to filter against.
*
* For example: the following code will create a filter that filters
* out all files except those that end in ".jpg" and ".tif":
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("jpg");
* filter.addExtension("tif");
*
* Note that the "." before the extension is not needed and will be ignored.
*/
public void addExtension(String extension) {
if(filters == null) {
filters = new Hashtable(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
/**
* Returns the human readable description of this filter. For
* example: "JPEG and GIF Image Files (*.jpg, *.gif)"
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
* @see FileFilter#getDescription
*/
public String getDescription() {
if(fullDescription == null) {
if(description == null || isExtensionListInDescription()) {
fullDescription = description==null ? "(" : description + " (";
// build the description from the extension list
Enumeration extensions = filters.keys();
if(extensions != null) {
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", ." + (String) extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
/**
* Sets the human readable description of this filter. For
* example: filter.setDescription("Gif and JPG Images");
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
*/
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
/**
* Determines whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see isExtensionListInDescription
*/
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
/**
* Returns whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see setExtensionListInDescription
*/
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}
| [
"iler.viraragavane@gmail.com"
] | iler.viraragavane@gmail.com |
f7f3dd9ec66bf8a7c10412b6dcbd2df265a3473d | 782a48edbc0567290cfe99510ba243b3a29ecd39 | /Week_04/Walking_Robot_Simulation_874.java | 59b755d841d38cf2c67d0282119709574dd746ad | [] | no_license | CodeFlow-Jun/algorithm016 | 093ab72033817065d2c649ac38d6475cc8bf1506 | 6f80b4e5716552cfe31be5784d92c70f4c5b6b57 | refs/heads/master | 2023-01-07T23:20:59.334186 | 2020-11-08T05:55:23 | 2020-11-08T05:55:23 | 292,844,687 | 1 | 0 | null | 2020-09-04T12:39:15 | 2020-09-04T12:39:14 | null | UTF-8 | Java | false | false | 1,290 | java | package com.company;
import java.util.HashSet;
import java.util.Set;
public class Walking_Robot_Simulation_874 {
public int robotSim(int[] commands, int[][] obstacles) {
int[][] dir = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int x = 0, y=0;
int dir_index=0;
int ans = 0;
Set<String> blockSet = new HashSet<String>();
for (int i=0;i<obstacles.length;i++) {
blockSet.add(obstacles[i][0]+","+obstacles[i][1]);
}
for (int i=0;i<commands.length;i++) {
if (commands[i]==-1) {
dir_index=(dir_index+1)%4;
}else if (commands[i]==-2) {
dir_index=(dir_index+3)%4;
}
else if (commands[i]>0) {
for (int j=1;j<=commands[i];j++) {
int next_x = x+ dir[dir_index][0];
int next_y = y+ dir[dir_index][1];
if (blockSet.contains(next_x+","+next_y)) {
break;
}else {
x = next_x;
y = next_y;
ans = Math.max(ans, x*x+y*y);
}
}
}
}
return ans;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a19c58a87099a6c470c1edf0d668b7671b205c6a | 275174da3e602aa775190da7f2c9d57b711bb366 | /64.最小路径和.java | a6839d19d40a1d7018dadc18e3656ee2e8525eb3 | [] | no_license | StormTian/LeetCode | a0551a0aff73147e9bfc89cf5b507a6e2e792201 | 05d5f915c791731a614ceb928f9b08ea501fa41e | refs/heads/main | 2023-07-13T19:35:35.504549 | 2021-08-25T05:23:17 | 2021-08-25T05:23:17 | 305,655,930 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | /*
* @lc app=leetcode.cn id=64 lang=java
*
* [64] 最小路径和
*/
// @lc code=start
class Solution {
public int minPathSum(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int[][] res = new int[n][m];
res[0][0] = grid[0][0];
for(int i = 1; i < n; i ++){
res[i][0] = res[i - 1][0] + grid[i][0];
}
for(int j = 1; j < m; j ++){
res[0][j] = res[0][j - 1] + grid[0][j];
}
for(int i = 1; i < n; i ++){
for(int j = 1; j < m; j ++){
res[i][j] = Math.min(res[i - 1][j], res[i][j - 1])+ grid[i][j];
}
}
return res[n - 1][m - 1];
}
}
// @lc code=end
| [
"tianxuejian@taptap.com"
] | tianxuejian@taptap.com |
f1aa89ab9f5a3a257f9caff4b42ad010e3820624 | 9f38bedf3a3365fdd8b78395930979a41330afc8 | /tags/dec21_before_sci2/scipolicy/plugins/normal_plugins/edu.iu.scipolicy.database.isi.load/src/edu/iu/scipolicy/database/isi/load/model/entity/Person.java | 9ce0c007453944d6f6aa81f81381b1d3a51dfe81 | [] | no_license | project-renard-survey/nwb | 6a6ca10abb1e65163374d251be088e033bf3c6e0 | 612f215ac032e14669b3e8f75bc13ac0d4eda9dc | refs/heads/master | 2020-04-01T16:11:01.156528 | 2015-08-03T18:30:34 | 2015-08-03T18:30:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,350 | java | package edu.iu.scipolicy.database.isi.load.model.entity;
import java.util.Dictionary;
import java.util.Hashtable;
import org.cishell.utilities.dictionary.DictionaryEntry;
import org.cishell.utilities.dictionary.DictionaryUtilities;
import edu.iu.cns.database.load.framework.DerbyFieldType;
import edu.iu.cns.database.load.framework.Entity;
import edu.iu.cns.database.load.framework.Schema;
import edu.iu.cns.database.load.framework.utilities.DatabaseTableKeyGenerator;
import edu.iu.nwb.shared.isiutil.database.ISI;
import edu.iu.scipolicy.database.isi.load.utilities.parser.PersonParser;
import edu.iu.scipolicy.database.isi.load.utilities.parser.exception.PersonParsingException;
public class Person extends Entity<Person> {
public static final Schema<Person> SCHEMA = new Schema<Person>(
true,
ISI.ADDITIONAL_NAME, DerbyFieldType.TEXT,
ISI.FAMILY_NAME, DerbyFieldType.TEXT,
ISI.FIRST_INITIAL, DerbyFieldType.TEXT,
ISI.FULL_NAME, DerbyFieldType.TEXT,
ISI.MIDDLE_INITIAL, DerbyFieldType.TEXT,
ISI.PERSONAL_NAME, DerbyFieldType.TEXT,
ISI.UNSPLIT_ABBREVIATED_NAME, DerbyFieldType.TEXT);
private String fullName;
private String unsplitAbbreviatedName;
public Person(
DatabaseTableKeyGenerator keyGenerator,
String unsplitAbbreviatedName,
String fullName) {
super(
keyGenerator,
new Hashtable<String, Object>());
this.unsplitAbbreviatedName = unsplitAbbreviatedName;
this.fullName = fullName;
}
public String getFullName() {
return this.fullName;
}
public String getUnsplitAbbreviatedName() {
return this.unsplitAbbreviatedName;
}
@Override
public Dictionary<String, Object> getAttributesForInsertion() {
Dictionary<String, Object> attributes = DictionaryUtilities.copy(super.getAttributes());
try {
PersonParser personParsingResult =
new PersonParser(this.unsplitAbbreviatedName, this.fullName);
fillAttributes(
attributes,
personParsingResult.getUnsplitAbbreviatedName(),
personParsingResult.getFullName(),
personParsingResult.getAdditionalName(),
personParsingResult.getFamilyName(),
personParsingResult.getFirstInitial(),
personParsingResult.getMiddleInitial(),
personParsingResult.getPersonalName());
} catch (PersonParsingException e) {}
return attributes;
}
@Override
public Object createMergeKey() {
return getPrimaryKey();
}
@Override
public void merge(Person otherPerson) {
}
private static void fillAttributes(
Dictionary<String, Object> attributes,
String unsplitAbbreviatedName,
String fullName,
String additionalName,
String familyName,
String firstInitial,
String middleInitial,
String personalName) {
DictionaryUtilities.addIfNotNull(
attributes,
new DictionaryEntry<String, Object>(
ISI.UNSPLIT_ABBREVIATED_NAME, unsplitAbbreviatedName),
new DictionaryEntry<String, Object>(ISI.FULL_NAME, fullName),
new DictionaryEntry<String, Object>(ISI.ADDITIONAL_NAME, additionalName),
new DictionaryEntry<String, Object>(ISI.FAMILY_NAME, familyName),
new DictionaryEntry<String, Object>(ISI.FIRST_INITIAL, firstInitial),
new DictionaryEntry<String, Object>(ISI.MIDDLE_INITIAL, middleInitial),
new DictionaryEntry<String, Object>(ISI.PERSONAL_NAME, personalName));
}
} | [
"kongch@indiana.edu"
] | kongch@indiana.edu |
70aacf895e24bf670da0cbfdd831917094c97a63 | eadf8a74ba0bd887f9fb0fbde1509bd934c7f9c8 | /cci/ArraysAndStrings/RotateMatrix.java | af0b460339fd29e437195879b9b36a9c1c8f5efa | [] | no_license | shreyavshetty/HobbyCodes | 69133a6fb0bb554d41e7bee974492beef36e69b1 | 46de9c09f30419cd74b15e3b792229c3f9e6bfba | refs/heads/master | 2021-01-18T11:37:38.081915 | 2020-09-20T06:15:36 | 2020-09-20T06:15:36 | 84,326,991 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,537 | java | package cci.ArraysAndStrings;
public class RotateMatrix {
public static void solution(int[][] mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n-i ; j++) {
int tmp = mat[i][j];
mat[i][j] = mat[n - j - 1][n - i - 1];
mat[n - j - 1][n - i - 1] = tmp;
}
}
printMatrix(mat, n);
for (int j = 0; j < n; j++) {
for (int i = 0; i < n/2 ; i++) {
int tmp = mat[i][j];
mat[i][j] = mat[n - i - 1][j];
mat[n - i - 1][j] = tmp;
}
}
}
public static void printMatrix(int[][] mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
System.out.println("************************");
}
public static void main(String[] args) {
int[][] mat = new int[4][4];
int[][] mat1 = new int[5][5];
int count = 1;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
mat[i][j] = count;
count++;
}
}
count = 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
mat1[i][j] = count;
count++;
}
}
printMatrix(mat1, 5);
solution(mat1, 5);
printMatrix(mat1, 5);
}
}
| [
"shreyav4@gmail.com"
] | shreyav4@gmail.com |
3632d2f7a0f365d37607462b19c8c5c6df13a407 | c37be0d1ddf85325c6bd02a0c57cb1dfe2df8c36 | /chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/ChromeHomeAppMenuTest.java | caf3a0b5717851fdf869cc7d205b7ee6ae57dc1d | [
"BSD-3-Clause"
] | permissive | idofilus/chromium | 0f78b085b1b4f59a5fc89d6fc0efef16beb63dcd | 47d58b9c7cb40c09a7bdcdaa0feead96ace95284 | refs/heads/master | 2023-03-04T18:08:14.105865 | 2017-11-14T18:26:28 | 2017-11-14T18:26:28 | 111,206,269 | 0 | 0 | null | 2017-11-18T13:06:33 | 2017-11-18T13:06:32 | null | UTF-8 | Java | false | false | 19,271 | java | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.appmenu;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import android.text.TextUtils;
import android.widget.ListView;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.Callback;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Restriction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeFeatureList;
import org.chromium.chrome.browser.feature_engagement.TrackerFactory;
import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings;
import org.chromium.chrome.browser.preferences.datareduction.DataReductionMainMenuItem;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet;
import org.chromium.chrome.browser.widget.bottomsheet.ChromeHomeIphMenuHeader;
import org.chromium.chrome.browser.widget.bottomsheet.ChromeHomeIphMenuHeader.ChromeHomeIphMenuHeaderTestObserver;
import org.chromium.chrome.browser.widget.bottomsheet.ChromeHomePromoDialog;
import org.chromium.chrome.browser.widget.bottomsheet.ChromeHomePromoDialog.ChromeHomePromoDialogTestObserver;
import org.chromium.chrome.browser.widget.bottomsheet.ChromeHomePromoMenuHeader;
import org.chromium.chrome.test.BottomSheetTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.util.ChromeTabUtils;
import org.chromium.chrome.test.util.MenuUtils;
import org.chromium.components.feature_engagement.FeatureConstants;
import org.chromium.components.feature_engagement.Tracker;
import org.chromium.components.feature_engagement.TriggerState;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.ui.test.util.UiRestriction;
import java.util.concurrent.TimeoutException;
/**
* Tests for the app menu when Chrome Home is enabled.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) // ChromeHome is only enabled on phones
public class ChromeHomeAppMenuTest {
private static final String TEST_PAGE = "/chrome/test/data/android/test.html";
private static class TestTracker implements Tracker {
public CallbackHelper mDimissedCallbackHelper = new CallbackHelper();
private String mEnabledFeature;
public TestTracker(String enabledFeature) {
mEnabledFeature = enabledFeature;
}
@Override
public void notifyEvent(String event) {}
@Override
public boolean shouldTriggerHelpUI(String feature) {
return TextUtils.equals(mEnabledFeature, feature);
}
@Override
public boolean wouldTriggerHelpUI(String feature) {
return TextUtils.equals(mEnabledFeature, feature);
}
@Override
public int getTriggerState(String feature) {
return TextUtils.equals(mEnabledFeature, feature) ? TriggerState.HAS_NOT_BEEN_DISPLAYED
: TriggerState.HAS_BEEN_DISPLAYED;
}
@Override
public void dismissed(String feature) {
Assert.assertEquals("Wrong feature dismissed.", mEnabledFeature, feature);
mDimissedCallbackHelper.notifyCalled();
}
@Override
public boolean isInitialized() {
return true;
}
@Override
public void addOnInitializedCallback(Callback<Boolean> callback) {}
}
private AppMenuHandler mAppMenuHandler;
private BottomSheet mBottomSheet;
private EmbeddedTestServer mTestServer;
private String mTestUrl;
@Rule
public BottomSheetTestRule mBottomSheetTestRule = new BottomSheetTestRule();
@Before
public void setUp() throws Exception {
mBottomSheetTestRule.startMainActivityOnBlankPage();
mAppMenuHandler = mBottomSheetTestRule.getActivity().getAppMenuHandler();
mBottomSheet = mBottomSheetTestRule.getBottomSheet();
mBottomSheetTestRule.setSheetState(BottomSheet.SHEET_STATE_PEEK, false);
mTestServer = EmbeddedTestServer.createAndStartServer(
InstrumentationRegistry.getInstrumentation().getContext());
mTestUrl = mTestServer.getURL(TEST_PAGE);
}
@After
public void tearDown() {
mTestServer.stopAndDestroyServer();
}
@Test
@SmallTest
public void testPageMenu() throws IllegalArgumentException, InterruptedException {
loadTestPage();
showAppMenuAndAssertMenuShown();
AppMenu appMenu = mAppMenuHandler.getAppMenu();
AppMenuIconRowFooter iconRow = (AppMenuIconRowFooter) appMenu.getFooterView();
assertFalse("Forward button should not be enabled",
iconRow.getForwardButtonForTests().isEnabled());
assertTrue("Bookmark button should be enabled",
iconRow.getBookmarkButtonForTests().isEnabled());
assertTrue("Download button should be enabled",
iconRow.getDownloadButtonForTests().isEnabled());
assertTrue(
"Info button should be enabled", iconRow.getPageInfoButtonForTests().isEnabled());
assertTrue(
"Reload button should be enabled", iconRow.getReloadButtonForTests().isEnabled());
// Navigate backward, open the menu and assert forward button is enabled.
ThreadUtils.runOnUiThreadBlocking(() -> {
mAppMenuHandler.hideAppMenu();
mBottomSheetTestRule.getActivity().getActivityTab().goBack();
});
showAppMenuAndAssertMenuShown();
iconRow = (AppMenuIconRowFooter) appMenu.getFooterView();
assertTrue(
"Forward button should be enabled", iconRow.getForwardButtonForTests().isEnabled());
}
@Test
@SmallTest
public void testTabSwitcherMenu() throws IllegalArgumentException {
ThreadUtils.runOnUiThreadBlocking(
() -> mBottomSheetTestRule.getActivity().getLayoutManager().showOverview(false));
showAppMenuAndAssertMenuShown();
AppMenu appMenu = mAppMenuHandler.getAppMenu();
assertNull("Footer view should be null", appMenu.getFooterView());
Assert.assertEquals(
"There should be four app menu items.", appMenu.getListView().getCount(), 4);
Assert.assertEquals("'New tab' should be the first item", R.id.new_tab_menu_id,
appMenu.getListView().getItemIdAtPosition(0));
Assert.assertEquals("'New incognito tab' should be the second item",
R.id.new_incognito_tab_menu_id, appMenu.getListView().getItemIdAtPosition(1));
Assert.assertEquals("'Close all tabs' should be the third item",
R.id.close_all_tabs_menu_id, appMenu.getListView().getItemIdAtPosition(2));
Assert.assertEquals("'Settings' should be the fourth item", R.id.preferences_id,
appMenu.getListView().getItemIdAtPosition(3));
}
@Test
@SmallTest
public void testNewTabMenu() {
MenuUtils.invokeCustomMenuActionSync(InstrumentationRegistry.getInstrumentation(),
mBottomSheetTestRule.getActivity(), R.id.new_tab_menu_id);
ThreadUtils.runOnUiThreadBlocking(() -> mBottomSheet.endAnimations());
showAppMenuAndAssertMenuShown();
AppMenu appMenu = mAppMenuHandler.getAppMenu();
assertNull("Footer view should be null", appMenu.getFooterView());
Assert.assertEquals(
"There should be four app menu items.", appMenu.getListView().getCount(), 4);
Assert.assertEquals("'New incognito tab' should be the first item",
R.id.new_incognito_tab_menu_id, appMenu.getListView().getItemIdAtPosition(0));
Assert.assertEquals("'Recent tabs' should be the second item", R.id.recent_tabs_menu_id,
appMenu.getListView().getItemIdAtPosition(1));
Assert.assertEquals("'Settings' should be the third item", R.id.preferences_id,
appMenu.getListView().getItemIdAtPosition(2));
Assert.assertEquals("'Help & feedback' should be the fourth item", R.id.help_id,
appMenu.getListView().getItemIdAtPosition(3));
}
@Test
@SmallTest
public void testNewIncognitoTabMenu() {
MenuUtils.invokeCustomMenuActionSync(InstrumentationRegistry.getInstrumentation(),
mBottomSheetTestRule.getActivity(), R.id.new_incognito_tab_menu_id);
ThreadUtils.runOnUiThreadBlocking(() -> mBottomSheet.endAnimations());
showAppMenuAndAssertMenuShown();
AppMenu appMenu = mAppMenuHandler.getAppMenu();
assertNull("Footer view should be null", appMenu.getFooterView());
Assert.assertEquals(
"There should be three app menu items.", appMenu.getListView().getCount(), 3);
Assert.assertEquals("'New tab' should be the first item", R.id.new_tab_menu_id,
appMenu.getListView().getItemIdAtPosition(0));
Assert.assertEquals("'Settings' should be the second item", R.id.preferences_id,
appMenu.getListView().getItemIdAtPosition(1));
Assert.assertEquals("'Help & feedback' should be the third item", R.id.help_id,
appMenu.getListView().getItemIdAtPosition(2));
}
@Test
@SmallTest
@CommandLineFlags.Add({"enable-features=" + ChromeFeatureList.CHROME_HOME_PROMO})
public void testPromoAppMenuHeader() throws InterruptedException, TimeoutException {
// Create a callback to be notified when the dialog is shown.
final CallbackHelper dialogShownCallback = new CallbackHelper();
ThreadUtils.runOnUiThreadBlocking(() -> {
ChromeHomePromoDialog.setObserverForTests(new ChromeHomePromoDialogTestObserver() {
@Override
public void onDialogShown(ChromeHomePromoDialog shownDialog) {
dialogShownCallback.notifyCalled();
}
});
});
// Load a test page and show the app menu. The header is only shown on the page menu.
loadTestPage();
showAppMenuAndAssertMenuShown();
// Check for the existence of a header.
ListView listView = mAppMenuHandler.getAppMenu().getListView();
Assert.assertEquals("There should be one header.", 1, listView.getHeaderViewsCount());
// Click the header.
ChromeHomePromoMenuHeader promoHeader = (ChromeHomePromoMenuHeader) listView.findViewById(
R.id.chrome_home_promo_menu_header);
ThreadUtils.runOnUiThreadBlocking(() -> { promoHeader.performClick(); });
// Wait for the dialog to show and the app menu to hide.
dialogShownCallback.waitForCallback(0);
assertFalse("Menu should be hidden.", mAppMenuHandler.isAppMenuShowing());
// Reset state.
ThreadUtils.runOnUiThreadBlocking(
() -> { ChromeHomePromoDialog.setObserverForTests(null); });
}
@Test
@SmallTest
@CommandLineFlags.Add({"disable-features=" + ChromeFeatureList.CHROME_HOME_PROMO})
public void testIphAppMenuHeader_Click() throws InterruptedException, TimeoutException {
TestTracker tracker = new TestTracker(FeatureConstants.CHROME_HOME_MENU_HEADER_FEATURE);
TrackerFactory.setTrackerForTests(tracker);
// Create a callback to be notified when the menu header is clicked.
final CallbackHelper menuItemClickedCallback = new CallbackHelper();
final CallbackHelper menuDismissedCallback = new CallbackHelper();
ThreadUtils.runOnUiThreadBlocking(() -> {
ChromeHomeIphMenuHeader.setObserverForTests(new ChromeHomeIphMenuHeaderTestObserver() {
@Override
public void onMenuItemClicked() {
menuItemClickedCallback.notifyCalled();
}
@Override
public void onMenuDismissed(boolean dismissIph) {
Assert.assertFalse("In-product help should not be dismissed when menu is"
+ " dismissed.",
dismissIph);
menuDismissedCallback.notifyCalled();
}
});
});
// Load a test page and show the app menu. The header is only shown on the page menu.
loadTestPage();
showAppMenuAndAssertMenuShown();
// Check for the existence of a header.
ListView listView = mAppMenuHandler.getAppMenu().getListView();
Assert.assertEquals("There should be one header.", 1, listView.getHeaderViewsCount());
// Click the header.
ChromeHomeIphMenuHeader iphHeader =
(ChromeHomeIphMenuHeader) listView.findViewById(R.id.chrome_home_iph_menu_header);
ThreadUtils.runOnUiThreadBlocking(() -> { iphHeader.performClick(); });
// Wait for the app menu to hide, then check state.
menuItemClickedCallback.waitForCallback(0);
menuDismissedCallback.waitForCallback(0);
assertFalse("Menu should be hidden.", mAppMenuHandler.isAppMenuShowing());
Assert.assertEquals("IPH should not be dimissed yet.", 0,
tracker.mDimissedCallbackHelper.getCallCount());
Assert.assertTrue("Bottom sheet help bubble should be showing.",
mBottomSheet.getHelpBubbleForTests().isShowing());
// Dismiss the help bubble
ThreadUtils.runOnUiThreadBlocking(
() -> { mBottomSheet.getHelpBubbleForTests().dismiss(); });
Assert.assertEquals(
"IPH should be dimissed.", 1, tracker.mDimissedCallbackHelper.getCallCount());
// Reset state.
ThreadUtils.runOnUiThreadBlocking(
() -> { ChromeHomeIphMenuHeader.setObserverForTests(null); });
TrackerFactory.setTrackerForTests(null);
}
@Test
@SmallTest
@CommandLineFlags.Add({"disable-features=" + ChromeFeatureList.CHROME_HOME_PROMO})
public void testIphAppMenuHeader_Dismiss() throws InterruptedException, TimeoutException {
TestTracker tracker = new TestTracker(FeatureConstants.CHROME_HOME_MENU_HEADER_FEATURE);
TrackerFactory.setTrackerForTests(tracker);
// Create a callback to be notified when the menu header is clicked.
final CallbackHelper menuItemClickedCallback = new CallbackHelper();
final CallbackHelper menuDismissedCallback = new CallbackHelper();
ThreadUtils.runOnUiThreadBlocking(() -> {
ChromeHomeIphMenuHeader.setObserverForTests(new ChromeHomeIphMenuHeaderTestObserver() {
@Override
public void onMenuItemClicked() {
menuItemClickedCallback.notifyCalled();
}
@Override
public void onMenuDismissed(boolean dismissIph) {
Assert.assertTrue("In-product help should be dismissed when menu is"
+ " dismissed.",
dismissIph);
menuDismissedCallback.notifyCalled();
}
});
});
// Load a test page and show the app menu. The header is only shown on the page menu.
loadTestPage();
showAppMenuAndAssertMenuShown();
// Check for the existence of a header.
ListView listView = mAppMenuHandler.getAppMenu().getListView();
Assert.assertEquals("There should be one header.", 1, listView.getHeaderViewsCount());
// Check that the right header is showing.
ChromeHomeIphMenuHeader iphHeader =
(ChromeHomeIphMenuHeader) listView.findViewById(R.id.chrome_home_iph_menu_header);
Assert.assertNotNull(iphHeader);
// Hide the app menu.
ThreadUtils.runOnUiThreadBlocking(() -> { mAppMenuHandler.hideAppMenu(); });
// Wait for the app menu to hide, then check state.
menuDismissedCallback.waitForCallback(0);
Assert.assertEquals("menuItemClickedCallback should not have been called.", 0,
menuItemClickedCallback.getCallCount());
Assert.assertEquals(
"IPH should be dimissed.", 1, tracker.mDimissedCallbackHelper.getCallCount());
Assert.assertNull(
"Bottom sheet help bubble should be null.", mBottomSheet.getHelpBubbleForTests());
// Reset state.
ThreadUtils.runOnUiThreadBlocking(
() -> { ChromeHomeIphMenuHeader.setObserverForTests(null); });
TrackerFactory.setTrackerForTests(null);
}
@Test
@SmallTest
@CommandLineFlags.Add({
"disable-features=IPH_ChromeHomeMenuHeader," + ChromeFeatureList.CHROME_HOME_PROMO,
"enable-features=" + ChromeFeatureList.DATA_REDUCTION_MAIN_MENU})
public void testDataSaverAppMenuHeader() {
showAppMenuAndAssertMenuShown();
// There should currently be no headers.
ListView listView = mAppMenuHandler.getAppMenu().getListView();
Assert.assertEquals("There should not be a header.", 0, listView.getHeaderViewsCount());
// Hide the app menu.
ThreadUtils.runOnUiThreadBlocking(() -> { mAppMenuHandler.hideAppMenu(); });
// Turn Data Saver on and re-open the menu.
ThreadUtils.runOnUiThreadBlocking(() -> {
DataReductionProxySettings.getInstance().setDataReductionProxyEnabled(
mBottomSheetTestRule.getActivity().getApplicationContext(), true);
});
showAppMenuAndAssertMenuShown();
// Check for the existence of a header.
listView = mAppMenuHandler.getAppMenu().getListView();
Assert.assertEquals("There should be one header.", 1, listView.getHeaderViewsCount());
// Check that the right header is showing.
DataReductionMainMenuItem dataReductionHeader =
(DataReductionMainMenuItem) listView.findViewById(R.id.data_reduction_menu_item);
Assert.assertNotNull(dataReductionHeader);
}
private void loadTestPage() throws InterruptedException {
final Tab tab = mBottomSheet.getActiveTab();
ChromeTabUtils.loadUrlOnUiThread(tab, mTestUrl);
ChromeTabUtils.waitForTabPageLoaded(tab, mTestUrl);
}
private void showAppMenuAndAssertMenuShown() {
ThreadUtils.runOnUiThread((Runnable) () -> mAppMenuHandler.showAppMenu(null, false));
CriteriaHelper.pollUiThread(new Criteria("AppMenu did not show") {
@Override
public boolean isSatisfied() {
return mAppMenuHandler.isAppMenuShowing();
}
});
}
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
7a76eb9172146330bc0ee443219197ca8ce49289 | 938fe94f82b95a497960aeecbea064a281b560f8 | /src/test/java/com/subham/financialgoal/FinancialgoalApplicationTests.java | 10fcd324dde0b906a43deb690589a6c8747f6e5c | [] | no_license | Subham1999/financialgoal | 5f853728069a99acefceedfe60111891175309ab | 25c9a1138739560cc5aa3550daef7381e32f2199 | refs/heads/master | 2022-12-30T23:47:07.812432 | 2020-10-21T06:45:04 | 2020-10-21T06:45:04 | 305,933,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 223 | java | package com.subham.financialgoal;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FinancialgoalApplicationTests {
@Test
void contextLoads() {
}
}
| [
"subhamsantra2016@gmail.com"
] | subhamsantra2016@gmail.com |
ffcf6d2803759c86f438994011d53d2f833d7a45 | 4912ed627431b9b63c5a10f43108e40cb5c8378b | /apache-0.32.x/qpid/java/amqp-1-0-common/src/main/java/org/apache/qpid/amqp_1_0/type/messaging/codec/MessageAnnotationsConstructor.java | b2f2ec57393994247870036e25bc63f56d8ba732 | [
"Apache-2.0",
"MIT",
"Python-2.0"
] | permissive | jo-soft/python-qpid | a56c908b7b703631ccd2d20eb39241b096cf4afb | 5735778c5823b2409fe3b45ff376b9d1ea08b011 | refs/heads/master | 2020-05-18T10:12:55.121721 | 2015-05-14T11:35:21 | 2015-05-14T11:35:21 | 35,607,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,025 | java |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.amqp_1_0.type.messaging.codec;
import org.apache.qpid.amqp_1_0.codec.DescribedTypeConstructor;
import org.apache.qpid.amqp_1_0.codec.DescribedTypeConstructorRegistry;
import org.apache.qpid.amqp_1_0.type.*;
import org.apache.qpid.amqp_1_0.type.messaging.*;
import org.apache.qpid.amqp_1_0.type.messaging.MessageAnnotations;
import java.util.Map;
public class MessageAnnotationsConstructor extends DescribedTypeConstructor<MessageAnnotations>
{
private static final Object[] DESCRIPTORS =
{
Symbol.valueOf("amqp:message-annotations:map"),UnsignedLong.valueOf(0x0000000000000072L),
};
private static final MessageAnnotationsConstructor INSTANCE = new MessageAnnotationsConstructor();
public static void register(DescribedTypeConstructorRegistry registry)
{
for(Object descriptor : DESCRIPTORS)
{
registry.register(descriptor, INSTANCE);
}
}
public MessageAnnotations construct(Object underlying)
{
if(underlying instanceof Map)
{
return new MessageAnnotations((Map)underlying);
}
else
{
// TODO - error
return null;
}
}
}
| [
"ichhabekeineemail@gmx.net"
] | ichhabekeineemail@gmx.net |
ecebda7d7d7cc6a19fb2bdafb91939d205fff729 | 6538df3f7f51162a7aff5ea1a4ed8d48d019b460 | /applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartEvents.java | a35132f75adf3a9d73b31fd5c4db5af3c53c3dac | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"MIT",
"CC-BY-2.5",
"EPL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | de-sage/ofbiz-plugin | 73b1294f31969274d4322ddec15e8ff6c7df44a6 | 6c2516ab9a7bcea44070a8043c0ee049e1321e98 | refs/heads/prod | 2023-04-19T10:30:48.352226 | 2021-05-09T01:42:39 | 2021-05-09T01:42:39 | 365,286,927 | 0 | 0 | Apache-2.0 | 2021-05-09T01:42:40 | 2021-05-07T16:05:23 | Java | UTF-8 | Java | false | false | 103,856 | java | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.order.shoppingcart;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.ObjectType;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilFormatOut;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilHttp;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilNumber;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericPK;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
import org.apache.ofbiz.order.shoppingcart.product.ProductPromoWorker;
import org.apache.ofbiz.product.catalog.CatalogWorker;
import org.apache.ofbiz.product.config.ProductConfigWorker;
import org.apache.ofbiz.product.config.ProductConfigWrapper;
import org.apache.ofbiz.product.product.ProductWorker;
import org.apache.ofbiz.product.store.ProductStoreSurveyWrapper;
import org.apache.ofbiz.product.store.ProductStoreWorker;
import org.apache.ofbiz.security.Security;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceUtil;
import org.apache.ofbiz.webapp.control.RequestHandler;
/**
* Shopping cart events.
*/
public class ShoppingCartEvents {
public static String module = ShoppingCartEvents.class.getName();
public static final String resource = "OrderUiLabels";
public static final String resource_error = "OrderErrorUiLabels";
private static final String NO_ERROR = "noerror";
private static final String NON_CRITICAL_ERROR = "noncritical";
private static final String ERROR = "error";
public static final MathContext generalRounding = new MathContext(10);
public static String addProductPromoCode(HttpServletRequest request, HttpServletResponse response) {
Locale locale = UtilHttp.getLocale(request);
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
String productPromoCodeId = request.getParameter("productPromoCodeId");
if (UtilValidate.isNotEmpty(productPromoCodeId)) {
String checkResult = cart.addProductPromoCode(productPromoCodeId, dispatcher);
if (UtilValidate.isNotEmpty(checkResult)) {
request.setAttribute("_ERROR_MESSAGE_", checkResult);
return "error";
}
}
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource, "OrderPromoAppliedSuccessfully", UtilMisc.toMap("productPromoCodeId", productPromoCodeId), locale));
return "success";
}
public static String removePromotion(HttpServletRequest request,HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
String promoCodeId = request.getParameter("promoCode");
String result = "error";
if (!promoCodeId.isEmpty()) {
cart.getProductPromoCodesEntered().clear();
GenericValue productPromoCode = null;
try {
productPromoCode = dispatcher.getDelegator().findOne("ProductPromoCode", UtilMisc.toMap("productPromoCodeId", promoCodeId), false);
if (!productPromoCode.isEmpty()) {
String productPromoId = productPromoCode.getString("productPromoId");
GenericValue productPromoAction = null;
Map<String, String> productPromoActionMap = new HashMap<String, String>();
productPromoActionMap.put("productPromoId", productPromoId);
productPromoActionMap.put("productPromoRuleId", "01");
productPromoActionMap.put("productPromoActionSeqId", "01");
productPromoAction = dispatcher.getDelegator().findOne("ProductPromoAction", productPromoActionMap, false);
if (!productPromoAction.isEmpty()) {
int index = cart.getAdjustmentPromoIndex(productPromoId);
/*Remove order adjustment*/
if (index != -1) {
cart.removeAdjustment(index);
result = "success";
}
/*Remove product adjustment*/
for (ShoppingCartItem checkItem : cart) {
List<GenericValue> itemAdjustments = checkItem.getAdjustments();
if (!itemAdjustments.isEmpty()) {
index = 0;
for (GenericValue adjustment : itemAdjustments ) {
if(adjustment.get("productPromoId").equals(productPromoId)) {
checkItem.getAdjustments().remove(index);
result = "success";
}
index++;
}
}
}
cart.removeProductPromoUse(productPromoId);
}
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
}
return result;
}
public static String addItemGroup(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
Map<String, Object> parameters = UtilHttp.getParameterMap(request);
String groupName = (String) parameters.get("groupName");
String parentGroupNumber = (String) parameters.get("parentGroupNumber");
String groupNumber = cart.addItemGroup(groupName, parentGroupNumber);
request.setAttribute("itemGroupNumber", groupNumber);
return "success";
}
public static String addCartItemToGroup(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
Map<String, Object> parameters = UtilHttp.getParameterMap(request);
String itemGroupNumber = (String) parameters.get("itemGroupNumber");
String indexStr = (String) parameters.get("lineIndex");
int index = Integer.parseInt(indexStr);
ShoppingCartItem cartItem = cart.findCartItem(index);
cartItem.setItemGroup(itemGroupNumber, cart);
return "success";
}
/** Event to add an item to the shopping cart. */
public static String addToCart(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String controlDirective = null;
Map<String, Object> result = null;
String productId = null;
String parentProductId = null;
String itemType = null;
String itemDescription = null;
String productCategoryId = null;
String priceStr = null;
BigDecimal price = null;
String quantityStr = null;
BigDecimal quantity = BigDecimal.ZERO;
String reservStartStr = null;
String reservEndStr = null;
Timestamp reservStart = null;
Timestamp reservEnd = null;
String reservLengthStr = null;
BigDecimal reservLength = null;
String reservPersonsStr = null;
BigDecimal reservPersons = null;
String accommodationMapId = null;
String accommodationSpotId = null;
String shipBeforeDateStr = null;
String shipAfterDateStr = null;
Timestamp shipBeforeDate = null;
Timestamp shipAfterDate = null;
String numberOfDay = null;
// not used right now: Map attributes = null;
String catalogId = CatalogWorker.getCurrentCatalogId(request);
Locale locale = UtilHttp.getLocale(request);
// Get the parameters as a MAP, remove the productId and quantity params.
Map<String, Object> paramMap = UtilHttp.getCombinedMap(request);
String itemGroupNumber = (String) paramMap.get("itemGroupNumber");
// Get shoppingList info if passed
String shoppingListId = (String) paramMap.get("shoppingListId");
String shoppingListItemSeqId = (String) paramMap.get("shoppingListItemSeqId");
if (paramMap.containsKey("ADD_PRODUCT_ID")) {
productId = (String) paramMap.remove("ADD_PRODUCT_ID");
} else if (paramMap.containsKey("add_product_id")) {
Object object = paramMap.remove("add_product_id");
try {
productId = (String) object;
} catch (ClassCastException e) {
List<String> productList = UtilGenerics.checkList(object);
productId = productList.get(0);
}
}
if (paramMap.containsKey("PRODUCT_ID")) {
parentProductId = (String) paramMap.remove("PRODUCT_ID");
} else if (paramMap.containsKey("product_id")) {
parentProductId = (String) paramMap.remove("product_id");
}
Debug.logInfo("adding item product " + productId, module);
Debug.logInfo("adding item parent product " + parentProductId, module);
if (paramMap.containsKey("ADD_CATEGORY_ID")) {
productCategoryId = (String) paramMap.remove("ADD_CATEGORY_ID");
} else if (paramMap.containsKey("add_category_id")) {
productCategoryId = (String) paramMap.remove("add_category_id");
}
if (productCategoryId != null && productCategoryId.length() == 0) {
productCategoryId = null;
}
if (paramMap.containsKey("ADD_ITEM_TYPE")) {
itemType = (String) paramMap.remove("ADD_ITEM_TYPE");
} else if (paramMap.containsKey("add_item_type")) {
itemType = (String) paramMap.remove("add_item_type");
}
if (UtilValidate.isEmpty(productId)) {
// before returning error; check make sure we aren't adding a special item type
if (UtilValidate.isEmpty(itemType)) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.noProductInfoPassed", locale));
return "success"; // not critical return to same page
}
} else {
try {
String pId = ProductWorker.findProductId(delegator, productId);
if (pId != null) {
productId = pId;
}
} catch (Throwable e) {
Debug.logWarning(e, module);
}
}
// check for an itemDescription
if (paramMap.containsKey("ADD_ITEM_DESCRIPTION")) {
itemDescription = (String) paramMap.remove("ADD_ITEM_DESCRIPTION");
} else if (paramMap.containsKey("add_item_description")) {
itemDescription = (String) paramMap.remove("add_item_description");
}
if (itemDescription != null && itemDescription.length() == 0) {
itemDescription = null;
}
// Get the ProductConfigWrapper (it's not null only for configurable items)
ProductConfigWrapper configWrapper = null;
configWrapper = ProductConfigWorker.getProductConfigWrapper(productId, cart.getCurrency(), request);
if (configWrapper != null) {
if (paramMap.containsKey("configId")) {
try {
configWrapper.loadConfig(delegator, (String) paramMap.remove("configId"));
} catch (Exception e) {
Debug.logWarning(e, "Could not load configuration", module);
}
} else {
// The choices selected by the user are taken from request and set in the wrapper
ProductConfigWorker.fillProductConfigWrapper(configWrapper, request);
}
if (!configWrapper.isCompleted()) {
// The configuration is not valid
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.configureProductBeforeAddingToCart", locale));
return "product";
} else {
// load the Config Id
ProductConfigWorker.storeProductConfigWrapper(configWrapper, delegator);
}
}
//Check for virtual products
if (ProductWorker.isVirtual(delegator, productId)) {
if ("VV_FEATURETREE".equals(ProductWorker.getProductVirtualVariantMethod(delegator, productId))) {
// get the selected features.
List<String> selectedFeatures = new LinkedList<String>();
Enumeration<String> paramNames = UtilGenerics.cast(request.getParameterNames());
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
if (paramName.startsWith("FT")) {
selectedFeatures.add(request.getParameterValues(paramName)[0]);
}
}
// check if features are selected
if (UtilValidate.isEmpty(selectedFeatures)) {
request.setAttribute("paramMap", paramMap);
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
return "product";
}
String variantProductId = ProductWorker.getVariantFromFeatureTree(productId, selectedFeatures, delegator);
if (UtilValidate.isNotEmpty(variantProductId)) {
productId = variantProductId;
} else {
request.setAttribute("paramMap", paramMap);
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.incompatibilityVariantFeature", locale));
return "product";
}
} else {
request.setAttribute("paramMap", paramMap);
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
return "product";
}
}
// get the override price
if (paramMap.containsKey("PRICE")) {
priceStr = (String) paramMap.remove("PRICE");
} else if (paramMap.containsKey("price")) {
priceStr = (String) paramMap.remove("price");
}
if (priceStr == null) {
priceStr = "0"; // default price is 0
}
if ("ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
if (paramMap.containsKey("numberOfDay")) {
numberOfDay = (String) paramMap.remove("numberOfDay");
reservStart = UtilDateTime.addDaysToTimestamp(UtilDateTime.nowTimestamp(), 1);
reservEnd = UtilDateTime.addDaysToTimestamp(reservStart, Integer.valueOf(numberOfDay));
}
}
// get the renting data
if ("ASSET_USAGE".equals(ProductWorker.getProductTypeId(delegator, productId)) || "ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
if (paramMap.containsKey("reservStart")) {
reservStartStr = (String) paramMap.remove("reservStart");
if (reservStartStr.length() == 10) // only date provided, no time string?
reservStartStr += " 00:00:00.000000000"; // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
if (reservStartStr.length() > 0) {
try {
reservStart = java.sql.Timestamp.valueOf(reservStartStr);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing Reservation start string: "
+ reservStartStr, module);
reservStart = null;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.rental.startDate", locale));
return "error";
}
} else reservStart = null;
}
if (paramMap.containsKey("reservEnd")) {
reservEndStr = (String) paramMap.remove("reservEnd");
if (reservEndStr.length() == 10) // only date provided, no time string?
reservEndStr += " 00:00:00.000000000"; // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
if (reservEndStr.length() > 0) {
try {
reservEnd = java.sql.Timestamp.valueOf(reservEndStr);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing Reservation end string: " + reservEndStr, module);
reservEnd = null;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.rental.endDate", locale));
return "error";
}
} else reservEnd = null;
}
if (reservStart != null && reservEnd != null) {
reservLength = new BigDecimal(UtilDateTime.getInterval(reservStart, reservEnd)).divide(new BigDecimal("86400000"), generalRounding);
}
if (reservStart != null && paramMap.containsKey("reservLength")) {
reservLengthStr = (String) paramMap.remove("reservLength");
// parse the reservation Length
try {
reservLength = (BigDecimal) ObjectType.simpleTypeConvert(reservLengthStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing reservation length string: "
+ reservLengthStr, module);
reservLength = BigDecimal.ONE;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderReservationLengthShouldBeAPositiveNumber", locale));
return "error";
}
}
if (reservStart != null && paramMap.containsKey("reservPersons")) {
reservPersonsStr = (String) paramMap.remove("reservPersons");
// parse the number of persons
try {
reservPersons = (BigDecimal) ObjectType.simpleTypeConvert(reservPersonsStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing reservation number of persons string: " + reservPersonsStr, module);
reservPersons = BigDecimal.ONE;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderNumberOfPersonsShouldBeOneOrLarger", locale));
return "error";
}
}
//check for valid rental parameters
if (UtilValidate.isEmpty(reservStart) && UtilValidate.isEmpty(reservLength) && UtilValidate.isEmpty(reservPersons)) {
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.enterBookingInforamtionBeforeAddingToCart", locale));
return "product";
}
//check accommodation for reservations
if ((paramMap.containsKey("accommodationMapId")) && (paramMap.containsKey("accommodationSpotId"))) {
accommodationMapId = (String) paramMap.remove("accommodationMapId");
accommodationSpotId = (String) paramMap.remove("accommodationSpotId");
}
}
// get the quantity
if (paramMap.containsKey("QUANTITY")) {
quantityStr = (String) paramMap.remove("QUANTITY");
} else if (paramMap.containsKey("quantity")) {
quantityStr = (String) paramMap.remove("quantity");
}
if (UtilValidate.isEmpty(quantityStr)) {
quantityStr = "1"; // default quantity is 1
}
// parse the price
try {
price = (BigDecimal) ObjectType.simpleTypeConvert(priceStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing price string: " + priceStr, module);
price = null;
}
// parse the quantity
try {
quantity = (BigDecimal) ObjectType.simpleTypeConvert(quantityStr, "BigDecimal", null, locale);
//For quantity we should test if we allow to add decimal quantity for this product an productStore :
// if not and if quantity is in decimal format then return error.
if(! ProductWorker.isDecimalQuantityOrderAllowed(delegator, productId, cart.getProductStoreId())){
BigDecimal remainder = quantity.remainder(BigDecimal.ONE);
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", locale));
return "error";
}
quantity = quantity.setScale(0, UtilNumber.getBigDecimalRoundingMode("order.rounding"));
}
else {
quantity = quantity.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getBigDecimalRoundingMode("order.rounding"));
}
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing quantity string: " + quantityStr, module);
quantity = BigDecimal.ONE;
}
// get the selected amount
String selectedAmountStr = null;
if (paramMap.containsKey("ADD_AMOUNT")) {
selectedAmountStr = (String) paramMap.remove("ADD_AMOUNT");
} else if (paramMap.containsKey("add_amount")) {
selectedAmountStr = (String) paramMap.remove("add_amount");
}
// parse the amount
BigDecimal amount = null;
if (UtilValidate.isNotEmpty(selectedAmountStr)) {
try {
amount = (BigDecimal) ObjectType.simpleTypeConvert(selectedAmountStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problem parsing amount string: " + selectedAmountStr, module);
amount = null;
}
} else {
amount = BigDecimal.ZERO;
}
// check for required amount
if ((ProductWorker.isAmountRequired(delegator, productId)) && (amount == null || amount.doubleValue() == 0.0)) {
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.enterAmountBeforeAddingToCart", locale));
return "product";
}
// get the ship before date (handles both yyyy-mm-dd input and full timestamp)
shipBeforeDateStr = (String) paramMap.remove("shipBeforeDate");
if (UtilValidate.isNotEmpty(shipBeforeDateStr)) {
if (shipBeforeDateStr.length() == 10) shipBeforeDateStr += " 00:00:00.000";
try {
shipBeforeDate = java.sql.Timestamp.valueOf(shipBeforeDateStr);
} catch (IllegalArgumentException e) {
Debug.logWarning(e, "Bad shipBeforeDate input: " + e.getMessage(), module);
shipBeforeDate = null;
}
}
// get the ship after date (handles both yyyy-mm-dd input and full timestamp)
shipAfterDateStr = (String) paramMap.remove("shipAfterDate");
if (UtilValidate.isNotEmpty(shipAfterDateStr)) {
if (shipAfterDateStr.length() == 10) shipAfterDateStr += " 00:00:00.000";
try {
shipAfterDate = java.sql.Timestamp.valueOf(shipAfterDateStr);
} catch (IllegalArgumentException e) {
Debug.logWarning(e, "Bad shipAfterDate input: " + e.getMessage(), module);
shipAfterDate = null;
}
}
// check for an add-to cart survey
List<String> surveyResponses = null;
if (productId != null) {
String productStoreId = ProductStoreWorker.getProductStoreId(request);
List<GenericValue> productSurvey = ProductStoreWorker.getProductSurveys(delegator, productStoreId, productId, "CART_ADD", parentProductId);
if (UtilValidate.isNotEmpty(productSurvey)) {
// TODO: implement multiple survey per product
GenericValue survey = EntityUtil.getFirst(productSurvey);
String surveyResponseId = (String) request.getAttribute("surveyResponseId");
if (surveyResponseId != null) {
surveyResponses = UtilMisc.toList(surveyResponseId);
} else {
String origParamMapId = UtilHttp.stashParameterMap(request);
Map<String, Object> surveyContext = UtilMisc.<String, Object>toMap("_ORIG_PARAM_MAP_ID_", origParamMapId);
GenericValue userLogin = cart.getUserLogin();
String partyId = null;
if (userLogin != null) {
partyId = userLogin.getString("partyId");
}
String formAction = "/additemsurvey";
String nextPage = RequestHandler.getOverrideViewUri(request.getPathInfo());
if (nextPage != null) {
formAction = formAction + "/" + nextPage;
}
ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(survey, partyId, surveyContext);
request.setAttribute("surveyWrapper", wrapper);
request.setAttribute("surveyAction", formAction); // will be used as the form action of the survey
return "survey";
}
}
}
if (surveyResponses != null) {
paramMap.put("surveyResponses", surveyResponses);
}
GenericValue productStore = ProductStoreWorker.getProductStore(request);
if (productStore != null) {
String addToCartRemoveIncompat = productStore.getString("addToCartRemoveIncompat");
String addToCartReplaceUpsell = productStore.getString("addToCartReplaceUpsell");
try {
if ("Y".equals(addToCartRemoveIncompat)) {
List<GenericValue> productAssocs = null;
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityOperator.OR, EntityCondition.makeCondition("productIdTo", EntityOperator.EQUALS, productId)),
EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_INCOMPATABLE")), EntityOperator.AND);
productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where(cond).filterByDate().queryList();
List<String> productList = new LinkedList<String>();
for (GenericValue productAssoc : productAssocs) {
if (productId.equals(productAssoc.getString("productId"))) {
productList.add(productAssoc.getString("productIdTo"));
continue;
}
if (productId.equals(productAssoc.getString("productIdTo"))) {
productList.add(productAssoc.getString("productId"));
continue;
}
}
for (ShoppingCartItem sci : cart) {
if (productList.contains(sci.getProductId())) {
try {
cart.removeCartItem(sci, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e.getMessage(), module);
}
}
}
}
if ("Y".equals(addToCartReplaceUpsell)) {
List<GenericValue> productList = null;
productList = EntityQuery.use(delegator).select("productId").from("ProductAssoc").where("productIdTo", productId, "productAssocTypeId", "PRODUCT_UPGRADE").queryList();
if (productList != null) {
for (ShoppingCartItem sci : cart) {
if (productList.contains(sci.getProductId())) {
try {
cart.removeCartItem(sci, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e.getMessage(), module);
}
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
}
// check for alternative packing
if(ProductWorker.isAlternativePacking(delegator, productId , parentProductId)){
GenericValue parentProduct = null;
try {
parentProduct = EntityQuery.use(delegator).from("Product").where("productId", parentProductId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting parent product", module);
}
BigDecimal piecesIncluded = BigDecimal.ZERO;
if(parentProduct != null){
piecesIncluded = new BigDecimal(parentProduct.getLong("piecesIncluded"));
quantity = quantity.multiply(piecesIncluded);
}
}
// Translate the parameters and add to the cart
result = cartHelper.addToCart(catalogId, shoppingListId, shoppingListItemSeqId, productId, productCategoryId,
itemType, itemDescription, price, amount, quantity, reservStart, reservLength, reservPersons,
accommodationMapId, accommodationSpotId,
shipBeforeDate, shipAfterDate, configWrapper, itemGroupNumber, paramMap, parentProductId);
controlDirective = processResult(result, request);
Integer itemId = (Integer)result.get("itemId");
if (UtilValidate.isNotEmpty(itemId)) {
request.setAttribute("itemId", itemId);
}
try {
GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
//Reset shipment method information in cart only if shipping applies on product.
if (UtilValidate.isNotEmpty(product) && ProductWorker.shippingApplies(product)) {
for (int shipGroupIndex = 0; shipGroupIndex < cart.getShipGroupSize(); shipGroupIndex++) {
String shipContactMechId = cart.getShippingContactMechId(shipGroupIndex);
if (UtilValidate.isNotEmpty(shipContactMechId)) {
cart.setShipmentMethodTypeId(shipGroupIndex, null);
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting product"+e.getMessage(), module);
}
// Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
if (cart.viewCartOnAdd()) {
return "viewcart";
} else {
return "success";
}
}
}
public static String addToCartFromOrder(HttpServletRequest request, HttpServletResponse response) {
String orderId = request.getParameter("orderId");
String itemGroupNumber = request.getParameter("itemGroupNumber");
String[] itemIds = request.getParameterValues("item_id");
ShoppingCart cart = getCartObject(request);
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String catalogId = CatalogWorker.getCurrentCatalogId(request);
Map<String, Object> result;
String controlDirective;
boolean addAll = ("true".equals(request.getParameter("add_all")));
result = cartHelper.addToCartFromOrder(catalogId, orderId, itemIds, addAll, itemGroupNumber);
controlDirective = processResult(result, request);
//Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
return "success";
}
}
/** Adds all products in a category according to quantity request parameter
* for each; if no parameter for a certain product in the category, or if
* quantity is 0, do not add
*/
public static String addToCartBulk(HttpServletRequest request, HttpServletResponse response) {
String categoryId = request.getParameter("category_id");
ShoppingCart cart = getCartObject(request);
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String controlDirective;
Map<String, Object> result;
//Convert the params to a map to pass in
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String catalogId = CatalogWorker.getCurrentCatalogId(request);
result = cartHelper.addToCartBulk(catalogId, categoryId, paramMap);
controlDirective = processResult(result, request);
//Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
return "success";
}
}
public static String quickInitPurchaseOrder(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Locale locale = UtilHttp.getLocale(request);
String supplierPartyId = request.getParameter("supplierPartyId_o_0");
// check the preferred currency of the supplier, if set, use that for the cart, otherwise use system defaults.
ShoppingCart cart = null;
try {
GenericValue supplierParty = EntityQuery.use(delegator).from("Party").where("partyId", supplierPartyId).queryOne();
if (UtilValidate.isNotEmpty(supplierParty.getString("preferredCurrencyUomId"))) {
cart = new WebShoppingCart(request, locale, supplierParty.getString("preferredCurrencyUomId"));
} else {
cart = new WebShoppingCart(request);
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
// TODO: the code below here needs some cleanups
String billToCustomerPartyId = request.getParameter("billToCustomerPartyId_o_0");
if (UtilValidate.isEmpty(billToCustomerPartyId) && UtilValidate.isEmpty(supplierPartyId)) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderCouldNotInitPurchaseOrder", locale));
return "error";
}
String orderId = request.getParameter("orderId_o_0");
// set the order id if supplied
if (UtilValidate.isNotEmpty(orderId)) {
GenericValue thisOrder = null;
try {
thisOrder = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
if (thisOrder == null) {
cart.setOrderId(orderId);
} else {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderIdAlreadyExistsPleaseChooseAnother", locale));
return "error";
}
}
cart.setBillToCustomerPartyId(billToCustomerPartyId);
cart.setBillFromVendorPartyId(supplierPartyId);
cart.setOrderPartyId(supplierPartyId);
cart.setOrderId(orderId);
String agreementId = request.getParameter("agreementId_o_0");
if (UtilValidate.isNotEmpty(agreementId)) {
ShoppingCartHelper sch = new ShoppingCartHelper(delegator, dispatcher, cart);
sch.selectAgreement(agreementId);
}
cart.setOrderType("PURCHASE_ORDER");
session.setAttribute("shoppingCart", cart);
session.setAttribute("productStoreId", cart.getProductStoreId());
session.setAttribute("orderMode", cart.getOrderType());
session.setAttribute("orderPartyId", cart.getOrderPartyId());
return "success";
}
public static String quickCheckoutOrderWithDefaultOptions(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
// Set the cart's default checkout options for a quick checkout
cart.setDefaultCheckoutOptions(dispatcher);
return "success";
}
/** Adds a set of requirements to the cart
*/
public static String addToCartBulkRequirements(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String controlDirective;
Map<String, Object> result;
//Convert the params to a map to pass in
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String catalogId = CatalogWorker.getCurrentCatalogId(request);
result = cartHelper.addToCartBulkRequirements(catalogId, paramMap);
controlDirective = processResult(result, request);
//Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
return "success";
}
}
/** Adds all products in a category according to default quantity on ProductCategoryMember
* for each; if no default for a certain product in the category, or if
* quantity is 0, do not add
*/
public static String addCategoryDefaults(HttpServletRequest request, HttpServletResponse response) {
String itemGroupNumber = request.getParameter("itemGroupNumber");
String categoryId = request.getParameter("category_id");
String catalogId = CatalogWorker.getCurrentCatalogId(request);
ShoppingCart cart = getCartObject(request);
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String controlDirective;
Map<String, Object> result;
BigDecimal totalQuantity;
Locale locale = UtilHttp.getLocale(request);
result = cartHelper.addCategoryDefaults(catalogId, categoryId, itemGroupNumber);
controlDirective = processResult(result, request);
//Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
totalQuantity = (BigDecimal)result.get("totalQuantity");
Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("totalQuantity", UtilFormatOut.formatQuantity(totalQuantity.doubleValue()));
request.setAttribute("_EVENT_MESSAGE_",
UtilProperties.getMessage(resource_error, "cart.add_category_defaults",
messageMap, locale));
return "success";
}
}
/** Delete an item from the shopping cart. */
public static String deleteFromCart(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCartHelper cartHelper = new ShoppingCartHelper(null, dispatcher, cart);
String controlDirective;
Map<String, Object> result;
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
//Delegate the cart helper
result = cartHelper.deleteFromCart(paramMap);
controlDirective = processResult(result, request);
//Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
return "success";
}
}
/** Update the items in the shopping cart. */
public static String modifyCart(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
ShoppingCart cart = getCartObject(request);
Locale locale = UtilHttp.getLocale(request);
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Security security = (Security) request.getAttribute("security");
ShoppingCartHelper cartHelper = new ShoppingCartHelper(null, dispatcher, cart);
String controlDirective;
Map<String, Object> result;
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String removeSelectedFlag = request.getParameter("removeSelected");
String selectedItems[] = request.getParameterValues("selectedItem");
boolean removeSelected = ("true".equals(removeSelectedFlag) && selectedItems != null && selectedItems.length > 0);
result = cartHelper.modifyCart(security, userLogin, paramMap, removeSelected, selectedItems, locale);
controlDirective = processResult(result, request);
//Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
} else {
return "success";
}
}
/** Empty the shopping cart. */
public static String clearCart(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
cart.clear();
// if this was an anonymous checkout process, go ahead and clear the session and such now that the order is placed; we don't want this to mess up additional orders and such
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
if (userLogin != null && "anonymous".equals(userLogin.get("userLoginId"))) {
Locale locale = UtilHttp.getLocale(session);
// here we want to do a full logout, but not using the normal logout stuff because it saves things in the UserLogin record that we don't want changed for the anonymous user
session.invalidate();
session = request.getSession(true);
if (null != locale) {
UtilHttp.setLocale(session, locale);
}
// to allow the display of the order confirmation page put the userLogin in the request, but leave it out of the session
request.setAttribute("temporaryAnonymousUserLogin", userLogin);
Debug.logInfo("Doing clearCart for anonymous user, so logging out but put anonymous userLogin in temporaryAnonymousUserLogin request attribute", module);
}
return "success";
}
/** Totally wipe out the cart, removes all stored info. */
public static String destroyCart(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
clearCart(request, response);
session.removeAttribute("shoppingCart");
session.removeAttribute("orderPartyId");
session.removeAttribute("orderMode");
session.removeAttribute("productStoreId");
session.removeAttribute("CURRENT_CATALOG_ID");
return "success";
}
/** Gets or creates the shopping cart object */
public static ShoppingCart getCartObject(HttpServletRequest request, Locale locale, String currencyUom) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = (ShoppingCart) request.getAttribute("shoppingCart");
HttpSession session = request.getSession(true);
if (cart == null) {
cart = (ShoppingCart) session.getAttribute("shoppingCart");
} else {
session.setAttribute("shoppingCart", cart);
}
if (cart == null) {
cart = new WebShoppingCart(request, locale, currencyUom);
session.setAttribute("shoppingCart", cart);
} else {
if (locale != null && !locale.equals(cart.getLocale())) {
cart.setLocale(locale);
}
if (currencyUom != null && !currencyUom.equals(cart.getCurrency())) {
try {
cart.setCurrency(dispatcher, currencyUom);
} catch (CartItemModifyException e) {
Debug.logError(e, "Unable to modify currency in cart", module);
}
}
}
return cart;
}
/** Main get cart method; uses the locale & currency from the session */
public static ShoppingCart getCartObject(HttpServletRequest request) {
return getCartObject(request, null, null);
}
public static String switchCurrentCartObject(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
String cartIndexStr = request.getParameter("cartIndex");
int cartIndex = -1;
if (UtilValidate.isNotEmpty(cartIndexStr) && UtilValidate.isInteger(cartIndexStr)) {
try {
cartIndex = Integer.parseInt(cartIndexStr);
} catch (NumberFormatException nfe) {
Debug.logWarning("Invalid value for cart index =" + cartIndexStr, module);
}
}
List<ShoppingCart> cartList = UtilGenerics.checkList(session.getAttribute("shoppingCartList"));
if (UtilValidate.isEmpty(cartList)) {
cartList = new LinkedList<ShoppingCart>();
session.setAttribute("shoppingCartList", cartList);
}
ShoppingCart currentCart = (ShoppingCart) session.getAttribute("shoppingCart");
if (currentCart != null) {
cartList.add(currentCart);
session.setAttribute("shoppingCartList", cartList);
session.removeAttribute("shoppingCart");
}
ShoppingCart newCart = null;
if (cartIndex >= 0 && cartIndex < cartList.size()) {
newCart = cartList.remove(cartIndex);
} else {
String productStoreId = request.getParameter("productStoreId");
if (UtilValidate.isNotEmpty(productStoreId)) {
session.setAttribute("productStoreId", productStoreId);
}
newCart = getCartObject(request);
}
session.setAttribute("shoppingCart", newCart);
return "success";
}
public static String clearCartFromList(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
String cartIndexStr = request.getParameter("cartIndex");
int cartIndex = -1;
if (UtilValidate.isNotEmpty(cartIndexStr) && UtilValidate.isInteger(cartIndexStr)) {
try {
cartIndex = Integer.parseInt(cartIndexStr);
} catch (NumberFormatException nfe) {
Debug.logWarning("Invalid value for cart index =" + cartIndexStr, module);
}
}
List<ShoppingCart> cartList = UtilGenerics.checkList(session.getAttribute("shoppingCartList"));
if (UtilValidate.isNotEmpty(cartList) && cartIndex >= 0 && cartIndex < cartList.size()) {
cartList.remove(cartIndex);
}
return "success";
}
/** Update the cart's UserLogin object if it isn't already set. */
public static String keepCartUpdated(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
ShoppingCart cart = getCartObject(request);
// if we just logged in set the UL
if (cart.getUserLogin() == null) {
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
if (userLogin != null) {
try {
cart.setUserLogin(userLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logWarning(e, module);
}
}
}
// same for autoUserLogin
if (cart.getAutoUserLogin() == null) {
GenericValue autoUserLogin = (GenericValue) session.getAttribute("autoUserLogin");
if (autoUserLogin != null) {
if (cart.getUserLogin() == null) {
try {
cart.setAutoUserLogin(autoUserLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logWarning(e, module);
}
} else {
cart.setAutoUserLogin(autoUserLogin);
}
}
}
// update the locale
Locale locale = UtilHttp.getLocale(request);
if (cart.getLocale() == null || !locale.equals(cart.getLocale())) {
cart.setLocale(locale);
}
return "success";
}
/** For GWP Promotions with multiple alternatives, selects an alternative to the current GWP */
public static String setDesiredAlternateGwpProductId(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
String alternateGwpProductId = request.getParameter("alternateGwpProductId");
String alternateGwpLineStr = request.getParameter("alternateGwpLine");
Locale locale = UtilHttp.getLocale(request);
if (UtilValidate.isEmpty(alternateGwpProductId)) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderCouldNotSelectAlternateGiftNoAlternateGwpProductIdPassed", locale));
return "error";
}
if (UtilValidate.isEmpty(alternateGwpLineStr)) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderCouldNotSelectAlternateGiftNoAlternateGwpLinePassed", locale));
return "error";
}
int alternateGwpLine = 0;
try {
alternateGwpLine = Integer.parseInt(alternateGwpLineStr);
} catch (Exception e) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderCouldNotSelectAlternateGiftAlternateGwpLineIsNotAValidNumber", locale));
return "error";
}
ShoppingCartItem cartLine = cart.findCartItem(alternateGwpLine);
if (cartLine == null) {
request.setAttribute("_ERROR_MESSAGE_", "Could not select alternate gift, no cart line item found for #" + alternateGwpLine + ".");
return "error";
}
if (cartLine.getIsPromo()) {
// note that there should just be one promo adjustment, the reversal of the GWP, so use that to get the promo action key
Iterator<GenericValue> checkOrderAdjustments = UtilMisc.toIterator(cartLine.getAdjustments());
while (checkOrderAdjustments != null && checkOrderAdjustments.hasNext()) {
GenericValue checkOrderAdjustment = checkOrderAdjustments.next();
if (UtilValidate.isNotEmpty(checkOrderAdjustment.getString("productPromoId")) &&
UtilValidate.isNotEmpty(checkOrderAdjustment.getString("productPromoRuleId")) &&
UtilValidate.isNotEmpty(checkOrderAdjustment.getString("productPromoActionSeqId"))) {
GenericPK productPromoActionPk = delegator.makeValidValue("ProductPromoAction", checkOrderAdjustment).getPrimaryKey();
cart.setDesiredAlternateGiftByAction(productPromoActionPk, alternateGwpProductId);
if (cart.getOrderType().equals("SALES_ORDER")) {
org.apache.ofbiz.order.shoppingcart.product.ProductPromoWorker.doPromotions(cart, dispatcher);
}
return "success";
}
}
}
request.setAttribute("_ERROR_MESSAGE_", "Could not select alternate gift, cart line item found for #" + alternateGwpLine + " does not appear to be a valid promotional gift.");
return "error";
}
/** Associates a party to order */
public static String addAdditionalParty(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
String partyId = request.getParameter("additionalPartyId");
String roleTypeId[] = request.getParameterValues("additionalRoleTypeId");
List<String> eventList = new LinkedList<String>();
Locale locale = UtilHttp.getLocale(request);
int i;
if (UtilValidate.isEmpty(partyId) || UtilValidate.isEmpty(roleTypeId) || roleTypeId.length < 1) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderPartyIdAndOrRoleTypeIdNotDefined", locale));
return "error";
}
if (request.getAttribute("_EVENT_MESSAGE_LIST_") != null) {
List<String> msg = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
eventList.addAll(msg);
}
for (i = 0; i < roleTypeId.length; i++) {
try {
cart.addAdditionalPartyRole(partyId, roleTypeId[i]);
} catch (Exception e) {
eventList.add(e.getLocalizedMessage());
}
}
request.removeAttribute("_EVENT_MESSAGE_LIST_");
request.setAttribute("_EVENT_MESSAGE_LIST_", eventList);
return "success";
}
/** Removes a previously associated party to order */
public static String removeAdditionalParty(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
String partyId = request.getParameter("additionalPartyId");
String roleTypeId[] = request.getParameterValues("additionalRoleTypeId");
List<String> eventList = new LinkedList<String>();
Locale locale = UtilHttp.getLocale(request);
int i;
if (UtilValidate.isEmpty(partyId) || roleTypeId.length < 1) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderPartyIdAndOrRoleTypeIdNotDefined", locale));
return "error";
}
if (request.getAttribute("_EVENT_MESSAGE_LIST_") != null) {
List<String> msg = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
eventList.addAll(msg);
}
for (i = 0; i < roleTypeId.length; i++) {
try {
cart.removeAdditionalPartyRole(partyId, roleTypeId[i]);
} catch (Exception e) {
Debug.logInfo(e.getLocalizedMessage(), module);
eventList.add(e.getLocalizedMessage());
}
}
request.removeAttribute("_EVENT_MESSAGE_LIST_");
request.setAttribute("_EVENT_MESSAGE_LIST_", eventList);
return "success";
}
/**
* This should be called to translate the error messages of the
* <code>ShoppingCartHelper</code> to an appropriately formatted
* <code>String</code> in the request object and indicate whether
* the result was an error or not and whether the errors were
* critical or not
*
* @param result The result returned from the
* <code>ShoppingCartHelper</code>
* @param request The servlet request instance to set the error messages
* in
* @return one of NON_CRITICAL_ERROR, ERROR or NO_ERROR.
*/
private static String processResult(Map<String, Object> result, HttpServletRequest request) {
//Check for errors
StringBuilder errMsg = new StringBuilder();
if (result.containsKey(ModelService.ERROR_MESSAGE_LIST)) {
List<String> errorMsgs = UtilGenerics.checkList(result.get(ModelService.ERROR_MESSAGE_LIST));
Iterator<String> iterator = errorMsgs.iterator();
errMsg.append("<ul>");
while (iterator.hasNext()) {
errMsg.append("<li>");
errMsg.append(iterator.next());
errMsg.append("</li>");
}
errMsg.append("</ul>");
} else if (result.containsKey(ModelService.ERROR_MESSAGE)) {
errMsg.append(result.get(ModelService.ERROR_MESSAGE));
request.setAttribute("_ERROR_MESSAGE_", errMsg.toString());
}
//See whether there was an error
if (errMsg.length() > 0) {
request.setAttribute("_ERROR_MESSAGE_", errMsg.toString());
if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) {
return NON_CRITICAL_ERROR;
} else {
return ERROR;
}
} else {
return NO_ERROR;
}
}
/** Assign agreement **/
public static String selectAgreement(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String agreementId = request.getParameter("agreementId");
Map<String, Object> result = cartHelper.selectAgreement(agreementId);
if (ServiceUtil.isError(result)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(result));
return "error";
}
return "success";
}
/** Assign currency **/
public static String setCurrency(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String currencyUomId = request.getParameter("currencyUomId");
Map<String, Object> result = cartHelper.setCurrency(currencyUomId);
if (ServiceUtil.isError(result)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(result));
return "error";
}
return "success";
}
/**
* set the order name of the cart based on request. right now will always return "success"
*
*/
public static String setOrderName(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
String orderName = request.getParameter("orderName");
cart.setOrderName(orderName);
return "success";
}
/**
* set the PO number of the cart based on request. right now will always return "success"
*
*/
public static String setPoNumber(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
String correspondingPoId = request.getParameter("correspondingPoId");
cart.setPoNumber(correspondingPoId);
return "success";
}
/**
* Add an order term *
*/
public static String addOrderTerm(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
Locale locale = UtilHttp.getLocale(request);
String termTypeId = request.getParameter("termTypeId");
String termValueStr = request.getParameter("termValue");
String termDaysStr = request.getParameter("termDays");
String textValue = request.getParameter("textValue");
String description = request.getParameter("description");
GenericValue termType = null;
Delegator delegator = (Delegator) request.getAttribute("delegator");
BigDecimal termValue = null;
Long termDays = null;
if (UtilValidate.isEmpty(termTypeId)) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
return "error";
}
try {
termType = EntityQuery.use(delegator).from("TermType").where("termTypeId", termTypeId).queryOne();
} catch (GenericEntityException gee) {
request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
return "error";
}
if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
return "error";
}
if (UtilValidate.isNotEmpty(termValueStr)) {
try {
termValue = new BigDecimal(termValueStr);
} catch (NumberFormatException e) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
return "error";
}
}
if (UtilValidate.isNotEmpty(termDaysStr)) {
try {
termDays = Long.valueOf(termDaysStr);
} catch (NumberFormatException e) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
return "error";
}
}
removeOrderTerm(request, response);
cart.addOrderTerm(termTypeId, null, termValue, termDays, textValue, description);
return "success";
}
/**
* Remove an order term *
*/
public static String removeOrderTerm(HttpServletRequest request, HttpServletResponse response) {
ShoppingCart cart = getCartObject(request);
String termIndexStr = request.getParameter("termIndex");
if (UtilValidate.isNotEmpty(termIndexStr)) {
try {
Integer termIndex = Integer.parseInt(termIndexStr);
if (termIndex >= 0) {
List<GenericValue> orderTerms = cart.getOrderTerms();
if (orderTerms != null && orderTerms.size() > termIndex) {
cart.removeOrderTerm(termIndex);
}
}
} catch (NumberFormatException e) {
Debug.logWarning(e, "Error parsing termIndex: " + termIndexStr, module);
}
}
return "success";
}
/** Initialize order entry from a shopping list **/
public static String loadCartFromShoppingList(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
String shoppingListId = request.getParameter("shoppingListId");
ShoppingCart cart = null;
try {
Map<String, Object> outMap = dispatcher.runSync("loadCartFromShoppingList",
UtilMisc.<String, Object>toMap("shoppingListId", shoppingListId,
"userLogin", userLogin));
cart = (ShoppingCart)outMap.get("shoppingCart");
} catch (GenericServiceException exc) {
request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
return "error";
}
session.setAttribute("shoppingCart", cart);
session.setAttribute("productStoreId", cart.getProductStoreId());
session.setAttribute("orderMode", cart.getOrderType());
session.setAttribute("orderPartyId", cart.getOrderPartyId());
return "success";
}
/** Initialize order entry from a quote **/
public static String loadCartFromQuote(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
String quoteId = request.getParameter("quoteId");
ShoppingCart cart = null;
try {
Map<String, Object> outMap = dispatcher.runSync("loadCartFromQuote",
UtilMisc.<String, Object>toMap("quoteId", quoteId,
"applyQuoteAdjustments", "true",
"userLogin", userLogin));
if (!ServiceUtil.isSuccess(outMap)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(outMap));
return "error";
}
cart = (ShoppingCart) outMap.get("shoppingCart");
} catch (GenericServiceException exc) {
request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
return "error";
}
// Set the cart's default checkout options for a quick checkout
cart.setDefaultCheckoutOptions(dispatcher);
// Make the cart read-only
cart.setReadOnlyCart(true);
session.setAttribute("shoppingCart", cart);
session.setAttribute("productStoreId", cart.getProductStoreId());
session.setAttribute("orderMode", cart.getOrderType());
session.setAttribute("orderPartyId", cart.getOrderPartyId());
return "success";
}
/** Initialize order entry from an existing order **/
public static String loadCartFromOrder(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
Delegator delegator = (Delegator) request.getAttribute("delegator");
String orderId = request.getParameter("orderId");
String createAsNewOrder = request.getParameter("createAsNewOrder");
ShoppingCart cart = null;
try {
Map<String, Object> outMap = dispatcher.runSync("loadCartFromOrder",
UtilMisc.<String, Object>toMap("orderId", orderId, "createAsNewOrder", createAsNewOrder,
"skipProductChecks", Boolean.TRUE, // the products have already been checked in the order, no need to check their validity again
"userLogin", userLogin));
if (!ServiceUtil.isSuccess(outMap)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(outMap));
return "error";
}
cart = (ShoppingCart) outMap.get("shoppingCart");
cart.removeAdjustmentByType("SALES_TAX");
cart.removeAdjustmentByType("VAT_TAX");
cart.removeAdjustmentByType("VAT_PRICE_CORRECT");
cart.removeAdjustmentByType("PROMOTION_ADJUSTMENT");
String shipGroupSeqId = null;
long groupIndex = cart.getShipInfoSize();
List<GenericValue> orderAdjustmentList = new ArrayList<GenericValue>();
List<GenericValue> orderAdjustments = new ArrayList<GenericValue>();
orderAdjustments = cart.getAdjustments();
try {
orderAdjustmentList = EntityQuery.use(delegator).from("OrderAdjustment").where("orderId", orderId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
for (long itr = 1; itr <= groupIndex; itr++) {
shipGroupSeqId = UtilFormatOut.formatPaddedNumber(itr, 5);
List<GenericValue> duplicateAdjustmentList = new ArrayList<GenericValue>();
for (GenericValue adjustment: orderAdjustmentList) {
if ("PROMOTION_ADJUSTMENT".equals(adjustment.get("orderAdjustmentTypeId"))) {
cart.addAdjustment(adjustment);
}
if ("SALES_TAX".equals(adjustment.get("orderAdjustmentTypeId"))) {
if (adjustment.get("description") != null
&& ((String)adjustment.get("description")).startsWith("Tax adjustment due")) {
cart.addAdjustment(adjustment);
}
if ("Y".equals(adjustment.getString("isManual"))) {
cart.addAdjustment(adjustment);
}
}
}
for (GenericValue orderAdjustment: orderAdjustments) {
if ("OrderAdjustment".equals(orderAdjustment.getEntityName())) {
if (("SHIPPING_CHARGES".equals(orderAdjustment.get("orderAdjustmentTypeId"))) &&
orderAdjustment.get("orderId").equals(orderId) &&
orderAdjustment.get("shipGroupSeqId").equals(shipGroupSeqId) && orderAdjustment.get("comments") == null) {
// Removing objects from list for old Shipping and Handling Charges Adjustment and Sales Tax Adjustment.
duplicateAdjustmentList.add(orderAdjustment);
}
}
}
orderAdjustments.removeAll(duplicateAdjustmentList);
}
} catch (GenericServiceException exc) {
request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
return "error";
}
cart.setAttribute("addpty", "Y");
session.setAttribute("shoppingCart", cart);
session.setAttribute("productStoreId", cart.getProductStoreId());
session.setAttribute("orderMode", cart.getOrderType());
session.setAttribute("orderPartyId", cart.getOrderPartyId());
// Since we only need the cart items, so set the order id as null
cart.setOrderId(null);
return "success";
}
public static String createQuoteFromCart(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
String destroyCart = request.getParameter("destroyCart");
ShoppingCart cart = getCartObject(request);
Map<String, Object> result = null;
String quoteId = null;
try {
result = dispatcher.runSync("createQuoteFromCart",
UtilMisc.toMap("cart", cart,
"userLogin", userLogin));
quoteId = (String) result.get("quoteId");
} catch (GenericServiceException exc) {
request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
return "error";
}
if (ServiceUtil.isError(result)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(result));
return "error";
}
request.setAttribute("quoteId", quoteId);
if (destroyCart != null && destroyCart.equals("Y")) {
ShoppingCartEvents.destroyCart(request, response);
}
return "success";
}
public static String createCustRequestFromCart(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
String destroyCart = request.getParameter("destroyCart");
ShoppingCart cart = getCartObject(request);
Map<String, Object> result = null;
String custRequestId = null;
try {
result = dispatcher.runSync("createCustRequestFromCart",
UtilMisc.toMap("cart", cart,
"userLogin", userLogin));
custRequestId = (String) result.get("custRequestId");
} catch (GenericServiceException exc) {
request.setAttribute("_ERROR_MESSAGE_", exc.getMessage());
return "error";
}
if (ServiceUtil.isError(result)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(result));
return "error";
}
request.setAttribute("custRequestId", custRequestId);
if (destroyCart != null && destroyCart.equals("Y")) {
ShoppingCartEvents.destroyCart(request, response);
}
return "success";
}
/** Initialize order entry **/
public static String initializeOrderEntry(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
HttpSession session = request.getSession();
Security security = (Security) request.getAttribute("security");
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
Locale locale = UtilHttp.getLocale(request);
String productStoreId = request.getParameter("productStoreId");
if (UtilValidate.isNotEmpty(productStoreId)) {
session.setAttribute("productStoreId", productStoreId);
}
ShoppingCart cart = getCartObject(request);
// TODO: re-factor and move this inside the ShoppingCart constructor
String orderMode = request.getParameter("orderMode");
if (orderMode != null) {
cart.setOrderType(orderMode);
session.setAttribute("orderMode", orderMode);
} else {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderPleaseSelectEitherSaleOrPurchaseOrder", locale));
return "error";
}
// check the selected product store
GenericValue productStore = null;
if (UtilValidate.isNotEmpty(productStoreId)) {
productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
if (productStore != null) {
// check permission for taking the order
boolean hasPermission = false;
if ((cart.getOrderType().equals("PURCHASE_ORDER")) && (security.hasEntityPermission("ORDERMGR", "_PURCHASE_CREATE", session))) {
hasPermission = true;
} else if (cart.getOrderType().equals("SALES_ORDER")) {
if (security.hasEntityPermission("ORDERMGR", "_SALES_CREATE", session)) {
hasPermission = true;
} else {
// if the user is a rep of the store, then he also has permission
List<GenericValue> storeReps = null;
try {
storeReps = EntityQuery.use(delegator).from("ProductStoreRole")
.where("productStoreId", productStore.getString("productStoreId"), "partyId", userLogin.getString("partyId"), "roleTypeId", "SALES_REP")
.filterByDate()
.queryList();
} catch (GenericEntityException gee) {
//
}
if (UtilValidate.isNotEmpty(storeReps)) {
hasPermission = true;
}
}
}
if (hasPermission) {
cart = ShoppingCartEvents.getCartObject(request, null, productStore.getString("defaultCurrencyUomId"));
} else {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderYouDoNotHavePermissionToTakeOrdersForThisStore", locale));
cart.clear();
session.removeAttribute("orderMode");
return "error";
}
cart.setProductStoreId(productStoreId);
} else {
cart.setProductStoreId(null);
}
}
if ("SALES_ORDER".equals(cart.getOrderType()) && UtilValidate.isEmpty(cart.getProductStoreId())) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderAProductStoreMustBeSelectedForASalesOrder", locale));
cart.clear();
session.removeAttribute("orderMode");
return "error";
}
String salesChannelEnumId = request.getParameter("salesChannelEnumId");
if (UtilValidate.isNotEmpty(salesChannelEnumId)) {
cart.setChannelType(salesChannelEnumId);
}
// set party info
String partyId = request.getParameter("supplierPartyId");
cart.setAttribute("supplierPartyId", partyId);
String originOrderId = request.getParameter("originOrderId");
cart.setAttribute("originOrderId", originOrderId);
if (UtilValidate.isNotEmpty(request.getParameter("partyId"))) {
partyId = request.getParameter("partyId");
}
String userLoginId = request.getParameter("userLoginId");
if (partyId != null || userLoginId != null) {
if (UtilValidate.isEmpty(partyId) && UtilValidate.isNotEmpty(userLoginId)) {
GenericValue thisUserLogin = null;
try {
thisUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
} catch (GenericEntityException gee) {
//
}
if (thisUserLogin != null) {
partyId = thisUserLogin.getString("partyId");
} else {
partyId = userLoginId;
}
}
if (UtilValidate.isNotEmpty(partyId)) {
GenericValue thisParty = null;
try {
thisParty = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
} catch (GenericEntityException gee) {
//
}
if (thisParty == null) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderCouldNotLocateTheSelectedParty", locale));
return "error";
} else {
cart.setOrderPartyId(partyId);
if ("PURCHASE_ORDER".equals(cart.getOrderType())) {
cart.setBillFromVendorPartyId(partyId);
}
}
} else if (partyId != null && partyId.length() == 0) {
cart.setOrderPartyId("_NA_");
partyId = null;
}
} else {
partyId = cart.getPartyId();
if (partyId != null && partyId.equals("_NA_")) partyId = null;
}
return "success";
}
/** Route order entry **/
public static String routeOrderEntry(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
// if the order mode is not set in the attributes, then order entry has not been initialized
if (session.getAttribute("orderMode") == null) {
return "init";
}
// if the request is coming from the init page, then orderMode will be in the request parameters
if (request.getParameter("orderMode") != null) {
return "agreements"; // next page after init is always agreements
}
// orderMode is set and there is an order in progress, so go straight to the cart
return "cart";
}
public static String doManualPromotions(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Delegator delegator = (Delegator) request.getAttribute("delegator");
ShoppingCart cart = getCartObject(request);
List<GenericValue> manualPromotions = new LinkedList<GenericValue>();
// iterate through the context and find all keys that start with "productPromoId_"
Map<String, Object> context = UtilHttp.getParameterMap(request);
String keyPrefix = "productPromoId_";
for (int i = 1; i <= 50; i++) {
String productPromoId = (String)context.get(keyPrefix + i);
if (UtilValidate.isNotEmpty(productPromoId)) {
try {
GenericValue promo = EntityQuery.use(delegator).from("ProductPromo").where("productPromoId", productPromoId).queryOne();
if (promo != null) {
manualPromotions.add(promo);
}
} catch (GenericEntityException gee) {
request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
return "error";
}
} else {
break;
}
}
ProductPromoWorker.doPromotions(cart, manualPromotions, dispatcher);
return "success";
}
public static String bulkAddProducts(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String controlDirective = null;
Map<String, Object> result = null;
String productId = null;
String productCategoryId = null;
String quantityStr = null;
String itemDesiredDeliveryDateStr = null;
BigDecimal quantity = BigDecimal.ZERO;
String catalogId = CatalogWorker.getCurrentCatalogId(request);
String itemType = null;
String itemDescription = "";
// Get the parameters as a MAP, remove the productId and quantity params.
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String itemGroupNumber = request.getParameter("itemGroupNumber");
// Get shoppingList info if passed. I think there can only be one shoppingList per request
String shoppingListId = request.getParameter("shoppingListId");
String shoppingListItemSeqId = request.getParameter("shoppingListItemSeqId");
// The number of multi form rows is retrieved
int rowCount = UtilHttp.getMultiFormRowCount(paramMap);
if (rowCount < 1) {
Debug.logWarning("No rows to process, as rowCount = " + rowCount, module);
} else {
for (int i = 0; i < rowCount; i++) {
controlDirective = null; // re-initialize each time
String thisSuffix = UtilHttp.getMultiRowDelimiter() + i; // current suffix after each field id
// get the productId
if (paramMap.containsKey("productId" + thisSuffix)) {
productId = (String) paramMap.remove("productId" + thisSuffix);
}
if (paramMap.containsKey("quantity" + thisSuffix)) {
quantityStr = (String) paramMap.remove("quantity" + thisSuffix);
}
if ((quantityStr == null) || (quantityStr.equals(""))) { // otherwise, every empty value causes an exception and makes the log ugly
quantityStr = "0"; // default quantity is 0, so without a quantity input, this field will not be added
}
// parse the quantity
try {
quantity = new BigDecimal(quantityStr);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing quantity string: " + quantityStr, module);
quantity = BigDecimal.ZERO;
}
try {
//For quantity we should test if we allow to add decimal quantity for this product an productStore :
// if not and if quantity is in decimal format then return error.
if(! ProductWorker.isDecimalQuantityOrderAllowed(delegator, productId, cart.getProductStoreId())){
BigDecimal remainder = quantity.remainder(BigDecimal.ONE);
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", cart.getLocale()));
return "error";
}
quantity = quantity.setScale(0, UtilNumber.getBigDecimalRoundingMode("order.rounding"));
}
else {
quantity = quantity.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getBigDecimalRoundingMode("order.rounding"));
}
} catch (GenericEntityException e) {
Debug.logWarning(e.getMessage(), module);
quantity = BigDecimal.ONE;
}
// get the selected amount
String selectedAmountStr = null;
if (paramMap.containsKey("amount" + thisSuffix)) {
selectedAmountStr = (String) paramMap.remove("amount" + thisSuffix);
}
// parse the amount
BigDecimal amount = null;
if (UtilValidate.isNotEmpty(selectedAmountStr)) {
try {
amount = new BigDecimal(selectedAmountStr);
} catch (Exception e) {
Debug.logWarning(e, "Problem parsing amount string: " + selectedAmountStr, module);
amount = null;
}
} else {
amount = BigDecimal.ZERO;
}
if (paramMap.containsKey("itemDesiredDeliveryDate" + thisSuffix)) {
itemDesiredDeliveryDateStr = (String) paramMap.remove("itemDesiredDeliveryDate" + thisSuffix);
}
// get the item type
if (paramMap.containsKey("itemType" + thisSuffix)) {
itemType = (String) paramMap.remove("itemType" + thisSuffix);
}
if (paramMap.containsKey("itemDescription" + thisSuffix)) {
itemDescription = (String) paramMap.remove("itemDescription" + thisSuffix);
}
Map<String, Object> itemAttributes = UtilMisc.<String, Object>toMap("itemDesiredDeliveryDate", itemDesiredDeliveryDateStr);
if (quantity.compareTo(BigDecimal.ZERO) > 0) {
Debug.logInfo("Attempting to add to cart with productId = " + productId + ", categoryId = " + productCategoryId +
", quantity = " + quantity + ", itemType = " + itemType + " and itemDescription = " + itemDescription, module);
result = cartHelper.addToCart(catalogId, shoppingListId, shoppingListItemSeqId, productId,
productCategoryId, itemType, itemDescription, null,
amount, quantity, null, null, null, null, null, null,
itemGroupNumber, itemAttributes,null);
// no values for price and paramMap (a context for adding attributes)
controlDirective = processResult(result, request);
if (controlDirective.equals(ERROR)) { // if the add to cart failed, then get out of this loop right away
return "error";
}
}
}
}
// Determine where to send the browser
return cart.viewCartOnAdd() ? "viewcart" : "success";
}
// request method for setting the currency, agreement, OrderId and shipment dates at once
public static String setOrderCurrencyAgreementShipDates(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Delegator delegator = (Delegator) request.getAttribute("delegator");
ShoppingCart cart = getCartObject(request);
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String agreementId = request.getParameter("agreementId");
String currencyUomId = request.getParameter("currencyUomId");
String workEffortId = request.getParameter("workEffortId");
String shipBeforeDateStr = request.getParameter("shipBeforeDate");
String shipAfterDateStr = request.getParameter("shipAfterDate");
String cancelBackOrderDateStr = request.getParameter("cancelBackOrderDate");
String orderId = request.getParameter("orderId");
String orderName = request.getParameter("orderName");
String correspondingPoId = request.getParameter("correspondingPoId");
Locale locale = UtilHttp.getLocale(request);
Map<String, Object> result = null;
// set the agreement if specified otherwise set the currency
if (UtilValidate.isNotEmpty(agreementId)) {
result = cartHelper.selectAgreement(agreementId);
}
if (UtilValidate.isNotEmpty(cart.getCurrency()) && UtilValidate.isNotEmpty(currencyUomId)) {
result = cartHelper.setCurrency(currencyUomId);
}
if (ServiceUtil.isError(result)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(result));
return "error";
}
// set the work effort id
cart.setWorkEffortId(workEffortId);
// set the order id if given
if (UtilValidate.isNotEmpty(orderId)) {
GenericValue thisOrder = null;
try {
thisOrder = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
if (thisOrder == null) {
cart.setOrderId(orderId);
} else {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderIdAlreadyExistsPleaseChooseAnother", locale));
return "error";
}
}
// set the order name
cart.setOrderName(orderName);
// set the corresponding purchase order id
cart.setPoNumber(correspondingPoId);
// set the default ship before and after dates if supplied
try {
if (UtilValidate.isNotEmpty(shipBeforeDateStr)) {
if (shipBeforeDateStr.length() == 10) shipBeforeDateStr += " 00:00:00.000";
cart.setDefaultShipBeforeDate(java.sql.Timestamp.valueOf(shipBeforeDateStr));
}
if (UtilValidate.isNotEmpty(shipAfterDateStr)) {
if (shipAfterDateStr.length() == 10) shipAfterDateStr += " 00:00:00.000";
cart.setDefaultShipAfterDate(java.sql.Timestamp.valueOf(shipAfterDateStr));
}
if (UtilValidate.isNotEmpty(cancelBackOrderDateStr)) {
if (cancelBackOrderDateStr.length() == 10) cancelBackOrderDateStr += " 00:00:00.000";
cart.setCancelBackOrderDate(java.sql.Timestamp.valueOf(cancelBackOrderDateStr));
}
} catch (IllegalArgumentException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
return "success";
}
public static String getConfigDetailsEvent(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String productId = request.getParameter("product_id");
String currencyUomId = ShoppingCartEvents.getCartObject(request).getCurrency();
ProductConfigWrapper configWrapper = ProductConfigWorker.getProductConfigWrapper(productId, currencyUomId, request);
if (configWrapper == null) {
Debug.logWarning("configWrapper is null", module);
request.setAttribute("_ERROR_MESSAGE_", "configWrapper is null");
return "error";
}
ProductConfigWorker.fillProductConfigWrapper(configWrapper, request);
if (configWrapper.isCompleted()) {
ProductConfigWorker.storeProductConfigWrapper(configWrapper, delegator);
request.setAttribute("configId", configWrapper.getConfigId());
}
request.setAttribute("totalPrice", org.apache.ofbiz.base.util.UtilFormatOut.formatCurrency(configWrapper.getTotalPrice(), currencyUomId, UtilHttp.getLocale(request)));
return "success";
}
public static String bulkAddProductsInApprovedOrder(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Locale locale = UtilHttp.getLocale(request);
String productId = null;
String productCategoryId = null;
String quantityStr = null;
String itemDesiredDeliveryDateStr = null;
BigDecimal quantity = BigDecimal.ZERO;
String itemType = null;
String itemDescription = "";
String orderId = null;
String shipGroupSeqId = null;
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
int rowCount = UtilHttp.getMultiFormRowCount(paramMap);
if (rowCount < 1) {
Debug.logWarning("No rows to process, as rowCount = " + rowCount, module);
} else {
for (int i = 0; i < rowCount; i++) {
String thisSuffix = UtilHttp.getMultiRowDelimiter() + i;
if (paramMap.containsKey("productId" + thisSuffix)) {
productId = (String) paramMap.remove("productId" + thisSuffix);
}
if (paramMap.containsKey("quantity" + thisSuffix)) {
quantityStr = (String) paramMap.remove("quantity" + thisSuffix);
}
if ((quantityStr == null) || (quantityStr.equals(""))) {
quantityStr = "0";
}
try {
quantity = new BigDecimal(quantityStr);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing quantity string: " + quantityStr, module);
quantity = BigDecimal.ZERO;
}
String selectedAmountStr = null;
if (paramMap.containsKey("amount" + thisSuffix)) {
selectedAmountStr = (String) paramMap.remove("amount" + thisSuffix);
}
BigDecimal amount = null;
if (UtilValidate.isNotEmpty(selectedAmountStr)) {
try {
amount = new BigDecimal(selectedAmountStr);
} catch (Exception e) {
Debug.logWarning(e, "Problem parsing amount string: " + selectedAmountStr, module);
amount = null;
}
} else {
amount = BigDecimal.ZERO;
}
if (paramMap.containsKey("itemDesiredDeliveryDate" + thisSuffix)) {
itemDesiredDeliveryDateStr = (String) paramMap.remove("itemDesiredDeliveryDate" + thisSuffix);
}
Timestamp itemDesiredDeliveryDate = null;
if (UtilValidate.isNotEmpty(itemDesiredDeliveryDateStr)) {
try {
itemDesiredDeliveryDate = Timestamp.valueOf(itemDesiredDeliveryDateStr);
} catch (Exception e) {
Debug.logWarning(e,"Problems parsing Reservation start string: " + itemDesiredDeliveryDateStr, module);
itemDesiredDeliveryDate = null;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"shoppingCartEvents.problem_parsing_item_desiredDeliveryDate_string", locale));
}
}
if (paramMap.containsKey("itemType" + thisSuffix)) {
itemType = (String) paramMap.remove("itemType" + thisSuffix);
}
if (paramMap.containsKey("itemDescription" + thisSuffix)) {
itemDescription = (String) paramMap.remove("itemDescription" + thisSuffix);
}
if (paramMap.containsKey("orderId" + thisSuffix)) {
orderId = (String) paramMap.remove("orderId" + thisSuffix);
}
if (paramMap.containsKey("shipGroupSeqId" + thisSuffix)) {
shipGroupSeqId = (String) paramMap.remove("shipGroupSeqId" + thisSuffix);
}
if (quantity.compareTo(BigDecimal.ZERO) > 0) {
Debug.logInfo("Attempting to add to cart with productId = " + productId + ", categoryId = " + productCategoryId +
", quantity = " + quantity + ", itemType = " + itemType + " and itemDescription = " + itemDescription, module);
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
Map<String, Object> appendOrderItemMap = new HashMap<String, Object>();
appendOrderItemMap.put("productId", productId);
appendOrderItemMap.put("quantity", quantity);
appendOrderItemMap.put("orderId", orderId);
appendOrderItemMap.put("userLogin", userLogin);
appendOrderItemMap.put("amount", amount);
appendOrderItemMap.put("itemDesiredDeliveryDate", itemDesiredDeliveryDate);
appendOrderItemMap.put("shipGroupSeqId", shipGroupSeqId);
try {
Map<String, Object> result = dispatcher.runSync("appendOrderItem", appendOrderItemMap);
request.setAttribute("shoppingCart", result.get("shoppingCart"));
ShoppingCartEvents.destroyCart(request, response);
} catch (GenericServiceException e) {
Debug.logError(e, "Failed to execute service appendOrderItem", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
}
}
}
request.setAttribute("orderId", orderId);
return "success";
}
}
| [
"gomotosho1@gmail.com"
] | gomotosho1@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.