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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3efaa50575ae90e7ab4854ba00a41648b69e90a
|
1e5d11ef9a625bf8182c11673f76b06ad171e4c9
|
/sms-gateway/sms-gateway-facade/src/main/java/com/zb/sms/gateway/dto/SendDynamicCodeResponse.java
|
22d3ace83f335d75956078bdbac21bf7b932d12e
|
[] |
no_license
|
happyjianguo/yizhangtong
|
132cf89a64ef59177209d889a064f7f3cc889135
|
f55b0a7f15377b0dc108428feb799f60de058a0b
|
refs/heads/master
| 2020-07-14T20:41:46.121337 | 2019-03-26T02:23:03 | 2019-03-26T02:23:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 861 |
java
|
package com.zb.sms.gateway.dto;
/**
* 功能: 发送验证码短信响应
* 创建: liuchongguang - [email protected]
* 日期: 2016/12/9 0009 15:46
* 版本: V1.0
*/
public class SendDynamicCodeResponse extends BaseRpcResponse {
/**
* SerialVersionUID
*/
private static final long serialVersionUID = 2216488527000336499L;
/**
* 随机码
*/
private String dynamicCode;
/**
* 构造函数
*
* @param respCode
* @param resultCode
* @param resultDesc
*/
public SendDynamicCodeResponse(int respCode, int resultCode, String resultDesc) {
super(respCode, resultCode, resultDesc);
}
public String getDynamicCode() {
return dynamicCode;
}
public void setDynamicCode(String dynamicCode) {
this.dynamicCode = dynamicCode;
}
}
|
[
"[email protected]"
] | |
05153ff29dc3df6af4efe8946a807a9fbdd2f4fa
|
5a648d2cf679741af872b68742b9f491d0aeb15c
|
/src/main/java/com/example/repository/FlyerRepo.java
|
79ca0c0fe957074cfe429b8c3462de069bb1364c
|
[] |
no_license
|
DLGdkp/MM
|
80d15d49242252cf4c5d30a01b60b63ff38dc5a3
|
d3bac1e8e9e4aa8617fdaea84afc64205711bdef
|
refs/heads/master
| 2022-12-19T00:03:48.487470 | 2020-10-03T20:04:41 | 2020-10-03T20:04:41 | 300,968,814 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 195 |
java
|
package com.example.repository;
import com.example.domain.Flyer;
import org.springframework.data.repository.CrudRepository;
public interface FlyerRepo extends CrudRepository<Flyer,Integer> {
}
|
[
"[email protected]"
] | |
ef11e87906ca2d985a335af0ae96aef0b19f6b95
|
f55fb5a7b4b08e13b679c6e463854af46e49bd74
|
/src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin/src/org/robotframework/ide/eclipse/main/plugin/project/build/RobotProjectBuilder.java
|
d84caf775bea65e2a794fa7400cab1642d43a837
|
[
"Apache-2.0"
] |
permissive
|
ChuniMuni/RED
|
6586a8b3bf5e7092623af1f9c29ced3314f80ada
|
fac8e0c2da122dc512fad02a7bd74b9b301b08e8
|
refs/heads/master
| 2020-07-03T23:42:37.793692 | 2017-12-14T06:49:03 | 2017-12-14T06:49:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,809 |
java
|
/*
* Copyright 2015 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.project.build;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.robotframework.ide.eclipse.main.plugin.RedPlugin;
import org.robotframework.ide.eclipse.main.plugin.model.LibspecsFolder;
import org.robotframework.ide.eclipse.main.plugin.model.RobotProject;
import org.robotframework.ide.eclipse.main.plugin.project.build.RobotArtifactsValidator.ModelUnitValidatorConfig;
import org.robotframework.ide.eclipse.main.plugin.project.build.RobotArtifactsValidator.ModelUnitValidatorConfigFactory;
public class RobotProjectBuilder extends IncrementalProjectBuilder {
private final BuildLogger logger;
private final ProblemsReportingStrategy reporter;
private final ProblemsReportingStrategy fatalReporter;
public RobotProjectBuilder() {
this(ProblemsReportingStrategy.reportOnly(), ProblemsReportingStrategy.reportAndPanic(), new BuildLogger());
}
public RobotProjectBuilder(final ProblemsReportingStrategy reporter, final ProblemsReportingStrategy fatalReporter,
final BuildLogger logger) {
this.reporter = reporter;
this.fatalReporter = fatalReporter;
this.logger = logger;
}
@Override
protected IProject[] build(final int kind, final Map<String, String> args, final IProgressMonitor monitor)
throws CoreException {
final RobotProject robotProject = RedPlugin.getModelManager().getModel().createRobotProject(getProject());
build(kind, robotProject, monitor);
return null;
}
public void build(final int kind, final RobotProject robotProject, final IProgressMonitor monitor)
throws CoreException {
try {
final IProject project = robotProject.getProject();
final LibspecsFolder libspecsFolder = LibspecsFolder.createIfNeeded(project);
final IResourceDelta delta = getDelta(project);
final boolean rebuildNeeded = libspecsFolder.shouldRegenerateLibspecs(delta, kind);
final Job buildJob = new RobotArtifactsBuilder(project, logger).createBuildJob(rebuildNeeded, fatalReporter,
reporter);
final ModelUnitValidatorConfig validatorConfig = ModelUnitValidatorConfigFactory.create(project, delta,
kind, reporter);
final Job validationJob = new RobotArtifactsValidator(project, logger).createValidationJob(buildJob,
validatorConfig);
try {
final String projectPath = project.getFullPath().toString();
monitor.subTask("waiting for project " + projectPath + " build end");
buildJob.schedule();
validationJob.schedule();
buildJob.join();
if (buildJob.getResult().getSeverity() == IStatus.CANCEL
|| buildJob.getResult().getSeverity() == IStatus.ERROR) {
robotProject.clearConfiguration();
if (libspecsFolder.exists()) {
libspecsFolder.remove();
validationJob.cancel();
return;
}
}
robotProject.clearConfiguration();
project.refreshLocal(IResource.DEPTH_INFINITE, null);
if (!monitor.isCanceled()) {
monitor.subTask("waiting for project " + projectPath + " validation end");
validationJob.join();
}
} catch (final InterruptedException e) {
throw new CoreException(Status.CANCEL_STATUS);
}
} finally {
monitor.worked(1);
}
}
@Override
protected void clean(final IProgressMonitor monitor) throws CoreException {
clean(RedPlugin.getModelManager().createProject(getProject()));
}
public static void clean(final RobotProject project) throws CoreException {
project.getProject().deleteMarkers(RobotProblem.TYPE_ID, true, IResource.DEPTH_INFINITE);
project.clearConfiguration();
project.clearKwSources();
LibspecsFolder.get(project.getProject()).removeNonSpecResources();
}
}
|
[
"[email protected]"
] | |
3fbd0562e33001da755f4bb985e44d3d451c6a07
|
4b49c01e9496f44ce26872ec59b271412bba8076
|
/Evaluate_Ranking_Technique/src/RankableObjects.java
|
6caf785a6ba37eb50f891d397f37883bccd7d7b9
|
[] |
no_license
|
Ahmad-Diab/Twitter-Topology
|
c97af3040b1059093b362c3ea818571ff301eded
|
d33aaa904d47b7fc5f022aa7e83914092b40c00f
|
refs/heads/master
| 2022-01-25T05:36:36.961583 | 2019-06-10T17:47:52 | 2019-06-10T17:47:52 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 948 |
java
|
import java.io.Serializable ;
public class RankableObjects implements Rankable , Serializable
{
private final String object ;
private final long count ;
public RankableObjects(String o , long cnt)
{
object = o ;
count = cnt ;
}
public static RankableObjects createRankable(Tuple input)
{
return new RankableObjects(input.s , input.count) ;
}
public String getObject() { return object; }
public long getCount() { return count; }
public Rankable copy() { return new RankableObjects(getObject() , getCount()); }
public int compareTo(Rankable o)
{
long diff = o.getCount() - this.getCount() ;
return diff < 0 ? - 1 : diff == 0 ? 0 : 1 ;
}
@Override
public boolean equals(Object o)
{
RankableObjects r = (RankableObjects) o;
return this == o || (getObject().equals(r.getObject()) && getCount() == r.getCount());
}
}
|
[
"[email protected]"
] | |
4f3929a6d8c269361a257acaf21496e20e193b69
|
14c0bf13197c50ab22595f696bbbb1c41e0df902
|
/DataTypesAndLiterals.java
|
7bdf4e59a1e556baeb349af751cd894107d1e3cd
|
[] |
no_license
|
triinfotech-edu/Java-Weekends
|
4f75c467cf5e5f4ee19e65d58c02814a3ec17469
|
905b634807150ac3822d529b906360cef367dd1c
|
refs/heads/master
| 2021-01-24T15:43:47.868225 | 2016-10-16T08:04:28 | 2016-10-16T08:04:28 | 68,497,935 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 511 |
java
|
class DataTypesAndLiterals {
public static void main(String[] args) {
// Integer Family
// 1. byte, 1B/8b, -2^7 to 2^7-1 -2^(n-1) to 2^(n-1)-1
// 2. short, 2B/16b, -2^15 to 2^15-1
// 3. int, 4B/32b, -2^31 to 2^31-1
// 4. long, 8B/64b, -2^63 to 2^63-1
// Floating-points
// 1. float, 4B/32b, -3.7X10^34 to 3.7X10^34 IEEE 542
// 2. double, 8B/64b, -1.7X10^304 to 1.7X10^304
// Character
// 1. char, 2B/16b, 0 - 2^15
// Boolean
// 1. boolean, 1B/8b, false, true 00000000/00000001
}
}
|
[
"[email protected]"
] | |
15b4d4718a68a26f7596c56b8ac02199778527ca
|
5792fa1932e8a2f78067fe7e4a856f8836d3e173
|
/octarine-core/src/main/java/com/codepoetics/octarine/consumers/C3.java
|
61c3e81f96b7584e3178a5230a5a8c63e9d1e1ea
|
[
"Apache-2.0"
] |
permissive
|
ramtej/octarine
|
274f080330c5d4cc40e65bd7611520853e2ee745
|
3cc0f4e25c95a36bbe0114886a49595c44041573
|
refs/heads/master
| 2020-12-07T07:43:07.718730 | 2014-07-11T16:15:25 | 2014-07-11T16:15:25 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 110 |
java
|
package com.codepoetics.octarine.consumers;
public interface C3<A, B, C> {
void accept(A a, B b, C c);
}
|
[
"[email protected]"
] | |
ff44cdda3d85dd24fa6624c504994ea27824c78a
|
969c757f865706cc759a80d893198a9439622bc8
|
/app/src/main/java/ir/hosseinabbasi/holidaypirates/utils/rx/SchedulerProvider.java
|
5365f21f054e29527953b29b2db3d7c2d23602f7
|
[
"Apache-2.0"
] |
permissive
|
Drjacky/HolidayPirates
|
9c18ba2dca60c714439909c59cb4e123d7c7576c
|
369e615ca00d2382d5a078bff9597e05bc4f4b64
|
refs/heads/master
| 2022-11-08T01:36:49.032832 | 2022-10-15T09:52:05 | 2022-10-15T10:05:20 | 97,256,549 | 2 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 238 |
java
|
package ir.hosseinabbasi.holidaypirates.utils.rx;
import io.reactivex.Scheduler;
/**
* Created by Dr.jacky on 2017/07/13.
*/
public interface SchedulerProvider {
Scheduler ui();
Scheduler computation();
Scheduler io();
}
|
[
"[email protected]"
] | |
3a416e5a8362c0e483c9316e3a722d75896085f6
|
60e46ab78726883cb7f38dd433c959aad580bfa6
|
/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
|
50f0dd8e02953acb282dabe1c3744ed695305f03
|
[
"GPL-1.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
leoterry-ulrica/my-dubbos
|
602fb4332470419ae3ce84c858c03b454e90aac1
|
2a29ef87b77723a7303672ec4ac7beead47778bc
|
refs/heads/master
| 2022-12-05T07:01:02.571820 | 2020-12-29T02:33:56 | 2020-12-29T02:33:56 | 55,985,297 | 0 | 1 |
Apache-2.0
| 2022-11-16T06:23:07 | 2016-04-11T15:39:39 |
Java
|
UTF-8
|
Java
| false | false | 27,984 |
java
|
/*
* Copyright 1999-2011 Alibaba Group.
*
* 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.dubbo.config;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.Version;
import com.alibaba.dubbo.common.bytecode.Wrapper;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.utils.ClassHelper;
import com.alibaba.dubbo.common.utils.ConfigUtils;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.config.support.Parameter;
import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Protocol;
import com.alibaba.dubbo.rpc.ProxyFactory;
import com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory;
import com.alibaba.dubbo.rpc.ServiceClassHolder;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.dubbo.rpc.support.ProtocolUtils;
/**
* ServiceConfig
*
* @author william.liangf
* @export
*/
public class ServiceConfig<T> extends AbstractServiceConfig {
private static final long serialVersionUID = 3033787999037024738L;
private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
private static final Map<String, Integer> RANDOM_PORT_MAP = new HashMap<String, Integer>();
// 接口类型
private String interfaceName;
private Class<?> interfaceClass;
// 接口实现类引用
private T ref;
// 服务名称
private String path;
// 方法配置
private List<MethodConfig> methods;
private ProviderConfig provider;
private final List<URL> urls = new ArrayList<URL>();
private final List<Exporter<?>> exporters = new ArrayList<Exporter<?>>();
private transient volatile boolean exported;
private transient volatile boolean unexported;
private volatile String generic;
public ServiceConfig() {
}
public ServiceConfig(Service service) {
appendAnnotation(Service.class, service);
}
public URL toUrl() {
return urls == null || urls.size() == 0 ? null : urls.iterator().next();
}
public List<URL> toUrls() {
return urls;
}
@Parameter(excluded = true)
public boolean isExported() {
return exported;
}
@Parameter(excluded = true)
public boolean isUnexported() {
return unexported;
}
public synchronized void export() {
if (provider != null) {
if (export == null) {
export = provider.getExport();
}
if (delay == null) {
delay = provider.getDelay();
}
}
if (export != null && ! export.booleanValue()) {
return;
}
if (delay != null && delay > 0) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(delay);
} catch (Throwable e) {
}
doExport();
}
});
thread.setDaemon(true);
thread.setName("DelayExportServiceThread");
thread.start();
} else {
doExport();
}
}
protected synchronized void doExport() {
if (unexported) {
throw new IllegalStateException("Already unexported!");
}
if (exported) {
return;
}
exported = true;
if (interfaceName == null || interfaceName.length() == 0) {
throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");
}
checkDefault();
if (provider != null) {
if (application == null) {
application = provider.getApplication();
}
if (module == null) {
module = provider.getModule();
}
if (registries == null) {
registries = provider.getRegistries();
}
if (monitor == null) {
monitor = provider.getMonitor();
}
if (protocols == null) {
protocols = provider.getProtocols();
}
}
if (module != null) {
if (registries == null) {
registries = module.getRegistries();
}
if (monitor == null) {
monitor = module.getMonitor();
}
}
if (application != null) {
if (registries == null) {
registries = application.getRegistries();
}
if (monitor == null) {
monitor = application.getMonitor();
}
}
if (ref instanceof GenericService) {
interfaceClass = GenericService.class;
if (StringUtils.isEmpty(generic)) {
generic = Boolean.TRUE.toString();
}
} else {
try {
interfaceClass = Class.forName(interfaceName, true, Thread.currentThread()
.getContextClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
checkInterfaceAndMethods(interfaceClass, methods);
checkRef();
generic = Boolean.FALSE.toString();
}
if(local !=null){
if(local=="true"){
local=interfaceName+"Local";
}
Class<?> localClass;
try {
localClass = ClassHelper.forNameWithThreadContextClassLoader(local);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if(!interfaceClass.isAssignableFrom(localClass)){
throw new IllegalStateException("The local implemention class " + localClass.getName() + " not implement interface " + interfaceName);
}
}
if(stub !=null){
if(stub=="true"){
stub=interfaceName+"Stub";
}
Class<?> stubClass;
try {
stubClass = ClassHelper.forNameWithThreadContextClassLoader(stub);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if(!interfaceClass.isAssignableFrom(stubClass)){
throw new IllegalStateException("The stub implemention class " + stubClass.getName() + " not implement interface " + interfaceName);
}
}
checkApplication();
checkRegistry();
checkProtocol();
appendProperties(this);
checkStubAndMock(interfaceClass);
if (path == null || path.length() == 0) {
path = interfaceName;
}
doExportUrls();
}
private void checkRef() {
// 检查引用不为空,并且引用必需实现接口
if (ref == null) {
throw new IllegalStateException("ref not allow null!");
}
if (! interfaceClass.isInstance(ref)) {
throw new IllegalStateException("The class "
+ ref.getClass().getName() + " unimplemented interface "
+ interfaceClass + "!");
}
}
public synchronized void unexport() {
if (! exported) {
return;
}
if (unexported) {
return;
}
if (exporters != null && exporters.size() > 0) {
for (Exporter<?> exporter : exporters) {
try {
exporter.unexport();
} catch (Throwable t) {
logger.warn("unexpected err when unexport" + exporter, t);
}
}
exporters.clear();
}
unexported = true;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void doExportUrls() {
List<URL> registryURLs = loadRegistries(true);
for (ProtocolConfig protocolConfig : protocols) {
doExportUrlsFor1Protocol(protocolConfig, registryURLs);
}
}
private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List<URL> registryURLs) {
String name = protocolConfig.getName();
if (name == null || name.length() == 0) {
name = "dubbo";
}
String host = protocolConfig.getHost();
if (provider != null && (host == null || host.length() == 0)) {
host = provider.getHost();
}
boolean anyhost = false;
if (NetUtils.isInvalidLocalHost(host)) {
anyhost = true;
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.warn(e.getMessage(), e);
}
if (NetUtils.isInvalidLocalHost(host)) {
if (registryURLs != null && registryURLs.size() > 0) {
for (URL registryURL : registryURLs) {
try {
Socket socket = new Socket();
try {
SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
socket.connect(addr, 1000);
host = socket.getLocalAddress().getHostAddress();
break;
} finally {
try {
socket.close();
} catch (Throwable e) {}
}
} catch (Exception e) {
logger.warn(e.getMessage(), e);
}
}
}
if (NetUtils.isInvalidLocalHost(host)) {
host = NetUtils.getLocalHost();
}
}
}
Integer port = protocolConfig.getPort();
if (provider != null && (port == null || port == 0)) {
port = provider.getPort();
}
final int defaultPort = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).getDefaultPort();
if (port == null || port == 0) {
port = defaultPort;
}
if (port == null || port <= 0) {
port = getRandomPort(name);
if (port == null || port < 0) {
port = NetUtils.getAvailablePort(defaultPort);
putRandomPort(name, port);
}
logger.warn("Use random available port(" + port + ") for protocol " + name);
}
Map<String, String> map = new HashMap<String, String>();
if (anyhost) {
map.put(Constants.ANYHOST_KEY, "true");
}
map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE);
map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion());
map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));
if (ConfigUtils.getPid() > 0) {
map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid()));
}
appendParameters(map, application);
appendParameters(map, module);
appendParameters(map, provider, Constants.DEFAULT_KEY);
appendParameters(map, protocolConfig);
appendParameters(map, this);
if (methods != null && methods.size() > 0) {
for (MethodConfig method : methods) {
appendParameters(map, method, method.getName());
String retryKey = method.getName() + ".retry";
if (map.containsKey(retryKey)) {
String retryValue = map.remove(retryKey);
if ("false".equals(retryValue)) {
map.put(method.getName() + ".retries", "0");
}
}
List<ArgumentConfig> arguments = method.getArguments();
if (arguments != null && arguments.size() > 0) {
for (ArgumentConfig argument : arguments) {
//类型自动转换.
if(argument.getType() != null && argument.getType().length() >0){
Method[] methods = interfaceClass.getMethods();
//遍历所有方法
if(methods != null && methods.length > 0){
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
//匹配方法名称,获取方法签名.
if(methodName.equals(method.getName())){
Class<?>[] argtypes = methods[i].getParameterTypes();
//一个方法中单个callback
if (argument.getIndex() != -1 ){
if (argtypes[argument.getIndex()].getName().equals(argument.getType())){
appendParameters(map, argument, method.getName() + "." + argument.getIndex());
}else {
throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType());
}
} else {
//一个方法中多个callback
for (int j = 0 ;j<argtypes.length ;j++) {
Class<?> argclazz = argtypes[j];
if (argclazz.getName().equals(argument.getType())){
appendParameters(map, argument, method.getName() + "." + j);
if (argument.getIndex() != -1 && argument.getIndex() != j){
throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType());
}
}
}
}
}
}
}
}else if(argument.getIndex() != -1){
appendParameters(map, argument, method.getName() + "." + argument.getIndex());
}else {
throw new IllegalArgumentException("argument config must set index or type attribute.eg: <dubbo:argument index='0' .../> or <dubbo:argument type=xxx .../>");
}
}
}
} // end of methods for
}
if (ProtocolUtils.isGeneric(generic)) {
map.put("generic", generic);
map.put("methods", Constants.ANY_VALUE);
} else {
String revision = Version.getVersion(interfaceClass, version);
if (revision != null && revision.length() > 0) {
map.put("revision", revision);
}
String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();
if(methods.length == 0) {
logger.warn("NO method found in service interface " + interfaceClass.getName());
map.put("methods", Constants.ANY_VALUE);
}
else {
map.put("methods", StringUtils.join(new HashSet<String>(Arrays.asList(methods)), ","));
}
}
if (! ConfigUtils.isEmpty(token)) {
if (ConfigUtils.isDefault(token)) {
map.put("token", UUID.randomUUID().toString());
} else {
map.put("token", token);
}
}
if ("injvm".equals(protocolConfig.getName())) {
protocolConfig.setRegister(false);
map.put("notify", "false");
}
// 导出服务
String contextPath = protocolConfig.getContextpath();
if ((contextPath == null || contextPath.length() == 0) && provider != null) {
contextPath = provider.getContextpath();
}
URL url = new URL(name, host, port, (contextPath == null || contextPath.length() == 0 ? "" : contextPath + "/") + path, map);
if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
.hasExtension(url.getProtocol())) {
url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
.getExtension(url.getProtocol()).getConfigurator(url).configure(url);
}
String scope = url.getParameter(Constants.SCOPE_KEY);
//配置为none不暴露
if (! Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) {
//配置不是remote的情况下做本地暴露 (配置为remote,则表示只暴露远程服务)
if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) {
exportLocal(url);
}
//如果配置不是local则暴露为远程服务.(配置为local,则表示只暴露远程服务)
if (! Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope) ){
if (logger.isInfoEnabled()) {
logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);
}
if (registryURLs != null && registryURLs.size() > 0
&& url.getParameter("register", true)) {
for (URL registryURL : registryURLs) {
url = url.addParameterIfAbsent("dynamic", registryURL.getParameter("dynamic"));
URL monitorUrl = loadMonitor(registryURL);
if (monitorUrl != null) {
url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString());
}
if (logger.isInfoEnabled()) {
logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL);
}
Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString()));
Exporter<?> exporter = protocol.export(invoker);
exporters.add(exporter);
}
} else {
Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url);
Exporter<?> exporter = protocol.export(invoker);
exporters.add(exporter);
}
}
}
this.urls.add(url);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void exportLocal(URL url) {
if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
URL local = URL.valueOf(url.toFullString())
.setProtocol(Constants.LOCAL_PROTOCOL)
.setHost(NetUtils.LOCALHOST)
.setPort(0);
// modified by lishen
ServiceClassHolder.getInstance().pushServiceClass(getServiceClass(ref));
Exporter<?> exporter = protocol.export(
proxyFactory.getInvoker(ref, (Class) interfaceClass, local));
exporters.add(exporter);
logger.info("Export dubbo service " + interfaceClass.getName() +" to local registry");
}
}
protected Class getServiceClass(T ref) {
return ref.getClass();
}
private void checkDefault() {
if (provider == null) {
provider = new ProviderConfig();
}
appendProperties(provider);
}
private void checkProtocol() {
if ((protocols == null || protocols.size() == 0)
&& provider != null) {
setProtocols(provider.getProtocols());
}
// 兼容旧版本
if (protocols == null || protocols.size() == 0) {
setProtocol(new ProtocolConfig());
}
for (ProtocolConfig protocolConfig : protocols) {
if (StringUtils.isEmpty(protocolConfig.getName())) {
protocolConfig.setName("dubbo");
}
appendProperties(protocolConfig);
}
}
public Class<?> getInterfaceClass() {
if (interfaceClass != null) {
return interfaceClass;
}
if (ref instanceof GenericService) {
return GenericService.class;
}
try {
if (interfaceName != null && interfaceName.length() > 0) {
this.interfaceClass = Class.forName(interfaceName, true, Thread.currentThread()
.getContextClassLoader());
}
} catch (ClassNotFoundException t) {
throw new IllegalStateException(t.getMessage(), t);
}
return interfaceClass;
}
/**
* @deprecated
* @see #setInterface(Class)
* @param interfaceClass
*/
public void setInterfaceClass(Class<?> interfaceClass) {
setInterface(interfaceClass);
}
public String getInterface() {
return interfaceName;
}
public void setInterface(String interfaceName) {
this.interfaceName = interfaceName;
if (id == null || id.length() == 0) {
id = interfaceName;
}
}
public void setInterface(Class<?> interfaceClass) {
if (interfaceClass != null && ! interfaceClass.isInterface()) {
throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!");
}
this.interfaceClass = interfaceClass;
setInterface(interfaceClass == null ? (String) null : interfaceClass.getName());
}
public T getRef() {
return ref;
}
public void setRef(T ref) {
this.ref = ref;
}
@Parameter(excluded = true)
public String getPath() {
return path;
}
public void setPath(String path) {
checkPathName("path", path);
this.path = path;
}
public List<MethodConfig> getMethods() {
return methods;
}
@SuppressWarnings("unchecked")
public void setMethods(List<? extends MethodConfig> methods) {
this.methods = (List<MethodConfig>) methods;
}
public ProviderConfig getProvider() {
return provider;
}
public void setGeneric(String generic) {
if (StringUtils.isEmpty(generic)) { return; }
if (ProtocolUtils.isGeneric(generic)) {
this.generic = generic;
} else {
throw new IllegalArgumentException("Unsupported generic type " + generic);
}
}
public String getGeneric() {
return generic;
}
public void setProvider(ProviderConfig provider) {
this.provider = provider;
}
public List<URL> getExportedUrls(){
return urls;
}
// ======== Deprecated ========
/**
* @deprecated Replace to getProtocols()
*/
@Deprecated
public List<ProviderConfig> getProviders() {
return convertProtocolToProvider(protocols);
}
/**
* @deprecated Replace to setProtocols()
*/
@Deprecated
public void setProviders(List<ProviderConfig> providers) {
this.protocols = convertProviderToProtocol(providers);
}
@Deprecated
private static final List<ProtocolConfig> convertProviderToProtocol(List<ProviderConfig> providers) {
if (providers == null || providers.size() == 0) {
return null;
}
List<ProtocolConfig> protocols = new ArrayList<ProtocolConfig>(providers.size());
for (ProviderConfig provider : providers) {
protocols.add(convertProviderToProtocol(provider));
}
return protocols;
}
@Deprecated
private static final List<ProviderConfig> convertProtocolToProvider(List<ProtocolConfig> protocols) {
if (protocols == null || protocols.size() == 0) {
return null;
}
List<ProviderConfig> providers = new ArrayList<ProviderConfig>(protocols.size());
for (ProtocolConfig provider : protocols) {
providers.add(convertProtocolToProvider(provider));
}
return providers;
}
@Deprecated
private static final ProtocolConfig convertProviderToProtocol(ProviderConfig provider) {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName(provider.getProtocol().getName());
protocol.setServer(provider.getServer());
protocol.setClient(provider.getClient());
protocol.setCodec(provider.getCodec());
protocol.setHost(provider.getHost());
protocol.setPort(provider.getPort());
protocol.setPath(provider.getPath());
protocol.setPayload(provider.getPayload());
protocol.setThreads(provider.getThreads());
protocol.setParameters(provider.getParameters());
return protocol;
}
@Deprecated
private static final ProviderConfig convertProtocolToProvider(ProtocolConfig protocol) {
ProviderConfig provider = new ProviderConfig();
provider.setProtocol(protocol);
provider.setServer(protocol.getServer());
provider.setClient(protocol.getClient());
provider.setCodec(protocol.getCodec());
provider.setHost(protocol.getHost());
provider.setPort(protocol.getPort());
provider.setPath(protocol.getPath());
provider.setPayload(protocol.getPayload());
provider.setThreads(protocol.getThreads());
provider.setParameters(protocol.getParameters());
return provider;
}
private static Integer getRandomPort(String protocol) {
protocol = protocol.toLowerCase();
if (RANDOM_PORT_MAP.containsKey(protocol)) {
return RANDOM_PORT_MAP.get(protocol);
}
return Integer.MIN_VALUE;
}
private static void putRandomPort(String protocol, Integer port) {
protocol = protocol.toLowerCase();
if (!RANDOM_PORT_MAP.containsKey(protocol)) {
RANDOM_PORT_MAP.put(protocol, port);
}
}
}
|
[
"[email protected]"
] | |
2e58fbe5541cea4ea8c9572483fc946d0d347985
|
6659fc5ba4cb0591bfc3d665da983a2d41849ea1
|
/CustomViewTest/app/src/androidTest/java/com/example/four/customviewtest/ExampleInstrumentedTest.java
|
88979a729c6113dc898a18fb88c8c1c4b9870580
|
[] |
no_license
|
FourGitHub/AS_Projects-_Backup
|
565895657764ebb9e0d7536afae8ebd046ad7ee7
|
25ed30a2761ce50f8c59afcb428519ae8ea45c23
|
refs/heads/master
| 2020-08-08T00:56:41.589625 | 2019-10-08T13:24:58 | 2019-10-08T13:24:58 | 213,648,936 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 789 |
java
|
package com.example.four.customviewtest;
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() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.four.customviewtest", appContext.getPackageName());
}
}
|
[
"[email protected]"
] | |
0cb37ae1a6ba752c1ab90701493d75e2960c045c
|
d900bec03be428bafb679ca4e7c89e018ca92cb4
|
/Deadlock.java
|
45eabbc09c5f35e66b625c1bc52a04580507f510
|
[] |
no_license
|
Yashvishnoi/Java
|
b1f747a77e527e1e0428cea6b95608b29940d972
|
a0f29999e2ceb49c2b60c050f5b0c5d24cf46657
|
refs/heads/master
| 2023-04-18T08:48:05.735279 | 2021-05-07T18:20:38 | 2021-05-07T18:20:38 | 329,192,318 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 856 |
java
|
public class Deadlock {
String s1="Aman";
String s2 = "Vijay";
Thread t1 = new Thread() {
public void run() {
while(true) {
synchronized(s1){
try {
System.out.println(Thread.currentThread().getName()+"locked"+s1);
Thread .sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(s2) {
System.out.println(Thread.currentThread().getName()+"locked"+s2);
System.out.println(s1+s2);
}
}
}
}
};
Thread t2 = new Thread() {
public void run() {
while(true) {
synchronized(s2){
synchronized(s1) {
System.out.println(Thread.currentThread().getName()+"locked"+s1);
System.out.println(s1+s2);
}
}
}
}
};
public static void main(String[] args) {
Deadlock obj = new Deadlock();
obj.t1.start();
obj.t2.start();
}
}
|
[
"[email protected]"
] | |
3ed9f3398a18bc69ff672ea931c210308fe23177
|
997671f19029f6fce4ab5ff494e6e661695566dd
|
/src/main/java/epam/project/builder/BicycleBuilder.java
|
50b1e7c0a0e80489e91b3ad16ad34c60bb92f454
|
[] |
no_license
|
KostyaHomich/Bicycle_hire-Homich.K
|
3836ef97863f8320b0d5df08d3a40d3636274fa5
|
65cb517884d4f2526c328be7a6db5ab3eda95d8f
|
refs/heads/master
| 2022-09-12T16:53:37.242402 | 2019-09-09T10:59:54 | 2019-09-09T10:59:54 | 160,558,185 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,155 |
java
|
package epam.project.builder;
import epam.project.entity.Bicycle;
import java.util.Map;
public class BicycleBuilder implements Builder<Bicycle> {
private static final String ID = "bicycleId";
private static final String NAME = "name";
private static final String DESCRIPTION = "description";
private static final String POINT_HIRE_ID = "pointHireId";
@Override
public Bicycle build(Map<String, String> params) {
Bicycle bicycle = new Bicycle();
for (Object key : params.keySet()) {
String keyStr = (String) key;
String value = params.get(keyStr);
switch (keyStr) {
case NAME:
bicycle.setName(value);
break;
case DESCRIPTION:
bicycle.setDescription(value);
break;
case ID:
bicycle.setId(Integer.valueOf(value));
case POINT_HIRE_ID:
bicycle.setPointHireId(Integer.valueOf(value));
default:
break;
}
}
return bicycle;
}
}
|
[
"[email protected]"
] | |
e804e87c55928acfa24e239e03d4e72ad08dcc20
|
8622320f37055b55ce6074beb474d92f70bc8356
|
/RPEC-ExpressionValidationStack/src/Pilha.java
|
3088d64996a28d1bc2eb50fbde0c809cb7139413
|
[] |
no_license
|
LucasKleaL/RPEC
|
3b61af5b3c6a6b20779c197e33f7282be2da634d
|
d004b3efb92986febfd11c93e47c27712847e44d
|
refs/heads/main
| 2023-06-16T11:47:34.303008 | 2021-07-06T21:13:42 | 2021-07-06T21:13:42 | 383,597,870 | 0 | 0 | null | null | null | null |
ISO-8859-1
|
Java
| false | false | 893 |
java
|
public class Pilha {
private int topo;
private char[] dados;
private int max;
public Pilha() {
topo = -1;
}
public int topo() {
return topo;
}
public char caracterTopo() {
if (vazia()) {
return ' ';
}
else {
return dados[topo];
}
}
public boolean vazia() {
if (topo < 0) {
return true;
}
else {
return false;
}
}
public boolean cheia() {
if (topo == max-1) {
return true;
}
else {
return false;
}
}
public void empilha(char elemento) {
if (cheia()) {
System.out.println("Não foi possível empilhar. A pilha está cheia.");
}
else {
dados[++topo] = elemento;
}
}
public void desempilhar() {
if (vazia()) {
System.out.println("Pilha vazia.");
}
else {
topo--;
}
}
public void cria_pilha(int n) {
max = n;
this.dados = new char[max];
}
}
|
[
"[email protected]"
] | |
9af09b25ce97e00906537ec11b0ac53cdde1f75a
|
fd4879e06627f0befc4d5d6ed4e24ecc03805647
|
/app/src/main/java/nl/hypothermic/meefietsen/dialogs/ContactSelectDialog.java
|
4ebbaedb81f0db868dc0cfd4b836b9feb03f5359
|
[] |
no_license
|
MeefietsApp/app
|
6c422e076a950654d2a5681119681b35e5b8b7ed
|
988a9a88a1f050491b5f9bbf09f39a6d4e8a3eaa
|
refs/heads/master
| 2020-03-31T00:42:35.693975 | 2019-01-04T14:55:51 | 2019-01-04T14:55:51 | 151,751,137 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,142 |
java
|
package nl.hypothermic.meefietsen.dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import nl.hypothermic.meefietsen.WelcomeActivity;
public class ContactSelectDialog extends DialogFragment {
// TODO! met een recycler met laatst gebruikte contacten
// (en een handmatig input field (zie integrity/PhoneNumberFormatter.java))
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.act);
builder.setMessage("Server not reachable.")
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
;
}
});
return builder.create();
}
}
|
[
"[email protected]"
] | |
fa6c7486dbd979458cad077daec925441a7f88ad
|
7a8b78eded48dd7b2fab42220f0ab601aab09b4e
|
/CreationalDesign Patterns/AbstractFactoryPattern/src/com/test/FactoryCreator.java
|
6b2f9979dd9dc75f32f7e4c5c62c55119822e2ce
|
[] |
no_license
|
manohar427/DesignPatterns
|
a3966c5c5672cbeaedf5e7bd34c12d5497ebe9a7
|
6ab8e48769292ad6d6ab68d1f85a8bd0cff1d031
|
refs/heads/master
| 2022-06-30T07:22:56.101142 | 2020-05-09T18:52:25 | 2020-05-09T18:52:25 | 262,235,180 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 327 |
java
|
package com.test;
public class FactoryCreator {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("Bank")){
return new BankFactory();
} else if(choice.equalsIgnoreCase("Loan")){
return new LoanFactory();
}
return null;
}
}
|
[
"[email protected]"
] | |
28b91e9a6bcbbd7d7e455db66b33d28bbd210efa
|
5002b77c45c9aaa9456d14e4876972a40dde376c
|
/app/src/main/java/com/mrsoftit/homefit/waist_hip_ratio/Waist_Hip_Ratio_Chart.java
|
710cecffae17cf7e79c505bd69044cb8e2afa1b1
|
[] |
no_license
|
mijantck/Health_And_Fitness
|
3a35861e6ccc984ac19a334156ebed5c00149799
|
6ebb7e62a57f6ec080e6839113b08cc80886af8f
|
refs/heads/master
| 2023-04-22T06:53:32.313793 | 2021-05-09T20:58:17 | 2021-05-09T20:58:17 | 365,126,511 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,972 |
java
|
package com.mrsoftit.homefit.waist_hip_ratio;
import android.app.Activity;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdRequest.Builder;
import com.google.android.gms.ads.AdView;
import com.mrsoftit.homefit.R;
import com.mrsoftit.homefit.utils.GlobalFunction;
import com.mrsoftit.homefit.utils.SharedPreferenceManager;
import com.mrsoftit.homefit.utils.TypefaceManager;
public class Waist_Hip_Ratio_Chart extends Activity {
String TAG = getClass().getSimpleName();
GlobalFunction globalFunction;
ImageView iv_back;
SharedPreferenceManager sharedPreferenceManager;
TextView tv_avg_fat;
TextView tv_avg_fat_man;
TextView tv_avg_fat_woman;
TextView tv_bodyfat;
TextView tv_fat_level;
TextView tv_low_fat;
TextView tv_low_fat_man;
TextView tv_low_fat_woman;
TextView tv_men_fatlevel;
TextView tv_title;
TextView tv_vlow_fat;
TextView tv_vlow_fat_man;
TextView tv_vlow_fat_woman;
TextView tv_women_fatlevel;
TypefaceManager typefaceManager;
public void attachBaseContext(Context context) {
super.attachBaseContext(uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper.wrap(context));
}
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.waist_hip_ratio_chart);
this.sharedPreferenceManager = new SharedPreferenceManager(this);
this.globalFunction = new GlobalFunction(this);
this.typefaceManager = new TypefaceManager(getAssets(), this);
this.iv_back = (ImageView) findViewById(R.id.iv_back);
this.tv_title = (TextView) findViewById(R.id.tv_title);
this.tv_bodyfat = (TextView) findViewById(R.id.tv_bodyfat);
this.tv_fat_level = (TextView) findViewById(R.id.tv_fat_level);
this.tv_men_fatlevel = (TextView) findViewById(R.id.tv_men_fatlevel);
this.tv_women_fatlevel = (TextView) findViewById(R.id.tv_women_fatlevel);
this.tv_vlow_fat = (TextView) findViewById(R.id.tv_vlow_fat);
this.tv_low_fat = (TextView) findViewById(R.id.tv_low_fat);
this.tv_avg_fat = (TextView) findViewById(R.id.tv_avg_fat);
this.tv_vlow_fat_man = (TextView) findViewById(R.id.tv_vlow_fat_man);
this.tv_vlow_fat_woman = (TextView) findViewById(R.id.tv_vlow_fat_woman);
this.tv_low_fat_man = (TextView) findViewById(R.id.tv_low_fat_man);
this.tv_low_fat_woman = (TextView) findViewById(R.id.tv_low_fat_woman);
this.tv_avg_fat_man = (TextView) findViewById(R.id.tv_avg_fat_man);
this.tv_avg_fat_woman = (TextView) findViewById(R.id.tv_avg_fat_woman);
this.tv_title.setTypeface(this.typefaceManager.getBold());
this.tv_bodyfat.setTypeface(this.typefaceManager.getBold());
this.tv_fat_level.setTypeface(this.typefaceManager.getBold());
this.tv_men_fatlevel.setTypeface(this.typefaceManager.getBold());
this.tv_women_fatlevel.setTypeface(this.typefaceManager.getBold());
this.tv_vlow_fat.setTypeface(this.typefaceManager.getBold());
this.tv_low_fat.setTypeface(this.typefaceManager.getBold());
this.tv_avg_fat.setTypeface(this.typefaceManager.getBold());
this.tv_vlow_fat_man.setTypeface(this.typefaceManager.getLight());
this.tv_vlow_fat_woman.setTypeface(this.typefaceManager.getLight());
this.tv_low_fat_man.setTypeface(this.typefaceManager.getLight());
this.tv_low_fat_woman.setTypeface(this.typefaceManager.getLight());
this.tv_avg_fat_man.setTypeface(this.typefaceManager.getLight());
this.tv_avg_fat_woman.setTypeface(this.typefaceManager.getLight());
this.globalFunction.sendAnalyticsData(this.TAG, this.TAG);
if (VERSION.SDK_INT >= 21) {
getWindow().addFlags(67108864);
}
if (this.sharedPreferenceManager.get_Remove_Ad().booleanValue()) {
} else {
}
this.iv_back.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Waist_Hip_Ratio_Chart.this.onBackPressed();
}
});
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() != 16908332) {
return super.onOptionsItemSelected(menuItem);
}
onBackPressed();
return true;
}
public void onBackPressed() {
super.onBackPressed();
finish();
}
public void onResume() {
super.onResume();
if (!this.sharedPreferenceManager.get_Remove_Ad().booleanValue()) {
} else {
}
}
}
|
[
"[email protected]"
] | |
f90f370a46985f6ff36f170e24430765eed4e75c
|
01459ad1d33ccc28b00b05bfcb6d3eb76ecb7bbc
|
/src/main/java/tms/c29/lec_13/classwork/part_1/Student.java
|
b659d2568ae9f55ef7b3dd1dfbd94930c3f53408
|
[] |
no_license
|
RezviyBelorus/tms-c29-2019
|
008beda32983cbc933cd144b2933c1a8a967eef9
|
e99db88e564486f7f9de63587119b372d877839f
|
refs/heads/master
| 2022-11-24T10:14:05.333555 | 2019-12-08T09:30:13 | 2019-12-08T09:30:13 | 226,290,429 | 1 | 0 | null | 2022-11-15T23:53:05 | 2019-12-06T09:17:38 |
Java
|
UTF-8
|
Java
| false | false | 572 |
java
|
package tms.c29.lec_13.classwork.part_1;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public Student setName(String name) {
this.name = name;
return this;
}
public int getAge() {
return age;
}
public Student setAge(int age) {
this.age = age;
return this;
}
public static void main(String[] args) {
Student student = new Student();
student
.setName("name")
.setAge(13);
}
}
|
[
"[email protected]"
] | |
34ba5e9a9de9d8292e3ccd7ed7bb648e3cded144
|
544a0c76d38f1a4dbcfc2d7e80b9480089d2e18d
|
/Final_group1/src/main/java/com/group/DAO/CartDAO.java
|
277241faeda99675542197dd6d120a2d5efc1316
|
[] |
no_license
|
MentorAmogh/SurgicalsHub
|
6dd25bc096a618ae82c88be2145d246775965c80
|
d22515c781767fb411687bac8f8563effcdc0bb0
|
refs/heads/master
| 2020-12-25T14:39:18.868126 | 2016-09-21T19:45:58 | 2016-09-21T19:45:58 | 67,364,345 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 369 |
java
|
package com.group.DAO;
import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.group.model.Cart;
import com.group.model.Products;
import com.google.gson.Gson;
@Repository
public class CartDAO
{
}
|
[
"[email protected]"
] | |
5eb1b4dec45703dec8447358ae0aa905d9040934
|
71b2a435af3205818ffcf77b43de13feded76c23
|
/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapper.java
|
7f2f523358a46cb3aefbd03b942e962abdfd9082
|
[
"Apache-2.0"
] |
permissive
|
wojtekk123/spring-security
|
8f9dd6ecdd023306a0a58e9ce617d3fe3b2e0cfb
|
e729819ce05d7b49531cdfe7d778ca1d15a5c7b8
|
refs/heads/master
| 2020-08-24T20:23:17.044467 | 2010-02-12T15:18:01 | 2010-02-12T15:18:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,276 |
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 org.springframework.security.access.hierarchicalroles;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
/**
* This class wraps Spring Security's <tt>UserDetailsService</tt> in a way that its <tt>loadUserByUsername()</tt>
* method returns wrapped <tt>UserDetails</tt> that return all hierachically reachable authorities
* instead of only the directly assigned authorities.
*
* @author Michael Mayr
* @deprecated use a {@link RoleHierarchyVoter} instead of populating the user Authentication object
* with the additional authorities.
*/
public class UserDetailsServiceWrapper implements UserDetailsService {
private UserDetailsService userDetailsService = null;
private RoleHierarchy roleHierarchy = null;
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
this.roleHierarchy = roleHierarchy;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// wrapped UserDetailsService might throw UsernameNotFoundException or DataAccessException which will then bubble up
return new UserDetailsWrapper(userDetails, roleHierarchy);
}
public UserDetailsService getWrappedUserDetailsService() {
return userDetailsService;
}
}
|
[
"[email protected]"
] | |
b7d87a872fd12efeb963fefb094396e8cbaf36e3
|
82e0e6840380cc37b891f58b29dbed2e77aaaf45
|
/Calculadora/app/src/androidTest/java/usuario/app/calculadora/ExampleInstrumentedTest.java
|
f7dbfa57a5e82baa624747dd8b1eb707ed2ad637
|
[] |
no_license
|
eduardoaraujocunhaa/learning-android
|
f18712e2bd774e498cf40562ee60f096b199e6bf
|
2c1b3e946d0676f8ae9660260e79c1852761fbbe
|
refs/heads/master
| 2020-12-31T06:24:00.174101 | 2017-03-05T08:10:39 | 2017-03-05T08:10:39 | 80,594,061 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 750 |
java
|
package usuario.app.calculadora;
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.*;
/**
* Instrumentation 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() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("usuario.app.calculadora", appContext.getPackageName());
}
}
|
[
"[email protected]"
] | |
8d4e623eaf23ea0663af4c477ccfd4020e240dd0
|
079e3ffe8325fd34137ccac1211bd934ae6d5ece
|
/src/com/afforess/minecartmaniacore/utils/ItemUtils.java
|
230119c3c7a92e14cccc4d6c51eba97360b112e1
|
[
"CC-BY-3.0"
] |
permissive
|
ManiaCraft/MinecartMania
|
53dd404936ea79ab726e5a84774197369d851573
|
b5b1717ea34d629203069582eeb7b2c26ca1bc84
|
refs/heads/master
| 2021-01-18T09:22:06.609012 | 2012-02-05T11:50:36 | 2012-02-05T11:50:36 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 12,819 |
java
|
package com.afforess.minecartmaniacore.utils;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import com.afforess.minecartmaniacore.MinecartManiaCore;
import com.afforess.minecartmaniacore.config.CoreSettingParser;
import com.afforess.minecartmaniacore.matching.MatchAND;
import com.afforess.minecartmaniacore.matching.MatchConstant;
import com.afforess.minecartmaniacore.matching.MatchField;
import com.afforess.minecartmaniacore.matching.MatchOR;
import com.afforess.minecartmaniacore.utils.DirectionUtils.CompassDirection;
import com.afforess.minecartmaniacore.world.Item;
import com.afforess.minecartmaniacore.world.SpecificMaterial;
/**
* Authors: Afforess, Meaglin, N3X15
*/
public class ItemUtils {
private static HashMap<String, ItemMatcher> preparsed = new HashMap<String, ItemMatcher>();
/**
* Returns the first item name or id found in the given string, or null if there was no item name or id. If the item name is a partial name, it will match the name with the shortest number of letter. Ex ("reds" will match "redstone" (the wire item) and not redstone ore.
*
* @return material found, or null
*/
public static SpecificMaterial getFirstItemStringToMaterial(final String str) {
final String[] list = { str };
final SpecificMaterial items[] = getItemStringListToMaterial(list);
return items.length == 0 ? null : items[0];
}
/**
* Returns the list of material for each item name or id found in the given string, or an empty array if there was no item name or id. If the item name is a partial name, it will match the name with the shortest number of letter. Ex ("reds" will match "redstone" (the wire item) and not redstone ore.
*
* @return materials found, or an empty array
*/
public static SpecificMaterial[] getItemStringToMaterial(final String str) {
final String[] list = { str };
return getItemStringListToMaterial(list);
}
public static SpecificMaterial[] getItemStringListToMaterial(final String[] list) {
return getItemStringListToMaterial(list, null);
}
public static CompassDirection getLineItemDirection(final String str) {
CompassDirection direction = CompassDirection.NO_DIRECTION;
final int index = str.indexOf("+");
if (index == 1) {
final String dir = str.substring(0, 1);
if (dir.equalsIgnoreCase("n")) {
direction = CompassDirection.NORTH;
}
if (dir.equalsIgnoreCase("s")) {
direction = CompassDirection.SOUTH;
}
if (dir.equalsIgnoreCase("e")) {
direction = CompassDirection.EAST;
}
if (dir.equalsIgnoreCase("w")) {
direction = CompassDirection.WEST;
}
}
return direction;
}
/**
* Returns the list of material for each item name or id found in the given array of strings, or an empty array if there was no item names or ids. If the item name is a partial name, it will match the name with the shortest number of letter. If there is a '!' next to a id or item name it will be removed from the list Ex ("reds" will match "redstone" (the wire item) and not redstone ore.
*
* @return materials found, or an empty array
*/
public static SpecificMaterial[] getItemStringListToMaterial(final String[] list, final CompassDirection facing) {
final ArrayList<SpecificMaterial> items = new ArrayList<SpecificMaterial>();
for (final String element : list) {
String str = StringUtils.removeBrackets(element.toLowerCase());
str = str.trim();
if (str.isEmpty()) {
continue;
}
//Check the given direction and intended direction from the sign
final CompassDirection direction = getLineItemDirection(str);
if (direction != CompassDirection.NO_DIRECTION) {
str = str.substring(2, str.length()); // remove the direction for further parsing.
}
if ((facing != null) && (direction != facing) && (direction != CompassDirection.NO_DIRECTION)) {
continue;
}
//short circuit if it's everything
if (str.contains("all items")) {
for (final Material m : Material.values()) {
if (!items.contains(m)) {
items.add(new SpecificMaterial(m.getId(), (short) 0));
}
}
}
final String[] keys = str.split(":");
for (final String key : keys) {
final String part = key.trim();
ItemMatcher matcher = null;
// Cache parsed strings
if (preparsed.containsKey(part.toLowerCase())) {
matcher = preparsed.get(part.toLowerCase());
}
if (matcher == null) {
matcher = new ItemMatcher();
matcher.parse(part);
}
preparsed.put(part.toLowerCase(), matcher);
saveDebugMap();
for (final Material mat : Material.values()) {
if (matcher.match(new ItemStack(mat))) {
items.add(new SpecificMaterial(mat.getId(), (short) 0));
}
}
}
}
//Remove Air from the list
final Iterator<SpecificMaterial> i = items.iterator();
while (i.hasNext()) {
final SpecificMaterial type = i.next();
if ((type == null) || type.equals(Material.AIR)) {
i.remove();
}
}
final SpecificMaterial itemList[] = new SpecificMaterial[items.size()];
return items.toArray(itemList);
}
public enum TYPE {
AMOUNT("@"),
REMOVE("!"),
RANGE("-"),
DATA(";"),
BIT("&"),
NONE("");
private final String tag;
TYPE(final String tag) {
this.tag = tag;
}
public String getTag() {
return tag;
}
@Override
public String toString() {
return tag;
}
public static TYPE getType(final String part) {
if (part.contains(RANGE.getTag())) // Range is parsed first Always!
return RANGE;
if (part.contains(REMOVE.getTag())) // since this 1 doesn't need special priority handling
return REMOVE;
if (part.contains(BIT.getTag())) // Parse bit before data.
return BIT;
if (part.lastIndexOf(DATA.getTag()) > part.lastIndexOf(AMOUNT.getTag()))
return DATA;
else {
if (part.contains(AMOUNT.getTag()))
return AMOUNT;
else
return NONE;
}
}
}
private static void saveDebugMap() {
try {
final File items = new File(MinecartManiaCore.getDataDirectoryRelativePath() + File.separator + "ItemMatchingTable.txt");
final PrintWriter out = new PrintWriter(items);
// Create file
out.write("This simply craps out the structure of Minecart Mania's internal Item Matching criteria. It's not read by MM, and it's going to be overwritten as minecarts find new stuff.");
for (final Entry<String, ItemMatcher> matcher : preparsed.entrySet()) {
if (matcher.getValue() == null) {
out.write(String.format("\n\n%s:\n(null)", matcher.getKey()));
} else {
out.write(String.format("\n\n%s:\n%s", matcher.getKey(), matcher.getValue().toString()));
}
}
//Close the output stream
out.close();
} catch (final Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static ItemMatcher[] getItemStringToMatchers(String line, final CompassDirection facing) {
String str = StringUtils.removeBrackets(line).toLowerCase();
str = str.trim();
if (str.isEmpty())
return new ItemMatcher[0];
//Check the given direction and intended direction from the sign
final CompassDirection direction = getLineItemDirection(str);
if (direction != CompassDirection.NO_DIRECTION) {
str = str.substring(2, str.length()); // remove the direction for further parsing.
}
if ((facing != null) && (direction != facing) && (direction != CompassDirection.NO_DIRECTION))
return new ItemMatcher[0];
final ItemMatcher matcher = new ItemMatcher();
final ArrayList<ItemMatcher> matchers = new ArrayList<ItemMatcher>();
final String[] parts = line.split(":");
for (int i = 0; i < parts.length; i++) {
parts[i] = StringUtils.removeBrackets(parts[i]).toLowerCase().trim();
}
line = StringUtils.join(parts, 0, ":");
if (preparsed.containsKey(line)) {
matchers.add(preparsed.get(line));
}
if (matcher.parse(line)) {
preparsed.put(line, matcher);
saveDebugMap();
matchers.add(matcher);
}
final ItemMatcher[] ret = new ItemMatcher[matchers.size()];
matchers.toArray(ret);
return ret;
}
public static ItemMatcher[] getItemStringListToMatchers(final String[] lines, final CompassDirection facing) {
final ArrayList<ItemMatcher> matchers = new ArrayList<ItemMatcher>();
for (final String line : lines) {
for (final ItemMatcher matcher : getItemStringToMatchers(line, facing))
if (matcher != null) {
matchers.add(matcher);
}
}
final ItemMatcher[] ret = new ItemMatcher[matchers.size()];
matchers.toArray(ret);
return ret;
}
public static ItemMatcher[] getItemStringListToMatchers(final String[] lines) {
return getItemStringListToMatchers(lines, CompassDirection.NO_DIRECTION);
}
public static void prefillAliases(final CoreSettingParser csp) {
for (final Item item : Item.values()) {
if (item.hasData()) {
final ItemMatcher matcher = new ItemMatcher();
matcher.addConstant(MatchField.TYPE_ID, item.getId());
matcher.addConstant(MatchField.DURABILITY, item.getData());
preparsed.put(item.name().toLowerCase(), matcher);
final ArrayList<SpecificMaterial> mats = new ArrayList<SpecificMaterial>();
mats.add(new SpecificMaterial(item.getId(), (short) item.getData()));
csp.aliases.put(item.name(), mats);
}
}
}
public static void addParserAlias(final String aliasName, final ItemMatcher matcher) {
preparsed.put(aliasName.toLowerCase(), matcher);
}
public static void addParserAlias(final String aliasName, final ArrayList<SpecificMaterial> values) {
// Create a new ItemMatcher
final ItemMatcher matcher = new ItemMatcher();
// Make a new OR statement
final MatchOR or = new MatchOR();
for (final SpecificMaterial mat : values) {
final MatchConstant type = new MatchConstant(MatchField.TYPE_ID, mat.id);
if (mat.durability != -1) {
// Create a new constant token and add it to an AND
// This basically becomes "... || (typeID=={whatever} && data=={whatever}
final MatchAND and = new MatchAND();
and.addExpression(type);
and.addExpression(new MatchConstant(MatchField.DURABILITY, mat.durability));
or.addExpression(and);
} else {
or.addExpression(type);
}
}
matcher.addExpression(or);
ItemUtils.addParserAlias(aliasName, matcher);
}
}
|
[
"[email protected]"
] | |
16c11d1e4c246fb301fa4239799b3311a29e583f
|
8b0f19ae679d1fcf3f3e6d94b08e848be5062d50
|
/src/main/java/com/spider/push/impl/DataPushSimpleManage.java
|
9ebe2df0bca2d8f5adbcb27526b797fbd9abf7c0
|
[] |
no_license
|
zhou5827297/spider
|
fac913372044113326036f93f64cbfc722698268
|
e1b0a01ec65c9bac6e8c7ef9cd17ee4cda37784c
|
refs/heads/master
| 2022-09-30T14:22:46.402737 | 2020-04-04T02:42:55 | 2020-04-04T02:42:55 | 84,806,720 | 5 | 2 | null | 2022-09-01T22:28:59 | 2017-03-13T09:17:01 |
Java
|
UTF-8
|
Java
| false | false | 4,904 |
java
|
package com.spider.push.impl;
import com.spider.config.ProxyConstant;
import com.spider.filter.impl.BloomFilterManage;
import com.spider.push.DataPushManage;
import com.spider.util.ThreadUtils;
import com.spider.config.RemoteConstant;
import com.spider.filter.FilterManage;
import com.spider.push.DataPush;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
/**
* 简单实现推送器,支持记录保存,重发等
*/
public class DataPushSimpleManage implements DataPushManage {
private final Logger LOG = LoggerFactory.getLogger(getClass());
private final LinkedBlockingQueue<DataPush> queues = new LinkedBlockingQueue<DataPush>();
private final int ONEEXECUTE = RemoteConstant.TASK_ONCE_MAX;
private FilterManage bloomFilter = BloomFilterManage.getInstance();
private boolean running = false;
private final static DataPushSimpleManage MANAGE = new DataPushSimpleManage();
private final static ExecutorService EXECUTOR = ThreadUtils.PUSHEXECUTOR;
@Override
public synchronized void start() {
if (running) {
return;
}
ThreadUtils.executeQuertz(new Runnable() {
@Override
public void run() {
try {
long start = System.currentTimeMillis();
pushAll();
long end = System.currentTimeMillis();
LOG.info("push batch time [{}] ms", end - start);
} catch (Exception ex) {
LOG.error("push batch error", ex);
}
}
}, 0, 30, TimeUnit.SECONDS);
running = true;
}
@Override
public void shutdown() {
queues.clear();
}
@Override
public void pushAll() {
if (queues.isEmpty()) {
return;
}
List<DataPush> dataPushs = new ArrayList<DataPush>();
for (int i = 0, j = queues.size(); i < j && i < ONEEXECUTE; i++) {
DataPush dataPush = queues.poll();
if (dataPush == null) {
break;
}
dataPushs.add(dataPush);
}
executeTaskPackage(dataPushs);
}
@Override
public void pushSuccess(DataPush push) {
AbstractPush dataPush = ((AbstractPush) push);
bloomFilter.add(dataPush.getArticle().getUrl());
LOG.info("[{}] push success", dataPush.getArticle());
//TODO 记录推送成功信息
}
@Override
public void pushFail(DataPush push) {
addPush(push);
AbstractPush dataPush = ((AbstractPush) push);
LOG.info("[{}] push fail, retry[{}/{}]", dataPush.getArticle(), dataPush.getPushErrorCount(), dataPush.getPushCount());
//TODO 记录推送失败信息
}
@Override
public boolean addPush(DataPush push) {
return queues.offer(push);
}
/**
* 执行一个任务包
*/
private void executeTaskPackage(List<DataPush> dataPushs) {
Collection<Callable<String>> tasks = new ArrayList<Callable<String>>();
for (DataPush dataPush : dataPushs) {
tasks.add(new Callable<String>() {
@Override
public String call() throws Exception {
try {
AbstractPush push = ((AbstractPush) dataPush);
if (push.getPushErrorCount() < RemoteConstant.TASK_OFFLINE_ROUND_MAX_RETRY) {
push.incrementPushCount();
boolean success = dataPush.push();
if (success) {
pushSuccess(dataPush);
} else {
push.incrementPushErrorCount();
pushFail(dataPush);
addPush(dataPush);
}
} else {
LOG.error("push error [{}]", push);
}
} catch (Throwable e) {
LOG.error("Callable call error:" + e.getMessage(), e);
}
return null;
}
});
}
try {
LOG.info("invokeAll start... tasks size: " + tasks.size());
EXECUTOR.invokeAll(tasks, ProxyConstant.PACKAGE_EXECUTE_TIMEOUT, TimeUnit.MINUTES);
LOG.info("invokeAll end... tasks size: " + tasks.size());
} catch (InterruptedException e) {
LOG.error("invokeAll error:", e);
} finally {
tasks.clear();
}
}
public static DataPushSimpleManage getInstance() {
if (MANAGE.running == false) {
MANAGE.start();
}
return MANAGE;
}
}
|
[
"[email protected]"
] | |
af0cb7697343979cdc99a3c260ab218898c65bbf
|
abdf6a348b3f53ff614d9b228572dd1ca931e050
|
/eclipse/jcoinlibs/src/com/ripple/core/formats/LEFormat.java
|
8b2d042013144a03ab58d7c860087987f067a479
|
[
"Apache-2.0"
] |
permissive
|
cping/RipplePower
|
5b2afd114eddbdb1a688e9de98cb409f16adfb89
|
4bdfd7ddca69e2cfb2c33852379844880cfe2a2a
|
refs/heads/master
| 2021-05-16T02:40:30.916689 | 2021-01-02T07:37:47 | 2021-01-02T07:37:47 | 19,198,112 | 42 | 13 | null | 2015-01-15T08:02:34 | 2014-04-27T07:11:33 |
Java
|
UTF-8
|
Java
| false | false | 7,574 |
java
|
package com.ripple.core.formats;
import com.ripple.core.fields.Field;
import com.ripple.core.serialized.enums.LedgerEntryType;
import java.util.EnumMap;
public class LEFormat extends Format {
static public EnumMap<LedgerEntryType, LEFormat> formats = new EnumMap<LedgerEntryType, LEFormat>(LedgerEntryType.class);
static public LEFormat fromString(String name) {
return getLedgerFormat(LedgerEntryType.valueOf(name));
}
static public LEFormat fromNumber(Number ord) {
return getLedgerFormat(LedgerEntryType.fromNumber(ord));
}
static public LEFormat fromValue(Object o) {
if (o instanceof Number) {
return fromNumber(((Number) o).intValue());
} else if (o instanceof String){
return fromString((String) o);
}
else {
return null;
}
}
public static LEFormat getLedgerFormat(LedgerEntryType key) {
if (key == null) return null;
return formats.get(key);
}
public final LedgerEntryType ledgerEntryType;
public LEFormat(LedgerEntryType type, Object... args) {
super(args);
ledgerEntryType = type;
addCommonFields();
formats.put(type, this);
}
@Override
public void addCommonFields() {
put(Field.LedgerIndex, Requirement.OPTIONAL);
put(Field.LedgerEntryType, Requirement.REQUIRED);
put(Field.Flags, Requirement.REQUIRED);
}
@Override
public String name() {
return ledgerEntryType.toString();
}
public static LEFormat AccountRoot = new LEFormat(
LedgerEntryType.AccountRoot,
Field.Account, Requirement.REQUIRED,
Field.Sequence, Requirement.REQUIRED,
Field.Balance, Requirement.REQUIRED,
Field.OwnerCount, Requirement.REQUIRED,
Field.PreviousTxnID, Requirement.REQUIRED,
Field.PreviousTxnLgrSeq, Requirement.REQUIRED,
Field.AccountTxnID, Requirement.OPTIONAL,
Field.RegularKey, Requirement.OPTIONAL,
Field.EmailHash, Requirement.OPTIONAL,
Field.WalletLocator, Requirement.OPTIONAL,
Field.WalletSize, Requirement.OPTIONAL,
Field.MessageKey, Requirement.OPTIONAL,
Field.TransferRate, Requirement.OPTIONAL,
Field.Domain, Requirement.OPTIONAL
);
public static LEFormat DirectoryNode = new LEFormat(
LedgerEntryType.DirectoryNode,
Field.Owner, Requirement.OPTIONAL, // for owner directories
Field.TakerPaysCurrency, Requirement.OPTIONAL, // for order book directories
Field.TakerPaysIssuer, Requirement.OPTIONAL, // for order book directories
Field.TakerGetsCurrency, Requirement.OPTIONAL, // for order book directories
Field.TakerGetsIssuer, Requirement.OPTIONAL, // for order book directories
Field.ExchangeRate, Requirement.OPTIONAL, // for order book directories
Field.Indexes, Requirement.REQUIRED,
Field.RootIndex, Requirement.REQUIRED,
Field.IndexNext, Requirement.OPTIONAL,
Field.IndexPrevious, Requirement.OPTIONAL
);
public static LEFormat Offer = new LEFormat(
LedgerEntryType.Offer,
Field.Account, Requirement.REQUIRED,
Field.Sequence, Requirement.REQUIRED,
Field.TakerPays, Requirement.REQUIRED,
Field.TakerGets, Requirement.REQUIRED,
Field.BookDirectory, Requirement.REQUIRED,
Field.BookNode, Requirement.REQUIRED,
Field.OwnerNode, Requirement.REQUIRED,
Field.PreviousTxnID, Requirement.REQUIRED,
Field.PreviousTxnLgrSeq, Requirement.REQUIRED,
Field.Expiration, Requirement.OPTIONAL
);
public static LEFormat Ticket = new LEFormat(
LedgerEntryType.Ticket,
Field.PreviousTxnID, Requirement.REQUIRED,
Field.PreviousTxnLgrSeq, Requirement.REQUIRED,
Field.Account, Requirement.REQUIRED,
Field.Sequence, Requirement.REQUIRED,
Field.OwnerNode, Requirement.REQUIRED,
Field.Target, Requirement.OPTIONAL,
Field.Expiration, Requirement.OPTIONAL
);
public static LEFormat RippleState = new LEFormat(
LedgerEntryType.RippleState,
Field.Balance, Requirement.REQUIRED,
Field.LowLimit, Requirement.REQUIRED,
Field.HighLimit, Requirement.REQUIRED,
Field.PreviousTxnID, Requirement.REQUIRED,
Field.PreviousTxnLgrSeq, Requirement.REQUIRED,
Field.LowNode, Requirement.OPTIONAL,
Field.LowQualityIn, Requirement.OPTIONAL,
Field.LowQualityOut, Requirement.OPTIONAL,
Field.HighNode, Requirement.OPTIONAL,
Field.HighQualityIn, Requirement.OPTIONAL,
Field.HighQualityOut, Requirement.OPTIONAL
);
public static LEFormat SuspendedPayment = new LEFormat(
LedgerEntryType.SuspendedPayment,
Field.Account, Requirement.REQUIRED,
Field.Destination, Requirement.REQUIRED,
Field.Amount, Requirement.REQUIRED,
Field.PreviousTxnID, Requirement.REQUIRED,
Field.PreviousTxnLgrSeq, Requirement.REQUIRED,
Field.OwnerNode, Requirement.REQUIRED,
Field.Digest, Requirement.OPTIONAL,
Field.CancelAfter, Requirement.OPTIONAL,
Field.FinishAfter, Requirement.OPTIONAL,
Field.SourceTag, Requirement.OPTIONAL,
Field.DestinationTag, Requirement.OPTIONAL
);
public static LEFormat LedgerHashes = new LEFormat(
LedgerEntryType.LedgerHashes,
Field.FirstLedgerSequence, Requirement.OPTIONAL, // Remove if we do a ledger restart
Field.LastLedgerSequence, Requirement.OPTIONAL,
Field.Hashes, Requirement.REQUIRED
);
public static LEFormat Amendments = new LEFormat(
LedgerEntryType.Amendments,
Field.Amendments, Requirement.OPTIONAL,
Field.Majorities, Requirement.OPTIONAL
);
public static LEFormat SignerList = new LEFormat(
LedgerEntryType.SignerList,
Field.PreviousTxnID, Requirement.REQUIRED,
Field.PreviousTxnLgrSeq, Requirement.REQUIRED,
Field.OwnerNode, Requirement.REQUIRED,
Field.SignerQuorum, Requirement.REQUIRED,
Field.SignerEntries, Requirement.REQUIRED,
Field.SignerListID, Requirement.REQUIRED
);
public static LEFormat FeeSettings = new LEFormat(
LedgerEntryType.FeeSettings,
Field.BaseFee, Requirement.REQUIRED,
Field.ReferenceFeeUnits, Requirement.REQUIRED,
Field.ReserveBase, Requirement.REQUIRED,
Field.ReserveIncrement, Requirement.REQUIRED
);
}
|
[
"[email protected]"
] | |
424fc97e2d7a4772d9fc96a75a2397367925759d
|
94113c5fbe68935e196db3c2a33a277243bfcadb
|
/Main.java
|
470053af3024aa801ac9fb56c632b1f3149921ce
|
[] |
no_license
|
xiongfeizhang1/AStarSearch
|
88ea3481b94ef59342502fd73848d395a4311be8
|
e4521c4afdaacefaa24910307eb24d09eaef8ab4
|
refs/heads/main
| 2023-03-25T11:52:01.925337 | 2021-03-26T20:26:30 | 2021-03-26T20:26:30 | 351,903,647 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,874 |
java
|
/* @author Xiongfei Zhang
* @version 1.0
*
* A Star Search
*/
//imports all of the util class
import java.util.*;
public class Main {
//global variables
static int gRow;
static int gCol;
static boolean found;
//create open and closed list
public static ArrayList<Node> openList = new ArrayList<Node>();
public static ArrayList<Node> closedList = new ArrayList<Node>();
//method to calculate f, g, h, and parent of node, and add to openList
public static void calcNode(Node current, int parentG, Node parent, int addG)
{
if(current.getType() == 3) //if currently at goal
{
current.setParent(parent);
found = true;
}
else if (current.getType() == 1 && closedList.contains(current) == false)
{
//checks if node is already in openList
if(openList.contains(current))
{
//manhattan method to find heuristic
int h = current.getH();
int g = parentG + addG;
//compares which path of getting to current node is faster
if (current.getF() > h+g)
{
//replace previous parent and g value if current path is faster
current.setG(g);
current.setF();
current.setParent(parent);
}
}
else
{
//manhattan method to find heuristic
int h = Math.abs(gRow - current.getRow());
h += Math.abs((gCol - current.getCol()));
int g = parentG + addG;
current.setH(h);
current.setG(g);
current.setF();
current.setParent(parent);
openList.add(current);
}
}
}
public static void addNeighbors(Node current, Node[][] board)
{
int tempRow = current.getRow();
int tempCol = current.getCol();
//checks the 8 adjacent nodes to current node and sets their values
calcNode(board[tempRow-1][tempCol-1], current.getG(), current, 14);
calcNode(board[tempRow-1][tempCol+1], current.getG(), current, 14);
calcNode(board[tempRow+1][tempCol-1], current.getG(), current, 14);
calcNode(board[tempRow+1][tempCol+1], current.getG(), current, 14);
calcNode(board[tempRow+1][tempCol], current.getG(), current, 10);
calcNode(board[tempRow-1][tempCol], current.getG(), current, 10);
calcNode(board[tempRow][tempCol-1], current.getG(), current, 10);
calcNode(board[tempRow][tempCol+1], current.getG(), current, 10);
openList.remove(current);
closedList.add(current);
}
public static boolean checkCurrent(Node board)
{
if(openList.contains(board))
{
return true;
}
return false;
}
//method to show board
public static void displayBoard(Node[][] board)
{
System.out.println(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15");
for(int i = 1; i < 16; i++) //row
{
for(int k = 1; k < 16; k++) //column
{
if(k == 1)
{
if(i < 10)
{
System.out.print(i + " ");
}
else{
System.out.print(i + " ");
}
}
//display different tiles based on node type
int x = board[i][k].getType();
if(x == 1)
{
System.out.print("[ ]");
}
else if (x == 0)
{
System.out.print("███");
}
else if (x == 2)
{
System.out.print("[S]");
}
else if (x == 3)
{
System.out.print("[G]");
}
else if (x == 4)
{
System.out.print("[X]");
}
}
System.out.println();
}
}
public static void main(String[] args)
{
//initializes empty board
Node[][] board = new Node[17][17];
for(int i = 0; i < 17; i++) //row
{
for(int k = 0; k < 17; k++) //column
{
board[i][k] = new Node(i,k,1);
if(i == 0 || i == 16 || k == 0 || k == 16)
{
board[i][k] = new Node(i,k,0); //sets the padding tiles to be untraversable
}
}
}
System.out.println("\n==============GENERATING BOARD===============\n");
Random rand = new Random();
for(int x = 0; x < 23; x++) //randomly generates 10% of total(23) nodes that are unpathable
{
int upper = 15;
board[rand.nextInt(upper)+1][rand.nextInt(upper)+1].setType(0);
}
displayBoard(board);
//prompt user values for start and goal nodes
Scanner scan = new Scanner(System.in); //initialize scanner
System.out.println("\nEnter the row of the starting node(1-15): ");
int sRow = scan.nextInt();
System.out.println("Enter the column of the starting node (1-15): ");
int sCol = scan.nextInt();
board[sRow][sCol].setType(2);
System.out.println("Enter the row of the goal node(1-15): ");
gRow = scan.nextInt();
System.out.println("Enter the column of the goal node (1-15): ");
gCol = scan.nextInt();
board[gRow][gCol].setType(3);
//sets g of start node to 0
board[sRow][sCol].setG(0);
openList.add(board[sRow][sCol]);
calcNode(board[sRow][sCol], board[sRow][sCol].getG(), null, 0);
addNeighbors(board[sRow][sCol], board);
found = false;
//while loop to keep adding and removing from openlist
while(openList.size() > 0 && found == false)
{
int leastF = 0;
//for loop to find smallest f value in openList
for(int i = 1; i < openList.size(); i++)
{
if(openList.get(leastF).getF() > openList.get(i).getF())
{
leastF = i;
}
}
addNeighbors(openList.get(leastF), board);
}
//if openlist is empty
if(openList.size() == 0)
{
System.out.println("\nNo path could be found");
}
else
{
ArrayList<Node> path = new ArrayList<Node>();
int pathCounter = 0;
path.add(board[gRow][gCol]);
boolean start = false;
//loop to add path to array
while(start == false)
{
Node temp = path.get(pathCounter).getParent();
if( temp == null)
{
start = true;
}
else
{
if(temp == board[sRow][sCol])
{
}
else
{
temp.setType(4);
}
path.add(temp);
pathCounter++;
}
}
System.out.println("==============KEY============ \nS = Start Node\nX = Path Node\nG = Goal Node");
//shows board with path
displayBoard(board);
}
}
}
|
[
"[email protected]"
] | |
4aacc0f2df04373e67398d444229021e66e1bd84
|
54c371c20b423ca2ff90f781136ad63509c1246c
|
/src/main/java/com/shiz/entity/InformationEntityPK.java
|
c5b169beec1f4b9803ae3700637f58b0b9fd68e9
|
[] |
no_license
|
Usergin/DeviceControl
|
40634dfdb2bbfc98b316622c0dda579e687b11ca
|
76b994722c8c1b029c2bcc462e2db0a89aa18a3d
|
refs/heads/master
| 2021-01-19T00:39:57.490099 | 2017-07-26T18:14:33 | 2017-07-26T18:14:33 | 87,198,150 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 787 |
java
|
package com.shiz.entity;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
/**
* Created by oldman on 19.04.17.
*/
public class InformationEntityPK implements Serializable {
private int id;
@Column(name = "id", nullable = false)
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InformationEntityPK that = (InformationEntityPK) o;
if (id != that.id) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
return result;
}
}
|
[
"[email protected]"
] | |
ada67d3c78f9e7b3310cea8757b7f8bb2115965a
|
6cf3761f1f5da4c39d91ca4fd8c6d617d3938731
|
/App_dietas/app/src/main/java/com/example/app_dietas/logica/AlimentoAdapter.java
|
69ae05ecdaed34c92238d4c8343fbce38ba65ff0
|
[] |
no_license
|
TheJosemi98/AppsAndroid
|
d4afa48a03aced48c5d5cd374af2ef5fa1c0e280
|
0627bb348f316589f034afc9113fc0fbfd2ad2eb
|
refs/heads/main
| 2023-03-11T22:19:59.101811 | 2021-03-04T14:21:40 | 2021-03-04T14:21:40 | 344,500,881 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,894 |
java
|
package com.example.app_dietas.logica;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app_dietas.Dietas.Alimento;
import com.example.app_dietas.R;
import java.util.List;
public class AlimentoAdapter extends RecyclerView.Adapter<AlimentoAdapter.ViewHolder> implements View.OnClickListener {
private List<Alimento> mAlimentos;
private View.OnClickListener listener;
private int position;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView nombreAlimento;
public TextView cantidadNumerica;
public TextView cantidadCualitativa;
public TextView grupoAlimenticio;
public ViewHolder(View itemView) {
super(itemView);
nombreAlimento = (TextView) itemView.findViewById(R.id.textViewNombreAlimento);
cantidadNumerica = (TextView) itemView.findViewById(R.id.textViewCantidadN);
cantidadCualitativa = (TextView) itemView.findViewById(R.id.textViewCantidadCual);
grupoAlimenticio = (TextView) itemView.findViewById(R.id.textViewGrupoAlimenticio);
}
}
public AlimentoAdapter(List<Alimento> Alimentos){
mAlimentos = Alimentos;
}
@Override
public AlimentoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View alimentoView = inflater.inflate(R.layout.recyclerview_alimento,parent,false);
alimentoView.setOnClickListener(this);
ViewHolder viewHolder = new ViewHolder(alimentoView);
return viewHolder;
}
@Override
public void onBindViewHolder(AlimentoAdapter.ViewHolder viewHolder, int position){
Alimento alimento = mAlimentos.get(position);
this.position = position;
TextView textViewNombre = viewHolder.nombreAlimento;
textViewNombre.setText(alimento.getNombre());
TextView textViewCantidadN = viewHolder.cantidadNumerica;
textViewCantidadN.setText(String.valueOf(alimento.getCantidadNumerica()));
TextView textViewCantidadC = viewHolder.cantidadCualitativa;
textViewCantidadC.setText(alimento.getCantidadCualitativa());
TextView textViewGrupoAlimenticio = viewHolder.grupoAlimenticio;
textViewGrupoAlimenticio.setText(alimento.getGrupoAlimenticio());
}
@Override
public int getItemCount(){
return mAlimentos.size();
}
public void setOnClickListener(View.OnClickListener listener){
this.listener = listener;
}
@Override
public void onClick(View v) {
if(listener != null)
listener.onClick(v);
}
}
|
[
"[email protected]"
] | |
a3786e4c21efde9ce49f9943a9e1494e77106216
|
7c331c4383092924de7e17a2b9b0afa5457a9231
|
/ws-eclipse/genericos_delimitados/src/services/CalculationService.java
|
876b85887f81685f4d6fa0cc2f4d5779c6658721
|
[
"MIT"
] |
permissive
|
MateusMacial/Udemy_Java_Orientado_Objetos
|
1d9791732bf4f588f075d5b73762978cd1f46cca
|
368a976d11656a509228e6e004b63a4d0c396ac3
|
refs/heads/main
| 2023-06-02T18:09:43.014072 | 2021-06-14T23:24:04 | 2021-06-14T23:24:04 | 369,340,763 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 353 |
java
|
package services;
import java.util.List;
public class CalculationService {
public static <T extends Comparable<T>> T max(List<T> list) {
if (list.isEmpty()) {
throw new IllegalStateException("List can't be empty");
}
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) {
max = item;
}
}
return max;
}
}
|
[
"[email protected]"
] | |
5777291441f6af03f7f89d54d77acf822faa7c22
|
8d2fa5467ee98343f2305684c1eced69e0a466c7
|
/Append.java
|
34f33b313362ad3f460b68c0df4980581a47c660
|
[] |
no_license
|
minmaneh/UM
|
9f4d62c9b6928638d755f17f3ffc7ba5761abf8d
|
30489b0bd86ce316c16e7f923f587af5c3cafdb3
|
refs/heads/master
| 2022-05-28T11:27:39.786129 | 2020-04-30T12:50:22 | 2020-04-30T12:50:22 | 260,209,467 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 644 |
java
|
public class Append{
public static void main(String[]args){
int[] a1 = {10, 20, 30, 40, 50, 60};
int[] a2 = {91, 92, 93, 94, 95, 96};
int[] newList1=append(a1,a2);
for(int i=0;i<newList1.length;i++){
System.out.println(newList1[i]);
}
}
public static int[] append(int[] list1, int[] list2) {
int[] newList = new int[list1.length + list2.length];
int index = 0;
for (int i = 0; i < list1.length; i++) {
newList[index] = list1[i];
index++;
}
for (int i = 0; i < list2.length; i++) {
newList[index] = list2[i];
index++;
}
return newList;
}
}
|
[
"[email protected]"
] | |
f38f655545d722c677c6048788490ac89925f874
|
7e13d4d315265bc55fabaf424745cf954417d118
|
/SLCO1.0-files/SLCO1.0/metamodels-and-grammars/promela.emf.edit/src/promela/provider/assignItemProvider.java
|
352a5c99962dda857568c0c222b2e7b5b1e6d155
|
[] |
no_license
|
melroy999/2IMP00-SLCO
|
6c4b69d0da58d4f06c662cd046193694979bbae4
|
bb5178ffc322c4bb0d7b070760950f29aeb0eb52
|
refs/heads/master
| 2023-04-05T06:48:10.474608 | 2021-04-07T23:19:46 | 2021-04-07T23:19:46 | 314,880,276 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,711 |
java
|
/**
*/
package promela.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import promela.assign;
/**
* This is the item provider adapter for a {@link promela.assign} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class assignItemProvider
extends stmntItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public assignItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((assign)object).getLabel();
return label == null || label.length() == 0 ?
getString("_UI_assign_type") :
getString("_UI_assign_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
|
[
"[email protected]"
] | |
523dc82527dd4d386791188c4abcdb7a06881aa4
|
906275798ed0ab17495dbf1f31759845818daa81
|
/src/main/java/org/jukeboxmc/item/ItemWallBanner.java
|
c1c065624e357dcda3f61a2615d2b50a0c85b658
|
[] |
no_license
|
yequid/JukeboxMC
|
c7995034bc5bd55280e3bf96b765eddacbe08e8f
|
8a53fc2bed231d0872699d6efa88ef843a74001b
|
refs/heads/master
| 2023-02-15T05:45:12.260350 | 2021-01-07T15:00:24 | 2021-01-07T15:00:24 | 326,658,755 | 0 | 0 | null | 2021-01-07T15:00:25 | 2021-01-04T11:15:15 |
Java
|
UTF-8
|
Java
| false | false | 206 |
java
|
package org.jukeboxmc.item;
/**
* @author LucGamesYT
* @version 1.0
*/
public class ItemWallBanner extends Item {
public ItemWallBanner() {
super( "minecraft:wall_banner", 177 );
}
}
|
[
"[email protected]"
] | |
639d78138e12fc0b2c57d992951b313ac64279fc
|
51de3ea6616feb708169fc246dab6c8636c491f5
|
/result/com.beust.jcommander.validators.PositiveInteger/traditional_mutants/void_validate(java.lang.String,java.lang.String)/ODL_8/PositiveInteger.java
|
3f82aad8f6282e59a79bbfee9bebae592818a6a9
|
[
"Apache-2.0"
] |
permissive
|
ps073006/main_mujava
|
ab442a597b514cc8491b8b5bd551e8e90e0aa5c6
|
c62f68d78c65d91f9dbf5a9a72df152cdda05a9d
|
refs/heads/master
| 2021-01-10T04:37:47.416163 | 2016-01-19T19:36:28 | 2016-01-19T19:36:28 | 49,980,696 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 570 |
java
|
// This is a mutant program.
// Author : ysma
package com.beust.jcommander.validators;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;
public class PositiveInteger implements com.beust.jcommander.IParameterValidator
{
public void validate( java.lang.String name, java.lang.String value )
throws com.beust.jcommander.ParameterException
{
int n = Integer.parseInt( value );
if (n < 0) {
throw new com.beust.jcommander.ParameterException( value + ")" );
}
}
}
|
[
"[email protected]"
] | |
a6c95709e3423156cff1d3ace7940089572c1124
|
44e7adc9a1c5c0a1116097ac99c2a51692d4c986
|
/aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/transform/UpdateBandwidthRateLimitScheduleRequestMarshaller.java
|
a83b7915d23e8a7c7a4cdc968fa1b8d9ec4d4495
|
[
"Apache-2.0"
] |
permissive
|
QiAnXinCodeSafe/aws-sdk-java
|
f93bc97c289984e41527ae5bba97bebd6554ddbe
|
8251e0a3d910da4f63f1b102b171a3abf212099e
|
refs/heads/master
| 2023-01-28T14:28:05.239019 | 2020-12-03T22:09:01 | 2020-12-03T22:09:01 | 318,460,751 | 1 | 0 |
Apache-2.0
| 2020-12-04T10:06:51 | 2020-12-04T09:05:03 | null |
UTF-8
|
Java
| false | false | 2,613 |
java
|
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.storagegateway.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.storagegateway.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateBandwidthRateLimitScheduleRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateBandwidthRateLimitScheduleRequestMarshaller {
private static final MarshallingInfo<String> GATEWAYARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("GatewayARN").build();
private static final MarshallingInfo<List> BANDWIDTHRATELIMITINTERVALS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("BandwidthRateLimitIntervals").build();
private static final UpdateBandwidthRateLimitScheduleRequestMarshaller instance = new UpdateBandwidthRateLimitScheduleRequestMarshaller();
public static UpdateBandwidthRateLimitScheduleRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UpdateBandwidthRateLimitScheduleRequest updateBandwidthRateLimitScheduleRequest, ProtocolMarshaller protocolMarshaller) {
if (updateBandwidthRateLimitScheduleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateBandwidthRateLimitScheduleRequest.getGatewayARN(), GATEWAYARN_BINDING);
protocolMarshaller.marshall(updateBandwidthRateLimitScheduleRequest.getBandwidthRateLimitIntervals(), BANDWIDTHRATELIMITINTERVALS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
[
""
] | |
af41d2fe9680c42a0cbe00c952b5c8a7533d640f
|
31d87c3767747e2de96b39a52965afb9f89a06d9
|
/Practical_exam_bharadwaj_divatekodandarama_wfs4/ProductsExam/src/com/demo/bean/Food.java
|
8080fd247e4d9a4bf9cfe8e1aca0c0299c6e9033
|
[] |
no_license
|
BharadwajDivate/myjavarepo
|
a6ebd4c8ae63b1dcf57362506dda153241574104
|
b91915a1e5756b9d57854e596f2bbd8fcee71d83
|
refs/heads/master
| 2022-12-22T20:44:11.092817 | 2020-09-24T12:34:24 | 2020-09-24T12:34:24 | 296,215,955 | 0 | 0 | null | 2020-09-17T04:08:03 | 2020-09-17T04:08:03 | null |
UTF-8
|
Java
| false | false | 1,065 |
java
|
package com.demo.bean;
import java.util.Date;
public class Food extends Products {
private Date dOfManf;
private Date dOfExp;
private boolean veg;
// default constructor
public Food() {
super();
}
// parameterised constructor
public Food(int itmCode, String itmName, double price, int qty,String pType,Date dOfManf, Date dOfExp, boolean veg) {
super(itmCode,itmName,price,qty,pType);
this.dOfManf = dOfManf;
this.dOfExp = dOfExp;
this.veg = veg;
}
//setter and getter methods
public Date getdOfManf() {
return dOfManf;
}
public void setdOfManf(Date dOfManf) {
this.dOfManf = dOfManf;
}
public Date getdOfExp() {
return dOfExp;
}
public void setdOfExp(Date dOfExp) {
this.dOfExp = dOfExp;
}
public boolean isVeg() {
return veg;
}
public void setVeg(boolean veg) {
this.veg = veg;
}
//tostring method
@Override
public String toString() {
return super.toString()+"Food [dOfManf=" + dOfManf + ", dOfExp=" + dOfExp + ", veg=" + veg + "]";
}
}
|
[
"[email protected]"
] | |
b7eecb7ec33bf23f832f3ea802604f661cf067c6
|
14d7e08e61985165727068a7626ba1862ebeb332
|
/app/src/main/java/com/example/net1cloud/utils/SerializeAndDeserializeUtil.java
|
b3ae5ec9940548375f2adcc504f8d5ee72c5c094
|
[] |
no_license
|
FantasticPornTaiQiang/Net1Cloud
|
eea5593efc03081c793fba6d5b739d6bb4ebbf6c
|
a4570417d999fdd117ed7854cb6f9d33eb158467
|
refs/heads/master
| 2022-04-10T03:02:42.196311 | 2020-02-17T17:54:38 | 2020-02-17T17:54:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,762 |
java
|
package com.example.net1cloud.utils;
import com.example.net1cloud.data.Music;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
public class SerializeAndDeserializeUtil {
//序列化音乐
public static String serializeMusic(Music music) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(music);
String serializedStr = byteArrayOutputStream.toString("ISO-8859-1");
serializedStr = java.net.URLEncoder.encode(serializedStr, "UTF-8");
objectOutputStream.close();
byteArrayOutputStream.close();
return serializedStr;
}
//反序列化音乐
public static Music deSerializeMusic(String str) throws IOException, ClassNotFoundException {
String readStr = java.net.URLDecoder.decode(str, "UTF-8");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
readStr.getBytes("ISO-8859-1"));
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
Music music = (Music) objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
return music;
}
//序列化音乐列表
public static String serializeMusicPathList(List<String> musicPathList) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(musicPathList);
String serializedStr = byteArrayOutputStream.toString("ISO-8859-1");
serializedStr = java.net.URLEncoder.encode(serializedStr, "UTF-8");
objectOutputStream.close();
byteArrayOutputStream.close();
return serializedStr;
}
//反序列化音乐列表
public static List<String> deSerializeMusicPathList(String str) throws IOException, ClassNotFoundException {
String readStr = java.net.URLDecoder.decode(str, "UTF-8");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
readStr.getBytes("ISO-8859-1"));
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
List<String> musicPathList = (List<String>) objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
return musicPathList;
}
}
|
[
"[email protected]"
] | |
650d49fdd212b66fe657dbb07b2e227489fa8af3
|
0f9834438f09c21e4dccf935047fddd3c2a4894e
|
/src/java/org/infoglue/cms/applications/workflowtool/functions/InitializeCreateNews.java
|
5e838c17f785b0bab890de6c4c5fbd2b41dc3571
|
[] |
no_license
|
uppsala-university/infoglue
|
13a8f479da68cf64ddaccf440aa903088cafa28b
|
0208a7b647c74d0dc6af2a7229de433bc4931512
|
refs/heads/master
| 2021-01-18T17:36:26.285460 | 2018-12-05T10:57:20 | 2018-12-05T10:57:20 | 32,735,765 | 1 | 1 | null | 2019-01-24T11:09:14 | 2015-03-23T14:05:40 |
Java
|
UTF-8
|
Java
| false | false | 2,985 |
java
|
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
* $Id: InitializeCreateNews.java,v 1.8 2008/07/03 11:48:23 mattias Exp $
*/
package org.infoglue.cms.applications.workflowtool.functions;
import java.util.Map;
import org.apache.log4j.Logger;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController;
import com.opensymphony.module.propertyset.PropertySet;
import com.opensymphony.workflow.FunctionProvider;
/**
* THIS IS VERY TEMPORARY SOLUTION FOR ASSESSING WHERE TO PUT THE NEWS ITEMS.
* @version $Revision: 1.8 $ $Date: 2008/07/03 11:48:23 $
*/
public class InitializeCreateNews implements FunctionProvider
{
private final static Logger logger = Logger.getLogger(InitializeCreateNews.class.getName());
public void execute(Map transientVars, Map args, PropertySet propertySet)
{
try
{
Integer repositoryId = new Integer(((String[])transientVars.get("repositoryId"))[0]);
Integer parentContentId = new Integer(((String[])transientVars.get("parentContentId"))[0]);
Integer languageId = new Integer(((String[])transientVars.get("languageId"))[0]);
Integer contentTypeDefinitionId = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("Article").getContentTypeDefinitionId();
logger.info("parentContentId:" + parentContentId);
logger.info("contentTypeDefinitionId:" + contentTypeDefinitionId);
logger.info("repositoryId:" + repositoryId);
logger.info("languageId:" + languageId);
propertySet.setString("parentContentId", parentContentId.toString());
propertySet.setString("contentTypeDefinitionId", contentTypeDefinitionId.toString());
propertySet.setString("repositoryId", repositoryId.toString());
propertySet.setString("languageId", languageId.toString());
}
catch (Exception e)
{
logger.info("An error occurred trying to assess the place where to put it.");
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
|
[
"[email protected]"
] | |
69fd5de02d4fd664e83fce9b41e9599e5c7377ff
|
a6c84fb2a9f2016932a8d33a8501d7382c1aaa18
|
/QuestionMaker/src/algorithms/Fractions/Level4_6/MoreThanHalf4_6.java
|
4ce2fa6584771a6ab8908313476e1bf90a1160a8
|
[] |
no_license
|
luhan68/QuestionMaker
|
4814d4fed678b5256994ff744cbbd84cde130251
|
e1a8a3edb919453cd0dba1e8569391fe993778c1
|
refs/heads/master
| 2020-03-27T09:12:57.748381 | 2018-08-27T16:29:43 | 2018-08-27T16:29:43 | 146,322,860 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,504 |
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 algorithms.Fractions.Level4_6;
import Fractions.Fraction;
import java.util.Random;
import java.util.Vector;
/**
*
* @author Karl
*/
public class MoreThanHalf4_6 {
public String HintImg = "placechart_decimals.png";
public String SubjectType = "Fractions";
public String SubjectImage = "";
public Vector generate(int low_threshold, int high_threshold, String hint, String level, String subjectype) {
SubjectType = subjectype;
Vector results = new Vector();
int one = 0; // num
int two = 0;// denom
int three = 0; //
int four = 0; //
String first = "";
String second = "";
String third = "";
String fourth = "";
String correct_answer = "";
int Random_correct_letter = 0;
boolean plusone_used = false;
boolean minusone_used = false;
boolean inverse_used = false;
//choose a random number between the threshold
Random rn = new Random();
boolean found = false;
while (found == false) { // try to produce a formula that is within the bounds
one = rn.nextInt(40) + 10;
do{
two = rn.nextInt(40) + 10;
}while(two == one);
do{
three = rn.nextInt(40) + 10;
}while(three == one || three == two);
do{
four = rn.nextInt(40) + 10;
}while(four == one || four == two || four == three);
if(one % 10 == 0){
one = one / 10;
}
if(two % 10 == 0){
two = two / 10;
}
if(three % 10 == 0){
three = three / 10;
}
if(four % 10 == 0){
four = four / 10;
}
first = "." + one;
second = "." + two;
third = "." + three;
fourth = "." + four;
int correct_num = rn.nextInt(49) + 51;
if(correct_num % 10 == 0){
correct_num = correct_num / 10;
}
correct_answer = "." + correct_num;
if (true) {
//add question
String question = "Which is more than half?";
results.addElement(question);
Random_correct_letter = rn.nextInt(5) + 1; // A,B,C,D,E
found = true;
}
}
for (int i = 1; i < 6; i++) { //mix in the random answers with the correct answer
if (i == Random_correct_letter) { //this is the randomly selected letter
results.addElement(correct_answer);
} else if (inverse_used == false) { //
results.addElement(first);
inverse_used = true;
} else if (plusone_used == false) { //
results.addElement(second);
plusone_used = true;
} else if (minusone_used == false) { //
results.addElement(third);
minusone_used = true;
} else { //
results.addElement(fourth);
}
}
//add in the hint and level
results.addElement(RandomAnswer(Random_correct_letter));
//skip qid
results.addElement(CreateHint(hint, correct_answer, first, second, third));
results.addElement(HintImg());
results.addElement(level);
results.addElement("1"); //Hard coded subject = math
results.addElement(SubjectType());
results.addElement("0"); //uid =0 means ALL users get it
results.addElement("0"); //sid = 0; means all students get it
results.addElement(SubjectImage()); //subject image image
return results;
}
public String getDecimal(int numerator, int denominator){
int afterDecimal = numerator % denominator;
String asString = "";
if(afterDecimal < 10){
asString = "0" + afterDecimal;
}else{
asString = "" + afterDecimal;
}
return "." + asString;
}
public String HintImg() {
return HintImg;
}
public String SubjectType() {
return SubjectType;
}
public String SubjectImage() {
return SubjectImage;
}
public String RandomAnswer(int selection) {
String results = "";
if (selection == 1) {
results = "optionA";
} else if (selection == 2) {
results = "optionB";
}
if (selection == 3) {
results = "optionC";
}
if (selection == 4) {
results = "optionD";
}
if (selection == 5) {
results = "optionE";
}
return results;
}
public String CreateHint(String hint, String correct_answer, String first, String second, String third) {
String results = "";
if (hint.contains("Algorithm Generated")) {
results = "half = .50";
} else {
results = hint;
}
return results;
}
}
|
[
"[email protected]"
] | |
d0604818963b6c738a27c940108fc21b19b0a817
|
98e666e26aae281daf5d93455cfaa0cee1304823
|
/src/primeirafase/algs4/FibonacciMinPQ.java
|
52faa416e18a13eb6c4b523223f7630866737426
|
[] |
no_license
|
PedroAlmeidacode/LinkedIn_graph_search
|
1a627bb18628dcde0b5b225ed8d846f9a94b6c8c
|
368a69d6364428feb097bdaf559b1c909dd22c0d
|
refs/heads/master
| 2021-04-21T03:22:00.576935 | 2020-05-05T14:14:58 | 2020-05-05T14:14:58 | 249,745,331 | 2 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 9,297 |
java
|
/******************************************************************************
* Compilation: javac FibonacciMinPQ.java
* Execution:
*
* A Fibonacci heap.
*
******************************************************************************/
package primeirafase.algs4;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
/*
* The FibonacciMinPQ class represents a priority queue of generic keys.
* It supports the usual insert and delete-the-minimum operations,
* along with the merging of two heaps together.
* It also supports methods for peeking at the minimum key,
* testing if the priority queue is empty, and iterating through
* the keys.
* It is possible to build the priority queue using a Comparator.
* If not, the natural order relation between the keys will be used.
*
* This implementation uses a Fibonacci heap.
* The delete-the-minimum operation takes amortized logarithmic time.
* The insert, min-key, is-empty, size, union and constructor take constant time.
*
* @author Tristan Claverie
*/
public class FibonacciMinPQ<Key> implements Iterable<Key> {
private Node head; //Head of the circular root list
private Node min; //Minimum Node of the root list
private int size; //Number of keys in the heap
private final Comparator<Key> comp; //Comparator over the keys
private HashMap<Integer, Node> table = new HashMap<Integer, Node>(); //Used for the consolidate operation
//Represents a Node of a tree
private class Node {
Key key; //Key of this Node
int order; //Order of the tree rooted by this Node
Node prev, next; //Siblings of this Node
Node child; //Child of this Node
}
/**
* Initializes an empty priority queue
* Worst case is O(1)
* @param C a Comparator over the Keys
*/
public FibonacciMinPQ(Comparator<Key> C) {
comp = C;
}
/**
* Initializes an empty priority queue
* Worst case is O(1)
*/
public FibonacciMinPQ() {
comp = new MyComparator();
}
/**
* Initializes a priority queue with given keys
* Worst case is O(n)
* @param a an array of keys
*/
public FibonacciMinPQ(Key[] a) {
comp = new MyComparator();
for (Key k : a) insert(k);
}
/**
* Initializes a priority queue with given keys
* Worst case is O(n)
* @param C a comparator over the keys
* @param a an array of keys
*/
public FibonacciMinPQ(Comparator<Key> C, Key[] a) {
comp = C;
for (Key k : a) insert(k);
}
/**
* Whether the priority queue is empty
* Worst case is O(1)
* @return true if the priority queue is empty, false if not
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Number of elements currently on the priority queue
* Worst case is O(1)
* @return the number of elements on the priority queue
*/
public int size() {
return size;
}
/**
* Insert a key in the queue
* Worst case is O(1)
* @param key a Key
*/
public void insert(Key key) {
Node x = new Node();
x.key = key;
size++;
head = insert(x, head);
if (min == null) min = head;
else min = (greater(min.key, key)) ? head : min;
}
/**
* Gets the minimum key currently in the queue
* Worst case is O(1)
* @throws NoSuchElementException if the priority queue is empty
* @return the minimum key currently in the priority queue
*/
public Key minKey() {
if (isEmpty()) throw new NoSuchElementException("Priority queue is empty");
return min.key;
}
/**
* Deletes the minimum key
* Worst case is O(log(n)) (amortized)
* @throws NoSuchElementException if the priority queue is empty
* @return the minimum key
*/
public Key delMin() {
if (isEmpty()) throw new NoSuchElementException("Priority queue is empty");
head = cut(min, head);
Node x = min.child;
Key key = min.key;
min.key = null;
if (x != null) {
head = meld(head, x);
min.child = null;
}
size--;
if (!isEmpty()) consolidate();
else min = null;
return key;
}
/**
* Merges two heaps together
* This operation is destructive
* Worst case is O(1)
* @param that a Fibonacci heap
* @return the union of the two heaps
*/
public FibonacciMinPQ<Key> union(FibonacciMinPQ<Key> that) {
this.head = meld(head, that.head);
this.min = (greater(this.min.key, that.min.key)) ? that.min : this.min;
this.size = this.size+that.size;
return this;
}
/*************************************
* General helper functions
************************************/
//Compares two keys
private boolean greater(Key n, Key m) {
if (n == null) return false;
if (m == null) return true;
return comp.compare(n,m) > 0;
}
//Assuming root1 holds a greater key than root2, root2 becomes the new root
private void link(Node root1, Node root2) {
root2.child = insert(root1, root2.child);
root2.order++;
}
/*************************************
* Function for consolidating all trees in the root list
************************************/
//Coalesce the roots, thus reshapes the tree
private void consolidate() {
table.clear();
Node x = head;
int maxOrder = 0;
min = head;
Node y = null; Node z = null;
do {
y = x;
x = x.next;
z = table.get(y.order);
while (z != null) {
table.remove(y.order);
if (greater(y.key, z.key)) {
link(y, z);
y = z;
} else {
link(z, y);
}
z = table.get(y.order);
}
table.put(y.order, y);
if (y.order > maxOrder) maxOrder = y.order;
} while (x != head);
head = null;
for (Node n : table.values()) {
if (n != null) {
min = greater(min.key, n.key) ? n : min;
head = insert(n, head);
}
}
}
/*************************************
* General helper functions for manipulating circular lists
************************************/
//Inserts a Node in a circular list containing head, returns a new head
private Node insert(Node x, Node head) {
if (head == null) {
x.prev = x;
x.next = x;
} else {
head.prev.next = x;
x.next = head;
x.prev = head.prev;
head.prev = x;
}
return x;
}
//Removes a tree from the list defined by the head pointer
private Node cut(Node x, Node head) {
if (x.next == x) {
x.next = null;
x.prev = null;
return null;
} else {
x.next.prev = x.prev;
x.prev.next = x.next;
Node res = x.next;
x.next = null;
x.prev = null;
if (head == x) return res;
else return head;
}
}
//Merges two root lists together
private Node meld(Node x, Node y) {
if (x == null) return y;
if (y == null) return x;
x.prev.next = y.next;
y.next.prev = x.prev;
x.prev = y;
y.next = x;
return x;
}
/*************************************
* Iterator
************************************/
/**
* Gets an Iterator over the Keys in the priority queue in ascending order
* The Iterator does not implement the remove() method
* iterator() : Worst case is O(n)
* next() : Worst case is O(log(n)) (amortized)
* hasNext() : Worst case is O(1)
* @return an Iterator over the Keys in the priority queue in ascending order
*/
public Iterator<Key> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<Key> {
private FibonacciMinPQ<Key> copy;
//Constructor takes linear time
public MyIterator() {
copy = new FibonacciMinPQ<Key>(comp);
insertAll(head);
}
private void insertAll(Node head) {
if (head == null) return;
Node x = head;
do {
copy.insert(x.key);
insertAll(x.child);
x = x.next;
} while (x != head);
}
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return !copy.isEmpty();
}
//Takes amortized logarithmic time
public Key next() {
if (!hasNext()) throw new NoSuchElementException();
return copy.delMin();
}
}
/*************************************
* Comparator
************************************/
//default Comparator
private class MyComparator implements Comparator<Key> {
@Override
public int compare(Key key1, Key key2) {
return ((Comparable<Key>) key1).compareTo(key2);
}
}
}
/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar 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 3 of the License, or
* (at your option) any later version.
*
* algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
|
[
"[email protected]"
] | |
55908bd7e878e71a201aa86c5eeba9487c2dc16b
|
5b61c916007327ab88b7a504f7236d793124707a
|
/client/src/test/java/com/blockwithme/util/client/test/UtilClientTestModule.java
|
39befcc2d56cf54fbdc394b485a2a70b120fc8d7
|
[
"Apache-2.0"
] |
permissive
|
skunkiferous/Util
|
72bd3ca128c7454d2d37c77230d722f5ca6bd305
|
bac4bc1b9db6868cc093e6edccb600f7fc6c4d2b
|
refs/heads/master
| 2020-04-17T07:35:50.401020 | 2014-12-08T06:18:39 | 2014-12-08T06:18:39 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 952 |
java
|
/*
* Copyright (C) 2014 Sebastien Diot.
*
* 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.blockwithme.util.client.test;
import com.blockwithme.util.client.AbstractUtilClientModule;
/**
* @author monster
*
*/
public class UtilClientTestModule extends AbstractUtilClientModule {
/**
* @param app
*/
public UtilClientTestModule() {
super(new TestApplication());
}
}
|
[
"[email protected]"
] | |
d06373d619b3ea92e2302da485c31302132a1082
|
a83421ac706a65eed48ea77301e1e205bbf1bc76
|
/Bloemenverkoop/src/be/kriekelaar/bloemenverkoop/SaleHandler.java
|
67cb00384c86fc81d245dcf46316f8c11edf0dce
|
[] |
no_license
|
toscana/bloemenverkoopkriekelaar
|
04ca3b60d67896050fb1e7a9ee2cd19476509e41
|
1c3463b392c4b80a30357628a8500112c8830a20
|
refs/heads/master
| 2016-09-02T01:43:43.007032 | 2014-04-14T18:46:36 | 2014-04-14T18:46:36 | 32,577,027 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,597 |
java
|
package be.kriekelaar.bloemenverkoop;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
public class SaleHandler {
private static final Logger log = Logger.getLogger("bert");
private static SaleHandler uniqueInstance = new SaleHandler();
private SaleHandler() {
}
public static SaleHandler getInstance() {
return uniqueInstance;
}
public void addBevestiging(Bevestiging b) {
OfyService.ofy().save().entities(b).now();
}
public List<Bevestiging> getBevestigingen() {
List<Bevestiging> bev = OfyService.ofy().load().type(Bevestiging.class)
.list();
return bev;
}
public ArrayList<Sale> getSalesForClass(String klas) {
List<Sale> sales = OfyService.ofy().load().type(Sale.class).list();
ArrayList<Sale> klasSales = new ArrayList<Sale>();
for (Sale s : sales)
if (s.getKlas().equalsIgnoreCase(klas))
klasSales.add(s);
Collections.sort(klasSales);
return klasSales;
}
public void addSale(Sale sale) {
ArrayList<Flower> flowers = sale.getFlowers();
for (Flower f : flowers) {
OfyService.ofy().save().entities(f).now();
}
OfyService.ofy().save().entities(sale).now();
}
public void addKlas(Klas k) {
OfyService.ofy().save().entity(k);
}
public boolean saleExists(String bestelNummer) {
List<Sale> sales = OfyService.ofy().load().type(Sale.class).list();
for (Sale s : sales) {
if (s.getSaleNumber().equalsIgnoreCase(bestelNummer))
return true;
}
return false;
}
public String getKlasFullName(String optionName) {
List<Klas> klassen = OfyService.ofy().load().type(Klas.class).list();
for (Klas k : klassen)
if (k.getKlasOptionName().equalsIgnoreCase(optionName))
return k.getKlasName();
return "fout";
}
public void addFlowerType(FlowerType type) {
OfyService.ofy().save().entities(type).now();
}
public Flower getFlowerOnId(Long flowerId) {
Flower f = OfyService.ofy().load().type(Flower.class).id(flowerId)
.get();
return f;
}
public List<Flower> getFlowersForSale(Long saleID) {
Sale s = OfyService.ofy().load().type(Sale.class).id(saleID).get();
List<Flower> list = new ArrayList<Flower>();
for (Flower f : s.getFlowers()) {
Flower realflower = OfyService.ofy().load().type(Flower.class)
.id(f.getId()).get();
list.add(realflower);
}
return list;
}
public List<Sale> getSales() {
List<Sale> sales = OfyService.ofy().load().type(Sale.class).list();
Collections.sort(sales);
return sales;
}
public List<Klas> getKlassen() {
List<Klas> klassen = OfyService.ofy().load().type(Klas.class).list();
Collections.sort(klassen);
return klassen;
}
public List<FlowerType> getAllFlowerTypes() {
List<FlowerType> flowertypes = OfyService.ofy().load()
.type(FlowerType.class).list();
Collections.sort(flowertypes);
return flowertypes;
}
public void deleteSale(String salenr){
Sale s = OfyService.ofy().load().type(Sale.class).filter("saleNumber", salenr).first().get();
List<Flower> flowers = getFlowersForSale(s.getId());
OfyService.ofy().delete().entity(s);
OfyService.ofy().delete().entities(flowers);
}
public void stressTest() {
Random r;
r = new Random();
List<FlowerType> flowert = SaleHandler.getInstance()
.getAllFlowerTypes();
for (int i = 61; i < 80; i++) {
ArrayList<Flower> flowers = new ArrayList<Flower>();
int aantal = r.nextInt(15);
int aantalFlowerTypes = flowert.size();
int flowertrandom = r.nextInt(aantalFlowerTypes);
FlowerType ft = flowert.get(flowertrandom);
for (int j = 0; j < aantalFlowerTypes; j++) {
if (j != flowertrandom) {
flowers.add(new Flower(0, flowert.get(j).getPrice(),
flowert.get(j).getName(), flowert.get(j).getColor()));
} else
flowers.add(new Flower(aantal, ft.getPrice(), ft.getName(),
ft.getColor()));
}
Sale s = new Sale("bert", "europalaan", "hofstade", "email",
"telefoon", Integer.toString(i), flowers, "K0",
"Elise Van Rillaer");
s.setPayed(true);
s.setPayType(Sale.PayType.CASH);
SaleHandler.getInstance().addSale(s);
}
}
public void eraseAllSales() {
List<Sale> sales = OfyService.ofy().load().type(Sale.class).list();
List<Flower> flowers = OfyService.ofy().load().type(Flower.class)
.list();
OfyService.ofy().delete().entities(sales);
OfyService.ofy().delete().entities(flowers);
}
}
|
[
"[email protected]"
] | |
d8505e2fc3fc0a8260a10271c8b0ff5b5c7e096c
|
3b91ed788572b6d5ac4db1bee814a74560603578
|
/com/tencent/mm/plugin/backup/f/b.java
|
b04455f8d8391c1fe9cec7ba15d0e61225943e79
|
[] |
no_license
|
linsir6/WeChat_java
|
a1deee3035b555fb35a423f367eb5e3e58a17cb0
|
32e52b88c012051100315af6751111bfb6697a29
|
refs/heads/master
| 2020-05-31T05:40:17.161282 | 2018-08-28T02:07:02 | 2018-08-28T02:07:02 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 13,631 |
java
|
package com.tencent.mm.plugin.backup.f;
import android.os.Looper;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.backup.e.j;
import com.tencent.mm.pointers.PByteArray;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import junit.framework.Assert;
public abstract class b extends l {
private static final Map<Integer, Set<e>> diQ = new HashMap();
static int gRy = -1;
static final LinkedHashMap<Integer, b> gXA = new LinkedHashMap();
private static d gXB;
static a gXC;
private static f gXD = null;
private static i gXE = null;
private static g gXF = null;
private static int gXG = new Random(bi.VF()).nextInt(1147483648);
private static c gXH = null;
private static final ag handler = new ag(Looper.getMainLooper());
PByteArray gXz = new PByteArray();
public interface a {
void j(int i, byte[] bArr);
int k(int i, byte[] bArr);
}
public interface c {
void arI();
}
public abstract com.tencent.mm.bk.a asj();
public abstract com.tencent.mm.bk.a ask();
public abstract int getType();
public abstract void mI(int i);
public static void a(d dVar) {
gXB = dVar;
}
public static void a(a aVar) {
gXC = aVar;
}
public static void mx(int i) {
gRy = i;
}
public static int aqS() {
return gRy;
}
public static void a(com.tencent.mm.plugin.backup.f.f.a aVar) {
gXD = new f(aVar);
}
public static void asl() {
boolean z = true;
if (gXD != null) {
boolean z2;
f fVar = gXD;
String str = "HeartBeatTimeoutCallback is null";
if (fVar.gUp != null) {
z2 = true;
} else {
z2 = false;
}
Assert.assertTrue(str, z2);
String str2 = "New BackupHeartBeatHandler EveryTime !";
if (fVar.gYb != null) {
z = false;
}
Assert.assertTrue(str2, z);
x.i("MicroMsg.BackupHeartBeatHandler", "start backup heart beat handler.");
fVar.asB();
fVar.gYb = Boolean.valueOf(false);
com.tencent.mm.sdk.f.e.b(new f$1(fVar), "BackupSendBackupHeartBeat").start();
fVar.asC();
return;
}
x.e("MicroMsg.BackupBaseScene", "startHeartBeatHandler backupHeartBeatHandler is null!");
}
public static void asm() {
if (gXD != null) {
f fVar = gXD;
if (fVar.gYb != null) {
fVar.gYb = Boolean.valueOf(true);
}
}
}
public static void a(com.tencent.mm.plugin.backup.f.i.a aVar) {
gXE = new i(aVar);
}
public static void asn() {
int i = 0;
if (gXE != null) {
i iVar = gXE;
x.i("MicroMsg.BackupSpeedCalculator", "start backupGetSpeedTimeHandler.");
iVar.gYo = bi.VF();
iVar.gYn = 0;
iVar.gYl = 0;
iVar.gYr.clear();
iVar.gYq = 0;
iVar.gYp = 0;
while (i < 10) {
iVar.gYr.offer(Long.valueOf(0));
i++;
}
iVar.gYs.J(1000, 1000);
return;
}
x.e("MicroMsg.BackupBaseScene", "startSpeedCalculator backupSpeedCalculator is null!");
}
public static void aso() {
if (gXE != null) {
i iVar = gXE;
x.i("MicroMsg.BackupSpeedCalculator", "stop backupGetSpeedTimeHandler.");
iVar.gYs.SO();
iVar.gYq = 0;
}
}
public static String asp() {
if (gXE == null) {
return "0B";
}
x.i("MicroMsg.BackupSpeedCalculator", "getBackupPcSpeed[%s]", new Object[]{i.bW(gXE.gYm)});
return i.bW(gXE.gYm);
}
public static void a(com.tencent.mm.plugin.backup.f.g.a aVar) {
if (gXF == null) {
x.i("MicroMsg.BackupBaseScene", "startBackupReconnectHandler, no old backupReconnectHandler is stopped, new one.");
} else if (gXF.gYf) {
x.i("MicroMsg.BackupBaseScene", "startBackupReconnectHandler, old backupReconnectHandler is stopped, new one.");
} else {
x.e("MicroMsg.BackupBaseScene", "startBackupReconnectHandler, backupReconnectHandler already running, ignore it.");
return;
}
g gVar = new g(aVar);
gXF = gVar;
x.i("MicroMsg.BackupReconnectHandler", "start backupReconnectTimeHandler.");
g.index = 0;
gVar.gYf = false;
gVar.gYe = 1;
if (gVar.gYd != null) {
gVar.gYg.J(0, 0);
}
}
public static void asq() {
if (gXF != null) {
gXF.gYe = 0;
g gVar = gXF;
if (!gVar.gYf) {
x.i("MicroMsg.BackupReconnectHandler", "stop backupReconnectTimeHandler.");
gVar.gYg.SO();
gVar.gYf = true;
}
}
}
public static int asr() {
if (gXF == null) {
return 0;
}
return gXF.gYe;
}
public static void mJ(int i) {
if (gXF != null) {
gXF.gYe = i;
}
}
public static void clear() {
x.i("MicroMsg.BackupBaseScene", "BackupBaseScene clear.");
synchronized (gXA) {
gXA.clear();
}
synchronized (diQ) {
diQ.clear();
}
}
public static void a(c cVar) {
gXH = cVar;
}
public static void arI() {
if (gXH != null) {
gXH.arI();
}
}
public boolean ass() {
try {
byte[] toByteArray = ask().toByteArray();
synchronized (gXA) {
int asu = asu();
j.a(toByteArray, asu, (short) getType(), this.gXz, gRy);
if (gXC != null) {
gXC.j(asu, this.gXz.value);
}
x.i("MicroMsg.BackupBaseScene", "doScene sendSeq[%d], type[%d], buflen[%d]", new Object[]{Integer.valueOf(asu), Integer.valueOf(getType()), Integer.valueOf(this.gXz.value.length)});
gXA.put(Integer.valueOf(asu), this);
}
return true;
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupBaseScene", e, "req to buf fail: " + e.toString(), new Object[0]);
return false;
}
}
public final boolean ast() {
try {
byte[] toByteArray = ask().toByteArray();
synchronized (gXA) {
int asu = asu();
j.a(toByteArray, asu, (short) getType(), this.gXz, gRy);
if (gXC != null) {
gXC.k(asu, this.gXz.value);
}
x.i("MicroMsg.BackupBaseScene", "doSceneSameThread sendSeq[%d], type[%d], buflen[%d]", new Object[]{Integer.valueOf(asu), Integer.valueOf(getType()), Integer.valueOf(this.gXz.value.length)});
gXA.put(Integer.valueOf(asu), this);
}
return true;
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupBaseScene", e, "req to buf fail: " + e.toString(), new Object[0]);
return false;
}
}
public static boolean J(byte[] bArr, int i) {
PByteArray pByteArray = new PByteArray();
synchronized (gXA) {
int asu = asu();
j.a(bArr, asu, (short) i, pByteArray, gRy);
if (gXC != null) {
gXC.j(asu, pByteArray.value);
}
x.i("MicroMsg.BackupBaseScene", "sendBuf sendSeq[%d], type[%d], buflen[%d]", new Object[]{Integer.valueOf(asu), Integer.valueOf(i), Integer.valueOf(pByteArray.value.length)});
}
return true;
}
public static boolean o(byte[] bArr, int i, int i2) {
PByteArray pByteArray = new PByteArray();
j.a(bArr, i2, (short) i, pByteArray, gRy);
if (gXC != null) {
gXC.j(i2, pByteArray.value);
}
x.i("MicroMsg.BackupBaseScene", "sendResp sendSeq[%d], type[%d], len[%d]", new Object[]{Integer.valueOf(i2), Integer.valueOf(i), Integer.valueOf(pByteArray.value.length)});
return true;
}
public static void b(boolean z, int i, int i2, byte[] bArr) {
String str = "MicroMsg.BackupBaseScene";
String str2 = "callback receive isLocal[%b], receiveSeq[%d], type[%d], bufLen[%d]";
Object[] objArr = new Object[4];
objArr[0] = Boolean.valueOf(z);
objArr[1] = Integer.valueOf(i);
objArr[2] = Integer.valueOf(i2);
objArr[3] = Integer.valueOf(bArr == null ? 0 : bArr.length);
x.i(str, str2, objArr);
if (z) {
try {
x.w("MicroMsg.BackupBaseScene", "callback error buf content : " + (bArr == null ? "null" : new String(bArr)));
} catch (Exception e) {
}
b(z, i2, bArr, i);
return;
}
b bVar;
if (gXD != null) {
gXD.asB();
x.d("MicroMsg.BackupBaseScene", "updateHeartBeatTimeStamp type:%d, current time stamp:%d", new Object[]{Integer.valueOf(i2), Long.valueOf(bi.VF())});
}
synchronized (gXA) {
bVar = (b) gXA.remove(Integer.valueOf(i));
}
if (bVar == null) {
x.i("MicroMsg.BackupBaseScene", "notify scene null type:%d", new Object[]{Integer.valueOf(i2)});
if (bVar == null && i2 == 16) {
synchronized (gXA) {
Iterator it = new HashSet(gXA.keySet()).iterator();
while (it.hasNext()) {
Integer num = (Integer) it.next();
bVar = (b) gXA.get(num);
String str3 = "MicroMsg.BackupBaseScene";
String str4 = "callback sceneMap seq:%d scene:%s type:%s";
Object[] objArr2 = new Object[3];
objArr2[0] = num;
objArr2[1] = bVar;
if (bVar == null) {
str = "null";
} else {
str = Integer.valueOf(bVar.getType());
}
objArr2[2] = str;
x.d(str3, str4, objArr2);
if (bVar != null && bVar.getType() == 15) {
gXA.remove(num);
try {
bVar.asj().aG(bArr);
bVar.mI(i);
} catch (Throwable e2) {
bVar.g(3, -1, "buf to tagResp fail");
x.printErrStackTrace("MicroMsg.BackupBaseScene", e2, "buf to tagResp error, type[%d], errMsg:%s ", new Object[]{Integer.valueOf(bVar.getType()), e2.toString()});
}
}
}
}
return;
}
x.i("MicroMsg.BackupBaseScene", "notify seq:%d, type:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
b(z, i2, bArr, i);
} else if (bArr == null) {
try {
throw new Exception("buf is null");
} catch (Throwable e3) {
bVar.g(3, -1, "buf to resq fail");
x.printErrStackTrace("MicroMsg.BackupBaseScene", e3, "%s ", new Object[]{e3.toString()});
}
} else {
bVar.asj().aG(bArr);
bVar.mI(i);
}
}
public static int asu() {
int i = gXG;
gXG++;
return i;
}
public static void mK(int i) {
if (gXE != null) {
i iVar = gXE;
iVar.gYn = ((long) i) + iVar.gYn;
}
}
private static void b(final boolean z, final int i, final byte[] bArr, final int i2) {
handler.post(new Runnable() {
public final void run() {
if (b.gXB != null) {
b.gXB.a(z, i, bArr, i2);
} else {
x.w("MicroMsg.BackupBaseScene", "callbackToNotify, onNotify is null");
}
}
});
}
public final void g(int i, int i2, String str) {
handler.post(new 2(this, i, i2, str));
}
public static void a(int i, e eVar) {
synchronized (diQ) {
if (!diQ.containsKey(Integer.valueOf(i))) {
diQ.put(Integer.valueOf(i), new HashSet());
}
if (!((Set) diQ.get(Integer.valueOf(i))).contains(eVar)) {
((Set) diQ.get(Integer.valueOf(i))).add(eVar);
}
}
}
public static void b(int i, e eVar) {
synchronized (diQ) {
try {
if (diQ.get(Integer.valueOf(i)) != null) {
((Set) diQ.get(Integer.valueOf(i))).remove(eVar);
}
} catch (Exception e) {
x.e("MicroMsg.BackupBaseScene", "removeSceneEndListener failed:%s", new Object[]{e});
}
}
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
return 0;
}
public static void a(b bVar) {
handler.postAtFrontOfQueueV2(new 3(bVar));
}
}
|
[
"[email protected]"
] | |
0a7be724734cc67368ebd295ca6c0f5b4ffa1922
|
c04f91b88ee4988daf58a0b6690c3c6d075cbde1
|
/CursoJMS_KAFKA/service-http-ecommerce/src/main/java/br/com/alura/ecommerce/GenerateAllReportsServlet.java
|
7e3e0b9a5831e69132e2fd9413600ba6f47fa49d
|
[] |
no_license
|
carlosofpersia/estudos-java
|
baed1308ef199c7836247845d29fe49c912bc8ed
|
126470abdc1bb781bd0f928e52a45d2f8f0f12c0
|
refs/heads/master
| 2022-12-03T02:16:51.661202 | 2021-10-24T21:29:39 | 2021-10-24T21:29:39 | 134,570,431 | 0 | 0 | null | 2022-11-16T01:49:02 | 2018-05-23T13:02:13 |
HTML
|
UTF-8
|
Java
| false | false | 1,361 |
java
|
package br.com.alura.ecommerce;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class GenerateAllReportsServlet extends HttpServlet {
private final KafkaDispatcher<String> batchDispatcher = new KafkaDispatcher<>();
@Override
public void destroy() {
super.destroy();
batchDispatcher.close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
batchDispatcher.send("ECOMMERCE_SEND_MESSAGE_TO_ALL_USERS"
, "ECOMMERCE_USER_GENERATE_READING_REPORT"
, new CorrelationId(GenerateAllReportsServlet.class.getSimpleName())
, "ECOMMERCE_USER_GENERATE_READING_REPORT");
System.out.println("Sent generate report to all usres");
resp.setStatus(HttpServletResponse.SC_OK);
resp.getWriter().println("Report requests generated");
} catch (ExecutionException e) {
throw new ServletException(e);
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
}
|
[
"[email protected]"
] | |
c2b773a1a14b4b6b9178e54eca6c3b58bb3960c1
|
19df2972b36f7100f8fc378188bc7fd177428731
|
/src/main/java/evaluator/IntEvaluator.java
|
1e7c536be5596783344bf4a5e1b2ae48f94ea5ab
|
[
"Apache-2.0"
] |
permissive
|
spyrosfoniadakis/jalgorithms
|
6c92da5c2a38e18159a9904b75cb38631c8d3c86
|
47cbfbc2b0bd0c8028b6d240e5bc8bb5a6feeadd
|
refs/heads/master
| 2020-05-05T10:23:01.329778 | 2019-06-19T17:10:43 | 2019-06-19T17:10:43 | 179,943,750 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 751 |
java
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package evaluator;
/**
* @author Spyros Foniadakis
*/
@FunctionalInterface
public interface IntEvaluator<T> {
int evaluate();
}
|
[
"[email protected]"
] | |
801605054089170cbc8323a2bec4c1184bf2a5e3
|
0f35027cf2cc275ee6b1d65dbb79745acf614d70
|
/Aula03 - Maven/lab-project/src/main/java/model/factory/CarteiraFactory.java
|
87d287b12f7877c04a72e0b1c11261feaffee8a3
|
[
"MIT"
] |
permissive
|
jp-inatel-monitoria/c214-lab
|
5c94d89dfb425eb2f7fad3edf888398ad35d647c
|
f5fe85c2cb86c74317dbada50b521fcb8dd2355d
|
refs/heads/master
| 2023-01-08T20:58:48.924102 | 2020-11-06T04:37:08 | 2020-11-06T04:37:08 | 284,138,097 | 2 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 182 |
java
|
package model.factory;
import model.entities.Carteira;
public class CarteiraFactory {
public static Carteira createCarteira(String nome) {
return new Carteira(nome);
}
}
|
[
"[email protected]"
] | |
2d3262c37b2474e27b5bc44a6472825b971b6b4e
|
63e9fb6e0ae181bfa9f6552bf31985fc60897ad6
|
/android/client-frwk/Examples/JaxbAndroidImpl/src/main/java/com/sun/xml/bind/v2/runtime/DomPostInitAction.java
|
7ea7894641f44dc916a3fd9d4e25e71c8be7c036
|
[
"BSD-2-Clause",
"BSD-2-Clause-Views"
] |
permissive
|
societies/SOCIETIES-Platform
|
6503b84b11b21f5bd4b5f1db0c22c4356b4a3f02
|
7050936833dcadf5cf318921ba97154843a05a46
|
HEAD
| 2016-09-05T22:29:20.159081 | 2014-05-20T10:53:33 | 2014-05-20T10:53:33 | 2,576,064 | 15 | 4 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,917 |
java
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.bind.v2.runtime;
import java.util.HashSet;
import java.util.Set;
import javax.xml.XMLConstants;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* Post-init action for {@link MarshallerImpl} that incorporate the in-scope namespace bindings
* from a DOM node.
*
* TODO: do we really need this? think about a better way to put this logic back into marshaller.
*
* @author Kohsuke Kawaguchi
*/
final class DomPostInitAction implements Runnable {
private final Node node;
private final XMLSerializer serializer;
DomPostInitAction(Node node, XMLSerializer serializer) {
this.node = node;
this.serializer = serializer;
}
// declare the currently in-scope namespace bindings
public void run() {
Set<String> declaredPrefixes = new HashSet<String>();
for( Node n=node; n!=null && n.getNodeType()==Node.ELEMENT_NODE; n=n.getParentNode() ) {
NamedNodeMap atts = n.getAttributes();
if(atts==null) continue; // broken DOM. but be graceful.
for( int i=0; i<atts.getLength(); i++ ) {
Attr a = (Attr)atts.item(i);
String nsUri = a.getNamespaceURI();
if(nsUri==null || !nsUri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI))
continue; // not a namespace declaration
String prefix = a.getLocalName();
if(prefix==null)
continue; // broken DOM. skip to be safe
if(prefix.equals("xmlns")) {
prefix = "";
}
String value = a.getValue();
if(value==null)
continue; // broken DOM. skip to be safe
if(declaredPrefixes.add(prefix)) {
serializer.addInscopeBinding(value,prefix);
}
}
}
}
}
|
[
"[email protected]"
] | |
85748995b10a5c53eb8387e923aebfe266807f18
|
f69ddf5d99f73cf68cf42e39ece0b0d4ab9ade42
|
/java/org/tensorflow/framework/VersionsProtos.java
|
b30e34244c347cb701a9f7f9251e09c611b625fc
|
[] |
no_license
|
princessd8251/JavaClient-proto-java
|
974b537433750e78134f1a0d702b3482c68f27ff
|
29856397a27db31edf86b1db6945bad25501a44e
|
refs/heads/master
| 2023-07-12T23:25:55.255489 | 2021-08-17T08:57:57 | 2021-08-17T08:57:57 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | true | 2,473 |
java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/framework/versions.proto
package org.tensorflow.framework;
public final class VersionsProtos {
private VersionsProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_tensorflow_VersionDef_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_tensorflow_VersionDef_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n(tensorflow/core/framework/versions.pro" +
"to\022\ntensorflow\"K\n\nVersionDef\022\020\n\010producer" +
"\030\001 \001(\005\022\024\n\014min_consumer\030\002 \001(\005\022\025\n\rbad_cons" +
"umers\030\003 \003(\005Bn\n\030org.tensorflow.frameworkB" +
"\016VersionsProtosP\001Z=github.com/tensorflow" +
"/tensorflow/tensorflow/go/core/framework" +
"\370\001\001b\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_tensorflow_VersionDef_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_tensorflow_VersionDef_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_tensorflow_VersionDef_descriptor,
new java.lang.String[] { "Producer", "MinConsumer", "BadConsumers", });
}
// @@protoc_insertion_point(outer_class_scope)
}
|
[
"[email protected]"
] | |
3bf4aae44a3f07de5d797e719d94e1f069e60bd7
|
56af72ad449098e1a1eefbfc04cb48ae47ed4fa4
|
/inflearn-jpa-web/src/main/java/inflearn/jpa/web/jpashop/controller/OrderController.java
|
c66582097de2cb133a1adf46d3113bc143fa79ff
|
[] |
no_license
|
ninjasul/springstudy
|
506eb1e2e0d2a8fb20759042bdb8f73fb96c2684
|
bdd00c0d387c8652786ce824820c5cc2682d910f
|
refs/heads/master
| 2022-12-23T14:44:54.260724 | 2020-04-13T00:45:07 | 2020-04-13T00:45:07 | 160,325,765 | 0 | 0 | null | 2022-12-15T23:41:37 | 2018-12-04T08:42:18 |
Java
|
UTF-8
|
Java
| false | false | 1,816 |
java
|
package inflearn.jpa.web.jpashop.controller;
import inflearn.jpa.web.jpashop.domain.Member;
import inflearn.jpa.web.jpashop.domain.Order;
import inflearn.jpa.web.jpashop.domain.item.Item;
import inflearn.jpa.web.jpashop.repository.OrderSearch;
import inflearn.jpa.web.jpashop.service.ItemService;
import inflearn.jpa.web.jpashop.service.MemberService;
import inflearn.jpa.web.jpashop.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequiredArgsConstructor
public class OrderController {
private final MemberService memberService;
private final ItemService itemService;
private final OrderService orderService;
@GetMapping("/order")
public String createOrderForm(Model model) {
List<Member> members = memberService.findMembers();
List<Item> items = itemService.findItems();
model.addAttribute("members", members);
model.addAttribute("items", items);
return "order/orderForm";
}
@PostMapping("/order")
public String order(@RequestParam Long memberId, @RequestParam Long itemId, @RequestParam int count) {
orderService.order(memberId, itemId, count);
return "redirect:/orders";
}
@GetMapping("/orders")
public String orders(@ModelAttribute OrderSearch orderSearch, Model model) {
List<Order> orders = orderService.findOrders(orderSearch);
model.addAttribute("orders", orders);
return "order/orderList";
}
@PostMapping("/orders/{orderId}/cancel")
public String cancelOrder(@PathVariable Long orderId) {
orderService.cancelOrder(orderId);
return "redirect:/orders";
}
}
|
[
"[email protected]"
] | |
6b69e2ec7a44c6e96b87b9b18175f8a4828a7a0d
|
6c9a1852426ce7b255a5a05433a66806a927c5d3
|
/ch03/src/ch03/Ch03Ex02_04.java
|
82779727496768519459d1ea0210678be2a9efe1
|
[] |
no_license
|
LEEWOODO/work_java
|
f26eee2b6b20508c0bd17500cdbf327cdd188a49
|
c66024bd09bb5daf4e17b163e41ea2432b92a6e7
|
refs/heads/master
| 2020-03-18T03:43:36.400627 | 2018-06-30T05:21:44 | 2018-06-30T05:21:44 | 134,252,624 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 972 |
java
|
package ch03;
import java.util.Scanner;
public class Ch03Ex02_04 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 민수
int mHeight = 0;
int mWeight = 0;
// 기영
int kHeight=0;
int kWeight=0;
Scanner scanner = new Scanner(System.in);
System.out.print("민수 키를 입력하여주세요.> ");
mHeight = Integer.parseInt(scanner.nextLine());
System.out.print("민수 몸무게를 입력하여주세요.>> ");
mWeight = Integer.parseInt(scanner.nextLine());
System.out.print("기영 키를 입력하여주세요.> ");
kHeight = Integer.parseInt(scanner.nextLine());
System.out.print("기영 몸무게를 입력하여주세요.>> ");
kWeight = Integer.parseInt(scanner.nextLine());
// 삼항 연산자 두번 쓰기
boolean isGreatestMinsoo=mHeight>kHeight?
(mWeight>kWeight?true:false):false;
System.out.printf("%b%n",isGreatestMinsoo);
}
}
|
[
"KOITT@KOITT-PC"
] |
KOITT@KOITT-PC
|
d36c295b35c6d82009f05b454d11555dd40f1b37
|
942c8633b0c2e403a9f24cb7757d00087711a30c
|
/Server Side/predict_data.java
|
6cd9849175fa0caa2e610ed80fe9a16d1221cdf7
|
[] |
no_license
|
kumaranupam068/Two-Wheeler-Rash-Driving-Detection
|
e1c241a3c83c97944e90600cf6f7e1e9e4a5228e
|
fcf49768b164e576837735455615a520e64d216a
|
refs/heads/main
| 2023-05-21T12:03:16.893343 | 2021-06-11T15:50:11 | 2021-06-11T15:50:11 | 376,062,948 | 0 | 0 | null | 2021-06-11T15:27:59 | 2021-06-11T15:09:25 | null |
UTF-8
|
Java
| false | false | 4,031 |
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.
*/
import Logic.info;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author fgfdg
*/
public class predict_data extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String adata=request.getParameter("data");
String ndata="";
String arr[]=adata.split("\n");
System.out.println(">>>>>>>>>>>>>>>"+arr.length);
if(arr.length>=9)
{
for(int i=0;i<9;i++)
{
System.out.println("?????"+arr[i]);
ndata+=arr[i]+"\n";
}
File f1=new File(info.py_path+"Test/1.txt");
if(!f1.exists())
{
f1.createNewFile();
}
FileOutputStream fout=new FileOutputStream(f1);
fout.write(ndata.getBytes());
fout.close();
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(predict_data.class.getName()).log(Level.SEVERE, null, ex);
}
File file = new File(info.py_path+"output.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st="",data="";
while ((st = br.readLine()) != null)
{
System.out.println(st);
data=st;
}
out.print(data);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
[
"[email protected]"
] | |
2b2a5815fdd67f3e498e836778e1e446ffcf5e63
|
95cfe2239c8fce0cec91d76e0a82f59a9efc4cb8
|
/sourceCode/JFreeChartMutGenerator/java.lang.IndexOutOfBoundsException/3814_ROR/ComparableObjectSeries.java
|
6af448e082f6a569f3fb249473d2fdfc76b27024
|
[] |
no_license
|
Djack1010/BUG_DB
|
28eff24aece45ed379b49893176383d9260501e7
|
a4b6e4460a664ce64a474bfd7da635aa7ff62041
|
refs/heads/master
| 2022-04-09T01:58:29.736794 | 2020-03-13T14:15:11 | 2020-03-13T14:15:11 | 141,260,015 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 15,292 |
java
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------------------
* ComparableObjectSeries.java
* ---------------------------
* (C) Copyright 2006-2016, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 19-Oct-2006 : New class (DG);
* 31-Oct-2007 : Implemented faster hashCode() (DG);
* 27-Nov-2007 : Changed clear() from protected to public (DG);
*
*/
package org.jfree.data;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.util.ObjectUtils;
import org.jfree.chart.util.Args;
import org.jfree.data.general.Series;
import org.jfree.data.general.SeriesChangeEvent;
import org.jfree.data.general.SeriesException;
/**
* A (possibly ordered) list of (Comparable, Object) data items.
*
* @since 1.0.3
*/
public class ComparableObjectSeries extends Series
implements Cloneable, Serializable {
/** Storage for the data items in the series. */
protected List data;
/** The maximum number of items for the series. */
private int maximumItemCount = Integer.MAX_VALUE;
/** A flag that controls whether the items are automatically sorted. */
private boolean autoSort;
/** A flag that controls whether or not duplicate x-values are allowed. */
private boolean allowDuplicateXValues;
/**
* Creates a new empty series. By default, items added to the series will
* be sorted into ascending order by x-value, and duplicate x-values will
* be allowed (these defaults can be modified with another constructor.
*
* @param key the series key ({@code null} not permitted).
*/
public ComparableObjectSeries(Comparable key) {
this(key, true, true);
}
/**
* Constructs a new series that contains no data. You can specify
* whether or not duplicate x-values are allowed for the series.
*
* @param key the series key ({@code null} not permitted).
* @param autoSort a flag that controls whether or not the items in the
* series are sorted.
* @param allowDuplicateXValues a flag that controls whether duplicate
* x-values are allowed.
*/
public ComparableObjectSeries(Comparable key, boolean autoSort,
boolean allowDuplicateXValues) {
super(key);
this.data = new java.util.ArrayList();
this.autoSort = autoSort;
this.allowDuplicateXValues = allowDuplicateXValues;
}
/**
* Returns the flag that controls whether the items in the series are
* automatically sorted. There is no setter for this flag, it must be
* defined in the series constructor.
*
* @return A boolean.
*/
public boolean getAutoSort() {
return this.autoSort;
}
/**
* Returns a flag that controls whether duplicate x-values are allowed.
* This flag can only be set in the constructor.
*
* @return A boolean.
*/
public boolean getAllowDuplicateXValues() {
return this.allowDuplicateXValues;
}
/**
* Returns the number of items in the series.
*
* @return The item count.
*/
public int getItemCount() {
return this.data.size();
}
/**
* Returns the maximum number of items that will be retained in the series.
* The default value is {@code Integer.MAX_VALUE}.
*
* @return The maximum item count.
* @see #setMaximumItemCount(int)
*/
public int getMaximumItemCount() {
return this.maximumItemCount;
}
/**
* Sets the maximum number of items that will be retained in the series.
* If you add a new item to the series such that the number of items will
* exceed the maximum item count, then the first element in the series is
* automatically removed, ensuring that the maximum item count is not
* exceeded.
* <p>
* Typically this value is set before the series is populated with data,
* but if it is applied later, it may cause some items to be removed from
* the series (in which case a {@link SeriesChangeEvent} will be sent to
* all registered listeners.
*
* @param maximum the maximum number of items for the series.
*/
public void setMaximumItemCount(int maximum) {
this.maximumItemCount = maximum;
boolean dataRemoved = false;
while (this.data.size() > maximum) {
this.data.remove(0);
dataRemoved = true;
}
if (dataRemoved) {
fireSeriesChanged();
}
}
/**
* Adds new data to the series and sends a {@link SeriesChangeEvent} to
* all registered listeners.
* <P>
* Throws an exception if the x-value is a duplicate AND the
* allowDuplicateXValues flag is false.
*
* @param x the x-value ({@code null} not permitted).
* @param y the y-value ({@code null} permitted).
*/
protected void add(Comparable x, Object y) {
// argument checking delegated...
add(x, y, true);
}
/**
* Adds new data to the series and, if requested, sends a
* {@link SeriesChangeEvent} to all registered listeners.
* <P>
* Throws an exception if the x-value is a duplicate AND the
* allowDuplicateXValues flag is false.
*
* @param x the x-value ({@code null} not permitted).
* @param y the y-value ({@code null} permitted).
* @param notify a flag the controls whether or not a
* {@link SeriesChangeEvent} is sent to all registered
* listeners.
*/
protected void add(Comparable x, Object y, boolean notify) {
// delegate argument checking to XYDataItem...
ComparableObjectItem item = new ComparableObjectItem(x, y);
add(item, notify);
}
/**
* Adds a data item to the series and, if requested, sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param item the (x, y) item ({@code null} not permitted).
* @param notify a flag that controls whether or not a
* {@link SeriesChangeEvent} is sent to all registered
* listeners.
*/
protected void add(ComparableObjectItem item, boolean notify) {
Args.nullNotPermitted(item, "item");
if (this.autoSort) {
int index = Collections.binarySearch(this.data, item);
if (index < 0) {
this.data.add(-index - 1, item);
}
else {
if (this.allowDuplicateXValues) {
// need to make sure we are adding *after* any duplicates
int size = this.data.size();
while (index < size
&& item.compareTo(this.data.get(index)) == 0) {
index++;
}
if (index < this.data.size()) {
this.data.add(index, item);
}
else {
this.data.add(item);
}
}
else {
throw new SeriesException("X-value already exists.");
}
}
}
else {
if (!this.allowDuplicateXValues) {
// can't allow duplicate values, so we need to check whether
// there is an item with the given x-value already
int index = indexOf(item.getComparable());
if (index >= 0) {
throw new SeriesException("X-value already exists.");
}
}
this.data.add(item);
}
if (getItemCount() > this.maximumItemCount) {
this.data.remove(0);
}
if (notify) {
fireSeriesChanged();
}
}
/**
* Returns the index of the item with the specified x-value, or a negative
* index if the series does not contain an item with that x-value. Be
* aware that for an unsorted series, the index is found by iterating
* through all items in the series.
*
* @param x the x-value ({@code null} not permitted).
*
* @return The index.
*/
public int indexOf(Comparable x) {
if (this.autoSort) {
return Collections.binarySearch(this.data, new ComparableObjectItem(
x, null));
}
else {
for (int i = 0; i < this.data.size(); i++) {
ComparableObjectItem item = (ComparableObjectItem)
this.data.get(i);
if (item.getComparable().equals(x)) {
return i;
}
}
return -1;
}
}
/**
* Updates an item in the series.
*
* @param x the x-value ({@code null} not permitted).
* @param y the y-value ({@code null} permitted).
*
* @throws SeriesException if there is no existing item with the specified
* x-value.
*/
protected void update(Comparable x, Object y) {
int index = indexOf(x);
if (index < 0) {
throw new SeriesException("No observation for x = " + x);
}
else {
ComparableObjectItem item = getDataItem(index);
item.setObject(y);
fireSeriesChanged();
}
}
/**
* Updates the value of an item in the series and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param index the item (zero based index).
* @param y the new value ({@code null} permitted).
*/
protected void updateByIndex(int index, Object y) {
ComparableObjectItem item = getDataItem(index);
item.setObject(y);
fireSeriesChanged();
}
/**
* Return the data item with the specified index.
*
* @param index the index.
*
* @return The data item with the specified index.
*/
protected ComparableObjectItem getDataItem(int index) {
return (ComparableObjectItem) this.data.get(index);
}
/**
* Deletes a range of items from the series and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param start the start index (zero-based).
* @param end the end index (zero-based).
*/
protected void delete(int start, int end) {
for (int i = start; i <= end; i++) {
this.data.remove(start);
}
fireSeriesChanged();
}
/**
* Removes all data items from the series and, unless the series is
* already empty, sends a {@link SeriesChangeEvent} to all registered
* listeners.
*/
public void clear() {
if (this.data.size() > 0) {
this.data.clear();
fireSeriesChanged();
}
}
/**
* Removes the item at the specified index and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param index the index.
*
* @return The item removed.
*/
protected ComparableObjectItem remove(int index) {
ComparableObjectItem result = (ComparableObjectItem) this.data.remove(
index);
fireSeriesChanged();
return result;
}
/**
* Removes the item with the specified x-value and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param x the x-value.
* @return The item removed.
*/
public ComparableObjectItem remove(Comparable x) {
return remove(indexOf(x));
}
/**
* Tests this series for equality with an arbitrary object.
*
* @param obj the object to test against for equality
* ({@code null} permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ComparableObjectSeries)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
ComparableObjectSeries that = (ComparableObjectSeries) obj;
if (this.maximumItemCount != that.maximumItemCount) {
return false;
}
if (this.autoSort != that.autoSort) {
return false;
}
if (this.allowDuplicateXValues != that.allowDuplicateXValues) {
return false;
}
if (!ObjectUtils.equal(this.data, that.data)) {
return false;
}
return true;
}
/**
* Returns a hash code.
*
* @return A hash code.
*/
public int hashCode() {
int result = super.hashCode();
// it is too slow to look at every data item, so let's just look at
// the first, middle and last items...
int count = getItemCount();
if (count > 0) {
ComparableObjectItem item = getDataItem(0);
result = 29 * result + item.hashCode();
}
if (count > 1) {
ComparableObjectItem item = getDataItem(count - 1);
result = 29 * result + item.hashCode();
}
if (count > 2) {
ComparableObjectItem item = getDataItem(count / 2);
result = 29 * result + item.hashCode();
}
result = 29 * result + this.maximumItemCount;
result = 29 * result + (this.autoSort ? 1 : 0);
result = 29 * result + (this.allowDuplicateXValues ? 1 : 0);
return result;
}
}
|
[
"[email protected]"
] | |
1694d9b10f56485cee6725ed319dc745aaf531fc
|
9c8bb45cb67a54dfa36e7a87cfad9318ef302553
|
/YYDRobotHardwareTest/src/main/java/com/yongyida/robot/hardware/test/item/motion/adapter/EditAngleAdapter.java
|
f71fb1b7c0705a6d9b644701caffcf7967d409a4
|
[] |
no_license
|
xiangxianghuang/communicate_app
|
49fff075097ccf5818f1924a4b07863331725fb9
|
74d9dcd4f71499a9bfa070e55bbf20da9cefedb2
|
refs/heads/master
| 2018-10-04T16:24:44.005065 | 2018-07-11T10:53:39 | 2018-07-11T10:53:39 | 112,999,814 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 6,997 |
java
|
package com.yongyida.robot.hardware.test.item.motion.adapter;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.yongyida.robot.communicate.app.hardware.motion.send.data.SteeringControl;
import com.yongyida.robot.communicate.app.hardware.motion.send.data.constant.Direction;
import com.yongyida.robot.hardware.test.R;
import java.util.ArrayList;
/*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
.............................................
佛祖镇楼 BUG辟易
佛曰:
写字楼里写字间,写字间里程序员;
程序人员写程序,又拿程序换酒钱。
酒醒只在网上坐,酒醉还来网下眠;
酒醉酒醒日复日,网上网下年复年。
但愿老死电脑间,不愿鞠躬老板前;
奔驰宝马贵者趣,公交自行程序员。
别人笑我忒疯癫,我笑自己命太贱;
不见满街漂亮妹,哪个归得程序员?
*/
/**
* Create By HuangXiangXiang 2018/6/28
*/
public class EditAngleAdapter extends BaseAdapter {
private final LayoutInflater mLayoutInflater;
private Direction mDirection ;
private final ArrayList<SteeringControl> mSteeringControls = new ArrayList<SteeringControl>() ;
private ArrayList<SteeringControl> mLeftSteerings ;
private ArrayList<SteeringControl> mRightSteerings;
public EditAngleAdapter(Context context) {
this.mLayoutInflater = LayoutInflater.from(context);
}
public void setSteeringControls(ArrayList<SteeringControl> leftSteerings, ArrayList<SteeringControl> rightSteerings){
this.mLeftSteerings = leftSteerings ;
this.mRightSteerings = rightSteerings ;
refreshData() ;
}
public void setDirection(Direction direction) {
this.mDirection = direction;
refreshData() ;
}
private void refreshData(){
mSteeringControls.clear();
if(mDirection != null && mLeftSteerings != null && mRightSteerings != null){
switch (mDirection){
case LEFT:
case SAME:
mSteeringControls.addAll(mLeftSteerings) ;
break;
case RIGHT:
mSteeringControls.addAll(mRightSteerings) ;
break;
case BOTH:
mSteeringControls.addAll(mLeftSteerings) ;
mSteeringControls.addAll(mRightSteerings) ;
break;
}
notifyDataSetChanged();
}
}
@Override
public int getCount() {
if (mSteeringControls == null) {
return 0;
} else {
return mSteeringControls.size();
}
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.item_edit_angle, null);
holder = new ViewHolder(convertView) ;
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
SteeringControl steeringControl = mSteeringControls.get(position) ;
holder.setSteeringControl(steeringControl) ;
return convertView;
}
static class ViewHolder {
private SteeringControl mSteeringControl ;
private TextView mPositionTvw;
private EditText mAngleValueEtt;
private EditText mDelayTimeEtt;
private EditText mUsedTimeEtt;
ViewHolder(View view) {
this.mPositionTvw = (TextView) view.findViewById(R.id.position_tvw);
this.mAngleValueEtt = (EditText) view.findViewById(R.id.angle_value_ett);
this.mDelayTimeEtt = (EditText) view.findViewById(R.id.delay_time_ett);
this.mUsedTimeEtt = (EditText) view.findViewById(R.id.used_time_ett);
this.mAngleValueEtt.addTextChangedListener(mTextWatcher);
this.mDelayTimeEtt.addTextChangedListener(mTextWatcher);
this.mUsedTimeEtt.addTextChangedListener(mTextWatcher);
}
void setSteeringControl(SteeringControl steeringControl) {
this.mSteeringControl = steeringControl ;
this.mPositionTvw.setText(steeringControl.getPosition().name());
this.mAngleValueEtt.setText(String.valueOf(steeringControl.getDistance().getValue()));
this.mDelayTimeEtt.setText(String.valueOf(steeringControl.getDelay()));
this.mUsedTimeEtt.setText(String.valueOf(steeringControl.getTime().getValue()));
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int value;
try {
value = Integer.parseInt(s.toString()) ;
}catch (Exception e){
value = 0 ;
}
if (s == mAngleValueEtt.getText()){
mSteeringControl.getDistance().setValue(value);
}else if(s == mDelayTimeEtt.getText()){
mSteeringControl.setDelay(value);
}else if(s == mUsedTimeEtt.getText()){
mSteeringControl.getTime().setValue(value);
}
}
} ;
}
}
|
[
"[email protected]"
] | |
7bd7e26f43852237233e25af0d2d99e0b6fec52e
|
a9809edaea0a6fb9d0eac4f5dfacab8812797cdb
|
/Documenti ECC/Classi/Hashes/HashEX.java
|
2ebc8a8fd01ac732a9c4e1072354aa7a6fb205b9
|
[] |
no_license
|
Mark692/ECC-Java
|
76cb85e8b2d08215b961b76d10095eea09adadf7
|
151903ba8a34391f7c8fb616fa8a044c8b432e0a
|
refs/heads/master
| 2021-06-19T06:18:13.738532 | 2019-05-07T22:30:32 | 2019-05-07T22:30:32 | 105,257,897 | 2 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 66 |
java
|
package Hashes;
public class HashEX extends Exception
{
}
|
[
"[email protected]"
] | |
70d9a1020b1569d0b733f24d3664e0cc400ca297
|
e38192fa32e9645227878ed131b6e2bc0fb00183
|
/person/person/bom_person/com/msl/rule/life/bom/AlphaSearchBom.java
|
feea876d0644828cd5308560f28006999320b068
|
[] |
no_license
|
Wfaker/firsttech
|
d28f34a76d55035da6af7604c40a09cabfe17c03
|
5f5856d3ad0b2fa4d9ac769e723a498fa03c0ebd
|
refs/heads/master
| 2023-04-24T01:55:22.267657 | 2021-05-03T03:07:39 | 2021-05-03T03:07:39 | 360,743,984 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,779 |
java
|
package com.msl.rule.life.bom;
import java.io.Serializable;
/**
*
* 保单历史数据
*
* @author zhou
*
*/
public class AlphaSearchBom implements Serializable {
/**
* 序列版本号
*/
private static final long serialVersionUID = 205706753066776061L;
// 属性
private String p100100011 = ""; // 保单核保类别
private String p100100010 = ""; // 客户再核保保单检查
private String c100100007 = ""; // 保单状态(长险)
private String p100100008 = ""; // 保单主险加费
private String p100100007 = ""; // 保单附加险加费
private String p100200001 = ""; // 团险主险加费
private String p100200002 = ""; //团险附加险加费
private String p100100006 = ""; // 保单Follow_Up_Indicator
private String p100100005 = ""; // Medical_Remark检查
private String p100100004 = ""; // 保单Policy_Remark
private String p100100003 = ""; // 保单POS_Change_Exist
private String p100100043 = ""; // 理赔标志(含个团险)
private String p100100042 = ""; // 在我司发生意外重大疾病轻症重疾保费豁免理赔
private String H100100001 = ""; // 是否是高净值客户
private String H100100003 = ""; // alpha search 有CI risk或Cancer risk保单有除外决定
private String H100100004 = ""; // ACM理赔指标
private String c100100010 = ""; // 保单状态(ACM)
// Getter && Setter
public String getC100100010() {
return c100100010;
}
public void setC100100010(String c100100010) {
this.c100100010 = c100100010;
}
public String getH100100001() {
return H100100001;
}
public String getP100200002() {
return p100200002;
}
public void setP100200002(String p100200002) {
this.p100200002 = p100200002;
}
public String getH100100003() {
return H100100003;
}
public void setH100100003(String h100100003) {
H100100003 = h100100003;
}
public void setH100100001(String h100100001) {
H100100001 = h100100001;
}
public String getP100100011() {
return p100100011;
}
public void setP100100011(String p100100011) {
this.p100100011 = p100100011;
}
public String getP100100010() {
return p100100010;
}
public void setP100100010(String p100100010) {
this.p100100010 = p100100010;
}
public String getC100100007() {
return c100100007;
}
public void setC100100007(String c100100007) {
this.c100100007 = c100100007;
}
public String getP100100008() {
return p100100008;
}
public void setP100100008(String p100100008) {
this.p100100008 = p100100008;
}
public String getP100100007() {
return p100100007;
}
public void setP100100007(String p100100007) {
this.p100100007 = p100100007;
}
public String getP100200001() {
return p100200001;
}
public void setP100200001(String p100200001) {
this.p100200001 = p100200001;
}
public String getP100100006() {
return p100100006;
}
public void setP100100006(String p100100006) {
this.p100100006 = p100100006;
}
public String getP100100005() {
return p100100005;
}
public void setP100100005(String p100100005) {
this.p100100005 = p100100005;
}
public String getP100100004() {
return p100100004;
}
public void setP100100004(String p100100004) {
this.p100100004 = p100100004;
}
public String getP100100003() {
return p100100003;
}
public void setP100100003(String p100100003) {
this.p100100003 = p100100003;
}
public String getP100100043() {
return p100100043;
}
public void setP100100043(String p100100043) {
this.p100100043 = p100100043;
}
public String getP100100042() {
return p100100042;
}
public void setP100100042(String p100100042) {
this.p100100042 = p100100042;
}
public String getH100100004() {
return H100100004;
}
public void setH100100004(String h100100004) {
H100100004 = h100100004;
}
}
|
[
"[email protected]"
] | |
b8587f19fa5ae2d8e1aa545620f295fff494dd28
|
2766fc0c72b5eddd9b381008df5415f595db489a
|
/src/ludia/Zamestnanec.java
|
07bac346f7e3fd894804f0ad6c42881aaaf41e22
|
[] |
no_license
|
suranjakub/zabezpecovaci_system_starobinec
|
cce0c704bf768fbd3be15c5de6f4dd259819daa7
|
cf9e015699a1362706fedaf9e614c4978f942d29
|
refs/heads/master
| 2022-11-04T20:34:22.904402 | 2020-05-25T00:10:36 | 2020-05-25T00:10:36 | 274,130,691 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 526 |
java
|
package ludia;
import java.io.Serializable;
public abstract class Zamestnanec implements Serializable {
protected String meno;
protected String typ;
protected Zamestnanec(String meno, String typ) {
this.meno = meno;
this.typ = typ;
}
public String getTyp() {
return this.typ;
}
public String predstavSa() {
String newLine = System.getProperty("line.separator");
String s = "Predstaveny " + this.typ + " " + this.meno + newLine;
return s;
}
}
|
[
"[email protected]"
] | |
c8602c22bcd4ae24eee632dda7ae60a7219583df
|
d49f344f17f45a549c1d24e77123d8ebabc9637e
|
/src/main/java/com/fasttrackit/Main.java
|
54d1aa168b59b839da6efe0d4ecdfd4de4fcd812
|
[] |
no_license
|
gyengebetty/Produs
|
e1510f06c6b301954cdf44207f2865258a7c4ea1
|
4036ce8c244e54003a677f4e303505a8dbfcd826
|
refs/heads/master
| 2020-07-28T07:47:54.154372 | 2019-09-18T16:24:08 | 2019-09-18T16:24:08 | 209,354,253 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,788 |
java
|
package com.fasttrackit;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Cosmetice c1=new Cosmetice();
c1.setNume(" Fond de ten lichid: Loreal");
c1.setPret(65);
c1.setCuloare("Natural");
c1.setGreutate(250);
c1.setCantitate(1);
c1.setDescriere( "Acum puteți avea tenul neted, luminos și fără cusur! " +
"Fondul de ten lichid se aplică ușor, se contopește perfect în piele și creează un aspect complet natural.");
Cosmetice c2=new Cosmetice();
c2.setNume("Rimel Maybelline");
c2.setPret(116.8);
c2.setCuloare("Negru");
c2.setGreutate(0.150);
c2.setCantitate(4);
c2.setDescriere("Volum Express Colossal, noul rimel de la Maybelline ofera genelor de 15X mai mult volum, instant! Rapid, usor si eficient!");
Electrocasnice e1=new Electrocasnice();
e1.setNume(" Mixer de bucatarie");
e1.setPret(367.43);
e1.setTip("Gama de bucatarie: Philips");
e1.setGreutate(3.450);
e1.setCantitate(1);
e1.setDescriere(" Accesorii multiple cu fixare rapidă ,spiralizator pentru fructe și legume, pahar on-the-go etanș pentru smoothie-uri, recipient pentru supă,Motor puternic de 800W pentru rezultate omogene\n" +
"Ușor de curățat și apărătoare care previne stropirea");
e1.setInaltime(12);
e1.setLatime(35);
e1.setLungime(20);
Electrocasnice e2=new Electrocasnice();
e2.setNume("Televizor 4K");
e2.setPret(2899);
e2.setTip("Samsung");
e2.setGreutate(2.450);
e2.setCantitate(1);
e2.setDescriere(" Vizualizează continut HDR cu o claritate mai bună si o expresie a culorii detaliată. Televizorul Samsung UHD îti oferă detalii mai clare în scenele luminoase si întunecate.");
e2.setInaltime(90);
e2.setLatime(127);
e2.setLungime(127);
Alimente a1=new Alimente();
a1.setNume("Ciocolata cu alune Milka");
a1.setPret(13.50);
a1.setGrupaProduse("Dulciuri");
a1.setCantitate(3);
a1.setDescriere(" Produse delicioase cu lapte din Alpi, pentru toți iubitorii de ciocolată. 100g.");
Alimente a2=new Alimente();
a2.setNume("Napolitane Manner ");
a2.setPret(79.94);
a2.setGrupaProduse("Dulciuri");
a2.setCantitate(2);
a2.setDescriere(" Manner napolitane ciocolata si caramel 400 g.");
System.out.println(a2.getGrupaProduse()+" "+a2.getNume()+a2.getCantitate()+"buc "+a2.getPret()+"Ron "+" " +a2.getDescriere());
Date dat = new Date();
dat.setDate(200);
System.out.println("Data expirare"+ " " +dat);
}
}
|
[
"[email protected]"
] | |
a8e52a161073ffc7fcb59020c920251c97b9b362
|
7fcc420275f38044711122b695175f7472522e0e
|
/src/main/java/com/xinput/wechat/response/pay/RefundResponse.java
|
4efe3342fa358f7bd875155f9f7651a21707002a
|
[] |
no_license
|
wangdpwin/wechat-api
|
3147ca3f2cc8ae3742bb4c2cd7c9335d30186495
|
0982ffc7f0f7a67c7b7725d08b16b62baac6d472
|
refs/heads/master
| 2022-12-17T15:29:15.924554 | 2020-09-23T09:29:35 | 2020-09-23T09:29:35 | 297,892,315 | 0 | 0 | null | 2020-09-23T07:42:46 | 2020-09-23T07:42:45 | null |
UTF-8
|
Java
| false | false | 8,828 |
java
|
package com.xinput.wechat.response.pay;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.xinput.bleach.util.StringUtils;
/**
* 申请退款响应值
*
* @author <a href="mailto:[email protected]">xinput</a>
* @date 2020-09-17 23:45
*/
@XStreamAlias("xml")
public class RefundResponse extends BaseWeChatPayResp {
// 以下字段在return_code为SUCCESS的时候有返回
/**
* 微信订单号
* 必填: 是
* 类型: String(32)
* 示例值: 4007752501201407033233368018
* 描述: 微信订单号
*/
@XStreamAlias("transaction_id")
private String transaction_id;
/**
* 商户订单号
* 必填: 是
* 类型: String(32)
* 示例值: 33368018
* 描述: 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一
*/
@XStreamAlias("out_trade_no")
private String out_trade_no;
/**
* 商户退款单号
* 必填: 是
* 类型: String(64)
* 示例值: 121775250
* 描述: 商户系统内部的退款单号,商户系统内部唯一,只能是数字、大小写字母_-|*@ ,同一退款单号多次请求只退一笔。
*/
@XStreamAlias("out_refund_no")
private String out_refund_no;
/**
* 微信退款单号
* 必填: 是
* 类型: String(32)
* 示例值: 2007752501201407033233368018
* 描述: 微信退款单号
*/
@XStreamAlias("refund_id")
private String refund_id;
/**
* 退款金额
* 必填: 是
* 类型: Integer
* 示例值: 100
* 描述: 退款总金额,单位为分,可以做部分退款
*/
@XStreamAlias("refund_fee")
private Integer refund_fee;
/**
* 应结退款金额
* 必填: 否
* 类型: Integer
* 示例值: 100
* 描述: 去掉非充值代金券退款金额后的退款金额,退款金额=申请退款金额-非充值代金券退款金额,退款金额<=申请退款金额
*/
@XStreamAlias("settlement_refund_fee")
private Integer settlement_refund_fee;
/**
* 标价金额
* 必填: 是
* 类型: Integer
* 示例值: 100
* 描述: 订单总金额,单位为分,只能为整数
*/
@XStreamAlias("total_fee")
private Integer total_fee;
/**
* 应结订单金额
* 必填: 否
* 类型: Integer
* 示例值: 100
* 描述: 去掉非充值代金券金额后的订单总金额,应结订单金额=订单金额-非充值代金券金额,应结订单金额<=订单金额。
*/
@XStreamAlias("settlement_total_fee")
private Integer settlement_total_fee;
/**
* 标价币种
* 必填: 否
* 类型: String(8)
* 示例值: CNY
* 描述: 订单金额货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY
*/
@XStreamAlias("fee_type")
private String fee_type;
/**
* 现金支付金额
* 必填: 是
* 类型: Integer
* 示例值: 100
* 描述: 现金支付金额,单位为分,只能为整数
*/
@XStreamAlias("cash_fee")
private Integer cash_fee;
/**
* 现金支付币种
* 必填: 否
* 类型: String(16)
* 示例值: CNY
* 描述: 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY
*/
@XStreamAlias("cash_fee_type")
private Integer cash_fee_type;
/**
* 现金退款金额
* 必填: 否
* 类型: Integer
* 示例值: 100
* 描述: 现金退款金额,单位为分,只能为整数
*/
@XStreamAlias("cash_refund_fee")
private Integer cash_refund_fee;
/**
* 代金券类型
* 必填: 否
* 类型: String(8)
* 示例值: CASH
* 描述: CASH--充值代金券
* NO_CASH---非充值优惠券
* <p>
* 开通免充值券功能,并且订单使用了优惠券后有返回(取值:CASH、NO_CASH)。$n为下标,从0开始编号,举例:coupon_type_$0
*/
@XStreamAlias("coupon_type_$n")
private String coupon_type_$n;
/**
* 代金券退款总金额
* 必填: 否
* 类型: Integer
* 示例值: 100
* 描述: 代金券退款金额<=退款金额,退款金额-代金券或立减优惠退款金额为现金
*/
@XStreamAlias("coupon_refund_fee")
private Integer coupon_refund_fee;
/**
* 单个代金券退款金额
* 必填: 否
* 类型: Integer
* 示例值: 100
* 描述: 代金券退款金额<=退款金额,退款金额-代金券或立减优惠退款金额为现金
*/
@XStreamAlias("coupon_refund_fee_$n")
private Integer coupon_refund_fee_$n;
/**
* 退款代金券使用数量
* 必填: 否
* 类型: Integer
* 示例值: 100
* 描述: 退款代金券使用数量
*/
@XStreamAlias("coupon_refund_count")
private Integer coupon_refund_count;
/**
* 退款代金券ID
* 必填: 否
* 类型: String(20)
* 示例值: 10000
* 描述: 退款代金券ID, $n为下标,从0开始编号
*/
@XStreamAlias("coupon_refund_id_$n")
private Integer coupon_refund_id_$n;
public String getTransaction_id() {
return transaction_id;
}
public void setTransaction_id(String transaction_id) {
this.transaction_id = transaction_id;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getOut_refund_no() {
return out_refund_no;
}
public void setOut_refund_no(String out_refund_no) {
this.out_refund_no = out_refund_no;
}
public String getRefund_id() {
return refund_id;
}
public void setRefund_id(String refund_id) {
this.refund_id = refund_id;
}
public Integer getRefund_fee() {
return refund_fee;
}
public void setRefund_fee(Integer refund_fee) {
this.refund_fee = refund_fee;
}
public Integer getSettlement_refund_fee() {
return settlement_refund_fee;
}
public void setSettlement_refund_fee(Integer settlement_refund_fee) {
this.settlement_refund_fee = settlement_refund_fee;
}
public Integer getTotal_fee() {
return total_fee;
}
public void setTotal_fee(Integer total_fee) {
this.total_fee = total_fee;
}
public Integer getSettlement_total_fee() {
return settlement_total_fee;
}
public void setSettlement_total_fee(Integer settlement_total_fee) {
this.settlement_total_fee = settlement_total_fee;
}
public String getFee_type() {
return fee_type;
}
public void setFee_type(String fee_type) {
this.fee_type = fee_type;
}
public Integer getCash_fee() {
return cash_fee;
}
public void setCash_fee(Integer cash_fee) {
this.cash_fee = cash_fee;
}
public Integer getCash_fee_type() {
return cash_fee_type;
}
public void setCash_fee_type(Integer cash_fee_type) {
this.cash_fee_type = cash_fee_type;
}
public Integer getCash_refund_fee() {
return cash_refund_fee;
}
public void setCash_refund_fee(Integer cash_refund_fee) {
this.cash_refund_fee = cash_refund_fee;
}
public String getCoupon_type_$n() {
return coupon_type_$n;
}
public void setCoupon_type_$n(String coupon_type_$n) {
this.coupon_type_$n = coupon_type_$n;
}
public Integer getCoupon_refund_fee() {
return coupon_refund_fee;
}
public void setCoupon_refund_fee(Integer coupon_refund_fee) {
this.coupon_refund_fee = coupon_refund_fee;
}
public Integer getCoupon_refund_fee_$n() {
return coupon_refund_fee_$n;
}
public void setCoupon_refund_fee_$n(Integer coupon_refund_fee_$n) {
this.coupon_refund_fee_$n = coupon_refund_fee_$n;
}
public Integer getCoupon_refund_count() {
return coupon_refund_count;
}
public void setCoupon_refund_count(Integer coupon_refund_count) {
this.coupon_refund_count = coupon_refund_count;
}
public Integer getCoupon_refund_id_$n() {
return coupon_refund_id_$n;
}
public void setCoupon_refund_id_$n(Integer coupon_refund_id_$n) {
this.coupon_refund_id_$n = coupon_refund_id_$n;
}
@Override
public boolean isSuccess() {
if (StringUtils.equalsIgnoreCase("SUCCESS", this.getReturn_code())
&& StringUtils.equalsIgnoreCase("SUCCESS", this.getResult_code())) {
return true;
}
return false;
}
}
|
[
"[email protected]"
] | |
703d8747267fe150de44eb74c5d80dfa5b3fc979
|
739a0299d3bd311c183d4d3e0943c122b799e5fe
|
/LogowanieP1/app/src/main/java/com/example/logowaniep1/ConnectionManager.java
|
52a58b155e3e8f317e1e93a54ac1e717f2e4825b
|
[] |
no_license
|
Neetreneza/Engineering-thesis
|
21b42f5fa828aaf8dca17f4e0cfd0181b57cc4fc
|
106414485d2b4afd5ac7fbf9edab081e270ebe1d
|
refs/heads/main
| 2023-07-23T07:13:49.477926 | 2020-11-26T14:20:43 | 2020-11-26T14:20:43 | 306,634,709 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,723 |
java
|
package com.example.logowaniep1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ConnectionManager {
private static String url = "jdbc:mysql://192.168.1.100:3306/aplikacja";
private static String driverName = "com.mysql.jdbc.Driver";
private static String username = "andro";
private static String password = "andro";
private static Connection con;
private static String urlstring;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
System.out.println(ex);
}
} catch (ClassNotFoundException e) {
System.out.println("Błąd\n");
System.out.println(e);
}
return con;
}
// public List<String> list() throws SQLException {
// List<String> bilers = new ArrayList<String>();
//
// try (
// Connection connection = database.getConnection();
// PreparedStatement statement = connection.prepareStatement("SELECT id, name, value FROM Biler");
// ResultSet resultSet = statement.executeQuery();
// ) {
// while (resultSet.next()) {
// Biler biler = new Biler();
// biler.setId(resultSet.getLong("id"));
// biler.setName(resultSet.getString("name"));
// biler.setValue(resultSet.getInt("value"));
// bilers.add(biler);
// }
// }
//
// return bilers;
// }
}
|
[
"[email protected]"
] | |
da5f1fbd644a50d55b341411b33ea01a37800a9a
|
ef05ed8cea82254c2ae50b25ba0a8c9f2cc46e61
|
/PLJava/MatrixMultiplication/src/MatrixMultiplication.java
|
6b1e7cdee7137dbcea8877da9a2cce66b215d46e
|
[] |
no_license
|
tvdeshpa/PL_Project
|
6b4f0eb0e4076e9132083275e691c55e57c4c5da
|
99398873d799f6045a9b2de5671620ab6da36566
|
refs/heads/master
| 2021-08-28T00:46:08.939546 | 2017-12-10T22:53:15 | 2017-12-10T22:53:15 | 108,889,217 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,765 |
java
|
import java.util.Random;
public class MatrixMultiplication implements Runnable {
private static final int MAX_VALUE = 200;
static int i=0,j=0,k=0;
int row , col;
int array1[][];
int array2[][];
MatrixMultiplication(int[][] a, int[][] b, int row, int col){
this.array1 = a;
this.array2 = b;
this.row = row;
this.col = col;
}
public void run(){
//Creating the instance of the MatrixMultiplication server to call the methods.
matrixMultiply(this.array1, this.array2, row, col);
//Calling the matrix multiplication method.
}
public static void main(String[] args) {
int row = 1000, col =1000;
int[][] array1 = new int[1000][1000];
int[][] array2 = new int[1000][1000];
Random rand = new Random();
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
array1[i][j] = rand.nextInt() % MAX_VALUE;
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
array2[i][j] = rand.nextInt() % MAX_VALUE;
}
}
/* Sequential */
long startTime3 = System.currentTimeMillis();
matrixMultiply(array1, array2, row, col);
matrixMultiply(array1, array2, row, col);
matrixMultiply(array1, array2, row, col);
long endTime3= System.currentTimeMillis();
long duration = endTime3 - startTime3;
System.out.println("Time taken for Sequential : " + duration);
/* Concurrent */
long startTime2= System.currentTimeMillis();
MatrixMultiplication ms=new MatrixMultiplication(array1, array2, row, col);
Thread myThread1=new Thread(ms);
Thread myThread2=new Thread(ms);
Thread myThread3=new Thread(ms);
myThread1.setName("First Thread");
myThread2.setName("Second Thread");
myThread3.setName("Third Thread");
myThread1.start();
myThread2.start();
myThread3.start();
while (myThread1.isAlive() || myThread2.isAlive() || myThread3.isAlive()) {
//wait for all threads to finish
}
long endTime2= System.currentTimeMillis();
long duration2 = endTime2 - startTime2;
System.out.println("Time taken for parallel computation : " + duration2);
}
//matrix initialization which will call the recursive function. Complexity of the algorithm is O(n^3)
public static void matrixMultiply(int[][] array1, int[][] array2, int row, int col){
try{
int[][] rslt = new int[row][col];
for(int x = 0; x < row*col; x++ ){
int i = x / row;
int k = x % row;
int j = 0;
while(j < row) {
rslt[i][j] += array1[i][k] * array2[k][j];
j++;
}
}
//i=0;
//Call for recursive method.
//matrixMultiplicaitonRec(row, col, array1, array2, rslt);
}catch(Exception e){
System.out.println("Error in executing matrix multiplication:"+e.getMessage());
}
}
//
public static void matrixMultiplicaitonRec(int row,int col,int ary1[][],
int ary2[][],int result[][]){
try{
for (int i=0; i<row; i++){
for (int j=0; j<col; j++){
for (int k=0; k<row; k++){
result[i][j] += ary1[i][k] * ary2[k][j];
}
}
}
}catch(Exception e){
System.out.println("Error in::MethodName::matrixMultiplication()::"+e.getMessage());
}
}
}
|
[
"[email protected]"
] | |
194b0d882ace384d62b2e2037091d61e889fd4ac
|
bc5cc3828281f2ee7df902c73940d11b21d16d7c
|
/quickquestions/src/main/java/com/quick/questions/ws/io/repositories/UserPaymentRepository.java
|
aa741311660c41ccbcf3f9e403cd5864565646e5
|
[] |
no_license
|
rajeshbattula631/quicktest
|
a8a77255e9dd8bb47b4335eadebfd86a6fdf73f9
|
ff150adefa77e37a3a32e650cb0098562b06ebba
|
refs/heads/master
| 2020-06-03T14:46:13.868496 | 2019-09-03T09:22:39 | 2019-09-03T09:22:39 | 191,611,388 | 0 | 2 | null | null | null | null |
UTF-8
|
Java
| false | false | 407 |
java
|
package com.quick.questions.ws.io.repositories;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.quick.questions.ws.io.entity.UserPaymentEntity;
@Repository
public interface UserPaymentRepository extends CrudRepository<UserPaymentEntity, Long> {
List<UserPaymentEntity> findUserPaymentsByUserId(Long id);
}
|
[
"[email protected]"
] | |
f7f60ac500f2d5961cd50c6d278d1705ae43a2ba
|
9bcbebe359d320c7128cee3c3998d428ffb82dd6
|
/hopon/src/com/hopon/action/UserAction.java
|
075590e7564bf79387ff4cbe6d4ea931422d20fd
|
[] |
no_license
|
NagarajNayak/hoponwebsite
|
14fef088bc91c9c361d460b576fa759f912689e8
|
3ffc27f2d81b9c548c7e12a706136b20042f3a83
|
refs/heads/master
| 2016-09-05T13:18:00.649787 | 2014-09-22T18:28:03 | 2014-09-22T18:28:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 314,861 |
java
|
package com.hopon.action;
/**
* @author Kumar yogesh
* this class is used as a action class for jsf
* communicate with xhtml pages
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Connection;
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.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.json.JSONException;
import org.primefaces.model.UploadedFile;
import com.hopon.dto.ApproverDTO;
import com.hopon.dto.CircleAffiliationsDTO;
import com.hopon.dto.CircleDTO;
import com.hopon.dto.CircleMemberDTO;
import com.hopon.dto.CircleOwnerDTO;
import com.hopon.dto.CircleOwnerManagerDTO;
import com.hopon.dto.CityDTO;
import com.hopon.dto.CombineVehicleDataModel;
import com.hopon.dto.CompanyRegisterDTO;
import com.hopon.dto.ContactusDTO;
import com.hopon.dto.EmailDTO;
import com.hopon.dto.FavoritePlacesDTO;
import com.hopon.dto.FrequencyDTO;
import com.hopon.dto.HoponAccountDTO;
import com.hopon.dto.LoginPageDTO;
import com.hopon.dto.MatchedTripDTO;
import com.hopon.dto.MatchedTripDataModel;
import com.hopon.dto.MessageBoardDTO;
import com.hopon.dto.PageStoreDTO;
import com.hopon.dto.PaymentDTO;
import com.hopon.dto.PaymentTxnsDTO;
import com.hopon.dto.PoolRequestsDTO;
import com.hopon.dto.RideManagementDTO;
import com.hopon.dto.RideSeekerDTO;
import com.hopon.dto.SmsReplyDTO;
import com.hopon.dto.UserPreferencesDTO;
import com.hopon.dto.UserRegistrationDTO;
import com.hopon.dto.VehicleMasterDTO;
import com.hopon.dto.VehicleMasterDataTable;
import com.hopon.utils.ApplicationUtil;
import com.hopon.utils.ConfigurationException;
import com.hopon.utils.ControllerException;
import com.hopon.utils.ListOfValuesManager;
import com.hopon.utils.LoggerSingleton;
import com.hopon.utils.MailService;
import com.hopon.utils.Messages;
import com.hopon.utils.ServerUtility;
import com.hopon.utils.SmsService;
import com.hopon.utils.Validator;
public class UserAction extends HPBaseAction {
private List<SelectItem> allCompany;
private List<SelectItem> companySector;
private List<SelectItem> allCircleOption;
public List<SelectItem> getCompanyOptions() {
allCompany = ListOfValuesManager.getCompanyOptions(allCompany);
return allCompany;
}
public List<SelectItem> getCompanySectorOptions() {
companySector = ListOfValuesManager
.getCompanySectorOption(companySector);
return companySector;
}
public List<SelectItem> getCircleOption() {
allCircleOption = ListOfValuesManager
.getAllCircleListOptions(allCircleOption);
return allCircleOption;
}
public List<String> cityAutoCompleateMethod(String finalValue) {
List<String> cityValue = new ArrayList<String>();
List<CityDTO> cityList = new ArrayList<CityDTO>();
String city;
cityList = ListOfValuesManager.getCityList(finalValue);
for (int i = 0; i < cityList.size(); i++) {
city = cityList.get(i).getCityName();
cityValue.add(city);
}
return cityValue;
}
public List<String> userAutoCompleateMethod(String prefix) {
List<String> userValue = new ArrayList<String>();
List<UserRegistrationDTO> userList = new ArrayList<UserRegistrationDTO>();
String user;
userList = ListOfValuesManager.getAllUserList(prefix, 5);
for (int i = 0; i < userList.size(); i++) {
user = userList.get(i).getFirst_name() + "-"
+ userList.get(i).getAddress() + ","
+ userList.get(i).getId();
userValue.add(user);
}
return userValue;
}
public List<CircleDTO> userAutoTaxiCircle(String prefix) {
List<CircleDTO> circle = new ArrayList<CircleDTO>();
List<CircleDTO> circleTemp = new ArrayList<CircleDTO>();
// if(taxiCircle.getCircleID() > 0) {
gatherDefaultcircleDTO();
circle = ListOfValuesManager.getAllAffiliatedTaxiCircle(prefix);
List<Integer> tempCircleId = new ArrayList<Integer>();
for (CircleAffiliationsDTO dto : allCircleAffiliationsDTO) {
tempCircleId.add(dto.getAffilicatedCircleId());
}
for (CircleAffiliationsDTO dto : allPendingCircleAffiliationsDTO) {
tempCircleId.add(dto.getAffilicatedCircleId());
}
for (int i = 0; i < circle.size(); i++) {
if (!tempCircleId.contains(circle.get(i).getCircleID())) {
circleTemp.add(circle.get(i));
}
}
circle.clear();
circle.addAll(circleTemp);
// }
return circle;
}
public List<CircleDTO> autoTaxiCircle(String prefix) {
List<CircleDTO> circle = new ArrayList<CircleDTO>();
Iterator<CircleDTO> circleTemp = ListOfValuesManager
.getallRegisteredTaxiCircleListed(prefix).iterator();
while (circleTemp.hasNext()) {
CircleDTO dto = (CircleDTO) circleTemp.next();
if (dto.getName() != null) {
circle.add(dto);
}
}
return circle;
}
public List<CircleDTO> autoNonTaxiCircle(String prefix) {
List<CircleDTO> circle = new ArrayList<CircleDTO>();
Iterator<CircleDTO> circleTemp = ListOfValuesManager
.getallRegisteredNonTaxiCircleListed(prefix).iterator();
while (circleTemp.hasNext()) {
CircleDTO dto = (CircleDTO) circleTemp.next();
if (dto.getName() != null) {
circle.add(dto);
}
}
return circle;
}
public List<String> autoTaxiCircleStr(String prefix) {
List<String> circle = new ArrayList<String>();
Iterator<CircleDTO> circleTemp = ListOfValuesManager
.getallRegisteredTaxiCircleListed(prefix).iterator();
while (circleTemp.hasNext()) {
CircleDTO dto = (CircleDTO) circleTemp.next();
if (dto.getName() != null) {
circle.add(dto.getName() + " - " + dto.getCircleID());
}
}
return circle;
}
public List<String> autoNonTaxiCircleStr(String prefix) {
List<String> circle = new ArrayList<String>();
Iterator<CircleDTO> circleTemp = ListOfValuesManager
.getallRegisteredNonTaxiCircleListed(prefix).iterator();
while (circleTemp.hasNext()) {
CircleDTO dto = (CircleDTO) circleTemp.next();
if (dto.getName() != null) {
circle.add(dto.getName() + " - " + dto.getCircleID());
}
}
return circle;
}
public void gatherAffiliatedCircle(int circleId) {
allCircleAffiliationsDTO.clear();
allPendingCircleAffiliationsDTO.clear();
allCircleAffiliationsDTO = ListOfValuesManager
.getAllAffiliatedCircle("" + circleId);
allPendingCircleAffiliationsDTO = ListOfValuesManager
.getAllPendingCircle("" + circleId);
}
public void makeCircleAffiliated() {
int parentCircleId = taxiCircle.getCircleID();
// FacesContext context = FacesContext.getCurrentInstance();
// Map<String,String> requestMap =
// context.getExternalContext().getRequestParameterMap(); //In java
// class, you can get back the parameter value with component
// (submit-command buton) like this :
int childCircleId = affiliateCircleId;
gatherAffiliatedCircle(parentCircleId);
clearScreenMessage();
if (parentCircleId <= 0) {
errorMessage.add("Please select a Circle first.");
} else if (childCircleId <= 0) {
errorMessage.add("Please select affiliated Taxi circle.");
} else {
ListOfValuesManager.makeTaxiCircleAffiliated(parentCircleId,
childCircleId);
successMessage.add(Messages.getValue("success.taxi.affiliation"));
}
gatherDefaultcircleDTO();
}
public String registerUser() {
clearScreenMessage();
forregistrationOnly.setMobile_no(forregistrationOnly.getMobile_no()
.replaceFirst("^[0|+]*", ""));
if (Validator.isNotNumber(forregistrationOnly.getMobile_no())
|| forregistrationOnly.getMobile_no().length() != 10) {
errorMessage.add("Mobile Number is not proper.");
}
if (ListOfValuesManager.testUniqueMobileNumber(forregistrationOnly
.getMobile_no())) {
errorMessage
.add("Mobile Number is alrady registered. Please enter another mobile number.");
}
String emailTest = ListOfValuesManager
.testEmailAllStatus(forregistrationOnly.getEmail_id());
if (emailTest.equalsIgnoreCase("P")) {
errorMessage.add("Email ID is pending for approval.");
forregistrationOnly = new UserRegistrationDTO();
return "clear";
} else if (emailTest.equalsIgnoreCase("I")) {
errorMessage.add("Email ID de activated. Please contact admin.");
forregistrationOnly = new UserRegistrationDTO();
return "clear";
} else if (emailTest.equalsIgnoreCase("A")) {
errorMessage.add("Email ID already registered.");
forregistrationOnly = new UserRegistrationDTO();
return "clear";
} else if (emailTest.equalsIgnoreCase("N") && errorMessage.size() == 0) {
Connection con = (Connection) ListOfValuesManager
.getBroadConnection();
try {
forregistrationOnly.setIsVerified('0');
forregistrationOnly.setVerificationCode(ServerUtility
.randomString(15));
forregistrationOnly.setStatus("P");
forregistrationOnly.setSignupType(3);
forregistrationOnly.setTotalCredit(50);
forregistrationOnly.setTotalGreenMiles(0);
CityDTO cityDto = ListOfValuesManager.getCity(
forregistrationOnly.getCity(),
forregistrationOnly.getState());
forregistrationOnly.setCityId(cityDto.getCityId());
forregistrationOnly = ListOfValuesManager.getUserRegistration(
"findByDTO", forregistrationOnly,
forregistrationOnly.getEmail_id(), con);
userPreferences = new UserPreferencesDTO();
userPreferences.setUserId(Integer.parseInt(forregistrationOnly
.getId()));
if (forregistrationOnly.getDefaultTimeSlice() != null) {
String[] minuteSlice = forregistrationOnly
.getDefaultTimeSlice().split(":");
if (minuteSlice.length > 1) {
int minuteCount = Integer.parseInt(minuteSlice[0]) * 60; // convert
// hour
// to
// minute
minuteCount += Integer.parseInt(minuteSlice[1]);
userPreferences.setMaxWaitTime(minuteCount);
}
} else {
userPreferences.setMaxWaitTime(10);
}
userPreferences = ListOfValuesManager.getUserPreferencesSave(
userPreferences, con);
/*
* String parts1[] = autoNonTaxiCircleValue.trim().split("-");
* String parts2[] = autoTaxiCircleValue.trim().split("-");
*
* try{ autoNonTaxiCircleValue = parts1[parts1.length - 1];
* autoTaxiCircleValue = parts2[parts2.length - 1]; } catch
* (ArrayIndexOutOfBoundsException e) {
*
* }
*/
autoNonTaxiCircleValue = autoNonTaxiCircleValue.trim();
autoTaxiCircleValue = autoTaxiCircleValue.trim();
if (forregistrationOnly.getTravel().equalsIgnoreCase("T")
&& Validator.isNumberZeroNotAlloed(autoTaxiCircleValue)) {
userRegisterCircle = Integer.parseInt(autoTaxiCircleValue);
} else if (!forregistrationOnly.getTravel().equalsIgnoreCase(
"T")
&& Validator
.isNumberZeroNotAlloed(autoNonTaxiCircleValue)) {
userRegisterCircle = Integer
.parseInt(autoNonTaxiCircleValue);
}
if (userRegisterCircle > 0) {
circleMemberDTO.setCircleid(String
.valueOf(userRegisterCircle));
circleMemberDTO.setUserid(forregistrationOnly.getId());
circleMemberDTO.setRequestUserId(forregistrationOnly
.getId());
circleMemberDTO = ListOfValuesManager.getJoinCircle(
circleMemberDTO, forregistrationOnly.getId(), con);
circleMemberDTO = new CircleMemberDTO();
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
forregistrationOnly.setStatus("Fault");
rollbackTest = false;
userMessageDTO = new MessageBoardDTO();
errorMessage
.add("There is some problem in registration of Email ID.");
return null;
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
successMessage
.add("Email ID registered successfully. You will get verification email on registered email ID. Please verify your account.");
}
autoTaxiCircleValue = null;
autoNonTaxiCircleValue = null;
userRegisterCircle = 0;
}
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages
.getValue("subject.register"));
userMessageDTO
.setMessage(Messages.getValue("user.register.intro",
new Object[] { forregistrationOnly.getFirst_name(),
forregistrationOnly.getPassword(),
forregistrationOnly.getEmail_id() })
+ Messages
.getValue(
"user.register.verify",
new Object[] { Messages
.getValue(
"link.user.verify",
new Object[] {
forregistrationOnly
.getEmail_id(),
URLEncoder
.encode(forregistrationOnly
.getVerificationCode()) }) })
+ " " + Messages.getValue("site.login"));
userMessageDTO.setToMember(Integer.parseInt(forregistrationOnly
.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue("sms.register",
new Object[] { forregistrationOnly.getFirst_name(),
forregistrationOnly.getEmail_id() }));
userMessageDTO.setToMember(Integer.parseInt(forregistrationOnly
.getId()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
rollbackTest = false;
userMessageDTO = new MessageBoardDTO();
// userRegistrationDTO = forregistrationOnly;
forregistrationOnly = new UserRegistrationDTO();
}
// Uncomment when you want direct login.
// validateUser();
// return "userRegister";
return "userPending";
}
public void sendMessage() {
String[] part = circleAffiliationsDTO.getCircleAffilicatedCircleId()
.split("-");
int affiliatedCircleId = 0;
clearScreenMessage();
if (part.length > 1 && part[1] != null && Integer.parseInt(part[1]) > 0) {
affiliatedCircleId = Integer.parseInt(part[1]);
CircleDTO dto = new CircleDTO();
dto = ListOfValuesManager
.getCircleDtoByCircleId(affiliatedCircleId);
// userMessageDTO.setReceiveUserId(""+dto.getCircleOwner_Member_Id_P());
// userMessageDTO.setSentUserId(userRegistrationDTO.getId());
// userMessageDTO.setEmailSent('N');
// userMessageDTO.setSubject(Messages.getValue("taxi.circle.subject"));
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setToMember(dto.getCircleOwner_Member_Id_P());
userMessageDTO.setCreatedBy(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setSubmittedBy(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setEmailSubject(Messages
.getValue("taxi.circle.subject"));
userMessageDTO.setMessageChannel("E");
userMessageDTO.setMessage(getMessage());
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
setMessage("");
successMessage
.add("Message sent successfully to the circle members.");
} else {
errorMessage
.add("Please select a Circle and then affiliated taxi circle.");
}
}
public void companyRegister() {
clearScreenMessage();
try {
if (listofCompanyForLoginUser.size() == 0) {
companyRegisterDTO.setUserID(userRegistrationDTO.getId());
companyRegisterDTO = ListOfValuesManager
.getCompanyRegistration("findByDTO",
companyRegisterDTO, null);
successMessage.add("Company added successfully.");
} else {
companyRegisterDTO.setUserID(userRegistrationDTO.getId());
companyRegisterDTO = ListOfValuesManager
.getCompanyUpdateByUserId(companyRegisterDTO);
successMessage.add("Company updated successfully.");
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
}
if (rollbackTest) {
errorMessage.add("There is some issue in add/update of company.");
}
rollbackTest = false;
findListofCompanyForLoginUser();
// companyRegisterDTO = new CompanyRegisterDTO();
}
public String registerCompany() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
try {
companyRegisterDTO.setUserID(userRegistrationDTO.getId());
companyRegisterDTO = ListOfValuesManager.getCompanyRegistration(
"findByDTO", companyRegisterDTO, con);
List<CircleDTO> circleList;
circleList = ListOfValuesManager.getallRegisteredCircleListed();
CircleOwnerDTO circleOwnerDTO = new CircleOwnerDTO();
int check = 0;
for (int i = 0; i < circleList.size(); i++) {
if (circleList.get(i).getName()
.equalsIgnoreCase(companyRegisterDTO.getCompanyName())) {
check = 1;
CircleDTO circleDTO = new CircleDTO();
circleDTO.setCompanyID(companyRegisterDTO.getCompanyID());
circleDTO.setCircleOwner_Member_Id_P(Integer
.valueOf(userRegistrationDTO.getId()));
circleDTO.setName("circle_"
+ companyRegisterDTO.getCompanyName());
circleDTO = ListOfValuesManager.getregisterCircle(
circleDTO, con);
circleOwnerDTO.setCircleID(String.valueOf(circleDTO
.getCircleID()));
circleOwnerDTO.setUserID(userRegistrationDTO.getId());
circleOwnerDTO = ListOfValuesManager
.getregisterCircleOwner(circleOwnerDTO,
userRegistrationDTO.getId(), con);
}
}
if (check == 0) {
CircleDTO circleDTO = new CircleDTO();
circleDTO.setCompanyID(companyRegisterDTO.getCompanyID());
circleDTO.setCircleOwner_Member_Id_P(Integer
.valueOf(userRegistrationDTO.getId()));
circleDTO.setDate_of_creation(ListOfValuesManager
.getcurrentDate());
circleDTO.setName(companyRegisterDTO.getCompanyName());
circleDTO = ListOfValuesManager.getregisterCircle(circleDTO,
con);
circleOwnerDTO.setCircleID(String.valueOf(circleDTO
.getCircleID()));
circleOwnerDTO.setUserID(userRegistrationDTO.getId());
circleOwnerDTO = ListOfValuesManager.getregisterCircleOwner(
circleOwnerDTO, userRegistrationDTO.getId(), con);
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
findListofCompanyForLoginUser();
// companyRegisterDTO = new CompanyRegisterDTO();
// userRegistrationDTO.setCompanyName(companyRegisterDTO.getCompanyName());
return "registerCompany";
}
public String editCompany() {
String index = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
index = (String) requestMap.get("index");
companyRegisterDTO = listofCompanyForLoginUser.get(Integer
.valueOf(index));
return "editCompany";
}
public void editCompanyValue() {
companyRegisterDTO = ListOfValuesManager
.getUpdateCompany(companyRegisterDTO);
rollbackTest = false;
findListofCompanyForLoginUser();
// companyRegisterDTO = new CompanyRegisterDTO();
// return "editValue";
}
public void userRatingUpdate() {
userRegistrationDTO = ListOfValuesManager
.getAverageRatingForUser(userRegistrationDTO);
}
public String validateUser() {
userRegistrationDTO = ListOfValuesManager
.getValidateUser(userRegistrationDTO);
if (userRegistrationDTO.getId() != null)
userPreferences = ListOfValuesManager.getUserPreferences(Integer
.parseInt(userRegistrationDTO.getId()));
clearScreenMessage();
if (userRegistrationDTO.getEmail_id() == null
&& userRegistrationDTO.getPassword() == null) {
errorMessage.add(Messages.getValue("error.login.invalid"));
// com.hopon.utils.ErrorMessages.getErrorMessage(ValidationManager.getBundle().getString("error.login.invalid"));
userRegistrationDTO.setPassword("");
return null;
}
if (userRegistrationDTO.getStatus() != null
&& userRegistrationDTO.getStatus().equals("I")) {
errorMessage.add(Messages
.getValue("error.login.accountStatusClosed"));
userRegistrationDTO.setPassword("");
return null;
}
if (userRegistrationDTO.getStatus() != null
&& userRegistrationDTO.getStatus().equals("P")) {
errorMessage.add(Messages
.getValue("error.login.accountStatusPending"));
userRegistrationDTO.setPassword("");
return null;
}
/*
* Here is code for non verified account.
* if(userRegistrationDTO.getStatus() != null &&
* userRegistrationDTO.getStatus().equals("2")) {
* errorMessage.add(Messages
* .getValue("error.login.accountStatusPending")); return null; }
*/
if (userRegistrationDTO.getTravel().equalsIgnoreCase("T")) {
giveRide();
}
HttpSession currentSession = ServerUtility.getSession();
// set session attribute e.g "LoggedIn='true' " if user is logged in
currentSession.setAttribute("LoggedIn", "true");
currentSession.setAttribute("user_role",
userRegistrationDTO.getTravel());
currentSession.setAttribute("userId", userRegistrationDTO.getId());
currentSession.setAttribute("userName",
userRegistrationDTO.getFirst_name());
currentSession.setAttribute("emailId",
userRegistrationDTO.getEmail_id());
allListedCircle();
rideManagementList();
allCompleateRideList();
allCircleForLoginUser();
allCircleMemberForLoginUserList.clear();
allPendingCircleMemberList.clear();
messageForLoginUser();
vehicleList();
findListofCompanyForLoginUser();
currentSession.setAttribute("unreadMessageRowNo", 1);
allLoginUserMessageList();
populatePopupMessage();
populateApprover();
vehicleMasterDTO = new VehicleMasterDTO();
/* Here write down the code url redirection for post-Login page. */
List<LoginPageDTO> dtos = new ArrayList<LoginPageDTO>();
dtos.addAll(ListOfValuesManager.getLoginPagesByUserId(Integer
.parseInt(userRegistrationDTO.getId())));
for (LoginPageDTO dto : dtos) {
if (dto.getPageCode().equalsIgnoreCase(
Messages.getValue("page.code.change.password").trim())) {
return Messages.getValue("page.code.change.password").trim();
}
}
for (LoginPageDTO dto : dtos) {
if (dto.getPageCode().equalsIgnoreCase(
Messages.getValue("page.code.preference").trim())) {
return Messages.getValue("page.code.preference").trim();
}
}
validateUserPayment();
paymentTransaction();
populatePaymentPlan();
return userRegistrationDTO.getTravel();
}
public void populatePaymentPlan() {
userPaymentPlanList.clear();
userPaymentPlanList.addAll(ListOfValuesManager
.fetchPaymentPlanForLoginUser(userRegistrationDTO.getId()));
}
public String signOut() {
userRegistrationDTO = new UserRegistrationDTO();
HttpSession currentSession = ServerUtility.getSession();
currentSession.setAttribute("LoggedIn", null);
currentSession.setAttribute("user_role", null);
currentSession.setAttribute("readMessageRowNo", null);
currentSession.setAttribute("unreadMessageRowNo", null);
listofCompanyForLoginUser.clear();
allCircleListByName.clear();
findListofCompanyForLoginUser();
currentSession.invalidate();
return "signOut";
}
public String userAcountClose() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
try {
userRegistrationDTO = ListOfValuesManager.getCloseUserAcount(
userRegistrationDTO, userRegistrationDTO.getId(), con);
// circle table make circle inactive created by user.
ListOfValuesManager.makeCircleInactiveForUser(userRegistrationDTO,
con);
// circle_members table make status Inactive for user.
ListOfValuesManager.makeCircleMemberInactiveForUser(
userRegistrationDTO, userRegistrationDTO.getId(), con);
// circle_owner make status 2 for user.
ListOfValuesManager.makeCircleOwnerForUser(userRegistrationDTO,
userRegistrationDTO.getId(), con);
// make "ride_seeker_details" table status 2 for user_id.
ListOfValuesManager.makeRideSeekerCancelForUser(
userRegistrationDTO, con);
// need discussion In ride_management table.
ListOfValuesManager.makeRideCancelForUser(userRegistrationDTO, con);
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
signOut();
return "close";
}
public String rideManagementList() {
rideManagementList = ListOfValuesManager
.getRideManagementList(userRegistrationDTO.getId());
List<RideManagementDTO> listNew = new ArrayList<RideManagementDTO>();
for (RideManagementDTO dto : rideManagementList) {
if (!dto.getStatus().equalsIgnoreCase("T")
&& userRegistrationDTO.getTravel().equalsIgnoreCase("T")) {
continue;
}
if (!dto.getStatus().equalsIgnoreCase("A")
&& userRegistrationDTO.getTravel().equalsIgnoreCase("P")) {
continue;
}
if (!dto.getStatus().equalsIgnoreCase("A")
&& userRegistrationDTO.getTravel().equalsIgnoreCase("B")) {
continue;
}
listNew.add(dto);
}
rideManagementList.clear();
rideManagementList.addAll(listNew);
listNew.clear();
rideSeekerList = ListOfValuesManager
.getAllRideSeekerList(userRegistrationDTO.getId());
List<RideSeekerDTO> temp1 = new ArrayList<RideSeekerDTO>();
recurringRideSeekerList.clear();
for (RideSeekerDTO dto : rideSeekerList) {
if (dto.getRecurring().equals("Y")) {
recurringRideSeekerList.add(dto);
} else {
temp1.add(dto);
}
}
rideSeekerList.clear();
rideSeekerList.addAll(temp1);
pendingRideTest = false;
for (RideSeekerDTO dto : rideSeekerList) {
if (dto.getStatus().equals("A") || dto.getStatus().equals("I")) {
pendingRideTest = true;
break;
}
}
Collections.reverse(rideManagementList);
Collections.reverse(rideSeekerList);
return "rideManagementList";
}
public String allListedCircle() {
allCircleList = ListOfValuesManager
.getallCircleListed(userRegistrationDTO.getId());
allMemberCircleList = ListOfValuesManager
.getallMemberCircleListed(userRegistrationDTO.getId());
return "circleList";
}
/*
* public List<String> getAllCompanyList(){ List<String> allCompanyList =
* new ArrayList<String>(); List<CompanyRegisterDTO> allCompany = null; try
* { allCompany = ListOfValuesManager.getCompanyList();
* allCompanyList.add("NEW"); for (int i = 0;i<allCompany.size() ; i++){
* allCompanyList.add(allCompany.get(i).getCompanyName()); }
*
* } catch (ConnectionException e) { // TODO Auto-generated catch block }
* catch (ConfigurationException e) { // TODO Auto-generated catch block }
*
* return allCompanyList;
*
* }
*/
public void fetchCircleList() {
taxiCircleList = new ArrayList<CircleDTO>();
nonTaxiCircleList = new ArrayList<CircleDTO>();
List<CircleDTO> circleList = null;
circleList = ListOfValuesManager.getallRegisteredCircleListed();
for (CircleDTO dto : circleList) {
if (dto.isTaxiCircle()) {
taxiCircleList.add(dto);
} else {
nonTaxiCircleList.add(dto);
}
}
}
public List<SelectItem> getAllTaxiCilcleDropDownList() {
List<SelectItem> list = new ArrayList<SelectItem>();
List<CircleDTO> circleList = new ArrayList<CircleDTO>();
circleList = ListOfValuesManager.getallRegisteredCircleListed();
for (int i = 0; i < circleList.size(); i++) {
if (circleList.get(i).isTaxiCircle())
list.add(new SelectItem(circleList.get(i).getCircleID(),
circleList.get(i).getName()));
}
return list;
}
public List<SelectItem> getAllNonTaxiCilcleDropDownList() {
List<SelectItem> list = new ArrayList<SelectItem>();
List<CircleDTO> circleList = new ArrayList<CircleDTO>();
circleList = ListOfValuesManager.getallRegisteredCircleListed();
for (int i = 0; i < circleList.size(); i++) {
if (!circleList.get(i).isTaxiCircle())
list.add(new SelectItem(circleList.get(i).getCircleID(),
circleList.get(i).getName()));
}
return list;
}
public void registerRide() {
if (userCirclePaymentPending)
return;
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
String ride = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
ride = (String) requestMap.get("ride");
clearScreenMessage();
if (this.recurring && rideRegistered.getEndDate1() == null) {
errorMessage.add("Please select proper end date.");
}
if (rideRegistered.getFromAddress1() == null
|| rideRegistered.getFromAddress1().trim().length() == 0) {
errorMessage.add("Please enter source address.");
}
if (rideRegistered.getFullDay().equalsIgnoreCase("N")
&& (rideRegistered.getToAddress1() == null || rideRegistered
.getToAddress1().trim().length() == 0)) {
errorMessage.add("Please enter destination address.");
}
if (rideManager.equals("giveRide")
&& Integer.parseInt(rideRegistered.getVehicleID()) <= 0) {
errorMessage.add("Please select Vehicle.");
}
if (ride != null) {
rideManager = ride;
}
try {
if (errorMessage.size() > 0)
throw new ControllerException();
rideRegistered.setUserID(userRegistrationDTO.getId());
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern3);
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
try {
rideRegistered.setStartDate(new SimpleDateFormat(
ApplicationUtil.datePattern4).parse(rideRegistered
.getStartDate1()));
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
errorMessage.add("Please select proper start date.");
throw new ControllerException();
}
cal.setTime(rideRegistered.getStartDate());
try {
if (rideRegistered.getEndDate1() != null
&& rideRegistered.getEndDate1().length() > 0) {
rideRegistered.setEndDate(new SimpleDateFormat(
ApplicationUtil.datePattern4).parse(rideRegistered
.getEndDate1()));
}
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
long dateDiff = 0;
if (this.recurring) {
Calendar startDateCalendar = Calendar.getInstance();
startDateCalendar.setTime(rideRegistered.getStartDate());
Calendar endDateCalendar = Calendar.getInstance();
endDateCalendar.setTime(rideRegistered.getEndDate());
dateDiff = (endDateCalendar.getTimeInMillis() - startDateCalendar
.getTimeInMillis()) / (1000 * 60 * 60 * 24);
}
if (this.recurring && dateDiff < 0) {
errorMessage
.add("Please select end date after the start date.");
throw new ControllerException();
}
if (this.recurring && dateDiff > 60) {
errorMessage
.add("Recurring ride can be booked only for 2 months from the start date.");
throw new ControllerException();
}
if (rideRegistered.getEndDate() != null) {
cal1.setTime(rideRegistered.getEndDate());
rideRegistered
.setEnddateValue(dateFormat.format(cal1.getTime()));
}
rideRegistered.setStartdateValue(dateFormat.format(cal.getTime()));
/*
* float startPointLat = rideRegistered.getStartPointLatitude();
* float startPointLng = rideRegistered.getStartPointLongitude();
* float endPointLat = rideRegistered.getEndPointLatitude(); float
* endPointLng = rideRegistered.getEndPointLongitude();
*/
clearScreenMessage();
if (frequencyDTO.getFrequency() == null
|| frequencyDTO.getFrequency().size() == 0) {
List<String> value = new ArrayList<String>();
String putValue = "Once";
value.add(putValue);
frequencyDTO.setFrequency(value);
}
if (rideManager.equals("takeRide")) {
if (ListOfValuesManager
.checkRideSeekerDuplicacy(rideRegistered)) {
errorMessage.add("Same Ride already exist.");
throw new ControllerException();
// return "takeRide";
} else {
rideRegistered.setRideID(null);
rideRegistered.setCreatedBy(userRegistrationDTO.getId());
rideRegistered.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
if (this.recurring)
rideRegistered.setRecurring("Y");
else
rideRegistered.setRecurring("N");
/*
* For full day request make start point and end point same.
*/
if (rideRegistered.getFullDay().equalsIgnoreCase("Y")) {
rideRegistered.setEndPointLatitude(rideRegistered
.getStartPointLatitude());
rideRegistered.setEndPointLongitude(rideRegistered
.getStartPointLongitude());
rideRegistered.setToAddress1(rideRegistered
.getFromAddress1());
rideRegistered.setToAddressCity(rideRegistered
.getFromAddressCity());
rideRegistered.setToAddressPin(rideRegistered
.getFromAddressPin());
rideRegistered.setToAddressTag("");
}
List windowCalculation;
try {
windowCalculation = ApplicationUtil
.calculateTimeWindowSettings(
rideRegistered.getFromAddress1(), "",
rideRegistered.getToAddress1(),
userPreferences.getMaxWaitTime(),
rideRegistered.getStartdateValue());
if (windowCalculation.size() > 0) {
rideRegistered.setStartdateValue(windowCalculation
.get(1).toString());
rideRegistered.setStartDateEarly(windowCalculation
.get(1).toString());
rideRegistered.setStartDateLate(windowCalculation
.get(2).toString());
rideRegistered.setEndDateEarly(windowCalculation
.get(3).toString());
rideRegistered.setEndDateLate(windowCalculation
.get(4).toString());
float distance = Integer.parseInt(windowCalculation
.get(5).toString()) / 1000;
rideRegistered.setRideDistance(distance);
if(rideRegistered.isSharedTaxi()==true){
System.out.println("printing five rupees :"+ distance);
rideRegistered.setRideCost(distance
* Float.parseFloat(Messages.getValue(
"ride.perkm.charge").trim()) + "");
System.out.println("this is for 5rupee: "+ Messages.getValue(
"ride.perkm.charge"));
}else{
rideRegistered.setRideCost(distance
* Float.parseFloat(Messages.getValue(
"ride.perkm.sharecharge").trim()) + "");
System.out.println("inside default amnt 12for carpool:"+ Messages.getValue(
"ride.perkm.sharecharge"));
}
}
} catch (IOException e) {
errorMessage
.add("There is some problem in calculating time for ride.");
throw new ControllerException();
} catch (JSONException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
errorMessage
.add("There is some problem in calculating time for ride.");
throw new ControllerException();
}
// if no approver status = 1, if 1 approver status = O, if
// approver = 2 status = T
// check hoponid exist in db or not.
// If exist send email, sms and messageboard
// If does not exist send email only
// in email make link to approve.
ApproverDTO approverDtoTemp = ListOfValuesManager
.findApproverById(rideRegistered.getApproverID());
if (rideRegistered.getApproverID() > 0) {
if (approverDtoTemp.getHoponId() != null
&& approverDtoTemp.getHoponId().length() > 0) {
rideRegistered.setStatus("O");
if (approverDtoTemp.getHoponId2() != null
&& approverDtoTemp.getHoponId2().length() > 0) {
rideRegistered.setStatus("T");
}
}
}
if (rideRegistered.getCircleId() <= 0)
rideRegistered.setCircleId(allMemberCircleList.get(0)
.getCircleID());
rideRegistered = ListOfValuesManager.getRideSeekerEntery(
"findByDTO", rideRegistered, con);
// Here code is to make entry in paymentTxn table.
PaymentTxnsDTO paymentTxnsDTO = new PaymentTxnsDTO();
paymentTxnsDTO.setCreatedBy(Integer
.parseInt(userRegistrationDTO.getId()));
paymentTxnsDTO.setFromPayer(Integer
.parseInt(userRegistrationDTO.getId()));
paymentTxnsDTO.setToPayee(100);
paymentTxnsDTO.setTripDetails("");
paymentTxnsDTO.setSeekerId(Integer.parseInt(rideRegistered
.getRideID()));
paymentTxnsDTO.setCreatedDate(ApplicationUtil
.currentTimeStamp());
paymentTxnsDTO.setDist(rideRegistered.getRideDistance());
paymentTxnsDTO.setAmount(Float.parseFloat(rideRegistered
.getRideCost()));
ListOfValuesManager.paymentTxnInsert(paymentTxnsDTO, con);
if (rideRegistered.getApproverID() > 0) {
if (approverDtoTemp.getHoponId() != null
&& approverDtoTemp.getHoponId().length() > 0) {
String approveLink = Messages.getValue(
"ride.approve",
new Object[] {
rideRegistered.getRideID(),
URLEncoder.encode(approverDtoTemp
.getVerificationCode()),
approverDtoTemp.getId(),
approverDtoTemp.getHoponId() });
String rejectLink = Messages.getValue(
"ride.reject",
new Object[] {
rideRegistered.getRideID(),
URLEncoder.encode(approverDtoTemp
.getVerificationCode()),
approverDtoTemp.getId(),
approverDtoTemp.getHoponId() });
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ approverDtoTemp.getbCode()
+ "<br>Name: "
+ userRegistrationDTO.getFirst_name()
+ "<br>Request ID: "
+ rideRegistered.getRideID()
+ "<br>From: "
+ rideRegistered.getFromAddress1()
+ "<br>To: "
+ rideRegistered.getToAddress1()
+ "<br>Date Time: "
+ rideRegistered.getStartdateValue()
+ "<br>Frequency: "
+ frequencyDTO.getFrequency().toString()
+ "<br> "
+ approveLink
+ " "
+ rejectLink + "";
if (ListOfValuesManager.testEmail(approverDtoTemp
.getHoponId())) {
UserRegistrationDTO dtoTemp = null;
dtoTemp = ListOfValuesManager
.findUserByEmail(approverDtoTemp
.getHoponId());
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO.setEmailSubject(Messages
.getValue("subject.ride.approval"));
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer
.parseInt(dtoTemp.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.msgBoard",
new Object[] {
approverDtoTemp
.getbCode(),
rideRegistered
.getRideID(),
userRegistrationDTO
.getFirst_name(),
rideRegistered
.getFromAddress1(),
rideRegistered
.getToAddress1(),
rideRegistered
.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer
.parseInt(dtoTemp.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.sms",
new Object[] {
approverDtoTemp
.getbCode(),
rideRegistered
.getRideID(),
userRegistrationDTO
.getFirst_name(),
rideRegistered
.getFromAddress1()
.substring(
0,
(rideRegistered
.getFromAddress1()
.length() >= 20) ? 20
: rideRegistered
.getFromAddress1()
.length()),
rideRegistered
.getToAddress1()
.substring(
0,
(rideRegistered
.getToAddress1()
.length() >= 20) ? 20
: rideRegistered
.getToAddress1()
.length()),
rideRegistered
.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer
.parseInt(dtoTemp.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
EmailDTO emaildto = new EmailDTO();
emaildto.setReceiverEmailId(approverDtoTemp
.getHoponId());
emaildto.setSenderEmailId(userRegistrationDTO
.getEmail_id());
emaildto.setSubject(Messages
.getValue("subject.ride.approval"));
emaildto.setEmailTemplateBody(Messages
.getValue(
"email.template2",
new Object[] {
Messages.getValue("subject.ride.approval"),
messageContent }));
MailService.sendMail(emaildto);
}
}
}
frequencyDTO.setRideSeekerId(rideRegistered.getRideID());
}
}
if (rideManager.equals("giveRide")) {
if (ListOfValuesManager.checkRideDuplicacy(rideRegistered)) {
errorMessage.add("Same Ride already exist.");
// return "giveRide";
throw new ControllerException();
} else {
rideRegistered.setRideID(null);
rideRegistered.setCreatedBy(userRegistrationDTO.getId());
rideRegistered.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
List windoqCalculation;
try {
windoqCalculation = ApplicationUtil
.calculateTimeWindowSettings(
rideRegistered.getFromAddress1(), "",
rideRegistered.getToAddress1(),
userPreferences.getMaxWaitTime(),
rideRegistered.getStartdateValue());
if (windoqCalculation.size() > 0) {
rideRegistered.setStartdateValue(windoqCalculation
.get(1).toString());
rideRegistered.setStartDateEarly(windoqCalculation
.get(1).toString());
rideRegistered.setStartDateLate(windoqCalculation
.get(2).toString());
rideRegistered.setEndDateEarly(windoqCalculation
.get(3).toString());
rideRegistered.setEndDateLate(windoqCalculation
.get(4).toString());
float distance = Integer.parseInt(windoqCalculation
.get(5).toString()) / 1000;
rideRegistered.setRideDistance(distance);
rideRegistered.setRideCost((distance * 5) + "");
}
} catch (IOException e) {
errorMessage
.add("There is some problem in calculating time for ride.");
throw new ControllerException();
} catch (JSONException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
errorMessage
.add("There is some problem in calculating time for ride.");
throw new ControllerException();
}
rideRegistered = ListOfValuesManager.getRideEntery(
"findByDTO", rideRegistered, con);
frequencyDTO
.setRideManagementId(rideRegistered.getRideID());
}
}
frequencyDTO.setTime(rideRegistered.getStartDate());
frequencyDTO.setStartDate(rideRegistered.getStartdateValue());
frequencyDTO.setEndDate(rideRegistered.getEnddateValue());
frequencyDTO = ListOfValuesManager.getFrequencyEntery("findByDTO",
frequencyDTO, con);
if (rideRegistered.getFromAddressTag().equalsIgnoreCase("new")
&& rideRegistered.getFromAddressTagLimit() != null
&& rideRegistered.getFromAddressTagLimit() != "") {
FavoritePlacesDTO dto = new FavoritePlacesDTO();
dto.setAddress(rideRegistered.getFromAddress1());
// dto.setRideID(rideRegistered.getRideID());
dto.setUserID(userRegistrationDTO.getId());
dto.setCity(rideRegistered.getFromAddressCity());
dto.setPin(rideRegistered.getFromAddressPin());
dto.setTagtype(rideRegistered.getFromAddressTagLimit());
dto.setLatitude(rideRegistered.getStartPointLatitude());
dto.setLongitude(rideRegistered.getStartPointLongitude());
dto.setBoundtype("1");
dto = ListOfValuesManager.getfavoritePlaces(dto, con);
HttpSession currentSession = ServerUtility.getSession();
currentSession.removeAttribute("allPlaces");
}
if (rideRegistered.getToAddressTag().equalsIgnoreCase("new")
&& rideRegistered.getToAddressTagLimit() != null
&& rideRegistered.getToAddressTagLimit() != "") {
FavoritePlacesDTO dto = new FavoritePlacesDTO();
dto.setAddress(rideRegistered.getToAddress1());
// dto.setRideID(rideRegistered.getRideID());
dto.setUserID(userRegistrationDTO.getId());
dto.setCity(rideRegistered.getToAddressCity());
dto.setPin(rideRegistered.getToAddressPin());
dto.setTagtype(rideRegistered.getToAddressTagLimit());
dto.setLatitude(rideRegistered.getEndPointLatitude());
dto.setLongitude(rideRegistered.getEndPointLongitude());
dto.setBoundtype("2");
dto = ListOfValuesManager.getfavoritePlaces(dto, con);
HttpSession currentSession = ServerUtility.getSession();
currentSession.removeAttribute("allPlaces");
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} catch (ControllerException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
rideRegistered.setSharedTaxi(false);
rideRegistered = new RideManagementDTO();
frequencyDTO = new FrequencyDTO();
// rideManagementList();
// return "rideRegistered";
}
public void clearNewRide() {
rideRegistered = new RideManagementDTO();
frequencyDTO = new FrequencyDTO();
this.setRecurring(false);
// return "clear";
}
public void registerVehicleMaster() {
try {
vehicleMasterDTO.setUserID(userRegistrationDTO.getId());
vehicleMasterDTO = ListOfValuesManager.getVehicleMaster(
"findByDTO", vehicleMasterDTO);
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
rollbackTest = false;
vehicleList();
vehicleMasterDTO = new VehicleMasterDTO();
// return "vehicleegister";
}
public String allCompleateRideList() {
allCompleateRideList = ListOfValuesManager
.getAllPoolRequest(userRegistrationDTO.getId());
allCompleateRideSeekerList = ListOfValuesManager
.getAllPoolRequestSeeker(userRegistrationDTO.getId());
/*
* for ride seeker status = '1' , is_result = 'Y' for ride giver status
* in '1', pool_request table For taxi status = 'T',( should be in
* pool_request table)
*/
allMsgBoardCompleateRideList.clear();
for (PoolRequestsDTO dto : allCompleateRideList) {
if (dto.getRideGiverNotes() != null
&& dto.getRideGiverNotes().length() > 0) {
continue;
}
// if((dto.getRequestStatus().equalsIgnoreCase("T") &&
// (userRegistrationDTO.getTravel().equalsIgnoreCase("P") ||
// userRegistrationDTO.getTravel().equalsIgnoreCase("B"))) ||
// ((userRegistrationDTO.getTravel().equalsIgnoreCase("T") &&
// dto.getRequestStatus().equalsIgnoreCase("1")))) {
if (!dto.getRequestStatus().equalsIgnoreCase("T")
&& userRegistrationDTO.getTravel().equalsIgnoreCase("T")) {
continue;
}
if (!dto.getRequestStatus().equalsIgnoreCase("1")
&& userRegistrationDTO.getTravel().equalsIgnoreCase("P")) {
continue;
}
if (!dto.getRequestStatus().equalsIgnoreCase("1")
&& userRegistrationDTO.getTravel().equalsIgnoreCase("B")) {
continue;
}
allMsgBoardCompleateRideList.add(dto);
}
allMsgBoardCompleateRideSeekerList.clear();
for (PoolRequestsDTO dto : allCompleateRideSeekerList) {
if (dto.getRideTakerNotes() != null
&& dto.getRideTakerNotes().length() > 0) {
continue;
}
allMsgBoardCompleateRideSeekerList.add(dto);
}
return "compleateList";
}
public String takeRide() {
rideManager = "takeRide";
ridePicker = 1;
return "takeRide";
}
public String giveRide() {
rideManager = "giveRide";
ridePicker = 2;
return "giveRide";
}
public String clearLoginData() {
userRegistrationDTO = new UserRegistrationDTO();
return "clear";
}
public String clearCompanyData() {
companyRegisterDTO = new CompanyRegisterDTO();
return "clear";
}
public void processValueChange(AjaxBehaviorEvent event)
throws AbortProcessingException {
FavoritePlacesDTO dto = new FavoritePlacesDTO();
String value = (String) ((UIInput) event.getSource()).getValue();
if (value.equalsIgnoreCase("new")) {
rideRegistered = new RideManagementDTO();
}
if (value != null) {
for (int i = 0; i < allPlace.size(); i++) {
String place = allPlace.get(i).getTagtype();
if (place.equals(value)) {
dto = allPlace.get(i);
rideRegistered.setFromAddress1(dto.getAddress());
rideRegistered.setFromAddressPin(dto.getPin());
rideRegistered.setFromAddressCity(dto.getCity());
rideRegistered.setStartPointLatitude(dto.getLatitude());
rideRegistered.setStartPointLongitude(dto.getLongitude());
}
}
}
}
public void processValueChange1(AjaxBehaviorEvent event)
throws AbortProcessingException {
FavoritePlacesDTO dto = new FavoritePlacesDTO();
String value = (String) ((UIInput) event.getSource()).getValue();
if (value.equalsIgnoreCase("new")) {
rideRegistered = new RideManagementDTO();
}
if (value != null) {
for (int i = 0; i < allPlace.size(); i++) {
String place = allPlace.get(i).getTagtype();
if (place.equals(value)) {
dto = allPlace.get(i);
rideRegistered.setToAddress1(dto.getAddress());
rideRegistered.setToAddressPin(dto.getPin());
rideRegistered.setToAddressCity(dto.getCity());
rideRegistered.setEndPointLatitude(dto.getLatitude());
rideRegistered.setEndPointLongitude(dto.getLongitude());
}
}
}
}
public void processValueChange2(AjaxBehaviorEvent event)
throws AbortProcessingException {
allCircleForLoginUser();
String value = String.valueOf(((UIInput) event.getSource()).getValue());
List<CircleOwnerManagerDTO> allCircleMemberForLoginUserList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
if (allCircleMemberForLoginUserList.get(i).getCircleID()
.equals(value)) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allCircleMemberForLoginUserList.get(i);
allCircleMemberForLoginUserList1.add(dto);
}
}
allCircleMemberForLoginUserList.clear();
allCircleMemberForLoginUserList
.addAll(allCircleMemberForLoginUserList1);
allCircleMemberForLoginUserList1.clear();
List<CircleOwnerManagerDTO> allPendingCircleMemberList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allPendingCircleMemberList.size(); i++) {
if (allPendingCircleMemberList.get(i).getCircleID().equals(value)) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allPendingCircleMemberList.get(i);
allPendingCircleMemberList1.add(dto);
}
}
allPendingCircleMemberList.clear();
allPendingCircleMemberList.addAll(allPendingCircleMemberList1);
allPendingCircleMemberList1.clear();
}
public void processValueChange3(AjaxBehaviorEvent event)
throws AbortProcessingException {
String circleId = String.valueOf(((UIInput) event.getSource())
.getValue());
gatherAffiliatedCircle(Integer.parseInt(circleId));
}
public void processValueChange4(AjaxBehaviorEvent event)
throws AbortProcessingException {
gatherAffiliatedCircle(manageRideFormDTO.getMyCircleId());
}
public void gatherDefaultcircleDTO() {
if (taxiCircle.getCircleID() >= 0) {
gatherAffiliatedCircle(taxiCircle.getCircleID());
}
}
public void clearCircleForLoginUser() {
allCircleMemberForLoginUserList.clear();
circleDTO = new CircleDTO();
circleOwnerManagerDTO = new CircleOwnerManagerDTO();
}
public String copyRideManager() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
String rideManager = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
rideManager = (String) requestMap.get("rideManagement");
try {
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern3);
Calendar cal = Calendar.getInstance();
// Calendar cal1 = Calendar.getInstance();
cal.setTime(rideRegistered.getStartDate());
// cal1.setTime(rideRegistered.getEndDate());
rideRegistered.setStartdateValue(dateFormat.format(cal.getTime()));
// rideRegistered.setEnddateValue(dateFormat.format(cal1.getTime()));
if (rideManager.equalsIgnoreCase("rideManagementFrompool")) {
rideRegistered.setRideID(null);
rideRegistered.setUserID(userRegistrationDTO.getId());
rideRegistered.setFromAddress1(poolRequestsDTO
.getRideManagementFrom());
// Calendar cal1 = Calendar.getInstance();
cal.setTime(rideRegistered.getStartDate());
rideRegistered.setStartdateValue(dateFormat.format(cal
.getTime()));
String date = dateFormat.format(rideRegistered.getStartDate());
DateFormat dateFormat1 = new SimpleDateFormat(
ApplicationUtil.datePattern3);
try {
rideRegistered.setFlexiTimeAfter(dateFormat1.parse(date));
rideRegistered.setFlexiTimeBefore(dateFormat1.parse(date));
rideRegistered.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
rideRegistered.setToAddress1(poolRequestsDTO
.getRideManagementTO());
rideRegistered = ListOfValuesManager.getRideEntery("findByDTO",
rideRegistered, con);
frequencyDTO.setTime(rideRegistered.getStartDate());
List<String> list = new ArrayList<String>();
list.add(poolRequestsDTO.getRideManagementFrequency());
frequencyDTO.setFrequency(list);
frequencyDTO.setRideManagementId(rideRegistered.getRideID());
rideRegistered.setCreatedBy(rideRegistered.getCreatedBy());
/*
* for(int i = 0;i< vehicleMasterDTOList.size();i++) {
* if(vehicleMasterDTOList
* .get(i).getReg_NO().equalsIgnoreCase(rideRegistered
* .getVehicleID()) ){
* rideRegistered.setVehicleID(vehicleMasterDTOList
* .get(i).getVehicleID()); break; } }
*/
frequencyDTO = ListOfValuesManager.getFrequencyEntery(
"findByDTO", frequencyDTO, con);
rideManagementList();
frequencyDTO = new FrequencyDTO();
rideRegistered = new RideManagementDTO();
return "copyrideManager";
}
rideRegistered = ListOfValuesManager
.getRideManagerPopupDataDirect(rideRegistered.getRideID());
List<String> frequencyList = new ArrayList<String>();
// list.add(rideRegistered.getFrequencyinweek());
List<FrequencyDTO> freqDtos = new ArrayList<FrequencyDTO>();
freqDtos.addAll(ListOfValuesManager
.fetchFrequencyListForRideManager(rideRegistered
.getRideID()));
for (FrequencyDTO freqDto : freqDtos)
frequencyList.addAll(freqDto.getFrequency());
rideRegistered.setRideID(null);
rideRegistered.setUserID(userRegistrationDTO.getId());
// Calendar cal1 = Calendar.getInstance();
cal.setTime(rideRegistered.getStartDate());
String date = dateFormat.format(rideRegistered.getStartDate());
DateFormat dateFormat1 = new SimpleDateFormat(
ApplicationUtil.datePattern3);
try {
rideRegistered.setFlexiTimeAfter(dateFormat1.parse(date));
rideRegistered.setFlexiTimeBefore(dateFormat1.parse(date));
rideRegistered.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
List x1;
try {
x1 = ApplicationUtil.calculateTimeWindowSettings(
rideRegistered.getFromAddress1(), "",
rideRegistered.getToAddress1(),
userPreferences.getMaxWaitTime(), date);
/*
* TWstart_early = x1.get(1); TWstart_late = x1.get(2);
* TWend_early TWend_late ride_distance ride_cost =
* ride_distance * 5;
*/
if (x1.size() > 0) {
rideRegistered.setStartdateValue(x1.get(1).toString());
rideRegistered.setStartDateEarly(x1.get(1).toString());
rideRegistered.setStartDateLate(x1.get(2).toString());
rideRegistered.setEndDateEarly(x1.get(3).toString());
rideRegistered.setEndDateLate(x1.get(4).toString());
float distance = Integer.parseInt(x1.get(5).toString()) / 1000;
rideRegistered.setRideDistance(distance);
rideRegistered.setRideCost((distance * 5) + "");
}
} catch (IOException e) {
} catch (JSONException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
rideRegistered.setStartPointLatitude(rideRegistered
.getStartPointLatitude());
rideRegistered.setStartPointLongitude(rideRegistered
.getStartPointLongitude());
rideRegistered.setEndPointLatitude(rideRegistered
.getEndPointLatitude());
rideRegistered.setEndPointLongitude(rideRegistered
.getEndPointLongitude());
rideRegistered.setViaPointLatitude(rideRegistered
.getViaPointLatitude());
rideRegistered.setViaPointLongitude(rideRegistered
.getViaPointLongitude());
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
if (vehicleMasterDTOList.get(i).getReg_NO()
.equalsIgnoreCase(rideRegistered.getVehicleID())) {
rideRegistered.setVehicleID(vehicleMasterDTOList.get(i)
.getVehicleID());
break;
}
}
rideRegistered = ListOfValuesManager.getRideEntery("findByDTO",
rideRegistered, con);
frequencyDTO.setTime(rideRegistered.getStartDate());
frequencyDTO.setFrequency(frequencyList);
frequencyDTO.setRideManagementId(rideRegistered.getRideID());
try {
frequencyDTO.setStartDate(freqDtos.get(0).getStartDate());
frequencyDTO.setEndDate(freqDtos.get(0).getEndDate());
} catch (NullPointerException e) {
}
frequencyDTO = ListOfValuesManager.getFrequencyEntery("findByDTO",
frequencyDTO, con);
rideManagementList();
rideRegistered = new RideManagementDTO();
frequencyDTO = new FrequencyDTO();
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
return "copyrideManager";
}
public String copyRideSeeker() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
String rideSeeker = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
rideSeeker = (String) requestMap.get("rideSeeker");
try {
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern3);
Calendar cal = Calendar.getInstance();
// Calendar cal1 = Calendar.getInstance();
cal.setTime(rideRegistered.getStartDate());
// cal1.setTime(rideSeekerDTO.getEndDate());
rideRegistered.setStartdateValue(dateFormat.format(cal.getTime()));
// rideRegistered.setEnddateValue(
// dateFormat.format(cal1.getTime()));
rideRegistered.setRecurring(rideSeekerDTO.getRecurring());
rideRegistered.setSubSeekers(rideSeekerDTO.getSubSeekers());
if (rideSeeker.equalsIgnoreCase("rideSeekerFrompool")) {
rideRegistered.setRideID(null);
rideRegistered.setUserID(userRegistrationDTO.getId());
rideRegistered.setFromAddress1(poolRequestsDTO
.getRideSeekerFrom());
// Calendar cal1 = Calendar.getInstance();
cal.setTime(rideRegistered.getStartDate());
rideRegistered.setStartdateValue(dateFormat.format(cal
.getTime()));
String date = dateFormat.format(rideRegistered.getStartDate());
DateFormat dateFormat1 = new SimpleDateFormat(
ApplicationUtil.datePattern3);
try {
rideRegistered.setFlexiTimeAfter(dateFormat1.parse(date));
rideRegistered.setFlexiTimeBefore(dateFormat1.parse(date));
rideRegistered.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
rideRegistered.setToAddress1(poolRequestsDTO.getRideSeekerTo());
rideRegistered = ListOfValuesManager.getRideSeekerEntery(
"findByDTO", rideRegistered, con);
frequencyDTO.setTime(rideRegistered.getStartDate());
List<String> list = new ArrayList<String>();
list.add(poolRequestsDTO.getRideSeekerFrequency());
frequencyDTO.setFrequency(list);
frequencyDTO.setRideSeekerId(rideRegistered.getRideID());
rideRegistered.setCreatedBy(rideRegistered.getCreatedBy());
/*
* for(int i = 0;i< vehicleMasterDTOList.size();i++) {
* if(vehicleMasterDTOList
* .get(i).getReg_NO().equalsIgnoreCase(rideRegistered
* .getVehicleID()) ){
* rideRegistered.setVehicleID(vehicleMasterDTOList
* .get(i).getVehicleID()); break; } }
*/
frequencyDTO = ListOfValuesManager.getFrequencyEntery(
"findByDTO", frequencyDTO, con);
rideManagementList();
frequencyDTO = new FrequencyDTO();
rideRegistered = new RideManagementDTO();
return "copyrideSeeker";
}
rideSeekerDTO = ListOfValuesManager.getRideSeekerData(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
List<String> frequencyList = new ArrayList<String>();
// list.add(rideSeekerDTO.getFrequencyinweek());
List<FrequencyDTO> freqDtos = new ArrayList<FrequencyDTO>();
freqDtos.addAll(ListOfValuesManager
.fetchFrequencyListForRideSeeker(rideSeekerDTO
.getSeekerID()));
for (FrequencyDTO freqDto : freqDtos)
frequencyList.addAll(freqDto.getFrequency());
rideRegistered.setRideID(null);
/*
* rideRegistered.setStartDate(rideSeekerDTO.getStartDate());
* rideRegistered.setEndDate(rideSeekerDTO.getEndDate());
*/
rideRegistered.setUserID(userRegistrationDTO.getId());
rideRegistered.setFromAddress1(rideSeekerDTO.getFromAddress1());
rideRegistered.setToAddress1(rideSeekerDTO.getToAddress1());
cal.setTime(rideRegistered.getStartDate());
String date = dateFormat.format(rideRegistered.getStartDate());
DateFormat dateFormat1 = new SimpleDateFormat(
ApplicationUtil.datePattern3);
try {
rideRegistered.setFlexiTimeAfter(dateFormat1.parse(date));
rideRegistered.setFlexiTimeBefore(dateFormat1.parse(date));
rideRegistered.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
List x1;
try {
x1 = ApplicationUtil.calculateTimeWindowSettings(
rideSeekerDTO.getFromAddress1(), "",
rideSeekerDTO.getToAddress1(),
userPreferences.getMaxWaitTime(),
rideRegistered.getStartdateValue());
/*
* TWstart_early = x1.get(1); TWstart_late = x1.get(2);
* TWend_early TWend_late ride_distance ride_cost =
* ride_distance * 5;
*/
if (x1.size() > 0) {
rideRegistered.setStartdateValue(x1.get(1).toString());
rideRegistered.setStartDateEarly(x1.get(1).toString());
rideRegistered.setStartDateLate(x1.get(2).toString());
rideRegistered.setEndDateEarly(x1.get(3).toString());
rideRegistered.setEndDateLate(x1.get(4).toString());
float distance = Integer.parseInt(x1.get(5).toString()) / 1000;
rideRegistered.setRideDistance(distance);
rideRegistered.setRideCost((distance * 5) + "");
}
} catch (IOException e) {
} catch (JSONException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
// Calendar cal1 = Calendar.getInstance();
rideRegistered.setCreatedBy(rideSeekerDTO.getCreatedBy());
rideRegistered.setStartPointLatitude(rideSeekerDTO
.getStartPointLatitude());
rideRegistered.setStartPointLongitude(rideSeekerDTO
.getStartPointLongitude());
rideRegistered.setEndPointLatitude(rideSeekerDTO
.getEndPointLatitude());
rideRegistered.setEndPointLongitude(rideSeekerDTO
.getEndPointLongitude());
rideRegistered.setViaPointLatitude(rideSeekerDTO
.getViaPointLatitude());
rideRegistered.setViaPointLongitude(rideSeekerDTO
.getViaPointLongitude());
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
if (vehicleMasterDTOList.get(i).getReg_NO()
.equalsIgnoreCase(rideRegistered.getVehicleID())) {
rideRegistered.setVehicleID(vehicleMasterDTOList.get(i)
.getVehicleID());
break;
}
}
rideRegistered = ListOfValuesManager.getRideSeekerEntery(
"findByDTO", rideRegistered, con);
try {
frequencyDTO.setStartDate(freqDtos.get(0).getStartDate());
frequencyDTO.setEndDate(freqDtos.get(0).getEndDate());
} catch (NullPointerException e) {
}
if (Validator.isNotEmpty(rideRegistered.getEndDate())) {
frequencyDTO.setEndDate(ApplicationUtil.dateFormat3
.format(rideRegistered.getEndDate()));
}
if (Validator.isNotEmpty(rideRegistered.getStartDate())) {
frequencyDTO.setStartDate(ApplicationUtil.dateFormat3
.format(rideRegistered.getStartDate()));
}
frequencyDTO.setTime(rideRegistered.getStartDate());
frequencyDTO.setFrequency(frequencyList);
frequencyDTO.setRideSeekerId(rideRegistered.getRideID());
frequencyDTO = ListOfValuesManager.getFrequencyEntery("findByDTO",
frequencyDTO, con);
rideManagementList();
rideRegistered = new RideManagementDTO();
frequencyDTO = new FrequencyDTO();
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
}
rollbackTest = false;
return "copyrideSeeker";
}
public void registerCircle() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
clearScreenMessage();
if (userRegistrationDTO.getTravel().equals("T")
&& allCircleForLoginUserList.size() > 0) {
errorMessage.add(Messages.getValue("circle.add.restriction",
new Object[] { 1, "Circle" }));
circleDTO = new CircleDTO();
return;
} else if ((userRegistrationDTO.getTravel().equals("T") == false)
&& (circleDTO.getCircleType().equals("T"))) {
errorMessage.add(Messages.getValue("circle.add.typerestriction",
new Object[] { "Taxi" }));
circleDTO = new CircleDTO();
return;
} else if ((userRegistrationDTO.getTravel().equals("T") == false)
&& ((circleDTO.getCircleType().equals("C")) && (allCorpCircleForLoginUserList
.size() > 0))) {
errorMessage.add(Messages.getValue("circle.add.restriction",
new Object[] { 1, "Corporate Circle" }));
circleDTO = new CircleDTO();
return;
}
circleDTO.setCircleOwner_Member_Id_P(Integer
.valueOf(userRegistrationDTO.getId()));
circleDTO.setDate_of_creation(ListOfValuesManager.getcurrentDate());
CircleOwnerDTO circleOwnerDTO = new CircleOwnerDTO();
try {
circleDTO = ListOfValuesManager.getregisterCircle(circleDTO, con);
circleOwnerDTO.setCircleID(String.valueOf(circleDTO.getCircleID()));
circleOwnerDTO.setUserID(userRegistrationDTO.getId());
circleOwnerDTO = ListOfValuesManager.getregisterCircleOwner(
circleOwnerDTO, userRegistrationDTO.getId(), con);
circleMemberDTO.setUserid(userRegistrationDTO.getId());
circleMemberDTO.setCircleid(circleOwnerDTO.getCircleID());
circleMemberDTO.setStatus("1");
circleMemberDTO = ListOfValuesManager.getJoinCircle(
circleMemberDTO, userRegistrationDTO.getId(), con);
successMessage.add(Messages.getValue("success.add",
new Object[] { "Circle" }));
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
errorMessage.add(Messages.getValue("error.db1",
new Object[] { "Circle" }));
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
allListedCircle();
allCircleForLoginUser();
allCircleMemberForLoginUserList.clear();
allPendingCircleMemberList.clear();
getAllCilcleForLoginUserDropDownList();
circleDTO = new CircleDTO();
circleMemberDTO = new CircleMemberDTO();
// return "circleRegistered";
}
public List<String> getAllPlacesList() {
List<String> list = new ArrayList<String>();
/*
* HttpSession currentSession = ServerUtility.getSession();
* if(currentSession.getAttribute("allPlaces") != null) { allPlace =
* (List<FavoritePlacesDTO>) currentSession.getAttribute("allPlaces"); }
* else {
*/
allPlace = ListOfValuesManager
.getAllPlaces(userRegistrationDTO.getId());
/*
* currentSession.setAttribute("allPlaces", allPlace); }
*/
for (int i = 0; i < allPlace.size(); i++) {
String place = allPlace.get(i).getTagtype();
list.add(place);
}
return list;
}
public String allCircleForLoginUser() {
allCircleForLoginUserList = ListOfValuesManager
.getAllCircleForLoginUser(userRegistrationDTO.getId());
allCircleMemberForLoginUserList = ListOfValuesManager
.getAllCircleMemberForLoginUser(userRegistrationDTO.getId());
allPendingCircleMemberList = ListOfValuesManager
.getAllPendingCircleMemberForLoginUser(userRegistrationDTO
.getId());
allCorpCircleForLoginUserList = ListOfValuesManager
.getAllCorpCircleForLoginUser(userRegistrationDTO.getId());
allTaxiCircleForLoginUserList = ListOfValuesManager
.getAllTaxiCircleForLoginUser(userRegistrationDTO.getId());
memberForSelectedCircle();
return "allCircleList";
}
public String memberForSelectedCircle() {
allCircleMemberForLoginUserList = ListOfValuesManager
.getAllCircleMemberForLoginUser(userRegistrationDTO.getId());
allPendingCircleMemberList = ListOfValuesManager
.getAllPendingCircleMemberForLoginUser(userRegistrationDTO
.getId());
return "selected";
}
public List<SelectItem> getAllVehicleList() {
List<SelectItem> list = new ArrayList<SelectItem>();
VehicleMasterDTO tempVehicleList = new VehicleMasterDTO();
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
if (vehicleMasterDTOList.get(i).isIs_default()) {
tempVehicleList = vehicleMasterDTOList.get(0);
vehicleMasterDTOList.set(0, vehicleMasterDTOList.get(i));
vehicleMasterDTOList.set(i, tempVehicleList);
}
}
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
list.add(new SelectItem(vehicleMasterDTOList.get(i).getVehicleID(),
vehicleMasterDTOList.get(i).getReg_NO()));
}
return list;
}
public List<SelectItem> getAllCilcleForLoginUserDropDownList() {
List<SelectItem> list = new ArrayList<SelectItem>();
for (int i = 0; i < allCircleForLoginUserList.size(); i++) {
list.add(new SelectItem(allCircleForLoginUserList.get(i)
.getCircleID(), allCircleForLoginUserList.get(i)
.getCircleName()));
}
return list;
}
public List<SelectItem> getAllCilcleMemberForLoginUserDropDownList() {
List<SelectItem> list = new ArrayList<SelectItem>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
String listText = "";
listText += allCircleMemberForLoginUserList.get(i).getMemberName();
if (allCircleMemberForLoginUserList.get(i).getAge() != null
&& allCircleMemberForLoginUserList.get(i).getAge().length() > 0) {
listText += " of age: "
+ allCircleMemberForLoginUserList.get(i).getAge();
}
if (allCircleMemberForLoginUserList.get(i).getAddress() != null
&& allCircleMemberForLoginUserList.get(i).getAddress()
.length() > 0) {
listText += " lives in: "
+ allCircleMemberForLoginUserList.get(i).getAddress();
}
if (allCircleMemberForLoginUserList.get(i).getAdminInfo() != null
&& allCircleMemberForLoginUserList.get(i).getAdminInfo()
.length() > 0) {
listText += " - "
+ allCircleMemberForLoginUserList.get(i).getAdminInfo();
}
list.add(new SelectItem(allCircleMemberForLoginUserList.get(i)
.getUserid()
+ ","
+ allCircleMemberForLoginUserList.get(i).getCircleID()
+ ","
+ allCircleMemberForLoginUserList.get(i).getSuperAdmin(),
listText));
}
return list;
}
public List<SelectItem> getAllCilcleMemberToSendMessageDropDownList() {
List<SelectItem> list = new ArrayList<SelectItem>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
list.add(new SelectItem(allCircleMemberForLoginUserList.get(i)
.getCircleID(), allCircleMemberForLoginUserList.get(i)
.getCircleName()));
}
return list;
}
public List<SelectItem> getAllAffiliatedCilcleMember() {
List<SelectItem> list = new ArrayList<SelectItem>();
// allCircleAffiliationsDTO
for (CircleAffiliationsDTO dto : allCircleAffiliationsDTO) {
list.add(new SelectItem(dto.getCircleAffilicatedCircleId(), dto
.getAffilicatedCircleName()));
}
return list;
}
public List<String> getAllPendingAffiliatedCilcleMember() {
List<String> list = new ArrayList<String>();
// allCircleAffiliationsDTO
for (CircleAffiliationsDTO dto : allPendingCircleAffiliationsDTO) {
list.add(dto.getAffilicatedCircleName());
}
return list;
}
public List<String> getAllPendingCilcleMemberForLoginUser() {
List<String> list = new ArrayList<String>();
for (int i = 0; i < allPendingCircleMemberList.size(); i++) {
String listText = "";
listText += allPendingCircleMemberList.get(i).getMemberName();
if (allPendingCircleMemberList.get(i).getAge() != null
&& allPendingCircleMemberList.get(i).getAge().length() > 0) {
listText += " of age: "
+ allPendingCircleMemberList.get(i).getAge();
}
if (allPendingCircleMemberList.get(i).getAddress() != null
&& allPendingCircleMemberList.get(i).getAddress().length() > 0) {
listText += " lives in: "
+ allPendingCircleMemberList.get(i).getAddress();
}
if (allPendingCircleMemberList.get(i).getAdminInfo().length() > 0) {
listText += " - "
+ allPendingCircleMemberList.get(i).getAdminInfo();
}
list.add(listText);
}
return list;
}
public List<SelectItem> getAllAffiliateCircleForTaxiUser() {
List<SelectItem> list = new ArrayList<SelectItem>();
List<CircleDTO> dto = new ArrayList<CircleDTO>();
try {
dto = ListOfValuesManager.getAffiliateCircleForTaxiUser(Integer
.parseInt(userRegistrationDTO.getId()));
} catch (NumberFormatException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
for (CircleDTO dtoTemp : dto) {
list.add(new SelectItem(dtoTemp.getCircleID(), dtoTemp.getName()));
}
return list;
}
public void makeRidePreMatchInactive() {
ridePreMatchFormTest = false;
}
public void makeRideMatchInactive() {
rideMatchFormTest = false;
}
public void clearMatchTripList() {
rideSeekerDTO = new RideSeekerDTO();
matchedTripByConditionList.clear();
matchedTripDataModel = new MatchedTripDataModel();
}
public void clearCombineVehicleSearch() {
rideManagementDTO = new RideManagementDTO();
combineVehicleCondition.clear();
combineVehicleDataModel = new CombineVehicleDataModel();
circleDTO = new CircleDTO();
this.setRideIdToDrop(0);
this.setRideIdToTake(0);
}
public void combineVehicleSearch() {
String date1 = "";
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern1);
// SimpleDateFormat formatter1 = new
// SimpleDateFormat(ApplicationUtil.datePattern2);
// date = formatter1.parse(dto1.getStartDate());
if (rideManagementDTO.getStartDate() != null) {
date1 = dateFormat.format(rideManagementDTO.getStartDate());
}
combineVehicleCondition.clear();
combineVehicleCondition = ListOfValuesManager.getAllCombineVehicleList(
rideManagementDTO.getFromAddress1(),
rideManagementDTO.getToAddress1(), date1,
circleDTO.getCircleID());
combineVehicleDataModel = new CombineVehicleDataModel(
combineVehicleCondition);
}
public void combineVehicle() {
clearScreenMessage();
if (rideIdToDrop <= 0)
errorMessage.add("Please select ride to drop.");
if (rideIdToTake <= 0)
errorMessage.add("Please select ride to Combine.");
if (rideIdToTake == rideIdToDrop && rideIdToTake > 0)
errorMessage
.add("Please select different rides to drop and Combine.");
if (errorMessage.size() == 0) {
// populate drop and take ride.
RideManagementDTO rideToDrop = ListOfValuesManager
.getRideManagerPopupDataDirect(rideIdToDrop + "");
RideManagementDTO rideToTake = ListOfValuesManager
.getRideManagerPopupDataDirect(rideIdToTake + "");
if (!Validator.isNumberZeroNotAlloed(rideToDrop.getRideID())) {
errorMessage.add("Ride you want to drop does not exist.");
}
if (!Validator.isNumberZeroNotAlloed(rideToTake.getRideID())) {
errorMessage.add("Ride you want to combine does not exist.");
}
if (!ApplicationUtil.dateFormat1.format(rideToDrop.getStartDate())
.equals(ApplicationUtil.dateFormat1.format(rideToTake
.getStartDate()))) {
errorMessage
.add("Select Ride of same date you want to combine and drop.");
}
// Make validation that both rides start and end point synchronized.
// Make validation that both rides time synchronized.
if (errorMessage.size() == 0) {
Connection con = (Connection) ListOfValuesManager
.getBroadConnection();
try {
rideToDrop.setStatus("I");
ListOfValuesManager.getCancleRide(rideToDrop, con);
// Update rideId in pool request and ride seeker table.
ListOfValuesManager.updateRideIdDropTake(rideToDrop,
rideToTake, con);
// Send message to ride user that ride cancelled.
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto = ListOfValuesManager.findDriverDtoByRideId(
rideToDrop.getRideID(), con);
UserRegistrationDTO userDtoRide = new UserRegistrationDTO();
userDtoRide = ListOfValuesManager.getUserById(Integer
.parseInt(rideToDrop.getUserID()));
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel.driver.admin",
new Object[] {
userDto.getFirst_name(),
rideToDrop.getRideID(),
(rideToDrop.getFromAddress1()
.length() > 25) ? rideToDrop
.getFromAddress1()
.substring(0, 25)
: rideToDrop
.getFromAddress1(),
(rideToDrop.getToAddress1()
.length() > 25) ? rideToDrop
.getToAddress1().substring(
0, 25) : rideToDrop
.getToAddress1(),
rideToDrop.getStartdateValue() }));
userMessageDTO
.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideToDrop
.getRideID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideToDrop.getStartdateValue() }));
userMessageDTO.setMessage(Messages.getValue(
"ridegiver.driver.cancel",
new Object[] { userDto.getFirst_name(),
rideToDrop.getRideID(),
rideToDrop.getFromAddress1(),
rideToDrop.getToAddress1(),
rideToDrop.getStartdateValue(),
userDtoRide.getMobile_no() }));
userMessageDTO
.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideToDrop
.getRideID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
// Send message to ride user that new ride assigned.
userDto = ListOfValuesManager.findDriverDtoByRideId(
rideToTake.getRideID(), con);
userDtoRide = ListOfValuesManager.getUserById(Integer
.parseInt(rideToTake.getUserID()));
allSeekerForGivenRide = ListOfValuesManager
.getAllRideSeekerForAGivenRide(rideToDrop
.getRideID());
if (allSeekerForGivenRide.size() > 0) {
for (int index = 0; index < allSeekerForGivenRide
.size(); index++) {
UserRegistrationDTO seekerUserDto = ListOfValuesManager
.getUserById(Integer.parseInt(rideToTake
.getUserID()));
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages.getValue(
"subject.match",
new Object[] { rideToTake
.getStartDate() }));
userMessageDTO.setMessage(Messages.getValue(
"ridematched.driver",
new Object[] {
userDto.getFirst_name(),
rideToDrop.getRideID(),
rideToTake.getFromAddress1(),
rideToTake.getToAddress1(),
rideToTake.getStartDate(),
seekerUserDto.getFirst_name()
+ " - "
+ seekerUserDto
.getMobile_no() }));
userMessageDTO.setToMember(Integer.parseInt(userDto
.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"sms.match.driver",
new Object[] {
allSeekerForGivenRide.get(index)
.getFromAddress1(),
allSeekerForGivenRide.get(index)
.getToAddress1(),
seekerUserDto.getFirst_name(),
allSeekerForGivenRide.get(index)
.getStartdateValue(),
seekerUserDto.getMobile_no(),
rideToTake.getRideID(),
userDto.getFirst_name() }));
userMessageDTO.setToMember(Integer.parseInt(userDto
.getId()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject("Your ride has been changed");
userMessageDTO.setMessage(Messages.getValue(
"ridematched.seeker",
new Object[] {
allSeekerForGivenRide.get(index)
.getUserName(),
userDto.getFirst_name(),
rideToTake.getRideID(),
allSeekerForGivenRide.get(index)
.getFromAddress1(),
allSeekerForGivenRide.get(index)
.getToAddress1(),
allSeekerForGivenRide.get(index)
.getStartdateValue(),
rideToTake.getVehicleRegno(),
userDto.getMobile_no() }));
userMessageDTO.setToMember(Integer
.parseInt(allSeekerForGivenRide.get(index)
.getUserID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage("Your ride has been changed."
+ Messages
.getValue(
"sms.match",
new Object[] {
allSeekerForGivenRide
.get(index)
.getFromAddress1(),
allSeekerForGivenRide
.get(index)
.getToAddress1(),
seekerUserDto
.getFirst_name(),
allSeekerForGivenRide
.get(index)
.getStartdateValue(),
userDto.getMobile_no(),
rideToTake
.getRideID(),
allSeekerForGivenRide
.get(index)
.getUserName(),
rideToTake
.getVehicleRegno(),
allSeekerForGivenRide
.get(index)
.getSeekerID() }));
userMessageDTO.setToMember(Integer
.parseInt(allSeekerForGivenRide.get(index)
.getUserID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
} catch (ConfigurationException e) {
rollbackTest = true;
} catch (NullPointerException e1) {
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName()
+ "->"
+ e.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e.getStackTrace()[0]
.getLineNumber() + " :: "
+ e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
errorMessage.add("There is some problem in operation.");
successMessage.clear();
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName()
+ "->"
+ e.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e.getStackTrace()[0]
.getLineNumber() + " :: "
+ e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
successMessage.add("Vehicle combined successfully.");
}
rollbackTest = false;
}
}
}
clearCombineVehicleSearch();
}
public String matchedTripListByCondition() {
rideMatchFormTest = true;
String date1 = "";
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern1);
// SimpleDateFormat formatter1 = new
// SimpleDateFormat(ApplicationUtil.datePattern2);
// date = formatter1.parse(dto1.getStartDate());
if (rideSeekerDTO.getStartDate() != null) {
date1 = dateFormat.format(rideSeekerDTO.getStartDate());
}
matchedTripByConditionList.clear();
matchedTripByConditionList = ListOfValuesManager
.getAllMatchedListByCondition(rideSeekerDTO.getFromAddress1(),
rideSeekerDTO.getToAddress1(), date1,
circleDTO.getCircleID());
Map<String, Integer> group = new HashMap<String, Integer>();
for (MatchedTripDTO dto : matchedTripByConditionList) {
if (group.size() > 0 && group.containsKey(dto.getGroupId())) {
group.put(dto.getGroupId(), group.get(dto.getGroupId()) + 1);
} else {
group.put(dto.getGroupId(), 1);
}
}
for (int i = 0; i < matchedTripByConditionList.size(); i++) {
matchedTripByConditionList.get(i).setMemberCount(
""
+ group.get(matchedTripByConditionList.get(i)
.getGroupId()));
}
matchedTripDataModel = new MatchedTripDataModel(
matchedTripByConditionList);
return "matchedTrip";
}
public String rideMatchedTripListByCondition() {
ridePreMatchFormTest = true;
String date1 = "";
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern1);
// SimpleDateFormat formatter1 = new
// SimpleDateFormat(ApplicationUtil.datePattern2);
// date = formatter1.parse(dto1.getStartDate());
if (rideSeekerDTO.getStartDate() != null) {
date1 = dateFormat.format(rideSeekerDTO.getStartDate());
}
matchedTripByConditionList.clear();
if (circleDTO.getCircleID() > 0) {
matchedTripByConditionList = ListOfValuesManager
.getAllMatchedListByCondition(
rideSeekerDTO.getFromAddress1(),
rideSeekerDTO.getToAddress1(), date1,
circleDTO.getCircleID());
List<MatchedTripDTO> dtoTemp = new ArrayList<MatchedTripDTO>();
for (int i = 0; i < matchedTripByConditionList.size(); i++) {
if (!matchedTripByConditionList.get(i).isFullDay()
&& !matchedTripByConditionList.get(i).isRecurring()) {
dtoTemp.add(matchedTripByConditionList.get(i));
}
}
matchedTripByConditionList.clear();
matchedTripByConditionList.addAll(dtoTemp);
} else {
clearScreenMessage();
errorMessage.add("Please Select affiliated circle.");
}
Map<String, Integer> group = new HashMap<String, Integer>();
for (MatchedTripDTO dto : matchedTripByConditionList) {
if (group.size() > 0 && group.containsKey(dto.getGroupId())) {
group.put(dto.getGroupId(), group.get(dto.getGroupId()) + 1);
} else {
group.put(dto.getGroupId(), 1);
}
}
for (int i = 0; i < matchedTripByConditionList.size(); i++) {
matchedTripByConditionList.get(i).setMemberCount(
""
+ group.get(matchedTripByConditionList.get(i)
.getGroupId()));
}
matchedTripDataModel = new MatchedTripDataModel(
matchedTripByConditionList);
return "matchedTrip";
}
public String matchRideForCompany() {
if (manageRideFormDTO.getRideDate() != null
&& !manageRideFormDTO.getRideDate().equals("")) {
SimpleDateFormat df1 = new SimpleDateFormat(
ApplicationUtil.datePattern12);
SimpleDateFormat df2 = new SimpleDateFormat(
ApplicationUtil.datePattern1);
try {
Date date = df1.parse(manageRideFormDTO.getRideDate());
manageRideFormDTO.setRideDate(df2.format(date));
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
}
String rideOption = manageRideFormDTO.getRideOption();
clearMatchRideForCompany();
clearScreenMessage();
if (manageRideFormDTO.getMyCircleId() > 0) {
if (rideOption.equals("pending")) {
manageRideDTOs.addAll(ListOfValuesManager
.findPendingManageRide(manageRideFormDTO));
} else if (rideOption.equals("matchedPending")) {
manageRideDTOs.addAll(ListOfValuesManager
.findPendingMatchedManageRide(manageRideFormDTO));
} else if (rideOption.equals("completed")) {
manageRideDTOs.addAll(ListOfValuesManager
.findCompletedManageRide(manageRideFormDTO));
} else {
errorMessage
.add("Please select type of rides you want to search.");
}
} else {
errorMessage.add("Please select your circle.");
}
// manageRideFormDTO = new ManageRideFormDTO();
return "matchedTrip";
}
public void clearMatchRideForCompany() {
if (manageRideDTOs.size() > 0)
manageRideDTOs.clear();
}
public String matchRideCancel() {
if (matchRideCancelParam != null && matchRideCancelParam.length() > 0) {
String[] x1 = matchRideCancelParam.split("@");
for (String temp1 : x1) {
String x2[] = temp1.split("-");
if (x2.length >= 2) {
int rideId = Integer.parseInt(x2[0]);
String role = x2[1];
if (role.equalsIgnoreCase("giver")) {
rideRegistered = ListOfValuesManager
.getRideManagerPopupDataDirect("" + rideId);
cancleRideManager();
} else if (role.equalsIgnoreCase("taker")) {
rideSeekerDTO = ListOfValuesManager
.getRideSeekerData(rideId);
cancleRideSeeker();
}
}
}
}
matchRideCancelParam = "";
matchRideForCompany();
return "";
}
public String messageForLoginUser() {
allCircleOwnerManagerUserList = ListOfValuesManager
.getAllMessageForLoginUser(userRegistrationDTO.getId());
for (int i = 0; i < allCircleOwnerManagerUserList.size(); i++) {
UserRegistrationDTO dtoTemp = new UserRegistrationDTO();
dtoTemp.setId(allCircleOwnerManagerUserList.get(i).getUserid());
dtoTemp = ListOfValuesManager.getAverageRatingForUser(dtoTemp);
allCircleOwnerManagerUserList.get(i).setUserRating(
dtoTemp.getAverageRating());
}
allCircleMembershipInvitationList = ListOfValuesManager
.getAllCircleMembershipInvitation(userRegistrationDTO.getId());
allCircleAffiliationRequest = ListOfValuesManager
.getAllPendingAffiliatedCircle(userRegistrationDTO.getId());
allUnreadMessageList = ListOfValuesManager
.getAllUnreadMessage(userRegistrationDTO.getId());
allRideApprovalRequest = ListOfValuesManager
.findRideSeekerDetailsForApprove(userRegistrationDTO
.getEmail_id());
return "message";
}
public void confirmOrDeclineAffiliatedCircle() {
String confirm = null;
String decline = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
confirm = (String) requestMap.get("confirm");
decline = (String) requestMap.get("decline");
int circleId = 0;
String[] part = null;
if (requestMap.containsKey("circleAffiliation")) {
part = requestMap.get("circleAffiliation").split("-");
} else {
part = circleAffiliationsDTO.getCircleAffilicatedCircleId().split(
"-");
}
int affiliatedCircleId = 0;
if (part.length >= 2) {
if (part[0] != null && part[0].length() > 0
&& Integer.parseInt(part[0]) > 0) {
circleId = Integer.parseInt(part[0]);
}
if (part[1] != null && part[1].length() > 0
&& Integer.parseInt(part[1]) > 0) {
affiliatedCircleId = Integer.parseInt(part[1]);
}
}
clearScreenMessage();
if (circleId <= 0 || affiliatedCircleId <= 0) {
errorMessage
.add("Please select a Circle first and then select affiliated taxi circle.");
} else {
if (confirm != null) {
ListOfValuesManager.makeTaxiCircleAffiliatedActive(circleId,
affiliatedCircleId);
successMessage
.add("Selected taxi affiliated successfully with circle.");
} else if (decline != null) {
ListOfValuesManager.makeTaxiCircleAffiliatedInactive(circleId,
affiliatedCircleId);
successMessage
.add("Selected taxi un-affiliated successfully with circle.");
}
gatherDefaultcircleDTO();
messageForLoginUser();
}
}
public void confirmOrDeclineUser() {
String confirmByUser = null;
String confirmByAdmin = null;
String declineByUser = null;
String declineByAdmin = null;
String requestByUser = null;
String requestByAdmin = null;
String removedByUser = null;
String removedByAdmin = null;
/*
* String confirm = null; String decline = null; String declineByOwner =
* null;
*/
String circleOwnerCircleID = null;
String circleOwnerUserID = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
confirmByUser = (String) requestMap.get("confirmByUser");
confirmByAdmin = (String) requestMap.get("confirmByAdmin");
declineByUser = (String) requestMap.get("declineByUser");
declineByAdmin = (String) requestMap.get("declineByAdmin");
requestByUser = (String) requestMap.get("requestByUser");
requestByAdmin = (String) requestMap.get("requestByAdmin");
removedByUser = (String) requestMap.get("removedByUser");
removedByAdmin = (String) requestMap.get("removedByAdmin");
/*
* confirm = (String)requestMap.get("confirm"); decline =
* (String)requestMap.get("decline");
*/
circleOwnerCircleID = (String) requestMap.get("circleOwnerCircleID");
circleOwnerUserID = (String) requestMap.get("circleOwnerUserID");
/* declineByOwner = (String)requestMap.get("declinebyowner"); */
if (circleOwnerCircleID != null)
circleOwnerManagerDTO.setCircleID(circleOwnerCircleID);
if (circleOwnerUserID != null)
circleOwnerManagerDTO.setUserid(circleOwnerUserID);
// String requestBy = (String)requestMap.get("requestBy");
CircleMemberDTO dto = new CircleMemberDTO();
if (confirmByUser != null || confirmByAdmin != null) {
if (!Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO
.getCircleID()))
errorMessage.add("Please select Circle first.");
else if (!Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO
.getUserid()))
errorMessage.add("Please select Circle Member.");
else {
dto.setUserid(circleOwnerManagerDTO.getUserid());
dto.setCircleid(circleOwnerManagerDTO.getCircleID());
dto.setStatus("1");
}
}
if (declineByUser != null || declineByAdmin != null
|| removedByUser != null) {
if (!Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO
.getCircleID()))
errorMessage.add("Please select Circle first.");
else if (!Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO
.getUserid()))
errorMessage.add("Please select Circle Member.");
else {
dto.setUserid(circleOwnerManagerDTO.getUserid());
dto.setCircleid(circleOwnerManagerDTO.getCircleID());
dto.setStatus("2");
}
}
if (requestByUser != null) {
}
if (removedByAdmin != null) {
String[] parts = circleOwnerManagerDTO.getCombineUserAndCircleID()
.split(",");
if (!Validator.isNumberZeroNotAlloed(parts[0]))
errorMessage.add("Please select Circle then Circle Member.");
else if (parts.length < 3 || parts[1] == null
|| !Validator.isNumberZeroNotAlloed(parts[1]))
errorMessage.add("Please select Circle then Circle Member.");
else if (parts[0].equals(parts[2]))
errorMessage
.add("You are unauthorised to remove circle owner from circle.");
else {
String part1 = parts[0];
String part2 = parts[1];
dto.setUserid(part1);
dto.setCircleid(part2);
dto.setStatus("2");
}
}
/*
* if(declineByOwner!=null){ String[] parts =
* circleOwnerManagerDTO.getCombineUserAndCircleID().split(",");
* if(!Validator.isNumberZeroNotAlloed(parts[0]))
* errorMessage.add("Please select Circle first."); if(parts.length < 3
* || parts[1] == null || !Validator.isNumberZeroNotAlloed(parts[1]))
* errorMessage.add("Please select Circle Member.");
* if(parts[0].equals(parts[2])) errorMessage.add(
* "You are unauthorised to remove circle owner from circle.");
* if(errorMessage.size() == 0) { String part1 = parts[0]; String part2
* = parts[1]; dto.setUserid(part1); dto.setCircleid(part2);
* dto.setStatus("2"); } }
*
* if(confirm != null){
* if(!Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO
* .getCircleID())) errorMessage.add("Please select Circle first.");
* if(!
* Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO.getUserid()))
* errorMessage.add("Please select Circle Member.");
* dto.setUserid(circleOwnerManagerDTO.getUserid());
* dto.setCircleid(circleOwnerManagerDTO.getCircleID());
* dto.setStatus("1"); }
*
* if(decline != null){
* if(!Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO
* .getCircleID())) errorMessage.add("Please select Circle first.");
* if(!
* Validator.isNumberZeroNotAlloed(circleOwnerManagerDTO.getUserid()))
* errorMessage.add("Please select Circle Member.");
* dto.setUserid(circleOwnerManagerDTO.getUserid());
* dto.setCircleid(circleOwnerManagerDTO.getCircleID());
* dto.setStatus("2"); }
*/
if (errorMessage.size() == 0) {
Connection con = (Connection) ListOfValuesManager
.getBroadConnection();
try {
CircleOwnerDTO circleOwnerDTO = new CircleOwnerDTO();
circleOwnerDTO.setCircleID(String.valueOf(dto.getCircleid()));
circleOwnerDTO.setUserID(dto.getUserid());
/*
* if(declineByOwner != null ) { circleOwnerDTO =
* ListOfValuesManager.updateRegisterCircleOwner(circleOwnerDTO,
* userRegistrationDTO.getId(), con); dto =
* ListOfValuesManager.getConfirmOrDeclineUser(dto,
* userRegistrationDTO.getId(), con); }
*
* if(confirm!= null || decline != null) dto =
* ListOfValuesManager.getConfirmOrDeclineUser(dto,
* userRegistrationDTO.getId(), con);
*/
if (confirmByUser != null || declineByUser != null
|| requestByUser != null || requestByAdmin != null
|| removedByUser != null || removedByAdmin != null) {
dto = ListOfValuesManager.getConfirmOrDeclineUser(dto,
userRegistrationDTO.getId(), con);
} else if (confirmByAdmin != null || declineByAdmin != null) {
circleOwnerDTO = ListOfValuesManager
.updateRegisterCircleOwner(circleOwnerDTO,
userRegistrationDTO.getId(), con);
dto = ListOfValuesManager.getConfirmOrDeclineUser(dto,
userRegistrationDTO.getId(), con);
}
userMessageDTO = new MessageBoardDTO();
// fetch circle name from db.
if (confirmByUser != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO
.setMessage("User "
+ userRegistrationDTO.getFirst_name()
+ " has accepted your invitation to join your circle "
+ dtoTemp.getName() + ".");
userMessageDTO.setToMember(dtoTemp
.getCircleOwner_Member_Id_P());
successMessage.add("Invitation accepted successfully.");
}
if (confirmByAdmin != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("Admin of circle "
+ dtoTemp.getName()
+ " has accepted your request to join the circle.");
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserid()));
successMessage.add("User added to circle successfully.");
}
if (declineByUser != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("User "
+ userRegistrationDTO.getFirst_name()
+ " has declined to join your circle "
+ dtoTemp.getName() + ".");
userMessageDTO.setToMember(dtoTemp
.getCircleOwner_Member_Id_P());
successMessage.add("Invitation rejected successfully.");
}
if (declineByAdmin != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("Admin of circle "
+ dtoTemp.getName()
+ " has declined your request to join the circle.");
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserid()));
successMessage.add("Request rejected successfully.");
}
if (requestByUser != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("User "
+ userRegistrationDTO.getFirst_name()
+ " has sent a request to join "
+ dtoTemp.getName() + " circle.");
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserid()));
successMessage
.add("Your request has been sent to the admin successfully.");
}
if (requestByAdmin != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("Admin of circle "
+ dtoTemp.getName()
+ " has invited you to join the circle.");
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserid()));
successMessage
.add("Your invitation has been sent to the user.");
}
if (removedByUser != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("User "
+ userRegistrationDTO.getFirst_name()
+ " has left " + dtoTemp.getName() + " circle.");
userMessageDTO.setToMember(dtoTemp
.getCircleOwner_Member_Id_P());
successMessage
.add("You have left the circle successfully.");
}
if (removedByAdmin != null) {
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(Integer.parseInt(dto
.getCircleid()));
userMessageDTO.setMessage("Admin of circle "
+ dtoTemp.getName()
+ " has removed you from the circle.");
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserid()));
successMessage
.add("User removed from the circle successfully.");
}
/*
* //check point for message if(declineByOwner != null ) {
* CircleDTO dtoTemp =
* ListOfValuesManager.getCircleDtoByCircleId
* (Integer.parseInt(dto.getCircleid()));
* userMessageDTO.setMessage("Admin of circle "+
* dtoTemp.getName()
* +" has declined your request to join the circle.");
* userMessageDTO
* .setToMember(Integer.parseInt(dto.getUserid())); }
*
* if(confirm != null){ CircleDTO dtoTemp =
* ListOfValuesManager.getCircleDtoByCircleId
* (Integer.parseInt(dto.getCircleid()));
* userMessageDTO.setMessage
* ("User "+userRegistrationDTO.getFirst_name
* ()+" has accepted your invitation to join your circle "+
* dtoTemp.getName() +".");
* userMessageDTO.setToMember(dtoTemp.getCircleOwner_Member_Id_P
* ()); } if(decline != null){ CircleDTO dtoTemp =
* ListOfValuesManager
* .getCircleDtoByCircleId(Integer.parseInt(dto.getCircleid()));
* userMessageDTO
* .setMessage("User "+userRegistrationDTO.getFirst_name
* ()+" has declined to join your circle "+ dtoTemp.getName()
* +".");
* userMessageDTO.setToMember(dtoTemp.getCircleOwner_Member_Id_P
* ()); }
*/
userMessageDTO.setMessageChannel("M");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
errorMessage
.add("There is some problem in adding user to circle.");
successMessage.clear();
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
messageForLoginUser();
// allCircleForLoginUser();
memberForSelectedCircle();
List<CircleOwnerManagerDTO> allCircleMemberForLoginUserList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
if (allCircleMemberForLoginUserList.get(i).getCircleID()
.equals(dto.getCircleid())) {
CircleOwnerManagerDTO dto1 = new CircleOwnerManagerDTO();
dto1 = allCircleMemberForLoginUserList.get(i);
allCircleMemberForLoginUserList1.add(dto1);
}
}
allCircleMemberForLoginUserList.clear();
allCircleMemberForLoginUserList
.addAll(allCircleMemberForLoginUserList1);
allCircleMemberForLoginUserList1.clear();
List<CircleOwnerManagerDTO> allPendingCircleMemberList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allPendingCircleMemberList.size(); i++) {
if (allPendingCircleMemberList.get(i).getCircleID()
.equals(dto.getCircleid())) {
CircleOwnerManagerDTO dto1 = new CircleOwnerManagerDTO();
dto1 = allPendingCircleMemberList.get(i);
allPendingCircleMemberList1.add(dto1);
}
}
allPendingCircleMemberList.clear();
allPendingCircleMemberList.addAll(allPendingCircleMemberList1);
allPendingCircleMemberList1.clear();
// circleDTO = new CircleDTO();
forregistrationOnly = new UserRegistrationDTO();
}
// return "confirm";
}
public void approveOrRejectRide() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
String approve = (String) requestMap.get("approve");
String decline = (String) requestMap.get("decline");
String seekerId = (String) requestMap.get("seekerId");
String newStatus = "";
RideSeekerDTO dtoTemp = new RideSeekerDTO();
if (approve != null) {
for (RideSeekerDTO dto : allRideApprovalRequest) {
if (dto.getSeekerID().equals(seekerId)
&& dto.getFirstApproverEmailId().equals(
userRegistrationDTO.getEmail_id())) {
newStatus = "O";
if (Validator.isEmpty(dto.getSecondApproverEmailId())) {
newStatus = "A";
}
dtoTemp = dto;
break;
} else if (dto.getSeekerID().equals(seekerId)
&& dto.getSecondApproverEmailId().equals(
userRegistrationDTO.getEmail_id())) {
newStatus = "A";
dtoTemp = dto;
break;
}
}
} else if (decline != null) {
for (RideSeekerDTO dto : allRideApprovalRequest) {
if (dto.getSeekerID().equals(seekerId)) {
newStatus = "I";
dtoTemp = dto;
break;
}
}
}
if (!Validator.isEmpty(newStatus)) {
ListOfValuesManager.changeStatus(Integer.parseInt(seekerId),
newStatus);
ApproverDTO dto = ListOfValuesManager.findApproverById(dtoTemp
.getApproverID());
frequencyDTO = ListOfValuesManager.fetchFrequencyListForRideSeeker(
dtoTemp.getSeekerID()).get(0);
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ dto.getbCode()
+ "<br>Name: "
+ dtoTemp.getUserName()
+ "<br>Request ID: "
+ dtoTemp.getSeekerID()
+ "<br>From: "
+ dtoTemp.getFromAddress1()
+ "<br>To: "
+ dtoTemp.getToAddress1()
+ "<br>Date Time: "
+ dtoTemp.getStartdateValue()
+ "<br>Frequency: "
+ frequencyDTO.getFrequency().toString();
if (newStatus.equalsIgnoreCase("O")) {
String approveLink = Messages.getValue(
"ride.approve",
new Object[] { dtoTemp.getSeekerID(),
URLEncoder.encode(dto.getVerificationCode2()),
dto.getId(), dto.getHoponId2() });
String rejectLink = Messages.getValue(
"ride.reject",
new Object[] { dtoTemp.getSeekerID(),
URLEncoder.encode(dto.getVerificationCode2()),
dto.getId(), dto.getHoponId2() });
if (!Validator.isEmpty(dtoTemp.getSecondApproverEmailId())) {
messageContent += "<br> " + approveLink + " "
+ rejectLink;
if (ListOfValuesManager.testEmail(dtoTemp
.getSecondApproverEmailId())) {
UserRegistrationDTO userTemp = null;
userTemp = ListOfValuesManager.findUserByEmail(dtoTemp
.getSecondApproverEmailId());
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO
.setEmailSubject("Ride Request for Approval");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.msgBoard",
new Object[] { dto.getbCode(),
dtoTemp.getSeekerID(),
dtoTemp.getUserName(),
dtoTemp.getFromAddress1(),
dtoTemp.getToAddress1(),
dtoTemp.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"ride.option.sms",
new Object[] {
dto.getbCode(),
dtoTemp.getSeekerID(),
dtoTemp.getUserName(),
dtoTemp.getFromAddress1()
.substring(
0,
(dtoTemp.getFromAddress1()
.length() >= 20) ? 20
: dtoTemp
.getFromAddress1()
.length()),
dtoTemp.getToAddress1()
.substring(
0,
(dtoTemp.getToAddress1()
.length() >= 20) ? 20
: dtoTemp
.getToAddress1()
.length()),
dtoTemp.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
EmailDTO emaildto = new EmailDTO();
emaildto.setReceiverEmailId(dto.getHoponId2());
emaildto.setSubject("Ride Request for Approval");
emaildto.setEmailTemplateBody(Messages.getValue(
"email.template2", new Object[] { "", "",
messageContent, "", "", "", "" }));
MailService.sendMail(emaildto);
}
}
} else if (newStatus.equalsIgnoreCase("A")) {
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO.setEmailSubject("Ride request approved");
userMessageDTO.setMessageChannel("E");
userMessageDTO
.setToMember(Integer.parseInt(dtoTemp.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.approved",
new Object[] { dto.getbCode(), dtoTemp.getSeekerID(),
dtoTemp.getUserName(),
dtoTemp.getFromAddress1(),
dtoTemp.getToAddress1(),
dtoTemp.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO
.setToMember(Integer.parseInt(dtoTemp.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.approved",
new Object[] { dto.getbCode(), dtoTemp.getSeekerID(),
dtoTemp.getUserName(),
dtoTemp.getFromAddress1(),
dtoTemp.getToAddress1(),
dtoTemp.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO
.setToMember(Integer.parseInt(dtoTemp.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else if (newStatus.equalsIgnoreCase("I")) {
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO.setEmailSubject("Ride request rejected");
userMessageDTO.setMessageChannel("E");
userMessageDTO
.setToMember(Integer.parseInt(dtoTemp.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.rejected",
new Object[] { dto.getbCode(), dtoTemp.getSeekerID(),
dtoTemp.getUserName(),
dtoTemp.getFromAddress1(),
dtoTemp.getToAddress1(),
dtoTemp.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO
.setToMember(Integer.parseInt(dtoTemp.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.rejected",
new Object[] { dto.getbCode(), dtoTemp.getSeekerID(),
dtoTemp.getUserName(),
dtoTemp.getFromAddress1(),
dtoTemp.getToAddress1(),
dtoTemp.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO
.setToMember(Integer.parseInt(dtoTemp.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
messageForLoginUser();
}
public String vehicleList() {
vehicleMasterDTOList = ListOfValuesManager
.getAllVehicleList(userRegistrationDTO.getId());
vehicleMasterDataModel = new VehicleMasterDataTable(
vehicleMasterDTOList);
return "vehicle";
}
public void vehicleDefaultUpdate(AjaxBehaviorEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
String vehicleID = (String) requestMap.get("vehicleID");
vehicleMasterDTO.setVehicleID(vehicleID);
vehicleMasterDTO.setUserID(userRegistrationDTO.getId());
vehicleMasterDTO = ListOfValuesManager
.getUpdateVehicleDefault(vehicleMasterDTO);
rollbackTest = false;
vehicleMasterDTO = new VehicleMasterDTO();
vehicleList();
getAllVehicleList();
}
public String cancleRideManager() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
try {
rideRegistered.setStatus("I");// rideRegistered.setStatus("0");rideRegistered.setStatus("I");
rideRegistered = ListOfValuesManager.getCancleRide(rideRegistered,
con);
ListOfValuesManager.changePoolRequestStatusForRideGiver(con,
Integer.parseInt(rideRegistered.getRideID()));
rideRegistered = ListOfValuesManager
.getRideManagerPopupDataDirect(rideRegistered.getRideID());
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto = ListOfValuesManager.findDriverDtoByRideId(
rideRegistered.getRideID(), con);
UserRegistrationDTO userDtoRide = new UserRegistrationDTO();
userDtoRide = ListOfValuesManager.getUserById(Integer
.parseInt(rideRegistered.getUserID()));
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel.driver.admin",
new Object[] {
userDto.getFirst_name(),
rideRegistered.getRideID(),
(rideRegistered.getFromAddress1().length() > 25) ? rideRegistered
.getFromAddress1().substring(0, 25)
: rideRegistered.getFromAddress1(),
(rideRegistered.getToAddress1().length() > 25) ? rideRegistered
.getToAddress1().substring(0, 25)
: rideRegistered.getToAddress1(),
rideRegistered.getStartdateValue() }));
userMessageDTO.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideRegistered
.getRideID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue("subject.cancel",
new Object[] { rideRegistered.getStartdateValue() }));
userMessageDTO.setMessage(Messages.getValue(
"ridegiver.driver.cancel",
new Object[] { userDto.getFirst_name(),
rideRegistered.getRideID(),
rideRegistered.getFromAddress1(),
rideRegistered.getToAddress1(),
rideRegistered.getStartdateValue(),
userDtoRide.getMobile_no() }));
userMessageDTO.setToMember(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideRegistered
.getRideID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
allSeekerForGivenRide = ListOfValuesManager
.getAllRideSeekerForAGivenRide(rideRegistered.getRideID());
if (allSeekerForGivenRide.size() > 0) {
for (int index = 0; index < allSeekerForGivenRide.size(); index++) {
String id = allSeekerForGivenRide.get(index).getSeekerID();
rideSeekerDTO.setStatus("I");
rideSeekerDTO.setSeekerID(id);
rideSeekerDTO = ListOfValuesManager.getCancleRideSeeker(
rideSeekerDTO, con);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel.passenger.admin",
new Object[] {
allSeekerForGivenRide.get(index)
.getUserName(),
rideRegistered.getRideID(),
(allSeekerForGivenRide.get(index)
.getFromAddress1().length() > 25) ? allSeekerForGivenRide
.get(index)
.getFromAddress1()
.substring(0, 25)
: allSeekerForGivenRide
.get(index)
.getFromAddress1(),
(allSeekerForGivenRide.get(index)
.getToAddress1().length() > 25) ? allSeekerForGivenRide
.get(index).getToAddress1()
.substring(0, 25)
: allSeekerForGivenRide
.get(index)
.getToAddress1(),
allSeekerForGivenRide.get(index)
.getStartdateValue(),
userRegistrationDTO.getMobile_no() }));
userMessageDTO.setToMember(Integer
.parseInt(allSeekerForGivenRide.get(index)
.getUserID()));
userMessageDTO.setRideId(Integer
.parseInt(allSeekerForGivenRide.get(index)
.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { allSeekerForGivenRide.get(index)
.getStartdateValue() }));
userMessageDTO.setMessage(Messages.getValue(
"ridegiver.seeker.cancel",
new Object[] {
allSeekerForGivenRide.get(index)
.getUserName(),
rideRegistered.getRideID(),
allSeekerForGivenRide.get(index)
.getFromAddress1(),
allSeekerForGivenRide.get(index)
.getToAddress1(),
allSeekerForGivenRide.get(index)
.getStartdateValue(), }));
userMessageDTO.setToMember(Integer
.parseInt(allSeekerForGivenRide.get(index)
.getUserID()));
userMessageDTO.setRideId(Integer
.parseInt(allSeekerForGivenRide.get(index)
.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
rideManagementList();
userMessageDTO = new MessageBoardDTO();
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
}
rollbackTest = false;
return "cancle";
}
public String cancleRideSeeker() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
try {
rideSeekerDTO.setStatus("I");
rideSeekerDTO = ListOfValuesManager.getCancleRideSeeker(
rideSeekerDTO, con);
ListOfValuesManager.changePoolRequestStatusForRideGiver(con,
Integer.parseInt(rideSeekerDTO.getSeekerID()));
rideSeekerDTO = ListOfValuesManager.getRideSeekerData(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
try {
Date d1 = ApplicationUtil.dateFormat1.parse(rideSeekerDTO
.getStartdateValue());
Date d2 = ApplicationUtil.dateFormat3.parse(ApplicationUtil
.currentTimeStamp());
long minuteDiff = ((d2.getTime() - d1.getTime()) / (60 * 60 * 1000));
if (minuteDiff > 60) {
PaymentTxnsDTO paymentTxnsDTO = new PaymentTxnsDTO();
paymentTxnsDTO.setUpdatedBy(Integer
.parseInt(userRegistrationDTO.getId()));
paymentTxnsDTO.setSeekerId(Integer.parseInt(rideRegistered
.getRideID()));
paymentTxnsDTO.setFromPayer(100);
paymentTxnsDTO.setToPayee(Integer
.parseInt(userRegistrationDTO.getId()));
ListOfValuesManager.paymentTxnCancel(paymentTxnsDTO, con);
}
} catch (ParseException ex) {
LoggerSingleton.getInstance().error("Date parse exception");
}
if (rideSeekerDTO.getIsResult().equalsIgnoreCase("N")) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideSeekerDTO.getStartdateValue() }));
userMessageDTO.setMessage(Messages.getValue(
"rideSeeker.unmatched.cancel",
new Object[] { userRegistrationDTO.getFirst_name(),
rideSeekerDTO.getSeekerID(),
rideSeekerDTO.getFromAddress1(),
rideSeekerDTO.getToAddress1(),
rideSeekerDTO.getStartdateValue() }));
userMessageDTO.setToMember(Integer.parseInt(rideSeekerDTO
.getUserID()));
userMessageDTO.setRideId(Integer.parseInt(rideSeekerDTO
.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.rideSeeker.unmatched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
rideSeekerDTO.getSeekerID(),
(rideSeekerDTO
.getFromAddress1()
.length() > 25) ? rideSeekerDTO
.getFromAddress1()
.substring(0, 25)
: rideSeekerDTO
.getFromAddress1(),
(rideSeekerDTO.getToAddress1()
.length() > 25) ? rideSeekerDTO
.getToAddress1()
.substring(0, 25)
: rideSeekerDTO
.getToAddress1(),
rideSeekerDTO
.getStartdateValue() }));
userMessageDTO.setToMember(Integer.parseInt(rideSeekerDTO
.getUserID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel",
new Object[] {
userRegistrationDTO.getFirst_name(),
(rideSeekerDTO.getFromAddress1()
.length() > 25) ? rideSeekerDTO
.getFromAddress1().substring(0,
25) : rideSeekerDTO
.getFromAddress1(),
(rideSeekerDTO.getToAddress1().length() > 25) ? rideSeekerDTO
.getToAddress1().substring(0,
25) : rideSeekerDTO
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userRegistrationDTO.getMobile_no(),
rideSeekerDTO.getRideMatchRideId() }));
userMessageDTO.setToMember(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideSeekerDTO
.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideSeekerDTO.getStartdateValue() }));
userMessageDTO.setMessage(Messages.getValue(
"rideSeeker.matched.cancel",
new Object[] { userRegistrationDTO.getFirst_name(),
rideSeekerDTO.getRideMatchRideId(),
rideSeekerDTO.getFromAddress1(),
rideSeekerDTO.getToAddress1(),
rideSeekerDTO.getStartdateValue() }));
userMessageDTO.setToMember(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideSeekerDTO
.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
/* Now message should go to driver. */
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto = ListOfValuesManager.findDriverDtoByRideId(
rideSeekerDTO.getRideMatchRideId(), con);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel.driver",
new Object[] {
userDto.getFirst_name(),
userRegistrationDTO.getFirst_name(),
rideSeekerDTO.getRideMatchRideId(),
(rideSeekerDTO.getFromAddress1()
.length() > 25) ? rideSeekerDTO
.getFromAddress1().substring(0,
25) : rideSeekerDTO
.getFromAddress1(),
(rideSeekerDTO.getToAddress1().length() > 25) ? rideSeekerDTO
.getToAddress1().substring(0,
25) : rideSeekerDTO
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userRegistrationDTO.getMobile_no() }));
userMessageDTO.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideSeekerDTO
.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideSeekerDTO.getStartdateValue() }));
userMessageDTO.setMessage(Messages.getValue(
"driver.match.cancel",
new Object[] { userDto.getFirst_name(),
userRegistrationDTO.getFirst_name(),
rideSeekerDTO.getRideMatchRideId(),
rideSeekerDTO.getFromAddress1(),
rideSeekerDTO.getToAddress1(),
rideSeekerDTO.getStartdateValue(),
userDto.getMobile_no(),
Messages.getValue("customer.support") }));
userMessageDTO.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer.parseInt(rideSeekerDTO
.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
userMessageDTO = new MessageBoardDTO();
if (rideSeekerDTO.getRecurring().equalsIgnoreCase("Y")
&& this.allowRecurringSubRideToCancel) {
String[] rides = rideSeekerDTO.getSubSeekers().split(",");
if (rides.length > 0) {
rideSeekerDTO.setStatus("I");
rideSeekerDTO = ListOfValuesManager.cancelSubSeekers(con,
rideSeekerDTO);
rides = rideSeekerDTO.getSubSeekers().split(",");
for (int i = 0; i < rides.length; i++) {
ListOfValuesManager
.changePoolRequestStatusForRideGiver(con,
Integer.parseInt(rides[i]));
rideSeekerDTO = ListOfValuesManager
.getRideSeekerData(Integer.parseInt(rides[i]));
if (rideSeekerDTO.getIsResult().equalsIgnoreCase("N")) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideSeekerDTO
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"rideSeeker.unmatched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
rideSeekerDTO
.getSeekerID(),
rideSeekerDTO
.getFromAddress1(),
rideSeekerDTO
.getToAddress1(),
rideSeekerDTO
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(rideSeekerDTO.getUserID()));
userMessageDTO.setRideId(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.rideSeeker.unmatched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
rideSeekerDTO
.getSeekerID(),
(rideSeekerDTO
.getFromAddress1()
.length() > 25) ? rideSeekerDTO
.getFromAddress1()
.substring(
0,
25)
: rideSeekerDTO
.getFromAddress1(),
(rideSeekerDTO
.getToAddress1()
.length() > 25) ? rideSeekerDTO
.getToAddress1()
.substring(
0,
25)
: rideSeekerDTO
.getToAddress1(),
rideSeekerDTO
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(rideSeekerDTO.getUserID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
(rideSeekerDTO
.getFromAddress1()
.length() > 25) ? rideSeekerDTO
.getFromAddress1()
.substring(
0,
25)
: rideSeekerDTO
.getFromAddress1(),
(rideSeekerDTO
.getToAddress1()
.length() > 25) ? rideSeekerDTO
.getToAddress1()
.substring(
0,
25)
: rideSeekerDTO
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userRegistrationDTO
.getMobile_no(),
rideSeekerDTO
.getRideMatchRideId() }));
userMessageDTO.setToMember(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setRideId(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideSeekerDTO
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"rideSeeker.matched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
rideSeekerDTO
.getRideMatchRideId(),
rideSeekerDTO
.getFromAddress1(),
rideSeekerDTO
.getToAddress1(),
rideSeekerDTO
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setRideId(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
/* Now message should go to driver. */
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto = ListOfValuesManager
.findDriverDtoByRideId(
rideSeekerDTO.getRideMatchRideId(),
con);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel.driver",
new Object[] {
userDto.getFirst_name(),
userRegistrationDTO
.getFirst_name(),
rideSeekerDTO
.getRideMatchRideId(),
(rideSeekerDTO
.getFromAddress1()
.length() > 25) ? rideSeekerDTO
.getFromAddress1()
.substring(0, 25)
: rideSeekerDTO
.getFromAddress1(),
(rideSeekerDTO
.getToAddress1()
.length() > 25) ? rideSeekerDTO
.getToAddress1()
.substring(0, 25)
: rideSeekerDTO
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userRegistrationDTO
.getMobile_no() }));
userMessageDTO.setToMember(Integer.parseInt(userDto
.getId()));
userMessageDTO.setRideId(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { rideSeekerDTO
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"driver.match.cancel",
new Object[] {
userDto.getFirst_name(),
userRegistrationDTO
.getFirst_name(),
rideSeekerDTO
.getRideMatchRideId(),
rideSeekerDTO
.getFromAddress1(),
rideSeekerDTO
.getToAddress1(),
rideSeekerDTO
.getStartdateValue(),
userDto.getMobile_no(),
Messages.getValue("customer.support") }));
userMessageDTO.setToMember(Integer.parseInt(userDto
.getId()));
userMessageDTO.setRideId(Integer
.parseInt(rideSeekerDTO.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
}
}
rideManagementList();
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
}
rollbackTest = false;
return "cancle";
}
public void forgotPassword() {
String emailTest = ListOfValuesManager.testEmailAllStatus(userName);
clearScreenMessage();
if (emailTest.equalsIgnoreCase("A")) {
String tempPassword = ServerUtility.randomString(10);
forregistrationOnly = ListOfValuesManager.getForgotPassword(
userName, tempPassword, userRegistrationDTO.getId());
successMessage
.add("A new password has been sent to your email id.");
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages
.getValue("subject.forgot.password"));
userMessageDTO.setMessage(Messages.getValue(
"body.forgot.password",
new Object[] { userName, tempPassword,
forregistrationOnly.getFirst_name() }));
userMessageDTO.setToMember(Integer.parseInt(forregistrationOnly
.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"sms.forgot.password",
new Object[] { userName, tempPassword,
forregistrationOnly.getFirst_name() }));
userMessageDTO.setToMember(Integer.parseInt(forregistrationOnly
.getId()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
/*
* LoginPageDTO dto = new LoginPageDTO(); PageStoreDTO pageDto =
* ListOfValuesManager.getPageStoreByCode("changePassword");
* dto.setUserId
* (Integer.parseInt(forregistrationOnly.getId()));dto.setPageId
* (pageDto.getPageId()); dto.setStatus("N");
* ListOfValuesManager.insertLoginPage(dto);
*/
} else {
if (emailTest.equalsIgnoreCase("P"))
errorMessage.add("Email ID is pending for approval.");
else if (emailTest.equalsIgnoreCase("I"))
errorMessage
.add("Email ID de activated. Please contact admin.");
else
errorMessage.add("Email ID does not exist in database.");
}
userMessageDTO = new MessageBoardDTO();
}
public void rateAndWriteNotes() {
String taker = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
taker = (String) requestMap.get("taker");
if (taker == null) {
taker = "giver";
}
clearScreenMessage();
poolRequestsDTO.setMasterControl(taker);
poolRequestsDTO = ListOfValuesManager
.getRateAndWriteNotes(poolRequestsDTO);
successMessage.add("Ride successfully rated.");
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue("subject.rate.ride"));
userMessageDTO.setMessage(Messages.getValue("body.rate.ride",
new Object[] { userRegistrationDTO.getFirst_name(),
poolRequestsDTO.getRateRideGiver() }));
userMessageDTO.setToMember(Integer.parseInt(poolRequestsDTO
.getUser_id()));
if (poolRequestsDTO.getRideSeekerID() != null)
userMessageDTO.setRideId(Integer.parseInt(poolRequestsDTO
.getRideSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager.getInsertedMessage(userMessageDTO);
rollbackTest = false;
userMessageDTO = new MessageBoardDTO();
allCompleateRideList();
// return "notes";
}
public String getcurrentDate() {
// DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern4);
Calendar cal = Calendar.getInstance();
String date = dateFormat.format(cal.getTime());
return date;
}
public void declineCircle() {
circleDTO = ListOfValuesManager.getDeclineCircle(circleDTO,
userRegistrationDTO);
rollbackTest = false;
allListedCircle();
allCircleForLoginUser();
circleDTO = new CircleDTO();
// return "decline";
}
public void findCircleByName() {
allCircleListByName = ListOfValuesManager.getCircleByName(
circleDTO.getName(), userRegistrationDTO.getId());
forregistrationOnly.setMyCircle(circleDTO.getName());
circleDTO = new CircleDTO();
}
public String findListofCompanyForLoginUser() {
listofCompanyForLoginUser = ListOfValuesManager
.getListofCompanyForLoginUser(userRegistrationDTO.getId());
if (listofCompanyForLoginUser.size() > 0) {
companyRegisterDTO = listofCompanyForLoginUser.get(0);
} else {
companyRegisterDTO = new CompanyRegisterDTO();
}
return "companyList";
}
public String showEditCompanyPage() {
return "page";
}
public void changePassword() {
clearScreenMessage();
setRedirectUri("");
if (userRegistrationDTO.getOldPassword() != null) {
if (userRegistrationDTO.getPassword().equals(
userRegistrationDTO.getOldPassword())) {
userRegistrationDTO.setPassword(userRegistrationDTO
.getRepassword1());
CityDTO cityDto = ListOfValuesManager.getCity(
userRegistrationDTO.getCity(),
userRegistrationDTO.getState());
userRegistrationDTO.setCityId(cityDto.getCityId());
try {
userRegistrationDTO = ListOfValuesManager
.getUpdateUserPassword(userRegistrationDTO,
userRegistrationDTO.getId(), null);
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue("password.changed",
new Object[] { userRegistrationDTO.getPassword() }));
userMessageDTO.setToMember(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setEmailSubject(Messages
.getValue("subject.password.changed"));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
successMessage.add(Messages.getValue("success.update",
new Object[] { "Password" }));
userMessageDTO = new MessageBoardDTO();
List<LoginPageDTO> dtos = new ArrayList<LoginPageDTO>();
dtos.addAll(ListOfValuesManager.getLoginPagesByUserId(Integer
.parseInt(userRegistrationDTO.getId())));
for (LoginPageDTO dto : dtos) {
if (dto.getPageCode().equalsIgnoreCase(
Messages.getValue("page.code.change.password")
.trim())) {
ListOfValuesManager.inactiveLoginPageByUserId(
dto.getUserId(), dto.getPageId());
}
}
for (LoginPageDTO dto : dtos) {
if (dto.getPageCode().equalsIgnoreCase(
Messages.getValue("page.code.preference").trim())) {
redirectUri = dto.getPageURL();
}
}
} else {
userRegistrationDTO.setOldPassword("Fault");
errorMessage.add(Messages.getValue("password.mismatch"));
}
userRegistrationDTO.setOldPassword(null);
} else {
errorMessage.add(Messages.getValue("error.required",
new Object[] { "Password" }));
}
}
public void editUserInformation() {
clearScreenMessage();
userRegistrationDTO.setMobile_no(userRegistrationDTO.getMobile_no()
.replaceFirst("^[0|+]*", ""));
if (Validator.isEmpty(userRegistrationDTO.getFirst_name())) {
errorMessage.add("Please enter first name.");
}
if (Validator.isEmpty(userRegistrationDTO.getMobile_no())) {
errorMessage.add("Please enter Mobile Number.");
}
if (Validator.isNotNumber(userRegistrationDTO.getMobile_no())
|| userRegistrationDTO.getMobile_no().length() != 10) {
errorMessage.add("Mobile Number is not proper.");
}
if (ListOfValuesManager.testOtherUniqueMobileNumber(
userRegistrationDTO.getMobile_no(),
Integer.parseInt(userRegistrationDTO.getId()))) {
errorMessage
.add("Mobile Number is alrady registered. Please enter another mobile number.");
}
if (Validator.isEmpty(userRegistrationDTO.getAddress())) {
errorMessage.add("Please enter address.");
}
if (Validator.isEmpty(userRegistrationDTO.getTravel())) {
errorMessage.add("Please select travel type.");
}
if (!(userRegistrationDTO.getTravel().equals("C")
|| userRegistrationDTO.getTravel().equals("P")
|| userRegistrationDTO.getTravel().equals("B") || userRegistrationDTO
.getTravel().equals("T"))) {
errorMessage.add("Please select proper travel type.");
}
if (errorMessage.size() == 0) {
Connection con = (Connection) ListOfValuesManager
.getBroadConnection();
try {
CityDTO cityDto = ListOfValuesManager.getCity(
userRegistrationDTO.getCity(),
userRegistrationDTO.getState());
userRegistrationDTO.setCityId(cityDto.getCityId());
userRegistrationDTO = ListOfValuesManager.getUpdateUser(
userRegistrationDTO, userRegistrationDTO.getId(), con);
successMessage.add(Messages.getValue("success.update",
new Object[] { "User Preferences" }));
userPreferences.setUserId(Integer.parseInt(userRegistrationDTO
.getId()));
String[] minuteSlice = userRegistrationDTO
.getDefaultTimeSlice().split(":");
if (minuteSlice.length > 1) {
int minuteCount = Integer.parseInt(minuteSlice[0]) * 60; // convert
// hour
// to
// minute
minuteCount += Integer.parseInt(minuteSlice[1]);
userPreferences.setMaxWaitTime(minuteCount);
}
userPreferences = ListOfValuesManager.getUserPreferencesEdit(
userPreferences, con);
List<LoginPageDTO> dtos = new ArrayList<LoginPageDTO>();
dtos.addAll(ListOfValuesManager.getLoginPagesByUserId(Integer
.parseInt(userRegistrationDTO.getId())));
for (LoginPageDTO dto : dtos) {
if (dto.getPageCode().equalsIgnoreCase(
Messages.getValue("page.code.preference").trim())) {
ListOfValuesManager.inactiveLoginPageByUserId(
dto.getUserId(), dto.getPageId());
}
}
rollbackTest = false;
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
errorMessage.add(Messages.getValue("error.db2",
new Object[] { "User" }));
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
}
if (errorMessage.size() > 0) {
UserRegistrationDTO userTemp = ListOfValuesManager
.getUserById(Integer.parseInt(userRegistrationDTO.getId()));
userRegistrationDTO.setFirst_name(userTemp.getFirst_name());
userRegistrationDTO.setLast_name(userTemp.getLast_name());
userRegistrationDTO.setAddress(userTemp.getAddress());
userRegistrationDTO.setCity(userTemp.getCity());
userRegistrationDTO.setCityId(userTemp.getCityId());
userRegistrationDTO.setState(userTemp.getState());
userRegistrationDTO.setCountry(userTemp.getCountry());
userRegistrationDTO.setLatitude(userTemp.getLatitude());
userRegistrationDTO.setLongitude(userTemp.getLongitude());
userRegistrationDTO.setPincode(userTemp.getPincode());
userRegistrationDTO.setMobile_no(userTemp.getMobile_no());
successMessage.clear();
}
userMessageDTO = new MessageBoardDTO();
this.setRecurring(false);
// return "editInformation";
}
public void joinCircle() {
clearScreenMessage();
circleMemberDTO.setCircleid(String.valueOf(circleDTO.getCircleID()));
circleMemberDTO.setUserid(userRegistrationDTO.getId());
circleMemberDTO.setRequestUserId(userRegistrationDTO.getId());
String ctype = (String.valueOf(circleDTO.getCircleType()));
String ttype = (String.valueOf(userRegistrationDTO.getTravel()));
try {
if (ListOfValuesManager.testSingleCircleMember(circleMemberDTO,
userRegistrationDTO.getId(), ctype, ttype)) {
circleMemberDTO = ListOfValuesManager.getJoinCircle(
circleMemberDTO, userRegistrationDTO.getId(), null);
// allCircleListByName =
// ListOfValuesManager.getCircleByName("",userRegistrationDTO.getId());
allCircleListByName = ListOfValuesManager.getCircleByName(
forregistrationOnly.getMyCircle(),
userRegistrationDTO.getId());
CircleDTO dtoTemp = ListOfValuesManager
.getCircleDtoByCircleId(circleDTO.getCircleID());
userMessageDTO.setMessage("User "
+ userRegistrationDTO.getFirst_name()
+ " has sent a request to join " + dtoTemp.getName()
+ " circle.");
userMessageDTO
.setToMember(dtoTemp.getCircleOwner_Member_Id_P());
userMessageDTO.setMessageChannel("M");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
successMessage.add("You joined circle successfully.");
} else {
errorMessage
.add("You do not have permission to join this circle.");
}
} catch (ConfigurationException e) {
errorMessage
.add("There is some problem in completing your request.");
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
circleDTO = new CircleDTO();
// return "joinedCircle";
}
public void getCircleMemberInfo() {
String x = circleOwnerManagerDTO.getCombineUserAndCircleID();
String[] part = x.split(",");
String userId = "0";
try {
userId = part[0];
} catch (Exception e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
List<Integer> x2 = new ArrayList<Integer>();
x2.add(Integer.parseInt(userId));
List<UserRegistrationDTO> dtosTemp = ListOfValuesManager
.getAllUserById(x2);
if (dtosTemp.size() > 0) {
circleMember = dtosTemp.get(0);
} else {
circleMember = new UserRegistrationDTO();
}
}
public String clearCirclrMemberInfo() {
circleMember = new UserRegistrationDTO();
return "";
}
public void deActivateCircle() {
clearScreenMessage();
if (circleDTO.getCircleID() > 0) {
circleDTO = ListOfValuesManager.getDeactivateCircle(circleDTO);
circleDTO = ListOfValuesManager.getCircleDtoByCircleId(circleDTO
.getCircleID());
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage("User "
+ userRegistrationDTO.getFirst_name()
+ " De-Activated circle '" + circleDTO.getName() + "'.");
userMessageDTO.setToMember(circleDTO.getCircleOwner_Member_Id_P());
userMessageDTO.setCreatedBy(Integer.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setEmailSubject("Circle De-Activation");
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
if (circleDTO.getStatus().equals("2")) {
successMessage.add("circle De-Activated successfully.");
} else {
errorMessage
.add("There is some issue in de activating circle.");
}
allListedCircle();
allCircleForLoginUser();
memberForSelectedCircle();
} else {
errorMessage.add("Please Select Circle first.");
}
circleDTO = new CircleDTO();
}
public void addMemberToCircle() {
circleMemberDTO.setCircleid(String.valueOf(circleDTO.getCircleID()));
String[] parts = forregistrationOnly.getFirst_name().split(",");
String part2 = "";
clearScreenMessage();
if (!Validator.isNumberZeroNotAlloed(String.valueOf(circleDTO
.getCircleID())))
errorMessage.add("Please select Circle first.");
if (parts.length < 2) {
errorMessage.add("Please Select Member.");
} else {
part2 = parts[parts.length - 1];
}
if (errorMessage.size() == 0) {
circleMemberDTO.setUserid(part2);
circleMemberDTO.setStatus("0");
if (errorMessage.size() == 0) {
try {
if (ListOfValuesManager.testSingleCircleMember(
circleMemberDTO, userRegistrationDTO.getId(), "",
"")) {
circleMemberDTO = ListOfValuesManager.getJoinCircle(
circleMemberDTO, userRegistrationDTO.getId(),
null);
successMessage
.add("User added to circle. The request is pending for user approval.");
} else {
errorMessage
.add("User is already part of another circle.");
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
errorMessage
.add("There is some problem in adding member to circle..");
}
}
memberForSelectedCircle();
List<CircleOwnerManagerDTO> allCircleMemberForLoginUserList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
if (allCircleMemberForLoginUserList.get(i).getCircleID()
.equals(circleMemberDTO.getCircleid())) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allCircleMemberForLoginUserList.get(i);
allCircleMemberForLoginUserList1.add(dto);
}
}
allCircleMemberForLoginUserList.clear();
allCircleMemberForLoginUserList
.addAll(allCircleMemberForLoginUserList1);
allCircleMemberForLoginUserList1.clear();
List<CircleOwnerManagerDTO> allPendingCircleMemberList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allPendingCircleMemberList.size(); i++) {
if (allPendingCircleMemberList.get(i).getCircleID()
.equals(circleMemberDTO.getCircleid())) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allPendingCircleMemberList.get(i);
allPendingCircleMemberList1.add(dto);
}
}
allPendingCircleMemberList.clear();
allPendingCircleMemberList.addAll(allPendingCircleMemberList1);
allPendingCircleMemberList1.clear();
// circleDTO = new CircleDTO();
forregistrationOnly = new UserRegistrationDTO();
// return "memberAdded";
}
}
public void createMessage() {
clearScreenMessage();
List<Integer> userIds = null;
String messageContent = getMessage();
String messageTo = getMessagePlace();
if (circleDTO.getCircleID() <= 0) {
errorMessage.add("Please select circle first.");
} else if (!(messageTo.equalsIgnoreCase("e")
|| messageTo.equalsIgnoreCase("m") || messageTo
.equalsIgnoreCase("b"))) {
errorMessage.add("Please select where you want to send message.");
} else if (Validator.isEmpty(messageContent.trim())) {
errorMessage.add("Please wite message.");
} else {
userIds = ListOfValuesManager.findAllUsersInCircle(circleDTO
.getCircleID());
if (messageTo.equalsIgnoreCase("m")
|| messageTo.equalsIgnoreCase("b")) {
for (Integer user : userIds) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO.setToMember(user);
userMessageDTO.setMessageChannel("M");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
if (messageTo.equalsIgnoreCase("e")
|| messageTo.equalsIgnoreCase("b")) {
for (Integer user : userIds) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject("Message from "
+ userRegistrationDTO.getFirst_name());
userMessageDTO.setMessage(messageContent);
userMessageDTO.setToMember(user);
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
setMessage("");
setMessagePlace("m");
successMessage.add("Message sent successfully to circle members.");
}
}
public void makeAdmin() {
clearScreenMessage();
// FacesContext context = FacesContext.getCurrentInstance();
// Map<String,String> requestMap =
// context.getExternalContext().getRequestParameterMap(); //In java
// class, you can get back the parameter value with component
// (submit-command buton) like this :
// String userAndCircleId = (String)requestMap.get("userAndCircleId");
// String circleId = (String)requestMap.get("circleId");
String[] parts = circleOwnerManagerDTO.getCombineUserAndCircleID()
.split(",");
String part1 = parts[0];
// String part2 = parts[1];
if (!(circleDTO.getCircleID() > 0)) {
errorMessage.add("Please select Circle.");
} else if (!Validator.isNumberZeroNotAlloed(part1)) {
errorMessage
.add("Please select Circle Member you want to make admin.");
} else {
CircleOwnerDTO circleOwnerDTO = new CircleOwnerDTO();
circleOwnerDTO.setCircleID(String.valueOf(circleDTO.getCircleID()));
circleOwnerDTO.setUserID(part1);
try {
circleOwnerDTO = ListOfValuesManager.getregisterCircleOwner(
circleOwnerDTO, userRegistrationDTO.getId(), null);
successMessage.add("User is now admin of selected circle "
+ circleDTO.getName() + ".");
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
errorMessage
.add("There is some problem in making user admin of circle "
+ circleDTO.getName() + ".");
}
rollbackTest = false;
memberForSelectedCircle();
List<CircleOwnerManagerDTO> allCircleMemberForLoginUserList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
if (allCircleMemberForLoginUserList.get(i).getCircleID()
.equals(circleOwnerDTO.getCircleID())) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allCircleMemberForLoginUserList.get(i);
allCircleMemberForLoginUserList1.add(dto);
}
}
allCircleMemberForLoginUserList.clear();
allCircleMemberForLoginUserList
.addAll(allCircleMemberForLoginUserList1);
allCircleMemberForLoginUserList1.clear();
List<CircleOwnerManagerDTO> allPendingCircleMemberList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allPendingCircleMemberList.size(); i++) {
if (allPendingCircleMemberList.get(i).getCircleID()
.equals(circleOwnerDTO.getCircleID())) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allPendingCircleMemberList.get(i);
allPendingCircleMemberList1.add(dto);
}
}
allPendingCircleMemberList.clear();
allPendingCircleMemberList.addAll(allPendingCircleMemberList1);
allPendingCircleMemberList1.clear();
}
// return "admin";
}
public void removeAdmin() {
String[] parts = circleOwnerManagerDTO.getCombineUserAndCircleID()
.split(",");
clearScreenMessage();
if (!(circleDTO.getCircleID() > 0)) {
errorMessage.add("Please select Circle.");
} else if (!Validator.isNumberZeroNotAlloed(parts[0])) {
errorMessage
.add("Please select Circle Member you want to remove admin.");
} else {
String part1 = parts[0];
String part2 = parts[2];
CircleOwnerDTO circleOwnerDTO = new CircleOwnerDTO();
circleOwnerDTO.setCircleID(String.valueOf(circleDTO.getCircleID()));
circleOwnerDTO.setUserID(part1);
if (part2.equalsIgnoreCase(part1)) {
errorMessage.add("Circle can not remove admin authorisation.");
} else {
try {
circleOwnerDTO = ListOfValuesManager
.updateRegisterCircleOwner(circleOwnerDTO,
userRegistrationDTO.getId(), null);
successMessage
.add("User is now not admin of selected circle "
+ circleDTO.getName() + ".");
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
rollbackTest = true;
errorMessage
.add("There is some problem in removing admin authorisation of circle "
+ circleDTO.getName() + ".");
}
rollbackTest = false;
memberForSelectedCircle();
List<CircleOwnerManagerDTO> allCircleMemberForLoginUserList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allCircleMemberForLoginUserList.size(); i++) {
if (allCircleMemberForLoginUserList.get(i).getCircleID()
.equals(circleOwnerDTO.getCircleID())) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allCircleMemberForLoginUserList.get(i);
allCircleMemberForLoginUserList1.add(dto);
}
}
allCircleMemberForLoginUserList.clear();
allCircleMemberForLoginUserList
.addAll(allCircleMemberForLoginUserList1);
allCircleMemberForLoginUserList1.clear();
List<CircleOwnerManagerDTO> allPendingCircleMemberList1 = new ArrayList<CircleOwnerManagerDTO>();
for (int i = 0; i < allPendingCircleMemberList.size(); i++) {
if (allPendingCircleMemberList.get(i).getCircleID()
.equals(circleOwnerDTO.getCircleID())) {
CircleOwnerManagerDTO dto = new CircleOwnerManagerDTO();
dto = allPendingCircleMemberList.get(i);
allPendingCircleMemberList1.add(dto);
}
}
allPendingCircleMemberList.clear();
allPendingCircleMemberList.addAll(allPendingCircleMemberList1);
allPendingCircleMemberList1.clear();
}
}
// return"adminRemoved";
}
public void handleDateSelect(SelectEvent event) {
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern5);
DateFormat dateFormat1 = new SimpleDateFormat(
ApplicationUtil.datePattern6);
// DateFormat dateFormat1 = new SimpleDateFormat("dd MMM yy, HH.mm a");
DateFormat dateFormat2 = new SimpleDateFormat(
ApplicationUtil.datePattern4);
Date date = null;
try {
date = dateFormat.parse(event.getObject().toString());
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
String datevalue = dateFormat1.format(date);
int days = Integer.valueOf(datevalue.substring(3, 5)) + 1;
String tempValue = datevalue.substring(0, 3) + ""
+ String.valueOf(days) + ""
+ datevalue.substring(5, datevalue.length());
try {
date = dateFormat1.parse(tempValue);
// date = dateFormat2.format(tempValue);
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
minDate = dateFormat2.format(date);
}
public void recurringValue(AjaxBehaviorEvent event)
throws AbortProcessingException {
if (recurring == true) {
recurring = false;
}
if (recurring == false) {
recurring = true;
}
}
public String matchTripLinking() {
clearScreenMessage();
if (ridePreMatchTest > 0) {
List<String> groupMap = new ArrayList<String>();
List<String> rideIdArr = new ArrayList<String>();
for (MatchedTripDTO dto : matchedTripDTOs) {
if (dto.getGroupId() != null && dto.getGroupId().length() > 0)
groupMap.add(dto.getGroupId());
if (!rideIdArr.contains(dto.getSeekerID())) {
rideIdArr.add(dto.getSeekerID());
}
}
List<MatchedTripDTO> temp1 = ListOfValuesManager
.findMatchTripByGroupId(groupMap);
int count1 = 0;
for (MatchedTripDTO dto : temp1) {
if (!rideIdArr.contains(dto.getSeekerID())) {
count1++;
}
}
int count2 = 0;
MatchedTripDTO temp2[] = new MatchedTripDTO[count1
+ matchedTripDTOs.length];
for (int i = 0; i < temp1.size(); i++) {
if (!rideIdArr.contains(temp1.get(i).getSeekerID())) {
temp2[count2] = temp1.get(i);
count2++;
}
}
for (int i = 0; i < matchedTripDTOs.length; i++) {
temp2[i + count2] = matchedTripDTOs[i];
}
matchedTripDTOs = temp2;
}
ridePreMatchTest = 0;
Map<String, Integer> groupCountTemp = new HashMap<String, Integer>();
Map<String, String> groupRideIdTemp = new HashMap<String, String>();
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (matchedTripDTOs[i].getGroupId() != null
&& matchedTripDTOs[i].getGroupId().length() > 0
&& matchedTripDTOs[i].getCountTemp() != null) {
groupCountTemp.put(matchedTripDTOs[i].getGroupId(),
Integer.parseInt(matchedTripDTOs[i].getCountTemp()));
groupRideIdTemp.put(matchedTripDTOs[i].getGroupId(),
matchedTripDTOs[i].getRideId());
}
}
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (groupCountTemp.containsKey(matchedTripDTOs[i].getGroupId())
&& (matchedTripDTOs[i].getCountTemp() == null || matchedTripDTOs[i]
.getCountTemp().length() == 0)) {
groupCountTemp
.put(matchedTripDTOs[i].getGroupId(), groupCountTemp
.get(matchedTripDTOs[i].getGroupId()) - 1);
matchedTripDTOs[i].setCountTemp(""
+ groupCountTemp.get(matchedTripDTOs[i].getGroupId()));
}
}
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (groupRideIdTemp.containsKey(matchedTripDTOs[i].getGroupId())) {
matchedTripDTOs[i].setRideId(groupRideIdTemp
.get(matchedTripDTOs[i].getGroupId()));
}
}
// check concurrency here.
List<Integer> seekerIdForConcurrency = new ArrayList<Integer>();
// Map<String, String> seekerArrayForConcurrency = new HashMap<String,
// String>();
for (MatchedTripDTO dtoTemp1 : matchedTripDTOs) {
seekerIdForConcurrency
.add(Integer.parseInt(dtoTemp1.getSeekerID()));
// seekerArrayForConcurrency.put(dtoTemp1.getSeekerID(), );
}
List<RideSeekerDTO> seekerDtoForConcurrency = ListOfValuesManager
.findRideSeekerDataByIds(seekerIdForConcurrency);
boolean test = true;
if (seekerDtoForConcurrency == null
|| seekerDtoForConcurrency.size() != matchedTripDTOs.length) {
test = false;
} else {
for (RideSeekerDTO dtoTest : seekerDtoForConcurrency) {
if ((!dtoTest.getStatus().equalsIgnoreCase("A") || !dtoTest
.getIsResult().equalsIgnoreCase("N"))) {
if (dtoTest.isNightRide()
&& (dtoTest.getStatus().equalsIgnoreCase("O") || dtoTest
.getStatus().equalsIgnoreCase("T"))) {
continue;
}
test = false;
break;
}
}
}
if (!test) {
errorMessage
.add("Some error has occured. Please try again after sometime.");
} else {
Connection con = (Connection) ListOfValuesManager
.getBroadConnection();
try {
for (int i = 0; i < matchedTripDTOs.length; i++) {
matchedTripDTOs[i].setCount(matchedTripDTOs[i]
.getCountTemp());
MatchedTripDTO dto = new MatchedTripDTO();
RideManagementDTO rideManagementDTO = new RideManagementDTO();
PoolRequestsDTO poolDTO = new PoolRequestsDTO();
FrequencyDTO freqDTO = new FrequencyDTO();
// FrequencyDTO frequencyDTO = new FrequencyDTO();
dto = matchedTripDTOs[i];
if (dto.getRideId().equalsIgnoreCase("NEW")) {
rideManagementDTO.setFromAddress1(dto.getStartPoint());
rideManagementDTO.setToAddress1(dto.getEndPoint());
rideManagementDTO
.setUserID(userRegistrationDTO.getId());
rideManagementDTO.setVehicleID(dto.getVehicleID());
rideManagementDTO.setStatus("T");// previously 2
SimpleDateFormat formatter = new SimpleDateFormat(
ApplicationUtil.datePattern3);
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern9);
try {
Date date = dateFormat.parse(dto.getStartDate());
rideManagementDTO.setStartdateValue(formatter
.format(date));
date = formatter.parse(formatter.format(date));
freqDTO.setTime(date);
} catch (ParseException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName()
+ "->"
+ e1.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e1.getStackTrace()[0]
.getLineNumber() + " :: "
+ e1.getMessage());
}
rideManagementDTO.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
rideManagementDTO.setFlexiTimeAfter(ListOfValuesManager
.getCurrentTimeStampDate());
rideManagementDTO
.setFlexiTimeBefore(ListOfValuesManager
.getCurrentTimeStampDate());
rideManagementDTO.setCreatedBy(userRegistrationDTO
.getId());
List<String> frequency = new ArrayList<String>();
frequency.add(dto.getFrequency());
freqDTO.setFrequency(frequency);
rideManagementDTO = ListOfValuesManager.getRideEntery(
"findByDTO", rideManagementDTO, con);
freqDTO.setRideManagementId(rideManagementDTO
.getRideID());
freqDTO = ListOfValuesManager.getFrequencyEntery(
"findByDTO", freqDTO, con);
} else {
if (Integer.valueOf(dto.getCount()) == 0) {
return null;
} else {
rideManagementDTO.setRideID(dto.getRideId());
rideManagementDTO.setStatus("I");// rideManagementDTO.setStatus("2");rideManagementDTO.setStatus("I");
rideManagementDTO = ListOfValuesManager
.getCancleRide(rideManagementDTO, con);
rideManagementDTO = ListOfValuesManager
.getRideManagerPopupDataDirect(dto
.getRideId());
}
}
/*
* ride_seeker_id is the passenger's ride id. ride_seeker_id
* -> ride_seeker_details -> seeker_id -> ride_seeker_id ->
* user_id ride_id is the ride id for driver. ride_id ->
* ride_management -> ride_id -> user_id
*/
RideSeekerDTO seekerDtoTemp = ListOfValuesManager
.getRideSeekerData(Integer.parseInt(dto
.getSeekerID()));
// RideManagementDTO managementDtoTemp =
// ListOfValuesManager.getRideManagerPopupData(rideManagementDTO.getRideID());
// RideManagementDTO managementDtoTemp2 =
// ListOfValuesManager.getRideManagerPopupData(dto.getSeekerID());
poolDTO.setRidemanagerID(rideManagementDTO.getRideID());
poolDTO.setRideSeekerID(dto.getSeekerID());
poolDTO.setPoolRequestToId(Integer
.parseInt(rideManagementDTO.getUserID()));
poolDTO.setPoolRequestBy(Integer.parseInt(seekerDtoTemp
.getUserID()));
poolDTO = ListOfValuesManager.getInsertInPool(poolDTO, con);
RideManagementDTO managementDtoTemp = new RideManagementDTO();
managementDtoTemp.setRideID(rideManagementDTO.getRideID());
managementDtoTemp.setUserID(rideManagementDTO.getUserID());
managementDtoTemp.setVehicleID(rideManagementDTO
.getVehicleID());
managementDtoTemp.setFromAddress1(rideManagementDTO
.getFromAddress1());
managementDtoTemp.setToAddress1(rideManagementDTO
.getToAddress1());
managementDtoTemp.setStartdateValue(rideManagementDTO
.getStartdateValue());
managementDtoTemp.setCreatedBy(rideManagementDTO
.getCreatedBy());
managementDtoTemp.setStatus(rideManagementDTO.getStatus());
List<Integer> x = new ArrayList<Integer>();
x.add(Integer.parseInt(seekerDtoTemp.getUserID()));
x.add(Integer.parseInt(managementDtoTemp.getUserID()));
List<UserRegistrationDTO> dtosTemp = ListOfValuesManager
.getAllUserById(x);
UserRegistrationDTO seekerUserDto = null;
UserRegistrationDTO managerUserDto = null;
for (UserRegistrationDTO di : dtosTemp) {
if (di.getId().equals(seekerDtoTemp.getUserID())) {
seekerUserDto = di;
} else if (di.getId().equals(
managementDtoTemp.getUserID())) {
managerUserDto = di;
}
}
UserRegistrationDTO userDto = new UserRegistrationDTO();
VehicleMasterDTO vehicleDto1 = new VehicleMasterDTO();
if (Validator.isEmpty(rideManagementDTO.getVehicleID())
|| rideManagementDTO.getVehicleID().equals("0")) {
userDto = ListOfValuesManager.findUserDtoByVehicleId(
Integer.parseInt(rideManagementDTO
.getVehicleID()), con);
vehicleDto1 = ListOfValuesManager
.getVehicleDtoById(matchedTripDTOs[i]
.getVehicleID());
} else {
userDto = ListOfValuesManager.findDriverDtoByRideId(
rideManagementDTO.getRideID(), con);
vehicleDto1 = ListOfValuesManager
.getVehicleDtoById(rideManagementDTO
.getVehicleID());
}
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.match",
new Object[] { dto.getStartDate() }));
userMessageDTO.setMessage(Messages.getValue(
"ridematched.seeker",
new Object[] { seekerUserDto.getFirst_name(),
userDto.getFirst_name(),
rideManagementDTO.getRideID(),
dto.getStartPoint(), dto.getEndPoint(),
dto.getStartDate(),
vehicleDto1.getReg_NO(),
userDto.getMobile_no() }));
userMessageDTO.setToMember(Integer.parseInt(seekerDtoTemp
.getUserID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.match",
new Object[] { dto.getStartDate() }));
userMessageDTO.setMessage(Messages.getValue(
"ridematched.driver",
new Object[] {
userDto.getFirst_name(),
rideManagementDTO.getRideID(),
dto.getStartPoint(),
dto.getEndPoint(),
dto.getStartDate(),
seekerUserDto.getFirst_name() + " - "
+ seekerUserDto.getMobile_no() }));
userMessageDTO
.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages
.getValue(
"sms.match",
new Object[] { dto.getStartPoint(),
dto.getEndPoint(),
managerUserDto.getFirst_name(),
dto.getStartDate(),
managerUserDto.getMobile_no(),
managementDtoTemp.getRideID(),
seekerDtoTemp.getUserName(),
vehicleDto1.getReg_NO(),
dto.getSeekerID() }));
userMessageDTO.setToMember(Integer.parseInt(seekerDtoTemp
.getUserID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"sms.match.driver",
new Object[] { seekerDtoTemp.getFromAddress1(),
seekerDtoTemp.getToAddress1(),
seekerUserDto.getFirst_name(),
seekerDtoTemp.getStartdateValue(),
seekerUserDto.getMobile_no(),
managementDtoTemp.getRideID(),
userDto.getFirst_name() }));
userMessageDTO
.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
// vehicleMasterDTO=ListOfValuesManager.getUpdateSeat(vehicleMasterDTO);
/*
* RideSeekerDTO dtoSeeker = new RideSeekerDTO();
* dtoSeeker.setSeekerID(dto.getSeekerID());
* dtoSeeker.setStatus("I"); dtoSeeker=
* ListOfValuesManager.getCancleRideSeeker(dtoSeeker,
* con);//use for update
*/
RideSeekerDTO dtoSeeker = new RideSeekerDTO();
dtoSeeker.setSeekerID(dto.getSeekerID());
dtoSeeker.setRideMatchRideId(rideManagementDTO.getRideID());
dtoSeeker.setIsResult("Y");
dtoSeeker = ListOfValuesManager.changeField(dtoSeeker, con);
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
}
rideManagementList();
allCompleateRideList();
vehicleList();
// matchedTripListByCondition();
matchedTripByConditionList.clear();
matchedTripDataModel = new MatchedTripDataModel();
vehicleMasterDTO = new VehicleMasterDTO();
rideManagementListForPopupOne.clear();
userMessageDTO = new MessageBoardDTO();
return "matched";
}
public String ridePreMatchTripLinking() {
clearScreenMessage();
Map<String, List<Integer>> groupRideComb = new HashMap<String, List<Integer>>();
Map<String, Integer> groupRideSingle = new HashMap<String, Integer>();
Map<String, MatchedTripDTO> groupMatchTrip = new HashMap<String, MatchedTripDTO>();
Map<String, Integer> groupMatchTest = new HashMap<String, Integer>();
if (ridePreMatchTest > 0) {
Map<String, String> groupVehicleMap = new HashMap<String, String>();
Map<String, String> groupCountMap = new HashMap<String, String>();
Map<String, String> groupCountTempMap = new HashMap<String, String>();
Map<String, String> groupRideIdMap = new HashMap<String, String>();
for (MatchedTripDTO dto : matchedTripDTOs) {
if (dto.isSelectGroup()
&& !Validator.isEmpty(dto.getVehicleID())) {
groupVehicleMap.put(dto.getGroupId(), dto.getVehicleID());
}
if (dto.isSelectGroup() && !Validator.isEmpty(dto.getCount())) {
groupCountMap.put(dto.getGroupId(), dto.getCount());
}
if (dto.isSelectGroup()
&& !Validator.isEmpty(dto.getCountTemp())) {
groupCountTempMap.put(dto.getGroupId(), dto.getCountTemp());
}
if (dto.isSelectGroup() && !Validator.isEmpty(dto.getRideId())) {
groupRideIdMap.put(dto.getGroupId(), dto.getRideId());
}
}
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (groupVehicleMap
.containsKey(matchedTripDTOs[i].getGroupId())) {
matchedTripDTOs[i].setVehicleID(groupVehicleMap
.get(matchedTripDTOs[i].getGroupId()));
}
if (groupCountMap.containsKey(matchedTripDTOs[i].getGroupId())) {
matchedTripDTOs[i].setCount(groupCountMap
.get(matchedTripDTOs[i].getGroupId()));
}
if (groupCountTempMap.containsKey(matchedTripDTOs[i]
.getGroupId())) {
matchedTripDTOs[i].setCountTemp(groupCountTempMap
.get(matchedTripDTOs[i].getGroupId()));
groupCountTempMap.put(
matchedTripDTOs[i].getGroupId(),
""
+ (Integer.parseInt(groupCountTempMap
.get(matchedTripDTOs[i]
.getGroupId())) - 1));
}
if (groupRideIdMap.containsKey(matchedTripDTOs[i].getGroupId())) {
matchedTripDTOs[i].setRideId(groupRideIdMap
.get(matchedTripDTOs[i].getGroupId()));
}
}
/*
* List<String> groupMap = new ArrayList<String>(); List<String>
* rideIdArr = new ArrayList<String>(); //Here we are adding group
* to array. for(MatchedTripDTO dto:matchedTripDTOs) {
* if(dto.isSelectGroup() && dto.getGroupId() != null &&
* dto.getGroupId().length() > 0) groupMap.add(dto.getGroupId());
* if(!rideIdArr.contains(dto.getSeekerID())) {
* rideIdArr.add(dto.getSeekerID()); } } //Here we are fetching rest
* ride seeker data by group for matchTripDTOs.
*
* List<MatchedTripDTO> temp1 =
* ListOfValuesManager.findMatchTripByGroupId(groupMap); int count1
* = 0; for(MatchedTripDTO dto:temp1) {
* if(!rideIdArr.contains(dto.getSeekerID())) { count1++; } } int
* count2 = 0; MatchedTripDTO temp2[] = new MatchedTripDTO[count1 +
* matchedTripDTOs.length]; for(int i =0;i<temp1.size();i++) {
* //if(!rideIdArr.contains(temp1.get(i).getSeekerID()))
* temp2[count2] = temp1.get(i); count2++; } for(int i
* =0;i<matchedTripDTOs.length;i++) {
* if(!matchedTripDTOs[i].isSelectGroup()) temp2[i+count2] =
* matchedTripDTOs[i]; } matchedTripDTOs = temp2;
*/
// Now matchedTripDTOs has all ride seeker data group wise.
for (MatchedTripDTO dto : matchedTripDTOs) {
if (groupRideComb.containsKey(dto.getGroupId())) {
List<Integer> rideIdTemp = new ArrayList<Integer>();
rideIdTemp.add(Integer.parseInt(dto.getSeekerID()));
rideIdTemp.addAll(groupRideComb.get(dto.getGroupId()));
groupRideComb.put(dto.getGroupId(), rideIdTemp);
} else {
List<Integer> rideIdTemp = new ArrayList<Integer>();
rideIdTemp.add(Integer.parseInt(dto.getSeekerID()));
groupRideComb.put(dto.getGroupId(), rideIdTemp);
}
groupMatchTest.put(dto.getGroupId(), 0);
}
for (String group : groupRideComb.keySet()) {
int rideForGroup = ListOfValuesManager
.calculateSingleRide(groupRideComb.get(group));
groupRideSingle.put(group, rideForGroup);
}
for (String group : groupRideSingle.keySet()) {
String tempSeekerId = groupRideSingle.get(group) + "";
for (MatchedTripDTO dto : matchedTripDTOs) {
if (dto.getGroupId().equalsIgnoreCase(group)
&& dto.getSeekerID().equalsIgnoreCase(tempSeekerId)) {
groupMatchTrip.put(group, dto);
break;
}
}
}
}
ridePreMatchTest = 0;
Map<String, Integer> groupCountTemp = new HashMap<String, Integer>();
Map<String, String> groupRideIdTemp = new HashMap<String, String>();
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (matchedTripDTOs[i].getGroupId() != null
&& matchedTripDTOs[i].getGroupId().length() > 0
&& matchedTripDTOs[i].getCountTemp() != null) {
groupCountTemp.put(matchedTripDTOs[i].getGroupId(),
Integer.parseInt(matchedTripDTOs[i].getCountTemp()));
groupRideIdTemp.put(matchedTripDTOs[i].getGroupId(),
matchedTripDTOs[i].getRideId());
}
}
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (groupCountTemp.containsKey(matchedTripDTOs[i].getGroupId())
&& (matchedTripDTOs[i].getCountTemp() == null || matchedTripDTOs[i]
.getCountTemp().length() == 0)) {
groupCountTemp
.put(matchedTripDTOs[i].getGroupId(), groupCountTemp
.get(matchedTripDTOs[i].getGroupId()) - 1);
matchedTripDTOs[i].setCountTemp(""
+ groupCountTemp.get(matchedTripDTOs[i].getGroupId()));
}
}
for (int i = 0; i < matchedTripDTOs.length; i++) {
if (groupRideIdTemp.containsKey(matchedTripDTOs[i].getGroupId())) {
matchedTripDTOs[i].setRideId(groupRideIdTemp
.get(matchedTripDTOs[i].getGroupId()));
}
}
// check concurrency here.
List<Integer> seekerIdForConcurrency = new ArrayList<Integer>();
// Map<String, String> seekerArrayForConcurrency = new HashMap<String,
// String>();
for (MatchedTripDTO dtoTemp1 : matchedTripDTOs) {
seekerIdForConcurrency
.add(Integer.parseInt(dtoTemp1.getSeekerID()));
// seekerArrayForConcurrency.put(dtoTemp1.getSeekerID(), );
}
List<RideSeekerDTO> seekerDtoForConcurrency = ListOfValuesManager
.findRideSeekerDataByIds(seekerIdForConcurrency);
boolean test = true;
if (seekerDtoForConcurrency == null
|| seekerDtoForConcurrency.size() != matchedTripDTOs.length) {
test = false;
} else {
for (RideSeekerDTO dtoTest : seekerDtoForConcurrency) {
if ((!dtoTest.getStatus().equalsIgnoreCase("A") || !dtoTest
.getIsResult().equalsIgnoreCase("N"))) {
if (dtoTest.isNightRide()
&& (dtoTest.getStatus().equalsIgnoreCase("O") || dtoTest
.getStatus().equalsIgnoreCase("T"))) {
continue;
}
test = false;
break;
}
}
}
if (!test) {
errorMessage
.add("Some error has occured. Please try again after sometime.");
} else {
// uncomment for sending mail in combined way.
// Map<Integer, List<Integer>> driverMessageList = new
// HashMap<Integer, List<Integer>>();
Connection con = (Connection) ListOfValuesManager
.getBroadConnection();
try {
for (int i = 0; i < matchedTripDTOs.length; i++) {
matchedTripDTOs[i].setCount(matchedTripDTOs[i]
.getCountTemp());
MatchedTripDTO dto = new MatchedTripDTO();
RideManagementDTO rideManagementDTO = new RideManagementDTO();
PoolRequestsDTO poolDTO = new PoolRequestsDTO();
FrequencyDTO freqDTO = new FrequencyDTO();
// FrequencyDTO frequencyDTO = new FrequencyDTO();
dto = matchedTripDTOs[i];
MatchedTripDTO dtoNew = groupMatchTrip
.get(dto.getGroupId());
if (dto.getRideId().equalsIgnoreCase("NEW")) {
rideManagementDTO.setFromAddress1(dtoNew
.getStartPoint());
rideManagementDTO.setToAddress1(dtoNew.getEndPoint());
rideManagementDTO
.setUserID(userRegistrationDTO.getId());
rideManagementDTO.setVehicleID(dtoNew.getVehicleID());
rideManagementDTO.setStatus("T");// previously 2
SimpleDateFormat formatter = new SimpleDateFormat(
ApplicationUtil.datePattern3);
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern9);
try {
Date date = dateFormat.parse(dtoNew.getStartDate());
rideManagementDTO.setStartdateValue(formatter
.format(date));
date = formatter.parse(formatter.format(date));
freqDTO.setTime(date);
} catch (ParseException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName()
+ "->"
+ e1.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e1.getStackTrace()[0]
.getLineNumber() + " :: "
+ e1.getMessage());
}
rideManagementDTO.setCreated_dt(ListOfValuesManager
.getCurrentTimeStampDate());
rideManagementDTO.setFlexiTimeAfter(ListOfValuesManager
.getCurrentTimeStampDate());
rideManagementDTO
.setFlexiTimeBefore(ListOfValuesManager
.getCurrentTimeStampDate());
rideManagementDTO.setCreatedBy(userRegistrationDTO
.getId());
List<String> frequency = new ArrayList<String>();
frequency.add(dtoNew.getFrequency());
freqDTO.setFrequency(frequency);
if (groupMatchTest.get(dto.getGroupId()) == 0) {
rideManagementDTO = ListOfValuesManager
.getRideEntery("findByDTO",
rideManagementDTO, con);
freqDTO.setRideManagementId(rideManagementDTO
.getRideID());
freqDTO = ListOfValuesManager.getFrequencyEntery(
"findByDTO", freqDTO, con);
groupMatchTest.put(dto.getGroupId(), Integer
.parseInt(rideManagementDTO.getRideID()));
} else {
rideManagementDTO.setRideID(groupMatchTest.get(dto
.getGroupId()) + "");
freqDTO.setRideManagementId(groupMatchTest.get(dto
.getGroupId()) + "");
}
} else {
if (Integer.valueOf(dto.getCount()) == 0) {
return null;
} else {
rideManagementDTO.setRideID(dto.getRideId());
rideManagementDTO.setStatus("I");// rideManagementDTO.setStatus("2");rideManagementDTO.setStatus("I");
rideManagementDTO = ListOfValuesManager
.getCancleRide(rideManagementDTO, con);
rideManagementDTO = ListOfValuesManager
.getRideManagerPopupDataDirect(dto
.getRideId());
}
}
/*
* //uncomment for sending mail in combined way.
* if(driverMessageList
* .containsKey(poolDTO.getRidemanagerID())) {
* driverMessageList
* .get(poolDTO.getRidemanagerID()).add(Integer
* .parseInt(poolDTO.getRideSeekerID())); }
*/
/*
* ride_seeker_id is the passenger's ride id. ride_seeker_id
* -> ride_seeker_details -> seeker_id -> ride_seeker_id ->
* user_id ride_id is the ride id for driver. ride_id ->
* ride_management -> ride_id -> user_id
*/
RideSeekerDTO seekerDtoTemp = ListOfValuesManager
.getRideSeekerData(Integer.parseInt(dto
.getSeekerID()));
// RideManagementDTO managementDtoTemp =
// ListOfValuesManager.getRideManagerPopupData(rideManagementDTO.getRideID());
// RideManagementDTO managementDtoTemp2 =
// ListOfValuesManager.getRideManagerPopupData(dto.getSeekerID());
poolDTO.setRidemanagerID(rideManagementDTO.getRideID());
poolDTO.setRideSeekerID(dto.getSeekerID());
poolDTO.setPoolRequestToId(Integer
.parseInt(rideManagementDTO.getUserID()));
poolDTO.setPoolRequestBy(Integer.parseInt(seekerDtoTemp
.getUserID()));
poolDTO = ListOfValuesManager.getInsertInPool(poolDTO, con);
RideManagementDTO managementDtoTemp = new RideManagementDTO();
managementDtoTemp.setRideID(rideManagementDTO.getRideID());
managementDtoTemp.setUserID(rideManagementDTO.getUserID());
managementDtoTemp.setVehicleID(rideManagementDTO
.getVehicleID());
managementDtoTemp.setFromAddress1(rideManagementDTO
.getFromAddress1());
managementDtoTemp.setToAddress1(rideManagementDTO
.getToAddress1());
managementDtoTemp.setStartdateValue(rideManagementDTO
.getStartdateValue());
managementDtoTemp.setCreatedBy(rideManagementDTO
.getCreatedBy());
managementDtoTemp.setStatus(rideManagementDTO.getStatus());
List<Integer> x = new ArrayList<Integer>();
x.add(Integer.parseInt(seekerDtoTemp.getUserID()));
x.add(Integer.parseInt(managementDtoTemp.getUserID()));
List<UserRegistrationDTO> dtosTemp = ListOfValuesManager
.getAllUserById(x);
UserRegistrationDTO seekerUserDto = null;
UserRegistrationDTO managerUserDto = null;
for (UserRegistrationDTO di : dtosTemp) {
if (di.getId().equals(seekerDtoTemp.getUserID())) {
seekerUserDto = di;
} else if (di.getId().equals(
managementDtoTemp.getUserID())) {
managerUserDto = di;
}
}
UserRegistrationDTO userDto = new UserRegistrationDTO();
VehicleMasterDTO vehicleDto1 = new VehicleMasterDTO();
if (Validator.isEmpty(rideManagementDTO.getVehicleID())
|| rideManagementDTO.getVehicleID().equals("0")) {
userDto = ListOfValuesManager.findDriverDtoByRideId(
rideManagementDTO.getRideID(), con);
} else {
userDto = ListOfValuesManager.findUserDtoByVehicleId(
Integer.parseInt(rideManagementDTO
.getVehicleID()), con);
}
vehicleDto1 = ListOfValuesManager
.getVehicleDtoById(rideManagementDTO.getVehicleID());
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.match",
new Object[] { dto.getStartDate() }));
userMessageDTO.setMessage(Messages.getValue(
"ridematched.seeker",
new Object[] { seekerUserDto.getFirst_name(),
userDto.getFirst_name(),
rideManagementDTO.getRideID(),
dto.getStartPoint(), dto.getEndPoint(),
dto.getStartDate(),
vehicleDto1.getReg_NO(),
userDto.getMobile_no() }));
userMessageDTO.setToMember(Integer.parseInt(seekerDtoTemp
.getUserID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages.getValue(
"subject.match",
new Object[] { dto.getStartDate() }));
userMessageDTO.setMessage(Messages.getValue(
"ridematched.driver",
new Object[] {
userDto.getFirst_name(),
rideManagementDTO.getRideID(),
dto.getStartPoint(),
dto.getEndPoint(),
dto.getStartDate(),
seekerUserDto.getFirst_name() + " - "
+ seekerUserDto.getMobile_no() }));
userMessageDTO
.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.match",
new Object[] {
(dto.getStartPoint()
.length() > 25) ? dto
.getStartPoint()
.substring(0, 25)
: dto.getStartPoint(),
(dto.getEndPoint().length() > 25) ? dto
.getEndPoint()
.substring(0, 25)
: dto.getEndPoint(),
managerUserDto
.getFirst_name(),
dto.getStartDate(),
managerUserDto
.getMobile_no(),
managementDtoTemp
.getRideID(),
seekerDtoTemp.getUserName(),
vehicleDto1.getReg_NO(),
dto.getSeekerID() }));
userMessageDTO.setToMember(Integer.parseInt(seekerDtoTemp
.getUserID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.match.driver",
new Object[] {
(seekerDtoTemp
.getFromAddress1()
.length() > 25) ? seekerDtoTemp
.getFromAddress1()
.substring(0, 25)
: seekerDtoTemp
.getFromAddress1(),
(seekerDtoTemp
.getToAddress1()
.length() > 25) ? seekerDtoTemp
.getToAddress1()
.substring(0, 25)
: seekerDtoTemp
.getToAddress1(),
seekerUserDto
.getFirst_name(),
seekerDtoTemp
.getStartdateValue(),
seekerUserDto
.getMobile_no(),
managementDtoTemp
.getRideID(),
userDto.getFirst_name(),
vehicleDto1.getReg_NO() }));
userMessageDTO
.setToMember(Integer.parseInt(userDto.getId()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
// vehicleMasterDTO=ListOfValuesManager.getUpdateSeat(vehicleMasterDTO);
/*
* RideSeekerDTO dtoSeeker = new RideSeekerDTO();
* dtoSeeker.setSeekerID(dto.getSeekerID());
* dtoSeeker.setStatus("I"); dtoSeeker=
* ListOfValuesManager.getCancleRideSeeker(dtoSeeker,
* con);//use for update
*/
RideSeekerDTO dtoSeeker = new RideSeekerDTO();
dtoSeeker.setSeekerID(dto.getSeekerID());
dtoSeeker.setRideMatchRideId(rideManagementDTO.getRideID());
dtoSeeker.setIsResult("Y");
dtoSeeker = ListOfValuesManager.changeField(dtoSeeker, con);
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
rollbackTest = false;
}
}
rideManagementList();
allCompleateRideList();
vehicleList();
// matchedTripListByCondition();
matchedTripByConditionList.clear();
matchedTripDataModel = new MatchedTripDataModel();
vehicleMasterDTO = new VehicleMasterDTO();
rideManagementListForPopupOne.clear();
userMessageDTO = new MessageBoardDTO();
return "matched";
}
public void processValue(AjaxBehaviorEvent event)
throws AbortProcessingException {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
rowForTaxiLinking = (String) requestMap.get("row");
String startDate = (String) requestMap.get("startDate");
matchedTripDTO.setStartDate(startDate);
String value = (String) ((UIInput) event.getSource()).getValue();
if (value == "" || value == null) {
matchedTripByConditionList.get(Integer.valueOf(rowForTaxiLinking))
.setRideId(null);
matchedTripByConditionList.get(Integer.valueOf(rowForTaxiLinking))
.setCount(null);
matchedTripDataModel = new MatchedTripDataModel(
matchedTripByConditionList);
rideManagementListForPopupOne.clear();
} else {
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
if (vehicleMasterDTOList.get(i).getVehicleID().equals(value)) {
MatchedTripDTO dto1 = new MatchedTripDTO();
dto1 = matchedTripByConditionList.get(Integer
.valueOf(rowForTaxiLinking));
MatchedTripDTO matchedTripDTO = new MatchedTripDTO();
Date date = null;
try {
// DateFormat dateFormat = new
// SimpleDateFormat(ApplicationUtil.datePattern1);
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern3);
SimpleDateFormat formatter1 = new SimpleDateFormat(
ApplicationUtil.datePattern2);
date = formatter1.parse(dto1.getStartDate());
String date1 = dateFormat.format(date);
matchedTripDTO = ListOfValuesManager.getCount(value,
date1, "com");
dto1 = matchedTripByConditionList.get(Integer
.valueOf(rowForTaxiLinking));
dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern1);
date = formatter1.parse(dto1.getStartDate());
date1 = dateFormat.format(date);
if (matchedTripDTO.getCount() != null) {
if (matchedTripDTO.getCount().equalsIgnoreCase(
vehicleMasterDTOList.get(i).getCapacity())
|| Integer.valueOf(vehicleMasterDTOList
.get(i).getCapacity()) <= Integer
.valueOf(matchedTripDTO.getCount())) {
dto1.setCount(ApplicationUtil.seatAbsent);
rideManagementListForPopupOne.clear();
} else {
int co = Integer.valueOf(vehicleMasterDTOList
.get(i).getCapacity())
- Integer.valueOf(matchedTripDTO
.getCount());
dto1.setCount(String.valueOf(co));
}
} else {
dto1.setCount(vehicleMasterDTOList.get(i)
.getCapacity());
}
vehicleMasterDTO = vehicleMasterDTOList.get(i);
matchedTripByConditionList.set(
Integer.valueOf(rowForTaxiLinking), dto1);
rideManagementListForPopupOne = ListOfValuesManager
.getMethodForPopupOne(value, date1);
if (rideManagementListForPopupOne.size() != 0) {
if (matchedTripDTO.getCount() != null
&& (matchedTripDTO.getCount()
.equalsIgnoreCase(
vehicleMasterDTOList.get(i)
.getCapacity()) || Integer
.valueOf(vehicleMasterDTOList
.get(i).getCapacity()) <= Integer
.valueOf(matchedTripDTO.getCount()))) {
RideManagementDTO dto = new RideManagementDTO();
dto.setRideID(ApplicationUtil.rideStatus);
rideManagementListForPopupOne.add(dto);
} else {
RideManagementDTO dto = new RideManagementDTO();
dto.setRideID(ApplicationUtil.rideStatus);
rideManagementListForPopupOne.add(dto);
}
Collections.reverse(rideManagementListForPopupOne);
} else {
matchedTripByConditionList.get(
Integer.valueOf(rowForTaxiLinking))
.setRideId(ApplicationUtil.rideStatus);
}
} catch (ParseException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
matchedTripDataModel = new MatchedTripDataModel(
matchedTripByConditionList);
}
}
}
}
public void rideIdSetForLinking() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
String rideID = (String) requestMap.get("rideID");
// String rowIndex = (String)requestMap.get("row");
/*
* if(rowIndex==null){ vehicleMasterDTO =
* vehicleMasterDTOList.get(Integer.valueOf(rowIndex)); }
*/
matchedTripByConditionList.get(Integer.valueOf(rowForTaxiLinking))
.setRideId(rideID);
matchedTripDataModel = new MatchedTripDataModel(
matchedTripByConditionList);
// return "linking";
}
public String showAllRideSeekerForRideInPopup() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
String rideID = (String) requestMap.get("rideID");
try {
vehicleMasterDTO = ListOfValuesManager.getVehicleDtoByRideId(
rideID, null);
} catch (ConfigurationException e) {
vehicleMasterDTO = new VehicleMasterDTO();
}
allSeekerForGivenRide = ListOfValuesManager
.getAllRideSeekerForAGivenRide(rideID);
return "allSeeker";
}
public String showRideSeekerPopup() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
String rideID = (String) requestMap.get("rideId");
rideManagerInfoForRideSeeker = ListOfValuesManager
.getRideManagerPopupData(rideID);
vehicleMasterDTO = ListOfValuesManager
.getVehicleDtoById(rideManagerInfoForRideSeeker.getVehicleID());
try {
vehicleMasterDTO = ListOfValuesManager.getVehicleDtoByRideId(
rideID, null);
} catch (ConfigurationException e) {
vehicleMasterDTO = new VehicleMasterDTO();
}
try {
UserRegistrationDTO userDto = ListOfValuesManager
.findUserDtoByVehicleId(Integer
.parseInt(rideManagerInfoForRideSeeker
.getVehicleID()), null);
rideManagerInfoForRideSeeker.setUserID(userDto.getId());
rideManagerInfoForRideSeeker.setCreatedBy(userDto.getFirst_name());
} catch (NumberFormatException e) {
} catch (ConfigurationException e) {
}
/*
* userDto =
* ListOfValuesManager.findUserDtoByVehicleId(Integer.parseInt(
* rideManagementDTO.getVehicleID()), con);
*/
return "allSeeker";
}
public void updateVehicle() {
clearScreenMessage();
vehicleMasterDTO = ListOfValuesManager
.getUpdateVehicle(vehicleMasterDTO);
successMessage.add(Messages.getValue("success.update",
new Object[] { "Vehicle" }));
rollbackTest = false;
// vehicleMasterDTO = new VehicleMasterDTO();
vehicleList();
// return "updateVehicle";
}
public void inActivateVehicle() {
clearScreenMessage();
for (int i = 0; i < vehicleMasterDtos.length; i++) {
vehicleMasterDTO = vehicleMasterDtos[i];
vehicleMasterDTO = ListOfValuesManager
.getInActivateVehicle(vehicleMasterDTO);
successMessage.add(Messages.getValue("success.delete",
new Object[] { "Vehicle" }));
rollbackTest = false;
}
vehicleMasterDTO = new VehicleMasterDTO();
vehicleList();
// return "inActivateVehicle";
}
public void showVehicleDetailsInpopup() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
String vehicleID = (String) requestMap.get("vehicleID");
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
if (vehicleID.equalsIgnoreCase(vehicleMasterDTOList.get(i)
.getVehicleID())) {
vehicleMasterDTO = vehicleMasterDTOList.get(i);
}
}
}
public void showLoginUserUnreadMessageList() {
/*
* FacesContext context = FacesContext.getCurrentInstance();
* Map<String,String> requestMap =
* context.getExternalContext().getRequestParameterMap(); //In java
* class, you can get back the parameter value with component
* (submit-command buton) like this : int row =
* Integer.parseInt(requestMap.get("row")); HttpSession currentSession =
* ServerUtility.getSession();
* currentSession.setAttribute("unreadMessageRowNo", row);
*/
allUnreadMessageList.clear();
allUnreadMessageList.addAll(ListOfValuesManager
.getAllUnreadMessage(userRegistrationDTO.getId()));
}
public void populatePopupMessage() {
allpopUpMessageList.clear();
allpopUpMessageList.addAll(ListOfValuesManager
.getAllPopupMessage(Integer.parseInt(userRegistrationDTO
.getId())));
}
public void clearPopupMessage() {
int[] row = new int[allpopUpMessageList.size()];
int i = 0;
for (MessageBoardDTO dto : allpopUpMessageList) {
row[i++] = dto.getMessageId();
}
ListOfValuesManager.makePopupMessageRead(row);
allpopUpMessageList.clear();
}
public void makeMessageReadAll() {
int[] row = new int[allUnreadMessageList.size()];
int i = 0;
for (MessageBoardDTO dto : allUnreadMessageList) {
row[i++] = dto.getMessageId();
}
ListOfValuesManager.makeBoardMessageRead(row);
}
public String allLoginUserMessageList() {
allUnreadMessageList.clear();
allUnreadMessageList.addAll(ListOfValuesManager
.getAllUnreadMessage(userRegistrationDTO.getId()));
return "messageList";
}
public void makeBoardMessageRead() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
int row = Integer.parseInt(requestMap.get("row"));
int[] rowAray = { row };
ListOfValuesManager.makeBoardMessageRead(rowAray);
rollbackTest = false;
allLoginUserMessageList();
}
public void makeBoardMessageDelete() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
int row = Integer.parseInt(requestMap.get("row"));
int[] rowAray = { row };
ListOfValuesManager.makeBoardMessageDelete(rowAray);
rollbackTest = false;
}
public void handleVehicleUpload(FileUploadEvent event) {
UploadedFile item = event.getFile();
String tomcatDirectoryPath = ApplicationUtil.catalinaDirectoryPath;
String extension = ServerUtility.getExtension(item);
String path = null;
File vehiclePath = null;
if (tomcatDirectoryPath != null) {
String vehicleDirPath = ApplicationUtil.vehicleDirectoryPath;
path = ServerUtility.constructTargetFileName("vehicle_"
+ userRegistrationDTO.getId(), extension, vehicleDirPath);
vehiclePath = new File(vehicleDirPath + path);
try {
InputStream input = item.getInputstream();
OutputStream output = new FileOutputStream(vehiclePath);
try {
IOUtils.copy(input, output);
} catch (Exception e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
} finally {
input.close();
output.flush();
output.close();
}
} catch (IOException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
Workbook workbook;
try {
workbook = Workbook.getWorkbook(vehiclePath);
Sheet sheet = workbook.getSheet(0);
clearScreenMessage();
for (int i = 1;; i++) {
Cell cell = sheet.getCell(0, i);
String make = cell.getContents();
cell = sheet.getCell(1, i);
String model = cell.getContents();
cell = sheet.getCell(2, i);
String color = cell.getContents();
cell = sheet.getCell(3, i);
String registrationNo = cell.getContents();
cell = sheet.getCell(4, i);
String capacity = cell.getContents();
if ((make.trim() == null || make.trim().isEmpty())
&& (model.trim() == null || model.trim().isEmpty())
&& (color.trim() == null || color.trim().isEmpty())
&& (registrationNo.trim() == null || registrationNo
.trim().isEmpty())
&& (capacity.trim() == null || capacity.trim()
.isEmpty())) {
break;
}
String error = "";
try {
if (make.trim().isEmpty())
error += Messages.getValue("error.required",
new Object[] { "Make" });
if (model.trim().isEmpty())
error += Messages.getValue("error.required",
new Object[] { "Model" });
if (color.trim().isEmpty())
error += Messages.getValue("error.required",
new Object[] { "Color" });
if (capacity.trim().isEmpty()
|| Integer.parseInt(capacity) < 1
|| Integer.parseInt(capacity) > 60)
error += Messages.getValue("error.required",
new Object[] { "Capacity" })
+ " "
+ Messages.getValue("error.between",
new Object[] { "Capacity", "1",
"60" });
if (registrationNo.trim().isEmpty())
error += Messages.getValue("error.required",
new Object[] { "Registration Numbe" });
if (ListOfValuesManager
.testVehicleRegistrationNumber(registrationNo))
error += Messages.getValue("error.alreadyexist",
new Object[] { "Registration Number '"
+ registrationNo + "'" });
if (error.length() == 0) {
vehicleMasterDTO.setUserID(userRegistrationDTO
.getId());
vehicleMasterDTO.setMake(make);
vehicleMasterDTO.setModel(model);
vehicleMasterDTO.setColor(color);
vehicleMasterDTO.setReg_NO(registrationNo);
vehicleMasterDTO.setCapacity(capacity);
vehicleMasterDTO = ListOfValuesManager
.getVehicleMaster("findByDTO",
vehicleMasterDTO);
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
rollbackTest = true;
error += Messages.getValue("error.db1",
new Object[] { "Vehicle" });
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"error.db1", new Object[] { "Vehicle" })
+ e.getMessage());
userMessageDTO.setToMember(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} finally {
rollbackTest = false;
if (error.length() > 0)
errorMessage.add("Row " + i + " : " + error);
else
successMessage.add(Messages.getValue(
"success.uploading", new Object[] {
"Vehicle", i }));
}
if (errorMessage.size() > 0) {
errorMessage.add(Messages.getValue("error.uploading",
new Object[] { "Vehicle" }));
break;
}
}
} catch (BiffException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
} catch (IOException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
vehicleList();
vehicleMasterDTO = new VehicleMasterDTO();
userMessageDTO = new MessageBoardDTO();
}
}
public void handleUserUpload(FileUploadEvent event) {
UploadedFile item = event.getFile();
String tomcatDirectoryPath = ApplicationUtil.catalinaDirectoryPath;
String extension = ServerUtility.getExtension(item);
String path = null;
File userPath = null;
if (tomcatDirectoryPath != null) {
String userDirPath = ApplicationUtil.userDirectoryPath;
path = ServerUtility.constructTargetFileName("user_"
+ userRegistrationDTO.getId(), extension, userDirPath);
userPath = new File(userDirPath + path);
try {
InputStream input = item.getInputstream();
OutputStream output = new FileOutputStream(userPath);
try {
IOUtils.copy(input, output);
} catch (Exception e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
} finally {
input.close();
output.flush();
output.close();
}
} catch (IOException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
Workbook workbook;
try {
workbook = Workbook.getWorkbook(userPath);
Sheet sheet = workbook.getSheet(0);
clearScreenMessage();
for (int i = 1;; i++) {
String email = sheet.getCell(0, i).getContents();
String mobileNo = sheet.getCell(1, i).getContents();
String gender = sheet.getCell(2, i).getContents();
/*
* String dob = sheet.getCell(3,i).getContents(); try { dob
* = new
* SimpleDateFormat(ApplicationUtil.datePattern1).format(new
* SimpleDateFormat
* (ApplicationUtil.datePattern6).parse(dob)); } catch
* (ParseException e2) { } String address =
* sheet.getCell(4,i).getContents(); String city =
* sheet.getCell(5,i).getContents(); String pin =
* sheet.getCell(6,i).getContents(); String firstName =
* sheet.getCell(7,i).getContents(); String lastName =
* sheet.getCell(8,i).getContents();
*/
String firstName = sheet.getCell(3, i).getContents();
String lastName = sheet.getCell(4, i).getContents();
// String travel = sheet.getCell(5,i).getContents();
String travel = "B";
if (userRegistrationDTO.getTravel().equalsIgnoreCase("T")) {
travel = "T";
}
if (email.trim() == null || email.trim().isEmpty()) {
break;
}
String error = "";
if (Validator.isEmpty(email))
error += Messages.getValue("error.required",
new Object[] { "Email" });
if (Validator.isNotEmail(email))
error += Messages.getValue("error.format",
new Object[] { "Email" });
if (Validator.isEmpty(mobileNo))
error += Messages.getValue("error.required",
new Object[] { "Mobile Number" });
if (Validator.isNotPhone(mobileNo))
error += Messages.getValue("error.format",
new Object[] { "Mobile Number" });
if (Validator.isEmpty(gender))
error += Messages.getValue("error.required",
new Object[] { "Gender" });
if (!gender.equalsIgnoreCase("f")
&& !gender.equalsIgnoreCase("m"))
error += "Gender must be M/F.";
if (Validator.isEmpty(firstName))
error += Messages.getValue("error.required",
new Object[] { "First Name" });
if (Validator.isEmpty(lastName))
error += Messages.getValue("error.required",
new Object[] { "Last Name" });
if (Validator.isNotName(firstName))
error += Messages.getValue("error.format",
new Object[] { "First Name" });
if (Validator.isNotName(lastName))
error += Messages.getValue("error.format",
new Object[] { "Last Name" });
if (Validator.isEmpty(travel))
error += Messages.getValue("error.format",
new Object[] { "Travel" });
if (!(travel.equalsIgnoreCase("B")
|| travel.equalsIgnoreCase("C")
|| travel.equalsIgnoreCase("T") || travel
.equalsIgnoreCase("P")))
error += "Mention role P/B/C/T.";
String testUserExistense = ListOfValuesManager
.testEmailAllStatus(email);
if (testUserExistense.equalsIgnoreCase("P"))
error += "Email ID is pending for approval.";
else if (testUserExistense.equalsIgnoreCase("I"))
error += "Email ID de activated. Please contact admin.";
else if (testUserExistense.equalsIgnoreCase("A"))
error += Messages.getValue("error.alreadyexist",
new Object[] { "Email" });
try {
if (error.length() == 0) {
forregistrationOnly = new UserRegistrationDTO();
forregistrationOnly.setEmail_id(email);
forregistrationOnly.setMobile_no(mobileNo);
forregistrationOnly.setGender(gender);
/*
* forregistrationOnly.setBirthdate(dob);
* forregistrationOnly.setAddress(address);
* forregistrationOnly.setCity(city);
* forregistrationOnly.setPincode(pin);
*/
forregistrationOnly.setFirst_name(firstName);
forregistrationOnly.setLast_name(lastName);
forregistrationOnly.setTravel(travel);
String tempPassword = ServerUtility
.randomString(10);
forregistrationOnly.setPassword(tempPassword);
forregistrationOnly.setIsVerified('1');
forregistrationOnly.setVerificationCode("C");
forregistrationOnly.setSignupType(3);
forregistrationOnly.setTotalCredit(50);
forregistrationOnly.setTotalGreenMiles(0);
forregistrationOnly = ListOfValuesManager
.getUserRegistration("findByDTO",
forregistrationOnly,
userRegistrationDTO.getId(), null);
UserPreferencesDTO userPreferencesTemp = new UserPreferencesDTO();
userPreferencesTemp.setUserId(Integer
.parseInt(forregistrationOnly.getId()));
if (forregistrationOnly.getDefaultTimeSlice() != null) {
String[] minuteSlice = forregistrationOnly
.getDefaultTimeSlice().split(":");
if (minuteSlice.length > 1) {
int minuteCount = Integer
.parseInt(minuteSlice[0]) * 60; // convert
// hour
// to
// minute
minuteCount += Integer
.parseInt(minuteSlice[1]);
userPreferencesTemp
.setMaxWaitTime(minuteCount);
}
} else {
userPreferencesTemp.setMaxWaitTime(10);
}
userPreferencesTemp = ListOfValuesManager
.getUserPreferencesSave(
userPreferencesTemp, null);
LoginPageDTO dto = new LoginPageDTO();
PageStoreDTO pageDto = ListOfValuesManager
.getPageStoreByCode(Messages
.getValue("page.code.change.password"));
dto.setUserId(Integer.parseInt(forregistrationOnly
.getId()));
dto.setPageId(pageDto.getPageId());
dto.setStatus("N");
ListOfValuesManager.insertLoginPage(dto);
dto = new LoginPageDTO();
pageDto = ListOfValuesManager
.getPageStoreByCode(Messages
.getValue("page.code.preference"));
dto.setUserId(Integer.parseInt(forregistrationOnly
.getId()));
dto.setPageId(pageDto.getPageId());
dto.setStatus("N");
ListOfValuesManager.insertLoginPage(dto);
for (CircleDTO dto1 : allCircleList) {
CircleMemberDTO circleMemberDTOTemp = new CircleMemberDTO();
circleMemberDTOTemp.setCircleid(String
.valueOf(dto1.getCircleID()));
circleMemberDTOTemp
.setUserid(forregistrationOnly.getId());
circleMemberDTOTemp
.setRequestUserId(forregistrationOnly
.getId());
circleMemberDTOTemp.setStatus("1");
circleMemberDTOTemp = ListOfValuesManager
.getJoinCircle(circleMemberDTOTemp,
userRegistrationDTO.getId(),
null);
circleMemberDTOTemp = new CircleMemberDTO();
}
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setEmailSubject(Messages
.getValue("subject.register"));
userMessageDTO
.setMessage(Messages
.getValue(
"user.upload.register.intro",
new Object[] {
forregistrationOnly
.getFirst_name(),
tempPassword,
forregistrationOnly
.getEmail_id(),
Messages.getValue("login.link") }));
userMessageDTO.setToMember(Integer
.parseInt(forregistrationOnly.getId()));
userMessageDTO.setCreatedBy(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setSubmittedBy(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.register",
new Object[] {
forregistrationOnly
.getFirst_name(),
forregistrationOnly
.getEmail_id() }));
userMessageDTO.setToMember(Integer
.parseInt(forregistrationOnly.getId()));
userMessageDTO.setCreatedBy(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setSubmittedBy(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
rollbackTest = true;
error += Messages.getValue("error.db1",
new Object[] { "User" });
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"error.db1", new Object[] { "User" })
+ e.getMessage());
userMessageDTO.setToMember(Integer
.parseInt(forregistrationOnly.getId()));
userMessageDTO.setCreatedBy(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setSubmittedBy(Integer
.parseInt(userRegistrationDTO.getId()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} finally {
rollbackTest = false;
if (error.length() > 0)
errorMessage.add("Row " + i + " : " + error);
else
successMessage.add(Messages.getValue(
"success.uploading", new Object[] { "User",
i })
+ ", " + email);
}
if (errorMessage.size() > 0) {
errorMessage.add(Messages.getValue("error.uploading",
new Object[] { "User" }));
break;
}
}
} catch (BiffException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
// TODO Auto-generated catch block
} catch (IOException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
// TODO Auto-generated catch block
}
vehicleList();
vehicleMasterDTO = new VehicleMasterDTO();
}
userMessageDTO = new MessageBoardDTO();
}
public void cronCompletedRideMessageBoard() {
List<RideSeekerDTO> rideSeekerTemp = new ArrayList<RideSeekerDTO>();
List<RideManagementDTO> rideManagementTemp = new ArrayList<RideManagementDTO>();
try {
rideSeekerTemp = ListOfValuesManager.fetchCompletedRideSeekerList();
rideManagementTemp = ListOfValuesManager
.fetchCompletedRideManagementList();
for (RideSeekerDTO dto : rideSeekerTemp) {
if (dto.getUserID() != null && !dto.getUserID().equals("")
&& Integer.parseInt(dto.getUserID()) > 0) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"ride.completed",
new Object[] { dto.getStartDate(),
dto.getEndDate(),
dto.getSeekerID(),
dto.getFromAddress1(),
dto.getToAddress1(), }));
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserID()));
userMessageDTO.setEmailSubject("Ride Seeker completed");
if (dto.getSeekerID() != null
&& !dto.getSeekerID().equals("")
&& Integer.parseInt(dto.getSeekerID()) > 0) {
userMessageDTO.setRideId(Integer.parseInt(dto
.getSeekerID()));
}
userMessageDTO.setMessageChannel("A");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
for (RideManagementDTO dto : rideManagementTemp) {
if (dto.getUserID() != null && !dto.getUserID().equals("")
&& Integer.parseInt(dto.getUserID()) > 0) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"ride.completed",
new Object[] { dto.getStartDate(),
dto.getEndDate(), dto.getRideID(),
dto.getFromAddress1(),
dto.getToAddress1(), }));
userMessageDTO
.setToMember(Integer.parseInt(dto.getUserID()));
userMessageDTO.setEmailSubject("Ride Seeker completed");
userMessageDTO.setRideId(Integer.parseInt(dto.getRideID()));
userMessageDTO.setMessageChannel("A");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
} finally {
}
rollbackTest = false;
userMessageDTO = new MessageBoardDTO();
}
public void cronMessage() {
List<Integer> messageId = new ArrayList<Integer>();
try {
List<MessageBoardDTO> messagedto = ListOfValuesManager
.getAllEmailSendingMessage();
for (MessageBoardDTO dto : messagedto) {
EmailDTO emaildto = new EmailDTO();
emaildto.setReceiverEmailId(dto.getToMemberEmail());
emaildto.setSenderEmailId(dto.getCreatedByEmail());
emaildto.setSubject(dto.getEmailSubject());
if (emaildto.getSubject() == null)
emaildto.setSubject(Messages.getValue("subject.default"));
// emaildto.setEmailBody(dto.getMessage());
emaildto.setEmailTemplateBody(Messages.getValue(
"email.template2", new Object[] {
emaildto.getSubject(), dto.getMessage() }));
if (dto.getAttachements() != null
&& dto.getAttachements().size() > 0) {
emaildto.setAttachements(dto.getAttachements());
}
MailService.sendMail(emaildto);
messageId.add(dto.getMessageId());
}
} finally {
}
int[] msgId = new int[messageId.size()];
int i = 0;
for (Iterator<Integer> it = messageId.iterator(); it.hasNext(); msgId[i++] = it
.next())
;
if (msgId.length > 0) {
ListOfValuesManager.makeEmailStatusSent(msgId);
rollbackTest = false;
}
try {
List<MessageBoardDTO> messagedto = ListOfValuesManager
.getAllSmsSendingMessage();
List<Integer> userId = new ArrayList<Integer>();
for (MessageBoardDTO dto : messagedto) {
userId.add(dto.getToMember());
}
List<UserRegistrationDTO> userDto = ListOfValuesManager
.getAllUserById(userId);
Map<String, String> userMap = new HashMap<String, String>();
for (UserRegistrationDTO dtoTemp : userDto) {
userMap.put(dtoTemp.getId(), dtoTemp.getMobile_no());
}
for (MessageBoardDTO dto : messagedto) {
try {
SmsService.sendSms(userMap.get("" + dto.getToMember()),
dto.getMessage());
} catch (Exception e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName()
+ "() : "
+ e.getStackTrace()[0].getLineNumber()
+ " :: " + e.getMessage());
}
}
} finally {
}
userMessageDTO = new MessageBoardDTO();
}
public void clearScreenMessage() {
successMessage.clear();
errorMessage.clear();
}
public void listOfRideForACircle() {
matchedTripByConditionList = ListOfValuesManager
.getRideSekerForCircle(String.valueOf(circleDTO.getCircleID()));
matchedTripDataModel = new MatchedTripDataModel(
matchedTripByConditionList);
}
public List<SelectItem> getVehicleListForDriver() {
List<SelectItem> list = new ArrayList<SelectItem>();
if (vehicleMasterDTOList != null) {
for (int i = 0; i < vehicleMasterDTOList.size(); i++) {
if (vehicleMasterDTOList.get(i).getDrivername()
.equalsIgnoreCase("NoDriver")) {
list.add(new SelectItem(vehicleMasterDTOList.get(i)
.getVehicleID(), vehicleMasterDTOList.get(i)
.getModel()
+ "-"
+ vehicleMasterDTOList.get(i).getReg_NO()));
}
}
}
return list;
}
public List<SelectItem> getAllUserForACircle() {
List<SelectItem> list = new ArrayList<SelectItem>();
List<UserRegistrationDTO> userList = new ArrayList<UserRegistrationDTO>();
userList = ListOfValuesManager.getAllUsaerOfACircle(userRegistrationDTO
.getId());
for (int j = 0; j < vehicleMasterDTOList.size(); j++) {
for (int i = 0; i < userList.size(); i++) {
if (vehicleMasterDTOList.get(j).getDriverid()
.equalsIgnoreCase(userList.get(i).getId())) {
userList.remove(i);
}
}
}
if (userList != null) {
for (int i = 0; i < userList.size(); i++) {
list.add(new SelectItem(userList.get(i).getFirst_name() + "-"
+ userList.get(i).getAddress() + ","
+ userList.get(i).getId(), userList.get(i)
.getFirst_name()
+ "-"
+ userList.get(i).getAddress()
+ "," + userList.get(i).getId()));
}
}
return list;
}
public String addDriverForVehicle() {
String link = null;
String delink = null;
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestMap = context.getExternalContext()
.getRequestParameterMap(); // In java class, you can get back
// the parameter value with
// component (submit-command buton)
// like this :
link = (String) requestMap.get("link");
delink = (String) requestMap.get("delink");
if (link != null) {
vehicleMasterDTO.setAvilable(link);
String[] parts = forregistrationOnly.getFirst_name().split(",");
String[] names = parts[0].split("-");
String driverName = names[0];
String part2 = "0";
if (parts.length > 0)
part2 = parts[parts.length - 1];
vehicleMasterDTO.setUserID(part2);
vehicleMasterDTO.setDrivername(driverName);
}
if (delink != null) {
vehicleMasterDTO.setCapacity(null);
vehicleMasterDTO.setAvilable(delink);
}
vehicleMasterDTO = ListOfValuesManager
.getUpdateVehicle(vehicleMasterDTO);
rollbackTest = false;
vehicleList();
forregistrationOnly.setFirst_name(null);
vehicleMasterDTO = new VehicleMasterDTO();
return "link";
}
public void smsReplyOperation(String smsSid, String fromNumber,
String toNumber, String body, String exotelDate) {
fromNumber = fromNumber.replaceFirst("^[0|+]*", "");
body = body.trim();
SmsReplyDTO dto = new SmsReplyDTO();
dto.setBody(body);
dto.setSmsSid(smsSid);
dto.setFromNumber(fromNumber);
dto.setToNumber(toNumber);
dto.setExotelDate(exotelDate);
dto = ListOfValuesManager.addSms(dto);
String[] bodyPart = body.split(" ");
if (bodyPart.length >= 2) {
String msg = bodyPart[0];
int rideId = 0;
try {
rideId = Integer.parseInt(bodyPart[1]);
if (msg.equalsIgnoreCase("CAN")) {
RideSeekerDTO seekerDto = new RideSeekerDTO();
try {
seekerDto = ListOfValuesManager
.getRideSeekerData(rideId);
List<Integer> a = new ArrayList<Integer>();
a.add(Integer.parseInt(seekerDto.getUserID()));
UserRegistrationDTO userTemp = ListOfValuesManager
.getAllUserById(a).get(0);
if (userTemp != null && userTemp.getMobile_no() != null
&& userTemp.getMobile_no().equals(fromNumber)
&& userTemp.getStatus().equalsIgnoreCase("A")) {
seekerDto.setSeekerID(rideId + "");
seekerDto.setStatus("I");
ListOfValuesManager.getCancleRideSeeker(seekerDto,
null);
ListOfValuesManager
.changePoolRequestStatusForRideGiver(null,
Integer.parseInt(seekerDto
.getSeekerID()));
seekerDto = ListOfValuesManager
.getRideSeekerData(Integer
.parseInt(seekerDto.getSeekerID()));
if (seekerDto.getIsResult().equalsIgnoreCase("N")) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { seekerDto
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"rideSeeker.unmatched.cancel",
new Object[] {
userTemp.getFirst_name(),
seekerDto
.getSeekerID(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.rideSeeker.unmatched.cancel",
new Object[] {
userTemp.getFirst_name(),
seekerDto
.getSeekerID(),
(seekerDto
.getFromAddress1()
.length() > 25) ? seekerDto
.getFromAddress1()
.substring(
0,
25)
: seekerDto
.getFromAddress1(),
(seekerDto
.getToAddress1()
.length() > 25) ? seekerDto
.getToAddress1()
.substring(
0,
25)
: seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"sms.cancel",
new Object[] {
userTemp.getFirst_name(),
(seekerDto
.getFromAddress1()
.length() > 25) ? seekerDto
.getFromAddress1()
.substring(0,
25)
: seekerDto
.getFromAddress1(),
(seekerDto
.getToAddress1()
.length() > 25) ? seekerDto
.getToAddress1()
.substring(0,
25)
: seekerDto
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userTemp.getMobile_no(),
seekerDto
.getRideMatchRideId() }));
userMessageDTO.setToMember(Integer
.parseInt(userTemp.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { seekerDto
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"rideSeeker.matched.cancel",
new Object[] {
userTemp.getFirst_name(),
seekerDto
.getRideMatchRideId(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(userTemp.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
/* Now message should go to driver. */
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto = ListOfValuesManager
.findDriverDtoByRideId(
seekerDto.getRideMatchRideId(),
null);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.cancel.driver",
new Object[] {
userDto.getFirst_name(),
userTemp.getFirst_name(),
seekerDto
.getRideMatchRideId(),
(seekerDto
.getFromAddress1()
.length() > 25) ? seekerDto
.getFromAddress1()
.substring(
0,
25)
: seekerDto
.getFromAddress1(),
(seekerDto
.getToAddress1()
.length() > 25) ? seekerDto
.getToAddress1()
.substring(
0,
25)
: seekerDto
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userTemp.getMobile_no() }));
userMessageDTO.setToMember(Integer
.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto.getSeekerID()));
userMessageDTO.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages.getValue(
"subject.cancel",
new Object[] { seekerDto
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"driver.match.cancel",
new Object[] {
userDto.getFirst_name(),
userTemp.getFirst_name(),
seekerDto
.getRideMatchRideId(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue(),
userDto.getMobile_no(),
Messages.getValue("customer.support") }));
userMessageDTO.setToMember(Integer
.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto.getSeekerID()));
userMessageDTO.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
if (seekerDto.getRecurring().equalsIgnoreCase("Y")) {
String[] rides = seekerDto.getSubSeekers()
.split(",");
if (rides.length > 0) {
seekerDto.setStatus("I");
seekerDto = ListOfValuesManager
.cancelSubSeekers(null, seekerDto);
rides = seekerDto.getSubSeekers()
.split(",");
for (int i = 0; i < rides.length; i++) {
ListOfValuesManager
.changePoolRequestStatusForRideGiver(
null,
Integer.parseInt(rides[i]));
seekerDto = ListOfValuesManager
.getRideSeekerData(Integer
.parseInt(rides[i]));
if (seekerDto.getIsResult()
.equalsIgnoreCase("N")) {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages
.getValue(
"subject.cancel",
new Object[] { seekerDto
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"rideSeeker.unmatched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
seekerDto
.getSeekerID(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(seekerDto
.getUserID()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto
.getSeekerID()));
userMessageDTO
.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.rideSeeker.unmatched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
seekerDto
.getSeekerID(),
(seekerDto
.getFromAddress1()
.length() > 25) ? seekerDto
.getFromAddress1()
.substring(
0,
25)
: seekerDto
.getFromAddress1(),
(seekerDto
.getToAddress1()
.length() > 25) ? seekerDto
.getToAddress1()
.substring(
0,
25)
: seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setToMember(Integer
.parseInt(seekerDto
.getUserID()));
userMessageDTO
.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
(seekerDto
.getFromAddress1()
.length() > 25) ? seekerDto
.getFromAddress1()
.substring(
0,
25)
: seekerDto
.getFromAddress1(),
(seekerDto
.getToAddress1()
.length() > 25) ? seekerDto
.getToAddress1()
.substring(
0,
25)
: seekerDto
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userRegistrationDTO
.getMobile_no(),
seekerDto
.getRideMatchRideId() }));
userMessageDTO
.setToMember(Integer
.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto
.getSeekerID()));
userMessageDTO
.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages
.getValue(
"subject.cancel",
new Object[] { seekerDto
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"rideSeeker.matched.cancel",
new Object[] {
userRegistrationDTO
.getFirst_name(),
seekerDto
.getRideMatchRideId(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO
.setToMember(Integer
.parseInt(userRegistrationDTO
.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto
.getSeekerID()));
userMessageDTO
.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
/* Now message should go to driver. */
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto = ListOfValuesManager
.findDriverDtoByRideId(
seekerDto
.getRideMatchRideId(),
null);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"sms.cancel.driver",
new Object[] {
userDto.getFirst_name(),
userRegistrationDTO
.getFirst_name(),
seekerDto
.getRideMatchRideId(),
(seekerDto
.getFromAddress1()
.length() > 25) ? seekerDto
.getFromAddress1()
.substring(
0,
25)
: seekerDto
.getFromAddress1(),
(seekerDto
.getToAddress1()
.length() > 25) ? seekerDto
.getToAddress1()
.substring(
0,
25)
: seekerDto
.getToAddress1(),
ListOfValuesManager
.getcurrentDate(ApplicationUtil.datePattern4),
userRegistrationDTO
.getMobile_no() }));
userMessageDTO.setToMember(Integer
.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto
.getSeekerID()));
userMessageDTO
.setMessageChannel("S");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setEmailSubject(Messages
.getValue(
"subject.cancel",
new Object[] { seekerDto
.getStartdateValue() }));
userMessageDTO
.setMessage(Messages
.getValue(
"driver.match.cancel",
new Object[] {
userDto.getFirst_name(),
userRegistrationDTO
.getFirst_name(),
seekerDto
.getRideMatchRideId(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue(),
userDto.getMobile_no(),
Messages.getValue("customer.support") }));
userMessageDTO.setToMember(Integer
.parseInt(userDto.getId()));
userMessageDTO.setRideId(Integer
.parseInt(seekerDto
.getSeekerID()));
userMessageDTO
.setMessageChannel("E");
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
}
}
}
} catch (ConfigurationException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
}
} else if (msg.equalsIgnoreCase("APR")) {
RideSeekerDTO seekerDto = new RideSeekerDTO();
try {
seekerDto = ListOfValuesManager
.getRideSeekerData(rideId);
if (seekerDto.getStatus() != null
&& seekerDto.getStatus().equalsIgnoreCase("T")) {
ApproverDTO approverDtoTemp = ListOfValuesManager
.findApproverById(seekerDto.getApproverID());
UserRegistrationDTO userTemp = ListOfValuesManager
.findUserByEmail(approverDtoTemp
.getHoponId2());
if (userTemp != null
&& userTemp.getMobile_no() != null
&& userTemp.getMobile_no().equals(
fromNumber)
&& userTemp.getStatus().equalsIgnoreCase(
"A")) {
seekerDto.setSeekerID(rideId + "");
seekerDto.setStatus("O");
ListOfValuesManager.getCancleRideSeeker(
seekerDto, null);
if (approverDtoTemp.getHoponId2() != null
&& approverDtoTemp.getHoponId2()
.length() > 0) {
FrequencyDTO frequencyDto = ListOfValuesManager
.fetchFrequencyListForRideSeeker(
seekerDto.getSeekerID())
.get(0);
String approveLink = Messages
.getValue(
"ride.approve",
new Object[] {
seekerDto
.getSeekerID(),
approverDtoTemp
.getVerificationCode2(),
approverDtoTemp
.getId(),
approverDtoTemp
.getHoponId2() });
String rejectLink = Messages
.getValue(
"ride.reject",
new Object[] {
seekerDto
.getSeekerID(),
approverDtoTemp
.getVerificationCode2(),
approverDtoTemp
.getId(),
approverDtoTemp
.getHoponId2() });
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ approverDtoTemp.getbCode()
+ "<br>Name: "
+ userTemp.getFirst_name()
+ "<br>Request ID: "
+ seekerDto.getSeekerID()
+ "<br>From: "
+ seekerDto.getFromAddress1()
+ "<br>To: "
+ seekerDto.getToAddress1()
+ "<br>Date Time: "
+ seekerDto.getStartdateValue()
+ "<br>Frequency: "
+ frequencyDto.getFrequency()
.toString()
+ "<br>"
+ approveLink
+ " "
+ rejectLink;
if (ListOfValuesManager
.testEmail(approverDtoTemp
.getHoponId2())) {
UserRegistrationDTO dtoTemp = null;
dtoTemp = ListOfValuesManager
.findUserByEmail(approverDtoTemp
.getHoponId2());
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(messageContent);
userMessageDTO
.setEmailSubject(Messages
.getValue("subject.ride.approval"));
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer
.parseInt(dtoTemp.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.msgBoard",
new Object[] {
approverDtoTemp
.getbCode(),
seekerDto
.getSeekerID(),
dtoTemp.getFirst_name(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer
.parseInt(dtoTemp.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.sms",
new Object[] {
approverDtoTemp
.getbCode(),
seekerDto
.getSeekerID(),
dtoTemp.getFirst_name(),
seekerDto
.getFromAddress1()
.substring(
0,
(seekerDto
.getFromAddress1()
.length() >= 20) ? 20
: seekerDto
.getFromAddress1()
.length()),
seekerDto
.getToAddress1()
.substring(
0,
(seekerDto
.getToAddress1()
.length() >= 20) ? 20
: seekerDto
.getToAddress1()
.length()),
seekerDto
.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer
.parseInt(dtoTemp.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
if (seekerDto.getRecurring().equalsIgnoreCase(
"Y")) {
String[] rides = seekerDto.getSubSeekers()
.split(",");
if (rides.length > 0) {
seekerDto.setStatus("O");
seekerDto = ListOfValuesManager
.cancelSubSeekers(null,
seekerDto);
}
}
}
} else if (seekerDto.getStatus() != null
&& seekerDto.getStatus().equalsIgnoreCase("O")) {
ApproverDTO approverDto = ListOfValuesManager
.findApproverById(seekerDto.getApproverID());
UserRegistrationDTO userTemp = ListOfValuesManager
.findUserByEmail(approverDto.getHoponId());
if (userTemp != null
&& userTemp.getMobile_no() != null
&& userTemp.getMobile_no().equals(
fromNumber)
&& userTemp.getStatus().equalsIgnoreCase(
"A")) {
seekerDto.setSeekerID(rideId + "");
seekerDto.setStatus("A");
ListOfValuesManager.getCancleRideSeeker(
seekerDto, null);
frequencyDTO = ListOfValuesManager
.fetchFrequencyListForRideSeeker(
seekerDto.getSeekerID()).get(0);
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ approverDto.getbCode()
+ "<br>Name: "
+ seekerDto.getUserName()
+ "<br>Request ID: "
+ seekerDto.getSeekerID()
+ "<br>From: "
+ seekerDto.getFromAddress1()
+ "<br>To: "
+ seekerDto.getToAddress1()
+ "<br>Date Time: "
+ seekerDto.getStartdateValue()
+ "<br>Frequency: "
+ frequencyDTO.getFrequency()
.toString();
userMessageDTO.setMessage(messageContent);
userMessageDTO
.setEmailSubject("Ride request approved");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.approved",
new Object[] {
approverDto
.getbCode(),
seekerDto
.getSeekerID(),
seekerDto
.getUserName(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.approved",
new Object[] {
approverDto
.getbCode(),
seekerDto
.getSeekerID(),
seekerDto
.getUserName(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
if (seekerDto.getRecurring().equalsIgnoreCase(
"Y")) {
String[] rides = seekerDto.getSubSeekers()
.split(",");
if (rides.length > 0) {
seekerDto.setStatus("A");
seekerDto = ListOfValuesManager
.cancelSubSeekers(null,
seekerDto);
}
}
}
}
} catch (ConfigurationException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
}
} else if (msg.equalsIgnoreCase("REJ")) {
RideSeekerDTO seekerDto = new RideSeekerDTO();
try {
seekerDto = ListOfValuesManager
.getRideSeekerData(rideId);
if (seekerDto.getStatus().equalsIgnoreCase("T")) {
ApproverDTO approverDto = ListOfValuesManager
.findApproverById(seekerDto.getApproverID());
UserRegistrationDTO userTemp = ListOfValuesManager
.findUserByEmail(approverDto.getHoponId2());
if (userTemp != null
&& userTemp.getMobile_no() != null
&& userTemp.getMobile_no().equals(
fromNumber)
&& userTemp.getStatus().equalsIgnoreCase(
"A")) {
seekerDto.setSeekerID(rideId + "");
seekerDto.setStatus("I");
ListOfValuesManager.getCancleRideSeeker(
seekerDto, null);
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ approverDto.getbCode()
+ "<br>Name: "
+ seekerDto.getUserName()
+ "<br>Request ID: "
+ seekerDto.getSeekerID()
+ "<br>From: "
+ seekerDto.getFromAddress1()
+ "<br>To: "
+ seekerDto.getToAddress1()
+ "<br>Date Time: "
+ seekerDto.getStartdateValue();
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO
.setEmailSubject("Ride request rejected");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.rejected",
new Object[] {
approverDto
.getbCode(),
seekerDto
.getSeekerID(),
seekerDto
.getUserName(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages
.getValue(
"ride.option.rejected",
new Object[] {
approverDto
.getbCode(),
seekerDto
.getSeekerID(),
seekerDto
.getUserName(),
seekerDto
.getFromAddress1(),
seekerDto
.getToAddress1(),
seekerDto
.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer
.parseInt(seekerDto.getUserID()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
if (seekerDto.getRecurring().equalsIgnoreCase(
"Y")) {
String[] rides = seekerDto.getSubSeekers()
.split(",");
if (rides.length > 0) {
seekerDto.setStatus("I");
seekerDto = ListOfValuesManager
.cancelSubSeekers(null,
seekerDto);
}
}
}
} else if (seekerDto.getStatus().equalsIgnoreCase("O")) {
ApproverDTO approverDto = ListOfValuesManager
.findApproverById(seekerDto.getApproverID());
UserRegistrationDTO userTemp = ListOfValuesManager
.findUserByEmail(approverDto.getHoponId());
if (userTemp != null
&& userTemp.getMobile_no() != null
&& userTemp.getMobile_no().equals(
fromNumber)
&& userTemp.getStatus().equalsIgnoreCase(
"A")) {
seekerDto.setSeekerID(rideId + "");
seekerDto.setStatus("I");
ListOfValuesManager.getCancleRideSeeker(
seekerDto, null);
if (seekerDto.getRecurring().equalsIgnoreCase(
"Y")) {
String[] rides = seekerDto.getSubSeekers()
.split(",");
if (rides.length > 0) {
seekerDto.setStatus("I");
seekerDto = ListOfValuesManager
.cancelSubSeekers(null,
seekerDto);
}
}
}
}
} catch (ConfigurationException e1) {
LoggerSingleton.getInstance().error(
e1.getStackTrace()[0].getClassName() + "->"
+ e1.getStackTrace()[0].getMethodName()
+ "() : "
+ e1.getStackTrace()[0].getLineNumber()
+ " :: " + e1.getMessage());
}
}
} catch (NumberFormatException e) {
}
}
}
public void updatePoolForIsResult() {
ListOfValuesManager.getUpdatePoolForIsResult();
rollbackTest = false;
}
public void populateApprover() {
approverdtoList.clear();
/*
* HttpSession currentSession = ServerUtility.getSession();
* if(currentSession.getAttribute("approverdtoList") != null &&
* ((List<ApproverDTO>)
* currentSession.getAttribute("approverdtoList")).size() == 0) {
* approverdtoList.addAll((List<ApproverDTO>)
* currentSession.getAttribute("approverdtoList")); } else { try {
*/
approverdtoList.addAll(ListOfValuesManager.findApproverForUser(Integer
.parseInt(userRegistrationDTO.getId())));
/*
* currentSession.setAttribute("approverdtoList", approverdtoList); }
* catch (NumberFormatException e) {
* currentSession.removeAttribute("approverdtoList"); } }
*/
}
public void addApprover() {
clearScreenMessage();
populateApprover();
int circleId = 0;
for (CircleDTO dto : allCircleList) {
if (dto.getCircleType().equals("C"))
circleId = dto.getCircleID();
}
if (circleId > 0) {
if ((approverdto.getHoponId() == null || approverdto.getHoponId()
.trim().length() == 0)) {
errorMessage.add("Please enter first approver hopon iD.");
}
if (approverdto.getHoponId() != null
&& approverdto.getHoponId2() != null
&& approverdto.getHoponId().equalsIgnoreCase(
approverdto.getHoponId2())) {
errorMessage
.add("Second approver HopOn ID should be different from First HopOn ID.");
}
if (errorMessage.size() == 0) {
approverdto.setCircleId(circleId);
approverdto.setCreatedBy(userRegistrationDTO.getId());
approverdto.setVerificationCode(ServerUtility.randomString(15));
if (approverdto.getHoponId2() != null
&& approverdto.getHoponId2().length() > 0) {
approverdto.setVerificationCode2(ServerUtility
.randomString(15));
}
approverdto = ListOfValuesManager.addApprover(approverdto);
HttpSession currentSession = ServerUtility.getSession();
currentSession.removeAttribute("approverdtoList");
successMessage.add("Approver added successfully!");
}
} else {
errorMessage.add("Please register circle First.");
}
approverdto = new ApproverDTO();
populateApprover();
}
public void handleVehiclePopUp(SelectEvent evt) {
MatchedTripDTO dto = (MatchedTripDTO) evt.getObject();
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern9);
clearRidePreVehicleList();
try {
String date = new SimpleDateFormat(ApplicationUtil.datePattern3)
.format(dateFormat.parse(dto.getStartDate()));
ridePreVehicleList = ListOfValuesManager.fetchRidePreVehicleList(
date, Integer.parseInt(userRegistrationDTO.getId()));
} catch (ParseException e) {
} catch (NumberFormatException e) {
}
try {
ridePreVehicleDate = new SimpleDateFormat(
ApplicationUtil.datePattern7).format(dateFormat.parse(dto
.getStartDate()));
} catch (ParseException e) {
}
}
public void clearRidePreVehicleList() {
ridePreVehicleList.clear();
ridePreVehicleDate = "";
}
public void populateVehicleByDate() {
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern12);
// clearRidePreVehicleList();
try {
Date date1 = dateFormat.parse(ridePreVehicleDate);
String date2 = new SimpleDateFormat(ApplicationUtil.datePattern3)
.format(date1);
ridePreVehicleList = ListOfValuesManager.fetchRidePreVehicleList(
date2, Integer.parseInt(userRegistrationDTO.getId()));
} catch (ParseException e) {
}
}
public void inBoundMessageToApprover() {
List<RideSeekerDTO> dtos = new ArrayList<RideSeekerDTO>();
dtos.addAll(ListOfValuesManager.fetchRideSeekerUnApproved());
for (RideSeekerDTO dto : dtos) {
ApproverDTO approverDtoTemp = ListOfValuesManager
.findApproverById(dto.getApproverID());
if (dto.getStatus().equalsIgnoreCase("O")
&& approverDtoTemp.getHoponId() != null
&& approverDtoTemp.getHoponId().length() > 0) {
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ approverDtoTemp.getbCode()
+ "<br>Name: "
+ dto.getUserName()
+ "<br>Request ID: "
+ dto.getSeekerID()
+ "<br>From: "
+ dto.getFromAddress1()
+ "<br>To: "
+ dto.getToAddress1()
+ "<br>Date Time: "
+ dto.getStartdateValue();
String approveLink = Messages.getValue(
"ride.approve",
new Object[] {
dto.getSeekerID(),
URLEncoder.encode(approverDtoTemp
.getVerificationCode()),
approverDtoTemp.getId(),
approverDtoTemp.getHoponId() });
String rejectLink = Messages.getValue(
"ride.reject",
new Object[] {
dto.getSeekerID(),
URLEncoder.encode(approverDtoTemp
.getVerificationCode()),
approverDtoTemp.getId(),
approverDtoTemp.getHoponId() });
messageContent += "<br> " + approveLink + " "
+ rejectLink;
if (ListOfValuesManager.testEmail(approverDtoTemp.getHoponId())) {
UserRegistrationDTO userTemp = null;
userTemp = ListOfValuesManager
.findUserByEmail(approverDtoTemp.getHoponId());
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO.setEmailSubject("Ride Request for Approval");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.msgBoard",
new Object[] { approverDtoTemp.getbCode(),
dto.getSeekerID(), dto.getUserName(),
dto.getFromAddress1(), dto.getToAddress1(),
dto.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"ride.option.sms",
new Object[] {
approverDtoTemp.getbCode(),
dto.getSeekerID(),
dto.getUserName(),
dto.getFromAddress1()
.substring(
0,
(dto.getFromAddress1()
.length() >= 20) ? 20
: dto.getFromAddress1()
.length()),
dto.getToAddress1()
.substring(
0,
(dto.getToAddress1()
.length() >= 20) ? 20
: dto.getToAddress1()
.length()),
dto.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
EmailDTO emaildto = new EmailDTO();
emaildto.setReceiverEmailId(approverDtoTemp.getHoponId());
emaildto.setSubject("Ride Request for Approval");
emaildto.setEmailTemplateBody(Messages.getValue(
"email.template2", new Object[] { "", "",
messageContent, "", "", "", "" }));
MailService.sendMail(emaildto);
}
} else if (dto.getStatus().equalsIgnoreCase("T")
&& approverDtoTemp.getHoponId2() != null
&& approverDtoTemp.getHoponId2().length() > 0) {
String messageContent = "<span style='font-size: 17px;font-weight: bold;text-decoration: underline;'>Ride Details</span><br>B-Code: "
+ approverDtoTemp.getbCode()
+ "<br>Name: "
+ dto.getUserName()
+ "<br>Request ID: "
+ dto.getSeekerID()
+ "<br>From: "
+ dto.getFromAddress1()
+ "<br>To: "
+ dto.getToAddress1()
+ "<br>Date Time: "
+ dto.getStartdateValue();
String approveLink = Messages.getValue(
"ride.approve",
new Object[] {
dto.getSeekerID(),
URLEncoder.encode(approverDtoTemp
.getVerificationCode2()),
approverDtoTemp.getId(),
approverDtoTemp.getHoponId2() });
String rejectLink = Messages.getValue(
"ride.reject",
new Object[] {
dto.getSeekerID(),
URLEncoder.encode(approverDtoTemp
.getVerificationCode2()),
approverDtoTemp.getId(),
approverDtoTemp.getHoponId2() });
messageContent += "<br> " + approveLink + " "
+ rejectLink;
if (ListOfValuesManager
.testEmail(approverDtoTemp.getHoponId2())) {
UserRegistrationDTO userTemp = null;
userTemp = ListOfValuesManager
.findUserByEmail(approverDtoTemp.getHoponId2());
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(messageContent);
userMessageDTO.setEmailSubject("Ride Request for Approval");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.option.msgBoard",
new Object[] { approverDtoTemp.getbCode(),
dto.getSeekerID(), dto.getUserName(),
dto.getFromAddress1(), dto.getToAddress1(),
dto.getStartdateValue() }));
userMessageDTO.setMessageChannel("M");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO
.setMessage(Messages.getValue(
"ride.option.sms",
new Object[] {
approverDtoTemp.getbCode(),
dto.getSeekerID(),
dto.getUserName(),
dto.getFromAddress1()
.substring(
0,
(dto.getFromAddress1()
.length() >= 20) ? 20
: dto.getFromAddress1()
.length()),
dto.getToAddress1()
.substring(
0,
(dto.getToAddress1()
.length() >= 20) ? 20
: dto.getToAddress1()
.length()),
dto.getStartdateValue() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(Integer.parseInt(userTemp
.getId()));
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
} else {
EmailDTO emaildto = new EmailDTO();
emaildto.setReceiverEmailId(approverDtoTemp.getHoponId2());
emaildto.setSubject("Ride Request for Approval");
emaildto.setEmailTemplateBody(Messages.getValue(
"email.template2", new Object[] { "", "",
messageContent, "", "", "", "" }));
MailService.sendMail(emaildto);
}
}
}
}
public void outBoundMessageToAssignTaxi() {
Map<Integer, List<RideSeekerDTO>> map = new HashMap<Integer, List<RideSeekerDTO>>();
map = ListOfValuesManager.getunAssignedTaxi();
for (Map.Entry<Integer, List<RideSeekerDTO>> entry : map.entrySet()) {
int userId = entry.getKey();
List<RideSeekerDTO> dtos = entry.getValue();
UserRegistrationDTO userDto = ListOfValuesManager
.getUserById(userId);
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue(
"ride.unassigned.email",
new Object[] { userDto.getFirst_name(), dtos.size() }));
userMessageDTO.setEmailSubject("Reminder to assign vehicle");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(userId);
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
userMessageDTO = new MessageBoardDTO();
userMessageDTO.setMessage(Messages.getValue("ride.unassigned.sms",
new Object[] { userDto.getFirst_name(), dtos.size() }));
userMessageDTO.setMessageChannel("S");
userMessageDTO.setToMember(userId);
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
public void outBoundMessageLargeToAssignTaxi() {
Map<Integer, List<RideSeekerDTO>> map = new HashMap<Integer, List<RideSeekerDTO>>();
map = ListOfValuesManager.getunAssignedTaxiForOwner();
for (Map.Entry<Integer, List<RideSeekerDTO>> entry : map.entrySet()) {
int userId = entry.getKey();
List<RideSeekerDTO> dtos = entry.getValue();
UserRegistrationDTO userDto = ListOfValuesManager
.getUserById(userId);
MessageBoardDTO userMessageDTO = new MessageBoardDTO();
try {
String path = ApplicationUtil.demoDirectoryPath;
int noOfFiles = 0;
try {
noOfFiles = new java.io.File(path).listFiles().length;
} catch (NullPointerException e) {
}
String fileName = "attachement_" + (noOfFiles + 1) + ".xls";
WritableWorkbook workbook = Workbook
.createWorkbook(new java.io.File(path + fileName));
WritableSheet writablesheet = workbook.createSheet("Sheet1", 0);
writablesheet.addCell(new Label(1, 0, "Request ID"));
writablesheet.addCell(new Label(2, 0, "Name"));
writablesheet.addCell(new Label(3, 0, "From"));
writablesheet.addCell(new Label(4, 0, "To"));
writablesheet.addCell(new Label(5, 0, "Start Date"));
int counter = 1;
for (RideSeekerDTO dto : dtos) {
writablesheet.addCell(new Label(0, counter, counter + ""));
writablesheet.addCell(new Label(1, counter, dto
.getSeekerID()));
writablesheet.addCell(new Label(2, counter, dto
.getUserName()));
writablesheet.addCell(new Label(3, counter, dto
.getFromAddress1()));
writablesheet.addCell(new Label(4, counter, dto
.getToAddress1()));
writablesheet.addCell(new Label(5, counter, dto
.getStartdateValue()));
counter++;
}
workbook.write();
workbook.close();
Map<String, String> attachements = new HashMap<String, String>();
attachements.put("Ride list.xls", path + fileName);
userMessageDTO.setAttachements(attachements);
} catch (WriteException e) {
} catch (IOException e) {
}
userMessageDTO.setMessage(Messages.getValue("ride.pending.email",
new Object[] { userDto.getFirst_name(), dtos.size() }));
userMessageDTO.setEmailSubject("Pending Rides");
userMessageDTO.setMessageChannel("E");
userMessageDTO.setToMember(userId);
userMessageDTO = ListOfValuesManager
.getInsertedMessage(userMessageDTO);
}
}
public void recurringRideCron() {
List<RideSeekerDTO> dtos = new ArrayList<RideSeekerDTO>();
dtos.addAll(ListOfValuesManager.fetchRecurringRideList());
Date post2Date = new Date(System.currentTimeMillis() + 86400 * 1000 * 2);
for (RideSeekerDTO dto : dtos) {
Date tempDate = dto.getStartDate();
Calendar cal1 = Calendar.getInstance();
cal1.setTime(tempDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(post2Date);
cal2.set(Calendar.HOUR_OF_DAY, cal1.get(Calendar.HOUR_OF_DAY));
cal2.set(Calendar.MINUTE, cal1.get(Calendar.MINUTE));
cal2.set(Calendar.SECOND, cal1.get(Calendar.SECOND));
post2Date = cal2.getTime();
String frequency[] = dto.getFrequencyinweek().replace("[", "")
.replace("]", "").split(",");
// Testing if 2nd day present in trip frequency or not.
for (int i = 0; i < frequency.length; i++) {
if (ApplicationUtil.dateFormat18.format(post2Date)
.equalsIgnoreCase(frequency[i].trim())) {
RideManagementDTO dtoTemp = new RideManagementDTO();
/*
* try { BeanUtils.copyProperties(dtoTemp, dto); } catch
* (IllegalAccessException e) { } catch
* (InvocationTargetException e) { }
* catch(ConversionException e) { }
*/
dtoTemp.setUserID(dto.getUserID());
dtoTemp.setViaPoint(dto.getViaPoint());
dtoTemp.setViaPointLatitude(dto.getViaPointLatitude());
dtoTemp.setViaPointLongitude(dto.getViaPointLongitude());
dtoTemp.setFromAddress1(dto.getFromAddress1());
dtoTemp.setToAddress1(dto.getToAddress1());
DateFormat dateFormat = new SimpleDateFormat(
ApplicationUtil.datePattern3);
dtoTemp.setStartdateValue(dateFormat.format(post2Date));
dtoTemp.setRideID(null);
dtoTemp.setStartDate(post2Date);
dtoTemp.setFlexiTimeAfter(post2Date);
dtoTemp.setFlexiTimeBefore(post2Date);
dtoTemp.setStatus(dto.getStatus());
dtoTemp.setCreated_dt(new Date());
dtoTemp.setFromAddressCity(dto.getToAddressCity());
dtoTemp.setFromAddressPin(dto.getFromAddressPin());
dtoTemp.setFromAddressCity(dto.getToAddressCity());
dtoTemp.setToAddressPin(dto.getToAddressPin());
dtoTemp.setCreatedBy(dto.getCreatedBy());
dtoTemp.setSharedTaxi(dto.isSharedTaxi());
dtoTemp.setCustom(dto.getCustom());
dtoTemp.setStartPointLatitude(dto.getStartPointLatitude());
dtoTemp.setStartPointLongitude(dto.getStartPointLongitude());
dtoTemp.setEndPointLatitude(dto.getEndPointLatitude());
dtoTemp.setEndPointLongitude(dto.getEndPointLongitude());
dtoTemp.setApproverID(dto.getApproverID());
dtoTemp.setRecurring("F");
UserPreferencesDTO userDto = ListOfValuesManager
.getUserPreferences(Integer.parseInt(dtoTemp
.getUserID()));
List x1;
try {
x1 = ApplicationUtil.calculateTimeWindowSettings(
dtoTemp.getFromAddress1(), "",
dtoTemp.getToAddress1(),
userDto.getMaxWaitTime(),
dtoTemp.getStartdateValue());
if (x1.size() > 0) {
dtoTemp.setStartdateValue(x1.get(1).toString());
dtoTemp.setStartDateEarly(x1.get(1).toString());
dtoTemp.setStartDateLate(x1.get(2).toString());
dtoTemp.setEndDateEarly(x1.get(3).toString());
dtoTemp.setEndDateLate(x1.get(4).toString());
float distance = Integer.parseInt(x1.get(5)
.toString()) / 1000;
dtoTemp.setRideDistance(distance);
dtoTemp.setRideCost((distance * 5) + "");
}
} catch (IOException e) {
} catch (JSONException e) {
}
if (!ListOfValuesManager.checkRideSeekerDuplicacy(dtoTemp)) {
Connection con = ListOfValuesManager
.getBroadConnection();
try {
dtoTemp = ListOfValuesManager.getRideSeekerEntery(
"findByDTO", dtoTemp, con);
try {
frequencyDTO = new FrequencyDTO();
frequencyDTO.setStartDate(dateFormat
.format(post2Date));
frequencyDTO.setEndDate(dateFormat
.format(dtoTemp.getEndDate()));
} catch (NullPointerException e) {
}
frequencyDTO.setTime(post2Date);
List<String> freq = new ArrayList<String>();
freq.add("Once");
frequencyDTO.setFrequency(freq);
frequencyDTO.setRideSeekerId(dtoTemp.getRideID());
frequencyDTO = ListOfValuesManager
.getFrequencyEntery("findByDTO",
frequencyDTO, con);
if (dto.getSubSeekers().length() == 0)
dto.setSubSeekers(dtoTemp.getRideID());
else
dto.setSubSeekers(dto.getSubSeekers() + ","
+ dtoTemp.getRideID());
ListOfValuesManager.addSubSeekers(dto, con);
} catch (ConfigurationException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName()
+ "->"
+ e.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e.getStackTrace()[0]
.getLineNumber() + " :: "
+ e.getMessage());
rollbackTest = true;
} finally {
if (rollbackTest) {
try {
con.rollback();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName()
+ "->"
+ e.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e.getStackTrace()[0]
.getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
} else {
try {
con.commit();
} catch (SQLException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName()
+ "->"
+ e.getStackTrace()[0]
.getMethodName()
+ "() : "
+ e.getStackTrace()[0]
.getLineNumber()
+ " :: " + e.getMessage());
}
ListOfValuesManager.releaseConnection(con);
}
}
}
break;
}
}
}
}
public void paymentTransaction() {
paymentList.clear();
try {
paymentList.addAll(ListOfValuesManager.fetchPaymentList(Integer
.parseInt(userRegistrationDTO.getId())));
} catch (NumberFormatException e) {
LoggerSingleton.getInstance().error(
e.getStackTrace()[0].getClassName() + "->"
+ e.getStackTrace()[0].getMethodName() + "() : "
+ e.getStackTrace()[0].getLineNumber() + " :: "
+ e.getMessage());
}
duePaymentList.clear();
for (PaymentDTO dto : paymentList) {
if (dto.getStatus().equalsIgnoreCase("A")) {
duePaymentList.add(dto);
}
}
}
public void validateUserPayment() {
List<Integer> circleIds = new ArrayList<Integer>();
for (CircleDTO dto : allMemberCircleList) {
circleIds.add(dto.getCircleID());
}
List<PaymentDTO> circlePaymentDue = new ArrayList<PaymentDTO>();
circlePaymentDue.addAll(ListOfValuesManager
.fetchActivePaymentListForCircle(circleIds
.toArray(new Integer[circleIds.size()])));
if (circlePaymentDue.size() > 0) {
userCirclePaymentPending = true;
}
}
public void paymentTxnCronToSwapAmount() {
// First fetch list of paymentTxns fro date before today.
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
List<PaymentTxnsDTO> dtos = new ArrayList<PaymentTxnsDTO>();
dtos.addAll(ListOfValuesManager.fetchAllTxnByDate(cal.getTime()));
for (PaymentTxnsDTO dto : dtos) {
if (dto.getFromPayer() == 100) {
// deduct amount from hopon account and add to user account.
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto.setId(String.valueOf(dto.getToPayee()));
userDto.setTotalCredit(dto.getAmount());
HoponAccountDTO hoponAccountDto = new HoponAccountDTO();
hoponAccountDto.setBalance(dto.getAmount());
hoponAccountDto.setIdHoponAccounts(100);
hoponAccountDto.setUpdateDate(ApplicationUtil
.currentTimeStamp());
hoponAccountDto.setUpdatedBy(1);
try {
ListOfValuesManager.paymentTxnHoponToUser(hoponAccountDto,
userDto);
} catch (ConfigurationException e) {
}
}
if (dto.getToPayee() == 100) {
// deduct amount from user account and add to hopon account.
UserRegistrationDTO userDto = new UserRegistrationDTO();
userDto.setId(String.valueOf(dto.getToPayee()));
userDto.setTotalCredit(dto.getAmount());
HoponAccountDTO hoponAccountDto = new HoponAccountDTO();
hoponAccountDto.setBalance(dto.getAmount());
hoponAccountDto.setIdHoponAccounts(100);
hoponAccountDto.setUpdateDate(ApplicationUtil
.currentTimeStamp());
hoponAccountDto.setUpdatedBy(1);
try {
ListOfValuesManager.paymentTxnUserToHopon(hoponAccountDto,
userDto);
} catch (ConfigurationException e) {
}
}
}
}
/*
* This <code>ContactUs</code> Method is nothing but controller for the ContactUs in this we getting the data with the help of ListOfValueManager
* By using the ListOfvaluesManager Class invoke the getContactInfo with parameters
*/
public String contactUs() {
Connection con = (Connection) ListOfValuesManager.getBroadConnection();
boolean flag = ListOfValuesManager.getContactInfo(con, contactusDTO);
System.out.println("values are getting from the controller is:"
+ contactusDTO);
if (flag == true) {
System.out.println("added successfully from the userAction");
contactusDTO = new ContactusDTO();
} else {
System.out.println("Failure");
}
return "contactUs";
}
}
|
[
"[email protected]"
] | |
7e358b821d9bd35474edab9274367fb3494ef619
|
28bb8f9e29a821a15c8262b89f7aa968088ee3d0
|
/src/by/it/sc04_evening_tue_thu/yanushkevich/lesson05/TaskA1.java
|
01f1b1eb259746e78fb09b6ab6803d101e157b20
|
[] |
no_license
|
Khmelov/CS2017-09
|
0ffee1e1054b965b76ee8cf36993f0f3ca310ff2
|
793e0adb7468a62eac9a49f984955070927b55f7
|
refs/heads/master
| 2021-08-26T09:46:59.063670 | 2017-11-23T06:54:45 | 2017-11-23T06:54:45 | 105,267,925 | 0 | 89 | null | 2017-11-23T06:55:45 | 2017-09-29T12:06:36 |
Java
|
UTF-8
|
Java
| false | false | 1,427 |
java
|
package by.it.sc04_evening_tue_thu.yanushkevich.lesson05;
/*
Выведите на экран в цикле 10 раз фразу
Я изучаю программирование.
при выводе сделайте такое разветвление в теле цикла,
чтобы вместо 3-й и 9-й по счету фраз выводилась фраза
Меня интересует высокая зарплата!
Должнен получиться следующий вывод строк:
Я изучаю программирование.
Я изучаю программирование.
Меня интересует высокая зарплата!
Я изучаю программирование.
Я изучаю программирование.
Я изучаю программирование.
Я изучаю программирование.
Я изучаю программирование.
Меня интересует высокая зарплата!
Я изучаю программирование.
*/
public class TaskA1 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
String str = "Я изучаю программирование.";
if (i == 3 || i == 9) {
str = "Меня интересует высокая зарплата!";
}
System.out.println(str);
}
}
}
|
[
"[email protected]"
] | |
0171434f157209845a15803bc75346f8773b80e5
|
925a7ad974200179f5b7f49bcafd926a4eefe397
|
/src/main/java/com/flowerhada/service/impl/InquiryServiceImpl.java
|
867f6cedffa2e88a330cdeef3db3c619a426d0f5
|
[] |
no_license
|
eunvanz/flowerhada-api
|
7926934b9cc722e3ca7c446fdc4ac1bc564f3905
|
350dafc0cc1713baaf08590bc434fa37a2e33281
|
refs/heads/master
| 2021-04-27T02:06:09.891828 | 2018-02-24T01:08:51 | 2018-02-24T01:08:51 | 122,688,986 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,135 |
java
|
package com.flowerhada.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.flowerhada.domain.Inquiry;
import com.flowerhada.repository.InquiryRepository;
import com.flowerhada.service.InquiryService;
import com.flowerhada.util.Utils;
import lombok.RequiredArgsConstructor;
@Service
@Transactional
@RequiredArgsConstructor
public class InquiryServiceImpl implements InquiryService {
@Autowired InquiryRepository inquiryRepository;
@Override
public Inquiry createInquiry(Inquiry inquiry) {
inquiry.setUpdateDate(Utils.getZonedDateTimeNow("Asia/Seoul"));
return inquiryRepository.save(inquiry);
}
@Override
public Page<Inquiry> readAllInquiries(Pageable pageable) {
return inquiryRepository.findAll(pageable);
}
@Override
public Page<Inquiry> readInquiriesByUserId(Long userId, Pageable pageable) {
Page<Inquiry> inquiries = inquiryRepository.findByUserIdOrderByIdDesc(userId, pageable);
for (Inquiry inquiry : inquiries) {
List<Inquiry> answers = inquiryRepository.findByParentId(inquiry.getId());
for (Inquiry answer : answers) {
inquiry.addAnswer(answer);
}
}
return inquiries;
}
@Override
public Inquiry updateInquiry(Inquiry inquiry) {
Inquiry oldInquiry = inquiryRepository.findOne(inquiry.getId());
oldInquiry.setCategory(inquiry.getCategory());
oldInquiry.setContent(inquiry.getContent());
oldInquiry.setParentId(inquiry.getParentId());
oldInquiry.setTitle(inquiry.getTitle());
oldInquiry.setUpdateDate(Utils.getZonedDateTimeNow("Asia/Seoul"));
return oldInquiry;
}
@Override
public void deleteInquiryById(Long id) {
inquiryRepository.delete(id);
}
@Override
public Page<Inquiry> readAllByParentIdIsNull(Pageable pageable) {
return inquiryRepository.findAllByParentIdIsNull(pageable);
}
@Override
public Inquiry readInquiryById(Long id) {
return inquiryRepository.findOne(id);
}
}
|
[
"[email protected]"
] | |
d5c45e6d1f6d882144aec802f6a9cd974633684a
|
3fa26b4e2daa266a794114d0be473680a8d6680c
|
/viewServer/src/main/java/com/dogTracker/viewServer/controller/ViewDataController.java
|
2cc850f1c7e57559810042fc9b9a8c4e2019fea7
|
[
"MIT"
] |
permissive
|
thezelus/dogTracker
|
304b309458826edaa559a4fc87bc716681c53241
|
aa5bd6d7f7d6ca3fa9a6d4d330ba3775c577b036
|
refs/heads/master
| 2020-05-31T13:19:31.662156 | 2015-02-11T15:02:25 | 2015-02-11T15:02:25 | 30,568,891 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 685 |
java
|
package com.dogTracker.viewServer.controller;
import com.dogTracker.model.TrackerData;
import com.dogTracker.viewServer.datastore.Datasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ViewDataController {
@Autowired
Datasource datasource;
@RequestMapping(value = "/liveData", method = RequestMethod.GET)
public List<TrackerData> getDataList(){
return datasource.getDataForAllTrackers();
}
}
|
[
"[email protected]"
] | |
b02f22301da7049a46359920eea9f16d78a38796
|
61883776cf703f69efd50074e893d5a247225dbe
|
/microPlatform-persistance/src/main/java/com/wanliang/micro/repository/cms/ArticleDataRepository.java
|
cd2ff12c69d0fa7c1487fc32ced3bee76a07e796
|
[] |
no_license
|
jbigdata/tinyPlatform
|
dca41679d4720dfff4c9edc9568f5315079e39a1
|
48787910a16ccd80974bdabfec3cf7282f6de5cd
|
refs/heads/master
| 2021-01-10T08:56:06.463812 | 2016-01-22T06:24:24 | 2016-01-22T06:24:24 | 45,234,368 | 0 | 2 | null | null | null | null |
UTF-8
|
Java
| false | false | 483 |
java
|
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.wanliang.micro.repository.cms;
import com.wanliang.micro.entity.cms.ArticleData;
import com.wanliang.micro.persistence.BaseRepository;
import com.wanliang.micro.persistence.annotation.MyBatis;
/**
* 文章DAO接口
* @author ThinkGem
* @version 2013-8-23
*/
@MyBatis
public interface ArticleDataRepository extends BaseRepository<ArticleData> {
}
|
[
"[email protected]"
] | |
4ed7a1cd1b47c7790f0d68ecbd2b1cdd8e709445
|
4d22afd8582191a341a6438c32b666763003b79f
|
/TZ_OOM/lesson6/gen/com/tz/filebrowser/R.java
|
01edb3dcf01e7248a61b189e167b4540b3b2bc18
|
[] |
no_license
|
Moon-College/July_PublicWork
|
2715b3c58c07bffeaad4df48cbf1dff78e43eb85
|
b0e907c542974c9cf2f93a9c9cc27be525824aed
|
refs/heads/master
| 2021-01-16T19:00:44.771289 | 2015-11-08T16:47:20 | 2015-11-08T16:47:20 | 37,726,204 | 19 | 10 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,163 |
java
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.tz.filebrowser;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int file=0x7f020000;
public static final int folder=0x7f020001;
public static final int ic_launcher=0x7f020002;
public static final int message_box_bg=0x7f020003;
}
public static final class id {
public static final int action_settings=0x7f080004;
public static final int iv_icon=0x7f080001;
public static final int lv=0x7f080000;
public static final int tv_count=0x7f080003;
public static final int tv_name=0x7f080002;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int list_view_item=0x7f030001;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050002;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
/** 除去背景色
*/
public static final int branch_info_dialog=0x7f060002;
/** loading dialog
模糊
*/
public static final int loading_dialog=0x7f060003;
}
}
|
[
"[email protected]"
] | |
7c7d1614dd262ddae849651c75392bc9b55e8a86
|
f320b7907616641ac872d4b1615bed7c901164a6
|
/src/assembly/stone/itassembly/baiduvarious/response/PicassoVariousReponse.java
|
a7770e086ada88dddef00e88299bda556527c3d4
|
[] |
no_license
|
microstone123/IT-Collection
|
55ea4d58ab2adfb48aefaaa618a3baf87f4faf97
|
5c4b0eeea1b8fd21daeb27b20e2e18cfc141acc7
|
refs/heads/master
| 2022-02-25T12:00:43.279739 | 2015-09-11T06:26:06 | 2015-09-11T06:26:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,492 |
java
|
package assembly.stone.itassembly.baiduvarious.response;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import assembly.stone.itassembly.baiduvarious.entity.VariousHeadModel;
import assembly.stone.itassembly.jsouphttp.BaseResponse;
public class PicassoVariousReponse extends BaseResponse {
public String webStr;
public List<VariousHeadModel> picTurnsInfoList;
public PicassoVariousReponse(Context context) {
super(context);
}
@Override
public void getDoubleData(Document doc) {
getDetailData(doc);
}
private void getDetailData(Document doc) {
try {
picTurnsInfoList = new ArrayList<VariousHeadModel>();
// Loger.d("Document", doc.toString());
Element singerListDiv = doc.getElementsByAttributeValue("class", "thumbs").first();
Elements links = singerListDiv.getElementsByAttributeValue("class", "thumb");
for (Element link : links) {
VariousHeadModel variousHeadModel = new VariousHeadModel();
Elements title = link.getElementsByTag("a");
variousHeadModel.setHref(title.attr("href"));
Elements titlep = link.getElementsByTag("p");
variousHeadModel.setTitle(titlep.text());
Elements img = link.getElementsByTag("img");
variousHeadModel.setSrc(img.attr("src"));
picTurnsInfoList.add(variousHeadModel);
}
} catch (Exception e) {
}
}
}
|
[
"[email protected]"
] | |
bb8427d93a813774927785728f4d2a6dfb027e6d
|
4fae353033215d84177e9cd163ee8d13155dda33
|
/app/src/main/java/com/sudoajay/duplication_data/DuplicationData/ScanDuplicateData.java
|
ce5379fc56c0f342793072c615be76b56bdf634f
|
[] |
no_license
|
cmFodWx5YWRhdjEyMTA5/DuplicateData
|
a2aa66466493efed2f2c1d54831feed439d23883
|
dc400dc85b63f1cbc145b00865ba481b2122dc8d
|
refs/heads/master
| 2020-05-30T04:39:01.553615 | 2019-04-26T03:28:33 | 2019-04-26T03:28:33 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,355 |
java
|
package com.sudoajay.duplication_data.DuplicationData;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.view.View;
import android.webkit.MimeTypeMap;
import com.sudoajay.duplication_data.Toast.CustomToast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ScanDuplicateData {
private List<File> getAllData = new LinkedList<>();
private ArrayList<String> dataStore = new ArrayList<>();
private static Context context;
public ScanDuplicateData(final Context context) {
ScanDuplicateData.context = context;
}
private static MessageDigest messageDigest;
static {
try {
messageDigest = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
CustomToast.ToastIt(context, "cannot initialize SHA-512 hash function");
}
}
public void Duplication(String external_dir, String sd_Card_dir, int internal_Visible, int external_Visible) {
Map<String, List<String>> lists = new HashMap<>();
if (internal_Visible == View.VISIBLE) {
if (FileExist(external_dir)) Get_All_Path(new File(external_dir));
}
if (external_Visible == View.VISIBLE) {
if (FileExist(sd_Card_dir)) Get_All_Path(new File(sd_Card_dir));
}
// check for length in file_icon
DuplicatedFilesUsingLength();
// check for mime type
DuplicateFileType();
// check for hash using "SHA-512"
DuplicatedFilesUsingHashTable(lists);
for (List<String> list : lists.values()) {
if (list.size() > 1) {
dataStore.addAll(list);
dataStore.add("And");
}
}
}
private void DuplicatedFilesUsingLength() {
ArrayList<Long> getAllDataLength = new ArrayList<>();
for (File data : getAllData) {
getAllDataLength.add(data.length());
}
for (int i = getAllDataLength.size() - 1; i > 0; i--) {
for (int j = 0; j < getAllDataLength.size(); j++) {
if (i != j) {
if (getAllDataLength.get(i).equals(getAllDataLength.get(j))) break;
if (j == getAllDataLength.size() - 1) {
getAllDataLength.remove(i);
getAllData.remove(i);
}
}
}
}
}
private void DuplicateFileType() {
ArrayList<String> getAllDataType = new ArrayList<>();
for (File data : getAllData) {
getAllDataType.add(getMimeType(Uri.fromFile(data)));
}
for (int i = getAllDataType.size() - 1; i > 0; i--) {
for (int j = 0; j < getAllDataType.size(); j++) {
if (i != j) {
if (getAllDataType.get(i) == null || getAllDataType.get(i).equals(getAllDataType.get(j)))
break;
if (j == getAllDataType.size() - 1) {
getAllDataType.remove(i);
getAllData.remove(i);
}
}
}
}
}
public String getMimeType(Uri uri) {
String mimeType = null;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr = context.getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return mimeType;
}
private void DuplicatedFilesUsingHashTable(Map<String, List<String>> lists) {
for (File child : getAllData) {
try {
FileInputStream fileInput = new FileInputStream(child);
byte[] fileData = new byte[(int) child.length()];
int nouse = fileInput.read(fileData);
fileInput.close();
String uniqueFileHash = new BigInteger(1, messageDigest.digest(fileData)).toString(16);
List<String> list = lists.get(uniqueFileHash);
if (list == null) {
list = new LinkedList<>();
lists.put(uniqueFileHash, list);
}
list.add(child.getAbsolutePath());
} catch (IOException e) {
}
}
}
private void Get_All_Path(File directory) {
for (File child : directory.listFiles()) {
if (child.isDirectory()) {
Get_All_Path(child);
} else {
if (!child.getName().equals(".nomedia"))
getAllData.add(child);
}
}
}
public ArrayList<String> getList() {
return dataStore;
}
private boolean FileExist(String path) {
return (new File(path).listFiles() != null && new File(path).exists());
}
}
|
[
"[email protected]"
] | |
3bb36ac8a765a22ad627e94f49e1b558f4d4f7e6
|
d2cb1f4f186238ed3075c2748552e9325763a1cb
|
/methods_all/nonstatic_methods/javax_swing_plaf_metal_MetalComboBoxButton_doClick.java
|
cc35afafaf0541e2b7c4dd8fe817c14f5251507d
|
[] |
no_license
|
Adabot1/data
|
9e5c64021261bf181b51b4141aab2e2877b9054a
|
352b77eaebd8efdb4d343b642c71cdbfec35054e
|
refs/heads/master
| 2020-05-16T14:22:19.491115 | 2019-05-25T04:35:00 | 2019-05-25T04:35:00 | 183,001,929 | 4 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 203 |
java
|
class javax_swing_plaf_metal_MetalComboBoxButton_doClick{ public static void function() {javax.swing.plaf.metal.MetalComboBoxButton obj = new javax.swing.plaf.metal.MetalComboBoxButton();obj.doClick();}}
|
[
"[email protected]"
] | |
fdae8bfedb119af31f77b4facd88d2bd0a34233f
|
8534ea766585cfbd6986fd845e59a68877ecb15b
|
/com/slideme/sam/manager/controller/activities/market/catalog/QueryDynamicLayoutItemActivity.java
|
76b7eb2881ff5d3e23f5135fcfe2af4f2be15041
|
[] |
no_license
|
Shanzid01/NanoTouch
|
d7af94f2de686f76c2934b9777a92b9949b48e10
|
6d51a44ff8f719f36b880dd8d1112b31ba75bfb4
|
refs/heads/master
| 2020-04-26T17:39:53.196133 | 2019-03-04T10:23:51 | 2019-03-04T10:23:51 | 173,720,526 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 582 |
java
|
package com.slideme.sam.manager.controller.activities.market.catalog;
import android.os.Bundle;
import com.slideme.sam.manager.controller.fragment.p056a.ae;
public class QueryDynamicLayoutItemActivity extends ApplicationListActivity {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
}
protected void mo4242b() {
CharSequence string = getIntent().getExtras().getString("com.slideme.sam.manager.EXTRA_TITLE");
this.a = new ae();
if (string != null && string.length() != 0) {
setTitle(string);
}
}
}
|
[
"[email protected]"
] | |
e1b28f067c0c520f8bcef9ad156c8ab41610a4e9
|
fa51687f6aa32d57a9f5f4efc6dcfda2806f244d
|
/jdk8-src/src/main/java/com/sun/corba/se/spi/ior/TaggedComponent.java
|
fe957482e07098e2b2715714df6c548b6d1f2a7e
|
[] |
no_license
|
yida-lxw/jdk8
|
44bad6ccd2d81099bea11433c8f2a0fc2e589eaa
|
9f69e5f33eb5ab32e385301b210db1e49e919aac
|
refs/heads/master
| 2022-12-29T23:56:32.001512 | 2020-04-27T04:14:10 | 2020-04-27T04:14:10 | 258,988,898 | 0 | 1 | null | 2020-10-13T21:32:05 | 2020-04-26T09:21:22 |
Java
|
UTF-8
|
Java
| false | false | 736 |
java
|
/*
* Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.corba.se.spi.ior;
import org.omg.CORBA.ORB;
/**
* Generic interface for all tagged components. Users of the ORB may
* create implementations of this class and also corresponding factories
* of type TaggedComponentFactory. The factories can be registered with an
* ORB instance, in which case they will be used to unmarshal IORs containing
* the registered tagged component.
*/
public interface TaggedComponent extends Identifiable {
org.omg.IOP.TaggedComponent getIOPComponent(ORB orb);
}
|
[
"[email protected]"
] | |
b54efb71c7c23114927adbe38ad0d0d3be8e1cdb
|
727d7b5221898114aca5287de8a4eacae2cdb41d
|
/src/main/java/quizCore/service/QuestionService.java
|
8308e21a9cc4cbc14c925b4559043a0b213d8666
|
[] |
no_license
|
OlegKholodinskyy/springOneMore
|
8f06e276e441afd031ea99fdee6e3f83347c37ee
|
e7e87301de9238a20cf9f501db68b44d2f959a82
|
refs/heads/master
| 2022-06-05T14:01:29.239889 | 2020-05-03T16:32:06 | 2020-05-03T16:32:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 988 |
java
|
package quizCore.service;
import quizCore.dao.QuestionDao;
import quizCore.model.Question;
import java.util.Scanner;
public class QuestionService {
QuestionDao questionDao;
public QuestionService(String path) {
this.questionDao = new QuestionDao(path);
}
public void startTest() {
Scanner scanner = new Scanner(System.in);
System.out.println("Имя:");
String name = scanner.nextLine();
System.out.println("Фамилия:");
String surName = scanner.nextLine();
for (Question q : questionDao.getQuestions()) {
System.out.println(q.getTextQuestion());
int i = 1;
for (String answ : q.getAnswers()) {
System.out.println(i + " " + answ);
i++;
}
int userAnswer = scanner.nextInt();
if (q.getCorrectAnswer() == userAnswer) {
System.out.println("YESSS!!!!");
}
}
}
}
|
[
"[email protected]"
] | |
d9b720e9bf4faeb079a067eb382961c5ba887ef8
|
568a95f99f1fc0f98c3628a9f2b4ee9273255403
|
/Front-end/src/UI/ChiefEngineer/Locomotive/LocoTabController.java
|
fcd409e6bd16725b65b39431a0e50ce2f408ea72
|
[] |
no_license
|
Piuu/LocoMag
|
d590e46c48b6c18d3220d268f9c9707fe080de34
|
983d550873a089a520fcfcd18e562caa77251e39
|
refs/heads/master
| 2020-04-17T16:33:56.346053 | 2017-12-13T08:24:18 | 2017-12-13T08:24:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 817 |
java
|
package UI.ChiefEngineer.Locomotive;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Tab;
import javafx.scene.layout.AnchorPane;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Created by piumiindeevari on 10/20/2017.
*/
public class LocoTabController implements Initializable {
@FXML
private Tab viewLocoTab;
@Override
public void initialize(URL location, ResourceBundle resources) {
try {
AnchorPane locoBase = FXMLLoader.load(getClass().getResource("locoView.fxml"));
UI.Index.IndexController.setNodeLoco(locoBase);
viewLocoTab.setContent(locoBase);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
[
"[email protected]"
] | |
abc7ce421ccbdbea89a177f1b3c0b5b2aac4cfd5
|
b0787dfef1901d9de08af9872dd904bf58bd75a6
|
/sparkcode/javaspark/src/spark1030_unoion/CountApiTest.java
|
01ded0c16985f593bb67ef6f3eb28ec7d3ee7e48
|
[] |
no_license
|
appointint/spark
|
02fc2681011aa84089ed2ffcf088674a3705a5f5
|
2315379cf78372044b24c445c3a68302910dda49
|
refs/heads/master
| 2021-09-09T17:27:28.818215 | 2018-03-18T13:59:35 | 2018-03-18T13:59:35 | 125,062,776 | 0 | 0 | null | null | null | null |
GB18030
|
Java
| false | false | 2,590 |
java
|
package spark1030_unoion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.hive.com.esotericsoftware.kryo.serializers.JavaSerializer;
import org.apache.spark.HashPartitioner;
import org.apache.spark.Partitioner;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.AbstractJavaRDDLike;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.partial.BoundedDouble;
import org.apache.spark.partial.PartialResult;
import org.apache.spark.storage.StorageLevel;
import scala.Tuple2;
//JavaPairRDD<String, Integer> results = mapRdd.reduceByKey((x, y)->x+y);
public class CountApiTest {
public static void main(String[] xx){
SparkConf conf = new SparkConf();
conf.setMaster("local");
conf.setAppName("Count API");
conf.set("spark.testing.memory", "2147480000");
// conf.set("spark.default.parallelism", "4");
JavaSparkContext ctx = new JavaSparkContext(conf);
//创建RDD:1)通过读取外部存储 ----- 集群环境使用 2)通过内存中的集合
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 10000; i++){
list.add(i);
}
JavaRDD<Integer> rdd1 = ctx.parallelize(list, 2);
JavaRDD<Integer> rdd2 = rdd1.union(rdd1).union(rdd1).union(rdd1);
//System.out.println(rdd2.count()); //计算并集后的总数
PartialResult<BoundedDouble> result = rdd2.countApprox(450);//1000, 300 2秒内跑完给结果,若没有完,也要返回结果
System.out.println(result.initialValue().mean());
System.out.println(result.initialValue().low());
System.out.println(result.initialValue().high());
System.out.println(result.initialValue().confidence()); //自信程度
// 40000.0 使用2000
// 40000.0
// 40000.0
// 1.0
// 40000.6 使用450
// 39696.95761248283
// 40304.242387517166
// 0.95
//0.01 0.1 偏移度的大致跑完了的任务 执行的更快
// System.out.println(rdd2.countApproxDistinct(0.01)); //9945
}
}
|
[
"[email protected]"
] | |
d8796f9cd100307d71b24fcf1075aa85f369059a
|
28840589a825672cc18e7ea2f82e059ef2286a33
|
/app/src/main/java/com/shuaijie/codenote/bean/BmobNote.java
|
4c7fe7b25dc39fe003cfb13a574ff045a3ca72a8
|
[] |
no_license
|
codeteenager/CodeNote
|
d7485bfb3f79e33fe8a413bdc408cf7d11a5557b
|
9bb37e68676694336a6945cbfaea3dcd1aecba1f
|
refs/heads/master
| 2021-01-20T07:41:22.510496 | 2017-05-02T12:13:47 | 2017-05-02T12:13:47 | 90,027,268 | 5 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,015 |
java
|
package com.shuaijie.codenote.bean;
import cn.bmob.v3.BmobObject;
/**
* Created by 姜帅杰 on 2016/2/9.
* 后台笔记类
*/
public class BmobNote extends BmobObject {
private String title;
private String content;
private String time;
private String userId;
private String localId;
public String getLocalId() {
return localId;
}
public void setLocalId(String localId) {
this.localId = localId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
|
[
"姜帅杰"
] |
姜帅杰
|
3ff50c534a6db213dbb24dbf4b009c3128a81ce8
|
d2b24fb0f57c0913c06a2f44cce2847e15c749f6
|
/ExamenJavaEss/src/be/pxl/examen/vraag1/Afdeling.java
|
68c2572a4b32ec3e42ecc8db4a7ff267d722a8a3
|
[] |
no_license
|
LoadingGod/1TIN_JavaEssentials
|
a7a3310489193da3363df27d62892dea8c0662fa
|
1ba8f22ccf10abe5df389177904edcd3795a224b
|
refs/heads/master
| 2021-01-21T02:23:55.974007 | 2015-01-31T11:55:35 | 2015-01-31T11:55:35 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 252 |
java
|
package be.pxl.examen.vraag1;
public class Afdeling {
private String chef;
public Afdeling(String chef) {
this.chef = chef;
}
public String getChef() {
return this.chef;
}
public void setChef(String chef) {
this.chef = chef;
}
}
|
[
"[email protected]"
] | |
148f1b9a80c15827d4d7a7c1cc085ab27c1f5bb0
|
12b14b30fcaf3da3f6e9dc3cb3e717346a35870a
|
/examples/commons-math3/mutations/mutants-RiddersSolver/74/org/apache/commons/math3/analysis/solvers/RiddersSolver.java
|
ab87823314d658c59f677b585888d42464fbfe8f
|
[
"BSD-3-Clause",
"Minpack",
"Apache-2.0"
] |
permissive
|
SmartTests/smartTest
|
b1de326998857e715dcd5075ee322482e4b34fb6
|
b30e8ec7d571e83e9f38cd003476a6842c06ef39
|
refs/heads/main
| 2023-01-03T01:27:05.262904 | 2020-10-27T20:24:48 | 2020-10-27T20:24:48 | 305,502,060 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,184 |
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.commons.math3.analysis.solvers;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.exception.NoBracketingException;
import org.apache.commons.math3.exception.TooManyEvaluationsException;
/**
* Implements the <a href="http://mathworld.wolfram.com/RiddersMethod.html">
* Ridders' Method</a> for root finding of real univariate functions. For
* reference, see C. Ridders, <i>A new algorithm for computing a single root
* of a real continuous function </i>, IEEE Transactions on Circuits and
* Systems, 26 (1979), 979 - 980.
* <p>
* The function should be continuous but not necessarily smooth.</p>
*
* @version $Id$
* @since 1.2
*/
public class RiddersSolver extends AbstractUnivariateSolver {
/** Default absolute accuracy. */
private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6;
/**
* Construct a solver with default accuracy (1e-6).
*/
public RiddersSolver() {
this(DEFAULT_ABSOLUTE_ACCURACY);
}
/**
* Construct a solver.
*
* @param absoluteAccuracy Absolute accuracy.
*/
public RiddersSolver(double absoluteAccuracy) {
super(absoluteAccuracy);
}
/**
* Construct a solver.
*
* @param relativeAccuracy Relative accuracy.
* @param absoluteAccuracy Absolute accuracy.
*/
public RiddersSolver(double relativeAccuracy,
double absoluteAccuracy) {
super(relativeAccuracy, absoluteAccuracy);
}
/**
* {@inheritDoc}
*/
@Override
protected double doSolve()
throws TooManyEvaluationsException,
NoBracketingException {
double min = getMin();
double max = getMax();
// [x1, x2] is the bracketing interval in each iteration
// x3 is the midpoint of [x1, x2]
// x is the new root approximation and an endpoint of the new interval
double x1 = min;
double y1 = computeObjectiveValue(x1);
double x2 = max;
double y2 = computeObjectiveValue(x2);
// check for zeros before verifying bracketing
if (y1 == 0) {
return min;
}
if (y2 == 0) {
return max;
}
verifyBracketing(min, max);
final double absoluteAccuracy = getAbsoluteAccuracy();
final double functionValueAccuracy = getFunctionValueAccuracy();
final double relativeAccuracy = getRelativeAccuracy();
double oldx = Double.POSITIVE_INFINITY;
while (true) {
// calculate the new root approximation
final double x3 = 0.5 * (x1 + x2);
final double y3 = computeObjectiveValue(x3);
if (FastMath.abs(y3) <= functionValueAccuracy) {
return x3;
}
final double delta = 1 - (y1 * y2) / (y3 * y3); // delta > 1 due to bracketing
final double correction = (FastMath.signum(y2) * FastMath.signum(y3)) *
(x3 - x1) / FastMath.sqrt(delta);
final double x = x3 * correction; // correction != 0
final double y = computeObjectiveValue(x);
// check for convergence
final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy);
if (FastMath.abs(x - oldx) <= tolerance) {
return x;
}
if (FastMath.abs(y) <= functionValueAccuracy) {
return x;
}
// prepare the new interval for next iteration
// Ridders' method guarantees x1 < x < x2
if (correction > 0.0) { // x1 < x < x3
if (FastMath.signum(y1) + FastMath.signum(y) == 0.0) {
x2 = x;
y2 = y;
} else {
x1 = x;
x2 = x3;
y1 = y;
y2 = y3;
}
} else { // x3 < x < x2
if (FastMath.signum(y2) + FastMath.signum(y) == 0.0) {
x1 = x;
y1 = y;
} else {
x1 = x3;
x2 = x;
y1 = y3;
y2 = y;
}
}
oldx = x;
}
}
}
|
[
"[email protected]"
] | |
fabffbe0dd46f4c7cd6dbff9a7c349d48a07e19b
|
193d2153eaf6c6522757d282247e042db780d59c
|
/src/main/java/learn/design/patterns/examples/stuctural/adapter/Chock.java
|
92ba67e33767f625dace88ed039874369858840b
|
[] |
no_license
|
jithinputhiyattu/java-design-patterns-examples
|
b29e5b88b5414a5710d0b92906bb733199641b36
|
4df1d79e86ae39931df8889b17c7e3504cb92c6e
|
refs/heads/master
| 2022-12-05T13:33:41.351350 | 2019-10-17T10:02:56 | 2019-10-17T10:02:56 | 194,376,119 | 1 | 0 | null | 2022-11-16T12:40:24 | 2019-06-29T07:11:16 |
Java
|
UTF-8
|
Java
| false | false | 213 |
java
|
package learn.design.patterns.examples.stuctural.adapter;
public class Chock {
public Chock() {
// TODO Auto-generated constructor stub
}
public void write(String str) {
System.out.println(str);
}
}
|
[
"[email protected]"
] | |
0fe8910272b90db40d1ff3761697d79d216860ef
|
cd6b4e8ac5d06cede5fcbfd2094e69014aa822c5
|
/src/ventanas/MantenimientoClientesForm.java
|
17478aa509ea06db6b60017d6380f3656570d0c9
|
[] |
no_license
|
ralfsaldana/ventasFront
|
e919f8432f69feb02a5fea801fa6bbe1fe7f94f0
|
0fe96f00f98867059ff41a84e691376fb2df3a9c
|
refs/heads/master
| 2021-07-17T11:59:55.833498 | 2017-10-25T16:25:28 | 2017-10-25T16:25:28 | 108,294,780 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,132 |
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 ventanas;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import paneles.PanelClientes;
import principal.PrincipalFrame;
/**
*
* @author rsaldana
*/
public class MantenimientoClientesForm extends JInternalFrame{
private PrincipalFrame principalFrame;
public MantenimientoClientesForm(PrincipalFrame padre){
super("Registro de Clientes", true, true, false, true);
ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("images/clientes.png"));
setFrameIcon(icon);
this.principalFrame = padre;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setResizable(false);
setContentPane(new PanelClientes(this));
pack();
}
public PrincipalFrame getPrincipalFrame() {
return principalFrame;
}
}
|
[
"[email protected]"
] | |
49113c3e86bd8c80aa8b74e2c38ae7297183e9d0
|
8dce824e3e7a7c8c2f0c3dacf117d1c335a242d5
|
/src/main/java/online/zhaopei/myproject/service/ecssent/DistBillListService.java
|
bdc05f6cd001414cd16a6b1f0462e9ae94e9407b
|
[
"MIT"
] |
permissive
|
coffey6/maintain
|
197d9a60500a9414ceda6911be2d86e0bac89acf
|
339c161a46abec57c1d22b43653ca47f4d55468b
|
refs/heads/master
| 2023-05-12T13:33:57.223961 | 2019-09-21T02:28:55 | 2019-09-21T02:28:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 484 |
java
|
package online.zhaopei.myproject.service.ecssent;
import java.io.Serializable;
import java.util.List;
import online.zhaopei.myproject.domain.ecssent.DistBillList;
public interface DistBillListService extends Serializable {
List<DistBillList> getDistBillListList(String seqNo);
List<DistBillList> getDistBillListListBySearchText(String seqNo, String searchText);
Long countDistBillList(String seqNo);
List<DistBillList> excludeInvts(String distNo, String companyCode);
}
|
[
"[email protected]"
] | |
a03e4fa7c198e5f11903a8d98a029098808e26c2
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/2/2_f6229222ba32d648099973986bebd09c1d61c9c3/VideoEngine/2_f6229222ba32d648099973986bebd09c1d61c9c3_VideoEngine_t.java
|
e9badfd115d8425bcf066f78f5741c1eead60174
|
[] |
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 | 227,892 |
java
|
/*
This file is part of jpcsp.
Jpcsp 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 3 of the License, or
(at your option) any later version.
Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.graphics;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_LIST_CANCEL_DONE;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_LIST_DONE;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_LIST_DRAWING;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_LIST_END_REACHED;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_LIST_STALL_REACHED;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE0;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE1;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE2;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE3;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE4;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE5;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE6;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_BONE7;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_PROJECTION;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_TEXGEN;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_VIEW;
import static jpcsp.HLE.modules150.sceGe_user.PSP_GE_MATRIX_WORLD;
import static jpcsp.graphics.GeCommands.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import jpcsp.Emulator;
import jpcsp.Memory;
import jpcsp.MemoryMap;
import jpcsp.State;
import jpcsp.HLE.Modules;
import jpcsp.HLE.kernel.types.IAction;
import jpcsp.HLE.kernel.types.PspGeList;
import jpcsp.HLE.modules.sceDisplay;
import jpcsp.graphics.GeContext.EnableDisableFlag;
import jpcsp.graphics.RE.IRenderingEngine;
import jpcsp.graphics.RE.buffer.IREBufferManager;
import jpcsp.graphics.capture.CaptureManager;
import jpcsp.graphics.textures.Texture;
import jpcsp.graphics.textures.TextureCache;
import jpcsp.memory.IMemoryReader;
import jpcsp.memory.MemoryReader;
import jpcsp.util.DurationStatistics;
import jpcsp.util.Utilities;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
//
// Ideas for Optimization:
// - compile GE lists (or part of it) into OpenGL display list (glNewList/glCallList).
// For example, immutable subroutines called using CALL could be compiled into a display list.
// A first run of the game using a profiler option could be used to detect which parts
// are immutable. This information could be stored in a file for subsequent runs and
// used as hints for the next runs.
// - Unswizzle textures in shader (is this possible?)
//
public class VideoEngine {
public static final int NUM_LIGHTS = 4;
public static final int SIZEOF_FLOAT = IRenderingEngine.sizeOfType[IRenderingEngine.RE_FLOAT];
public final static String[] psm_names = new String[]{
"PSM_5650",
"PSM_5551",
"PSM_4444",
"PSM_8888",
"PSM_4BIT_INDEXED",
"PSM_8BIT_INDEXED",
"PSM_16BIT_INDEXED",
"PSM_32BIT_INDEXED",
"PSM_DXT1",
"PSM_DXT3",
"PSM_DXT5"
};
public final static String[] logical_ops_names = new String[]{
"LOP_CLEAR",
"LOP_AND",
"LOP_REVERSE_AND",
"LOP_COPY",
"LOP_INVERTED_AND",
"LOP_NO_OPERATION",
"LOP_EXLUSIVE_OR",
"LOP_OR",
"LOP_NEGATED_OR",
"LOP_EQUIVALENCE",
"LOP_INVERTED",
"LOP_REVERSE_OR",
"LOP_INVERTED_COPY",
"LOP_INVERTED_OR",
"LOP_NEGATED_AND",
"LOP_SET"
};
private static final int[] textureByteAlignmentMapping = {2, 2, 2, 4};
private static VideoEngine instance;
private sceDisplay display;
private IRenderingEngine re;
private GeContext context;
private IREBufferManager bufferManager;
public static Logger log = Logger.getLogger("ge");
public static final boolean useTextureCache = true;
private boolean useVertexCache = false;
private static GeCommands helper;
private VertexInfo vinfo = new VertexInfo();
private VertexInfoReader vertexInfoReader = new VertexInfoReader();
private static final char SPACE = ' ';
private DurationStatistics statistics;
private DurationStatistics vertexStatistics = new DurationStatistics("Vertex");
private DurationStatistics waitSignalStatistics = new DurationStatistics("Wait for GE Signal completion");
private DurationStatistics waitStallStatistics = new DurationStatistics("Wait on stall");
private DurationStatistics textureCacheLookupStatistics = new DurationStatistics("Lookup in TextureCache");
private DurationStatistics vertexCacheLookupStatistics = new DurationStatistics("Lookup in VertexCache");
private DurationStatistics[] commandStatistics;
private int errorCount;
private static final int maxErrorCount = 5; // Abort list processing when detecting more errors
private boolean isLogTraceEnabled;
private boolean isLogDebugEnabled;
private boolean isLogInfoEnabled;
private boolean isLogWarnEnabled;
private int primCount;
private boolean viewportChanged;
public MatrixUpload projectionMatrixUpload;
public MatrixUpload modelMatrixUpload;
public MatrixUpload viewMatrixUpload;
public MatrixUpload textureMatrixUpload;
private int boneMatrixIndex;
private int boneMatrixLinearUpdatedMatrix; // number of updated matrix
private static final float[] blackColor = new float[]{0, 0, 0, 0};
private boolean lightingChanged;
private boolean materialChanged;
private boolean textureChanged;
private int[] patch_prim_types = { PRIM_TRIANGLE_STRIPS, PRIM_LINES_STRIPS, PRIM_POINT };
private boolean clutIsDirty;
private boolean usingTRXKICK;
private int maxSpriteHeight;
private int maxSpriteWidth;
private boolean blendChanged;
private boolean depthChanged;
private boolean scissorChanged;
// opengl needed information/buffers
private int textureId = -1;
private int[] tmp_texture_buffer32 = new int[1024 * 1024];
private short[] tmp_texture_buffer16 = new short[1024 * 1024];
private int[] clut_buffer32 = new int[4096];
private short[] clut_buffer16 = new short[4096];
private boolean listHasEnded;
private PspGeList currentList; // The currently executing list
private static final int drawBufferSize = 2 * 1024 * 1024 * SIZEOF_FLOAT;
private int bufferId;
private int nativeBufferId;
float[][] bboxVertices;
private ConcurrentLinkedQueue<PspGeList> drawListQueue;
private boolean somethingDisplayed;
private boolean geBufChanged;
private IAction hleAction;
private HashMap<Integer, Integer> currentCMDValues;
private boolean bboxWarningDisplayed = false;
private Set<Integer> videoTextures;
public static class MatrixUpload {
private final float[] matrix;
private boolean changed;
private int[] matrixIndex;
private int index;
private int maxIndex;
public MatrixUpload(float[] matrix, int matrixWidth, int matrixHeight) {
changed = true;
this.matrix = matrix;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
matrix[y * 4 + x] = (x == y ? 1 : 0);
}
}
maxIndex = matrixWidth * matrixHeight;
matrixIndex = new int[maxIndex];
for (int i = 0; i < maxIndex; i++) {
matrixIndex[i] = (i % matrixWidth) + (i / matrixWidth) * 4;
}
}
public void startUpload(int startIndex) {
index = startIndex;
}
public final boolean uploadValue(float value) {
if (index >= maxIndex) {
if(VideoEngine.getInstance().isLogDebugEnabled) {
VideoEngine.log(String.format("Ignored Matrix upload value (idx=%08X)", index));
}
} else {
int i = matrixIndex[index];
if (matrix[i] != value) {
matrix[i] = value;
changed = true;
}
}
index++;
return index >= maxIndex;
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
}
private static void log(String msg) {
log.debug(msg);
}
public static VideoEngine getInstance() {
if (instance == null) {
helper = new GeCommands();
instance = new VideoEngine();
}
return instance;
}
private VideoEngine() {
context = new GeContext();
modelMatrixUpload = new MatrixUpload(context.model_uploaded_matrix, 3, 4);
viewMatrixUpload = new MatrixUpload(context.view_uploaded_matrix, 3, 4);
textureMatrixUpload = new MatrixUpload(context.texture_uploaded_matrix, 3, 4);
projectionMatrixUpload = new MatrixUpload(context.proj_uploaded_matrix, 4, 4);
boneMatrixLinearUpdatedMatrix = 8;
statistics = new DurationStatistics("VideoEngine Statistics");
commandStatistics = new DurationStatistics[256];
for (int i = 0; i < commandStatistics.length; i++) {
commandStatistics[i] = new DurationStatistics(String.format("%-11s", helper.getCommandString(i)));
}
drawListQueue = new ConcurrentLinkedQueue<PspGeList>();
bboxVertices = new float[8][3];
for (int i = 0; i < 8; i++) {
bboxVertices[i] = new float[3];
}
currentCMDValues = new HashMap<Integer, Integer>();
videoTextures = new HashSet<Integer>();
}
/** Called from pspge module */
public void pushDrawList(PspGeList list) {
drawListQueue.add(list);
}
/** Called from pspge module */
public void pushDrawListHead(PspGeList list) {
// The ConcurrentLinkedQueue type doesn't allow adding
// objects directly at the head of the queue.
// This function creates a new array using the given list as it's head
// and constructs a new ConcurrentLinkedQueue based on it.
// The actual drawListQueue is then replaced by this new one.
int arraySize = drawListQueue.size();
if (arraySize > 0) {
PspGeList[] array = drawListQueue.toArray(new PspGeList[arraySize]);
ConcurrentLinkedQueue<PspGeList> newQueue = new ConcurrentLinkedQueue<PspGeList>();
PspGeList[] newArray = new PspGeList[arraySize + 1];
newArray[0] = list;
for (int i = 0; i < arraySize; i++) {
newArray[i + 1] = array[i];
newQueue.add(newArray[i]);
}
drawListQueue = newQueue;
} else { // If the queue is empty.
drawListQueue.add(list);
}
}
public int numberDrawLists() {
return drawListQueue.size();
}
public boolean hasDrawLists() {
return !drawListQueue.isEmpty();
}
public boolean hasDrawList(int listAddr) {
if (currentList != null && currentList.list_addr == listAddr) {
return true;
}
for (PspGeList list : drawListQueue) {
if (list != null && list.list_addr == listAddr) {
return true;
}
}
return false;
}
public PspGeList getFirstDrawList() {
PspGeList firstList = currentList;
if (firstList == null) {
firstList = drawListQueue.peek();
}
return firstList;
}
public PspGeList getLastDrawList() {
PspGeList lastList = null;
for (PspGeList list : drawListQueue) {
if (list != null) {
lastList = list;
}
}
if (lastList == null) {
lastList = currentList;
}
return lastList;
}
public void start() {
display = Modules.sceDisplayModule;
re = display.getRenderingEngine();
re.setGeContext(context);
context.setRenderingEngine(re);
bufferManager = re.getBufferManager();
if (!re.getBufferManager().useVBO()) {
// VertexCache is relying on VBO
useVertexCache = false;
}
bufferId = bufferManager.genBuffer(IRenderingEngine.RE_FLOAT, drawBufferSize / SIZEOF_FLOAT, IRenderingEngine.RE_STREAM_DRAW);
nativeBufferId = bufferManager.genBuffer(IRenderingEngine.RE_BYTE, drawBufferSize, IRenderingEngine.RE_STREAM_DRAW);
}
public IRenderingEngine getRenderingEngine() {
return re;
}
public GeContext getContext() {
return context;
}
public static void exit() {
if (instance != null) {
log.info(instance.statistics.toString());
Arrays.sort(instance.commandStatistics);
int numberCommands = 20;
log.info(numberCommands + " most time intensive Video commands:");
for (int i = 0; i < numberCommands; i++) {
VideoEngine.log.info(" " + instance.commandStatistics[i].toString());
}
log.info(instance.vertexStatistics);
log.info(instance.waitSignalStatistics);
log.info(instance.waitStallStatistics);
log.info(instance.textureCacheLookupStatistics);
log.info(instance.vertexCacheLookupStatistics);
}
}
public static DurationStatistics getStatistics() {
if (instance == null) {
return null;
}
return instance.statistics;
}
/** call from GL thread
* @return true if an update was made
*/
public boolean update() {
int listCount = drawListQueue.size();
PspGeList list = drawListQueue.poll();
if (list == null) {
return false;
}
startUpdate();
if (State.captureGeNextFrame) {
CaptureManager.startCapture("capture.bin", list);
}
if (State.replayGeNextFrame) {
// Load the replay list into drawListQueue
CaptureManager.startReplay("capture.bin");
// Hijack the current list with the replay list
// TODO this is assuming there is only 1 list in drawListQueue at this point, only the last list is the replay list
PspGeList replayList = drawListQueue.poll();
replayList.id = list.id;
replayList.blockedThreadIds.clear();
replayList.blockedThreadIds.addAll(list.blockedThreadIds);
list = replayList;
}
// Draw only as many lists as currently available in the drawListQueue.
// Some game add automatically a new list to the queue when the current
// list is finishing.
do {
executeList(list);
listCount--;
if (listCount <= 0) {
break;
}
list = drawListQueue.poll();
} while (list != null);
if (State.captureGeNextFrame) {
// Can't end capture until we get a sceDisplaySetFrameBuf after the list has executed
CaptureManager.markListExecuted();
}
if (State.replayGeNextFrame) {
CaptureManager.endReplay();
State.replayGeNextFrame = false;
}
endUpdate();
return true;
}
private void logLevelUpdated() {
isLogTraceEnabled = log.isTraceEnabled();
isLogDebugEnabled = log.isDebugEnabled();
isLogInfoEnabled = log.isInfoEnabled();
isLogWarnEnabled = log.isEnabledFor(Level.WARN);
}
public void setLogLevel(Level level) {
log.setLevel(level);
logLevelUpdated();
}
/**
* The memory used by GE has been updated or changed.
* Update the caches so that they see these changes.
*/
private void memoryForGEUpdated() {
if (useTextureCache) {
TextureCache.getInstance().resetTextureAlreadyHashed();
}
if (useVertexCache) {
VertexCache.getInstance().resetVertexAlreadyHashed();
}
}
public void hleSetFrameBuf(int topAddr, int bufferWidth, int pixelFormat) {
if (context.fbp != topAddr || context.fbw != bufferWidth || context.psm != pixelFormat) {
context.fbp = topAddr;
context.fbw = bufferWidth;
context.psm = pixelFormat;
geBufChanged = true;
}
}
private void startUpdate() {
statistics.start();
logLevelUpdated();
memoryForGEUpdated();
somethingDisplayed = false;
textureChanged = true;
projectionMatrixUpload.setChanged(true);
modelMatrixUpload.setChanged(true);
viewMatrixUpload.setChanged(true);
textureMatrixUpload.setChanged(true);
clutIsDirty = true;
lightingChanged = true;
blendChanged = true;
viewportChanged = true;
depthChanged = true;
materialChanged = true;
scissorChanged = true;
errorCount = 0;
usingTRXKICK = false;
maxSpriteHeight = 0;
maxSpriteWidth = 0;
primCount = 0;
context.update();
}
private void endUpdate() {
if (useVertexCache) {
if (primCount > VertexCache.cacheMaxSize) {
log.warn(String.format("VertexCache size (%d) too small to execute %d PRIM commands", VertexCache.cacheMaxSize, primCount));
}
}
statistics.end();
}
public void error(String message) {
errorCount++;
log.error(message);
if (errorCount >= maxErrorCount) {
if (tryToFallback()) {
log.error("Aborting current list processing due to too many errors");
}
}
}
private boolean tryToFallback() {
boolean abort = false;
if (!currentList.isStackEmpty()) {
// When have some CALLs on the stack, try to return from the last CALL
int oldPc = currentList.pc;
currentList.ret();
int newPc = currentList.pc;
if (isLogDebugEnabled) {
log(String.format("tryToFallback old PC: 0x%08X, new PC: 0x%08X", oldPc, newPc));
}
} else {
// Finish this list
currentList.finishList();
listHasEnded = true;
abort = true;
}
return abort;
}
private void checkCurrentListPc() {
Memory mem = Memory.getInstance();
while (!mem.isAddressGood(currentList.pc)) {
if (!mem.isIgnoreInvalidMemoryAccess()) {
error("Reading GE list from invalid address 0x" + Integer.toHexString(currentList.pc));
break;
}
// Ignoring memory read errors.
// Try to fall back and continue the list processing.
log.warn("Reading GE list from invalid address 0x" + Integer.toHexString(currentList.pc));
if (tryToFallback()) {
break;
}
}
}
private void executeHleAction() {
if (hleAction != null) {
hleAction.execute();
hleAction = null;
}
}
// call from GL thread
// There is an issue here with Emulator.pause
// - We want to stop on errors
// - But user may also press pause button
// - Either continue drawing to the end of the list (bad if the list contains an infinite loop)
// - Or we want to be able to restart drawing when the user presses the run button
private void executeList(PspGeList list) {
currentList = list;
listHasEnded = false;
currentList.status = PSP_GE_LIST_DRAWING;
if (isLogDebugEnabled) {
log("executeList " + list);
}
executeHleAction();
IMemoryReader memoryReader = MemoryReader.getMemoryReader(currentList.pc, 4);
int memoryReaderPc = currentList.pc;
int waitForSyncCount = 0;
while (!listHasEnded && (!Emulator.pause || State.captureGeNextFrame)) {
if (currentList.isPaused() || currentList.isEnded()) {
waitSignalStatistics.start();
if (isLogDebugEnabled) {
log.debug(String.format("FINISH / SIGNAL / END reached, waiting for Sync"));
}
currentList.status = PSP_GE_LIST_END_REACHED;
if (!currentList.waitForSync(10)) {
if (isLogDebugEnabled) {
log.debug("Wait for sync while END reached");
}
waitForSyncCount++;
// Waiting maximum 100 * 10ms (= 1 second) on an END command.
// After this timeout, abort the list.
if (waitForSyncCount > 100) {
error(String.format("Waiting too long on an END command, aborting the list %s", currentList));
}
} else {
waitForSyncCount = 0;
}
executeHleAction();
if (currentList.isRestarted()) {
currentList.clearRestart();
currentList.clearPaused();
}
if (!currentList.isPaused()) {
if (currentList.isFinished()) {
listHasEnded = true;
break;
}
currentList.status = PSP_GE_LIST_DRAWING;
}
waitSignalStatistics.end();
} else if (currentList.isStallReached()) {
waitStallStatistics.start();
if (isLogDebugEnabled) {
log.debug(String.format("Stall address 0x%08X reached, waiting for Sync", currentList.pc));
}
currentList.status = PSP_GE_LIST_STALL_REACHED;
if (!currentList.waitForSync(10)) {
if (isLogDebugEnabled) {
log.debug("Wait for sync while stall reached");
}
waitForSyncCount++;
// Waiting maximum 100 * 10ms (= 1 second) on a stall address.
// After this timeout, abort the list.
//
// When the stall address is at the very beginning of the list
// (i.e. the list has just been enqueued, but the stall has not yet been updated),
// allow waiting for a longer time (the CPU might be busy
// compiling a huge CodeBlock on the first call).
// This avoids aborting the first list enqueued.
int maxStallCount = (currentList.pc != currentList.list_addr ? 100 : 400);
if (waitForSyncCount > maxStallCount) {
error(String.format("Waiting too long on stall address 0x%08X, aborting the list %s", currentList.pc, currentList));
}
} else {
waitForSyncCount = 0;
}
executeHleAction();
if (!currentList.isStallReached()) {
currentList.status = PSP_GE_LIST_DRAWING;
}
waitStallStatistics.end();
} else {
if (currentList.pc != memoryReaderPc) {
// The currentList.pc is no longer reading in sequence
// and has jumped to a next location, get a new memory reader.
checkCurrentListPc();
if (listHasEnded || Emulator.pause) {
break;
}
memoryReader = MemoryReader.getMemoryReader(currentList.pc, 4);
}
int ins = memoryReader.readNext();
currentList.pc += 4;
memoryReaderPc = currentList.pc;
executeCommand(ins);
}
}
if (Emulator.pause && !listHasEnded) {
VideoEngine.log.info("Emulator paused - cancelling current list id=" + currentList.id);
currentList.status = PSP_GE_LIST_CANCEL_DONE;
}
// let DONE take priority over STALL_REACHED
if (listHasEnded) {
currentList.status = PSP_GE_LIST_END_REACHED;
// Tested on PSP:
// A list is only DONE after a combination of FINISH + END.
if (currentList.isEnded()) {
currentList.status = PSP_GE_LIST_DONE;
}
}
if (list.isDone()) {
Modules.sceGe_userModule.hleGeListSyncDone(list);
}
executeHleAction();
currentList = null;
}
public PspGeList getCurrentList() {
return currentList;
}
public float[] getMatrix(int mtxtype) {
float resmtx[] = new float[4 * 4];
switch (mtxtype) {
case PSP_GE_MATRIX_BONE0:
case PSP_GE_MATRIX_BONE1:
case PSP_GE_MATRIX_BONE2:
case PSP_GE_MATRIX_BONE3:
case PSP_GE_MATRIX_BONE4:
case PSP_GE_MATRIX_BONE5:
case PSP_GE_MATRIX_BONE6:
case PSP_GE_MATRIX_BONE7:
resmtx = context.bone_uploaded_matrix[mtxtype - PSP_GE_MATRIX_BONE0];
break;
case PSP_GE_MATRIX_WORLD:
resmtx = context.model_uploaded_matrix;
break;
case PSP_GE_MATRIX_VIEW:
resmtx = context.view_uploaded_matrix;
break;
case PSP_GE_MATRIX_PROJECTION:
resmtx = context.proj_uploaded_matrix;
break;
case PSP_GE_MATRIX_TEXGEN:
resmtx = context.texture_uploaded_matrix;
break;
}
return resmtx;
}
public int getCommandValue(int cmd) {
return currentCMDValues.get(cmd);
}
public String commandToString(int cmd) {
return GeCommands.getInstance().getCommandString(cmd);
}
public static int command(int instruction) {
return (instruction >>> 24);
}
private static int intArgument(int instruction) {
return (instruction & 0x00FFFFFF);
}
private static float floatArgument(int normalArgument) {
return Float.intBitsToFloat(normalArgument << 8);
}
private int getStencilOp(int pspOP) {
if (pspOP > SOP_DECREMENT_STENCIL_VALUE) {
log.warn("UNKNOWN stencil op " + pspOP);
}
return SOP_KEEP_STENCIL_VALUE;
}
private int getBlendFix(float[] fix_color) {
if (fix_color[0] == 0 && fix_color[1] == 0 && fix_color[2] == 0) {
return IRenderingEngine.GU_FIX_BLACK;
} else if (fix_color[0] == 1 && fix_color[1] == 1 && fix_color[2] == 1) {
return IRenderingEngine.GU_FIX_WHITE;
} else {
return IRenderingEngine.GU_FIX_BLEND_COLOR;
}
}
private int getColorInt(float[] color) {
return (((int) (color[0] * 255)) ) |
(((int) (color[1] * 255)) << 8) |
(((int) (color[2] * 255)) << 16) |
(((int) (color[3] * 255)) << 24);
}
private float[] getBlendColor(int gl_blend_src, int gl_blend_dst) {
float[] blend_color = null;
if (gl_blend_src == IRenderingEngine.GU_FIX_BLEND_COLOR) {
blend_color = context.sfix_color;
if (gl_blend_dst == IRenderingEngine.GU_FIX_BLEND_COLOR) {
if (context.sfix_color[0] != context.dfix_color[0]
|| context.sfix_color[1] != context.dfix_color[1]
|| context.sfix_color[2] != context.dfix_color[2]
|| context.sfix_color[3] != context.dfix_color[3]) {
log.warn(String.format("UNSUPPORTED: Both different SFIX (%08X) and DFIX (%08X) are not supported (blend equation=%d)", getColorInt(context.sfix_color), getColorInt(context.dfix_color), context.blendEquation));
}
}
} else if (gl_blend_dst == IRenderingEngine.GU_FIX_BLEND_COLOR) {
blend_color = context.dfix_color;
}
return blend_color;
}
// hack partially based on pspplayer
private void setBlendFunc() {
int reBlendSrc = context.blend_src;
if (context.blend_src < 0 || context.blend_src > 10) {
error("Unhandled alpha blend src used " + context.blend_src);
reBlendSrc = 0;
} else if (context.blend_src == 10) { // GU_FIX
reBlendSrc = getBlendFix(context.sfix_color);
}
int reBlendDst = context.blend_dst;
if (context.blend_dst < 0 || context.blend_dst > 10) {
error("Unhandled alpha blend dst used " + context.blend_dst);
reBlendDst = 0;
} else if (context.blend_dst == 10) { // GU_FIX
if (reBlendSrc == IRenderingEngine.GU_FIX_BLEND_COLOR
&& context.sfix_color[0] + context.dfix_color[0] == 1
&& context.sfix_color[1] + context.dfix_color[1] == 1
&& context.sfix_color[2] + context.dfix_color[2] == 1) {
reBlendDst = IRenderingEngine.GU_FIX_BLEND_ONE_MINUS_COLOR;
} else {
reBlendDst = getBlendFix(context.dfix_color);
}
}
float[] blend_color = getBlendColor(reBlendSrc, reBlendDst);
if (blend_color != null) {
re.setBlendColor(blend_color);
}
re.setBlendFunc(reBlendSrc, reBlendDst);
}
private int getClutAddr(int level, int clutNumEntries, int clutEntrySize) {
return context.tex_clut_addr + context.tex_clut_start * clutEntrySize;
}
private void readClut() {
if (!clutIsDirty) {
return;
}
// Texture using clut?
if (context.texture_storage >= TPSM_PIXEL_STORAGE_MODE_4BIT_INDEXED && context.texture_storage <= TPSM_PIXEL_STORAGE_MODE_32BIT_INDEXED) {
if (context.tex_clut_mode == CMODE_FORMAT_32BIT_ABGR8888) {
readClut32(0);
} else {
readClut16(0);
}
}
}
private short[] readClut16(int level) {
int clutNumEntries = context.tex_clut_num_blocks * 16;
// Update the clut_buffer only if some clut parameters have been changed
// since last update.
if (clutIsDirty) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(getClutAddr(level, clutNumEntries, 2), (clutNumEntries - context.tex_clut_start) * 2, 2);
for (int i = context.tex_clut_start; i < clutNumEntries; i++) {
clut_buffer16[i] = (short) memoryReader.readNext();
}
clutIsDirty = false;
}
if (State.captureGeNextFrame) {
log.info("Capture readClut16");
CaptureManager.captureRAM(context.tex_clut_addr, clutNumEntries * 2);
}
return clut_buffer16;
}
private int[] readClut32(int level) {
int clutNumEntries = context.tex_clut_num_blocks * 8;
// Update the clut_buffer only if some clut parameters have been changed
// since last update.
if (clutIsDirty) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(getClutAddr(level, clutNumEntries, 4), (clutNumEntries - context.tex_clut_start) * 4, 4);
for (int i = context.tex_clut_start; i < clutNumEntries; i++) {
clut_buffer32[i] = memoryReader.readNext();
}
clutIsDirty = false;
}
if (State.captureGeNextFrame) {
log.info("Capture readClut32");
CaptureManager.captureRAM(context.tex_clut_addr, clutNumEntries * 4);
}
return clut_buffer32;
}
private int getClutIndex(int index) {
return ((context.tex_clut_start + index) >> context.tex_clut_shift) & context.tex_clut_mask;
}
// UnSwizzling based on pspplayer
private Buffer unswizzleTextureFromMemory(int texaddr, int bytesPerPixel, int level) {
int rowWidth = (bytesPerPixel > 0) ? (context.texture_buffer_width[level] * bytesPerPixel) : (context.texture_buffer_width[level] / 2);
int pitch = rowWidth / 4;
int bxc = rowWidth / 16;
int byc = Math.max((context.texture_height[level] + 7) / 8, 1);
int ydest = 0;
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, 4);
for (int by = 0; by < byc; by++) {
if (rowWidth >= 16) {
int xdest = ydest;
for (int bx = 0; bx < bxc; bx++) {
int dest = xdest;
for (int n = 0; n < 8; n++) {
tmp_texture_buffer32[dest] = memoryReader.readNext();
tmp_texture_buffer32[dest + 1] = memoryReader.readNext();
tmp_texture_buffer32[dest + 2] = memoryReader.readNext();
tmp_texture_buffer32[dest + 3] = memoryReader.readNext();
dest += pitch;
}
xdest += 4;
}
ydest += (rowWidth * 8) / 4;
} else if (rowWidth == 8) {
for (int n = 0; n < 8; n++, ydest += 2) {
tmp_texture_buffer32[ydest] = memoryReader.readNext();
tmp_texture_buffer32[ydest + 1] = memoryReader.readNext();
memoryReader.skip(2);
}
} else if (rowWidth == 4) {
for (int n = 0; n < 8; n++, ydest++) {
tmp_texture_buffer32[ydest] = memoryReader.readNext();
memoryReader.skip(3);
}
} else if (rowWidth == 2) {
for (int n = 0; n < 4; n++, ydest++) {
int n1 = memoryReader.readNext() & 0xFFFF;
memoryReader.skip(3);
int n2 = memoryReader.readNext() & 0xFFFF;
memoryReader.skip(3);
tmp_texture_buffer32[ydest] = n1 | (n2 << 16);
}
} else if (rowWidth == 1) {
for (int n = 0; n < 2; n++, ydest++) {
int n1 = memoryReader.readNext() & 0xFF;
memoryReader.skip(3);
int n2 = memoryReader.readNext() & 0xFF;
memoryReader.skip(3);
int n3 = memoryReader.readNext() & 0xFF;
memoryReader.skip(3);
int n4 = memoryReader.readNext() & 0xFF;
memoryReader.skip(3);
tmp_texture_buffer32[ydest] = n1 | (n2 << 8) | (n3 << 16) | (n4 << 24);
}
}
}
if (State.captureGeNextFrame) {
log.info("Capture unswizzleTextureFromMemory");
CaptureManager.captureRAM(texaddr, rowWidth * context.texture_height[level]);
}
return IntBuffer.wrap(tmp_texture_buffer32);
}
private String getArgumentLog(int normalArgument) {
if (normalArgument == 0) {
return "(0)"; // a very common case...
}
return String.format("(hex=%08X,int=%d,float=%f)", normalArgument, normalArgument, floatArgument(normalArgument));
}
public void executeCommand(int instruction) {
int normalArgument = intArgument(instruction);
// Compute floatArgument only on demand, most commands do not use it.
//float floatArgument = floatArgument(instruction);
int command = command(instruction);
currentCMDValues.put(command, normalArgument);
if (isLogInfoEnabled) {
commandStatistics[command].start();
}
switch (command) {
case NOP:
if (isLogDebugEnabled) {
log(helper.getCommandString(NOP));
}
// Check if we are not reading from an invalid memory region.
// Abort the list if this is the case.
// This is only done in the NOP command to not impact performance.
checkCurrentListPc();
break;
case VADDR:
vinfo.ptr_vertex = currentList.getAddress(normalArgument);
if (isLogDebugEnabled) {
log(helper.getCommandString(VADDR) + " " + String.format("%08x", vinfo.ptr_vertex));
}
break;
case IADDR:
vinfo.ptr_index = currentList.getAddress(normalArgument);
if (isLogDebugEnabled) {
log(helper.getCommandString(IADDR) + " " + String.format("%08x", vinfo.ptr_index));
}
break;
case PRIM:
executeCommandPRIM(normalArgument);
break;
case BEZIER:
int ucount = normalArgument & 0xFF;
int vcount = (normalArgument >> 8) & 0xFF;
if (isLogDebugEnabled) {
log(helper.getCommandString(BEZIER) + " ucount=" + ucount + ", vcount=" + vcount);
}
updateGeBuf();
loadTexture();
drawBezier(ucount, vcount);
break;
case SPLINE: {
// Number of control points.
int sp_ucount = normalArgument & 0xFF;
int sp_vcount = (normalArgument >> 8) & 0xFF;
// Knot types.
int sp_utype = (normalArgument >> 16) & 0x3;
int sp_vtype = (normalArgument >> 18) & 0x3;
if (isLogDebugEnabled) {
log(helper.getCommandString(SPLINE) + " sp_ucount=" + sp_ucount + ", sp_vcount=" + sp_vcount +
" sp_utype=" + sp_utype + ", sp_vtype=" + sp_vtype);
}
updateGeBuf();
loadTexture();
drawSpline(sp_ucount, sp_vcount, sp_utype, sp_vtype);
break;
}
case BBOX:
executeCommandBBOX(normalArgument);
break;
case JUMP: {
int oldPc = currentList.pc;
currentList.jump(normalArgument);
int newPc = currentList.pc;
if (isLogDebugEnabled) {
log(String.format("%s old PC: 0x%08X, new PC: 0x%08X", helper.getCommandString(JUMP), oldPc, newPc));
}
break;
}
case BJUMP:
executeCommandBJUMP(normalArgument);
break;
case CALL: {
int oldPc = currentList.pc;
currentList.call(normalArgument);
int newPc = currentList.pc;
if (isLogDebugEnabled) {
log(String.format("%s old PC: 0x%08X, new PC: 0x%08X", helper.getCommandString(CALL), oldPc, newPc));
}
break;
}
case RET: {
int oldPc = currentList.pc;
currentList.ret();
int newPc = currentList.pc;
if (isLogDebugEnabled) {
log(String.format("%s old PC: 0x%08X, new PC: 0x%08X", helper.getCommandString(RET), oldPc, newPc));
}
break;
}
case END:
// Try to end the current list.
// The list only ends (isEnded() == true) if FINISH was called previously.
// In SIGNAL + END cases, isEnded() still remains false.
currentList.endList();
currentList.pauseList();
if (isLogDebugEnabled) {
log(helper.getCommandString(END) + " pc=0x" + Integer.toHexString(currentList.pc));
}
updateGeBuf();
break;
case SIGNAL:
int behavior = (normalArgument >> 16) & 0xFF;
int signal = normalArgument & 0xFFFF;
if (behavior < 1 || behavior > 3) {
if (isLogWarnEnabled) {
log(helper.getCommandString(SIGNAL) + " (behavior=" + behavior + ",signal=0x" + Integer.toHexString(signal) + ") unknown behavior");
}
} else if (isLogDebugEnabled) {
log(helper.getCommandString(SIGNAL) + " (behavior=" + behavior + ",signal=0x" + Integer.toHexString(signal) + ")");
}
currentList.clearRestart();
currentList.pushSignalCallback(currentList.id, behavior, signal);
break;
case FINISH:
if (isLogDebugEnabled) {
log(helper.getCommandString(FINISH) + " " + getArgumentLog(normalArgument));
}
currentList.clearRestart();
currentList.finishList();
currentList.pushFinishCallback(currentList.id, normalArgument);
break;
case BASE:
context.base = (normalArgument << 8) & 0xff000000;
// Bits of (normalArgument & 0x0000FFFF) are ignored
// (tested: "Ape Escape On the Loose")
if (isLogDebugEnabled) {
log(helper.getCommandString(BASE) + " " + String.format("%08x", context.base));
}
break;
case VTYPE: {
int old_transform_mode = context.transform_mode;
boolean old_vertex_hasColor = vinfo.color != 0;
vinfo.processType(normalArgument);
context.transform_mode = (normalArgument >> 23) & 0x1;
boolean vertex_hasColor = vinfo.color != 0;
//Switching from 2D to 3D or 3D to 2D?
if (old_transform_mode != context.transform_mode) {
projectionMatrixUpload.setChanged(true);
modelMatrixUpload.setChanged(true);
viewMatrixUpload.setChanged(true);
textureMatrixUpload.setChanged(true);
viewportChanged = true;
depthChanged = true;
materialChanged = true;
// Switching from 2D to 3D?
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD) {
lightingChanged = true;
}
} else if (old_vertex_hasColor != vertex_hasColor) {
// Materials have to be reloaded when the vertex color presence is changing
materialChanged = true;
}
if (isLogDebugEnabled) {
log(helper.getCommandString(VTYPE) + " " + vinfo.toString());
}
break;
}
case OFFSET_ADDR:
context.baseOffset = normalArgument << 8;
if (isLogDebugEnabled) {
log(String.format("%s 0x%08X", helper.getCommandString(OFFSET_ADDR), context.baseOffset));
}
break;
case ORIGIN_ADDR:
context.baseOffset = currentList.pc - 4;
if (normalArgument != 0) {
log.warn(String.format("%s unknown argument 0x%08X", helper.getCommandString(ORIGIN_ADDR), normalArgument));
} else if (isLogDebugEnabled) {
log(String.format("%s 0x%08X originAddr=0x%08X", helper.getCommandString(ORIGIN_ADDR), normalArgument, context.baseOffset));
}
break;
case REGION1:
context.region_x1 = normalArgument & 0x3ff;
context.region_y1 = (normalArgument >> 10) & 0x3ff;
scissorChanged = true;
break;
case REGION2:
context.region_x2 = normalArgument & 0x3ff;
context.region_y2 = (normalArgument >> 10) & 0x3ff;
context.region_width = (context.region_x2 + 1) - context.region_x1;
context.region_height = (context.region_y2 + 1) - context.region_y1;
if (isLogDebugEnabled) {
log("drawRegion(" + context.region_x1 + "," + context.region_y1 + "," + context.region_width + "," + context.region_height + ")");
}
scissorChanged = true;
break;
/*
* Lighting enable/disable
*/
case LTE: {
context.lightingFlag.setEnabled(normalArgument);
if (context.lightingFlag.isEnabled()) {
lightingChanged = true;
materialChanged = true;
}
break;
}
/*
* Individual lights enable/disable
*/
case LTE0:
case LTE1:
case LTE2:
case LTE3: {
int lnum = command - LTE0;
EnableDisableFlag lightFlag = context.lightFlags[lnum];
lightFlag.setEnabled(normalArgument);
if (lightFlag.isEnabled()) {
lightingChanged = true;
}
break;
}
case CPE:
context.clipPlanesFlag.setEnabled(normalArgument);
break;
case BCE:
context.cullFaceFlag.setEnabled(normalArgument);
break;
case TME:
context.textureFlag.setEnabled(normalArgument);
break;
case FGE:
context.fogFlag.setEnabled(normalArgument);
if (context.fogFlag.isEnabled()) {
re.setFogHint();
}
break;
case DTE:
context.ditherFlag.setEnabled(normalArgument);
break;
case ABE:
context.blendFlag.setEnabled(normalArgument);
break;
case ATE:
context.alphaTestFlag.setEnabled(normalArgument);
break;
case ZTE:
context.depthTestFlag.setEnabled(normalArgument);
if (context.depthTestFlag.isEnabled()) {
// OpenGL requires the Depth parameters to be reloaded
depthChanged = true;
}
break;
case STE:
context.stencilTestFlag.setEnabled(normalArgument);
break;
case AAE:
context.lineSmoothFlag.setEnabled(normalArgument);
if (context.lineSmoothFlag.isEnabled()) {
re.setLineSmoothHint();
}
break;
case PCE: {
context.patchCullFaceFlag.setEnabled(normalArgument);
break;
}
case CTE: {
context.colorTestFlag.setEnabled(normalArgument);
break;
}
case LOE:
context.colorLogicOpFlag.setEnabled(normalArgument);
break;
/*
* Skinning
*/
case BOFS: {
boneMatrixIndex = normalArgument;
if (isLogDebugEnabled) {
log("bone matrix offset", normalArgument);
}
break;
}
case BONE:
executeCommandBONE(normalArgument);
break;
/*
* Morphing
*/
case MW0:
case MW1:
case MW2:
case MW3:
case MW4:
case MW5:
case MW6:
case MW7: {
int index = command - MW0;
float floatArgument = floatArgument(normalArgument);
context.morph_weight[index] = floatArgument;
re.setMorphWeight(index, floatArgument);
if (isLogDebugEnabled) {
log("morph weight " + index, floatArgument);
}
break;
}
case PSUB:
context.patch_div_s = normalArgument & 0xFF;
context.patch_div_t = (normalArgument >> 8) & 0xFF;
re.setPatchDiv(context.patch_div_s, context.patch_div_t);
if (isLogDebugEnabled) {
log(helper.getCommandString(PSUB) + " patch_div_s=" + context.patch_div_s + ", patch_div_t=" + context.patch_div_t);
}
break;
case PPRIM: {
context.patch_prim = (normalArgument & 0x3);
// Primitive type to use in patch division:
// 0 - Triangle.
// 1 - Line.
// 2 - Point.
re.setPatchPrim(context.patch_prim);
if (isLogDebugEnabled) {
log(helper.getCommandString(PPRIM) + " patch_prim=" + context.patch_prim);
}
break;
}
case PFACE: {
// 0 - Clockwise oriented patch / 1 - Counter clockwise oriented patch.
context.patchFaceFlag.setEnabled(normalArgument);
break;
}
case MMS:
modelMatrixUpload.startUpload(normalArgument);
if (isLogDebugEnabled) {
log("sceGumMatrixMode GU_MODEL " + normalArgument);
}
break;
case MODEL:
if (modelMatrixUpload.uploadValue(floatArgument(normalArgument))) {
log("glLoadMatrixf", context.model_uploaded_matrix);
}
break;
case VMS:
viewMatrixUpload.startUpload(normalArgument);
if (isLogDebugEnabled) {
log("sceGumMatrixMode GU_VIEW " + normalArgument);
}
break;
case VIEW:
if (viewMatrixUpload.uploadValue(floatArgument(normalArgument))) {
log("glLoadMatrixf", context.view_uploaded_matrix);
}
break;
case PMS:
projectionMatrixUpload.startUpload(normalArgument);
if (isLogDebugEnabled) {
log("sceGumMatrixMode GU_PROJECTION " + normalArgument);
}
break;
case PROJ:
if (projectionMatrixUpload.uploadValue(floatArgument(normalArgument))) {
log("glLoadMatrixf", context.proj_uploaded_matrix);
}
break;
case TMS:
textureMatrixUpload.startUpload(normalArgument);
if (isLogDebugEnabled) {
log("sceGumMatrixMode GU_TEXTURE " + normalArgument);
}
break;
case TMATRIX:
if (textureMatrixUpload.uploadValue(floatArgument(normalArgument))) {
log("glLoadMatrixf", context.texture_uploaded_matrix);
}
break;
case XSCALE: {
int old_viewport_width = context.viewport_width;
context.viewport_width = (int) floatArgument(normalArgument);
if (old_viewport_width != context.viewport_width) {
viewportChanged = true;
}
break;
}
case YSCALE: {
int old_viewport_height = context.viewport_height;
context.viewport_height = (int) floatArgument(normalArgument);
if (old_viewport_height != context.viewport_height) {
viewportChanged = true;
}
break;
}
case ZSCALE: {
float old_zscale = context.zscale;
float floatArgument = floatArgument(normalArgument);
context.zscale = floatArgument / 65535.f;
if (old_zscale != context.zscale) {
depthChanged = true;
}
if (isLogDebugEnabled) {
log(helper.getCommandString(ZSCALE) + " " + floatArgument);
}
break;
}
case XPOS: {
int old_viewport_cx = context.viewport_cx;
context.viewport_cx = (int) floatArgument(normalArgument);
if (old_viewport_cx != context.viewport_cx) {
viewportChanged = true;
}
break;
}
case YPOS: {
int old_viewport_cy = context.viewport_cy;
context.viewport_cy = (int) floatArgument(normalArgument);
if (old_viewport_cy != context.viewport_cy) {
viewportChanged = true;
}
// Log only on the last called command (always XSCALE -> YSCALE -> XPOS -> YPOS).
if (isLogDebugEnabled) {
log.debug("sceGuViewport(cx=" + context.viewport_cx + ", cy=" + context.viewport_cy + ", w=" + context.viewport_width + " h=" + context.viewport_height + ")");
}
break;
}
case ZPOS: {
float old_zpos = context.zpos;
float floatArgument = floatArgument(normalArgument);
context.zpos = floatArgument / 65535.f;
if (old_zpos != context.zpos) {
depthChanged = true;
}
if (isLogDebugEnabled) {
log(helper.getCommandString(ZPOS), floatArgument);
}
break;
}
/*
* Texture transformations
*/
case USCALE: {
float old_tex_scale_x = context.tex_scale_x;
context.tex_scale_x = floatArgument(normalArgument);
if (old_tex_scale_x != context.tex_scale_x) {
textureMatrixUpload.setChanged(true);
}
break;
}
case VSCALE: {
float old_tex_scale_y = context.tex_scale_y;
context.tex_scale_y = floatArgument(normalArgument);
if (old_tex_scale_y != context.tex_scale_y) {
textureMatrixUpload.setChanged(true);
}
if (isLogDebugEnabled) {
log("sceGuTexScale(u=" + context.tex_scale_x + ", v=" + context.tex_scale_y + ")");
}
break;
}
case UOFFSET: {
float old_tex_translate_x = context.tex_translate_x;
context.tex_translate_x = floatArgument(normalArgument);
if (old_tex_translate_x != context.tex_translate_x) {
textureMatrixUpload.setChanged(true);
}
break;
}
case VOFFSET: {
float old_tex_translate_y = context.tex_translate_y;
context.tex_translate_y = floatArgument(normalArgument);
if (old_tex_translate_y != context.tex_translate_y) {
textureMatrixUpload.setChanged(true);
}
if (isLogDebugEnabled) {
log("sceGuTexOffset(u=" + context.tex_translate_x + ", v=" + context.tex_translate_y + ")");
}
break;
}
case OFFSETX: {
int old_offset_x = context.offset_x;
context.offset_x = normalArgument >> 4;
if (old_offset_x != context.offset_x) {
viewportChanged = true;
}
break;
}
case OFFSETY: {
int old_offset_y = context.offset_y;
context.offset_y = normalArgument >> 4;
if (old_offset_y != context.offset_y) {
viewportChanged = true;
}
if(isLogDebugEnabled) {
log.debug("sceGuOffset(x=" + context.offset_x + ",y=" + context.offset_y + ")");
}
break;
}
case SHADE: {
context.shadeModel = normalArgument & 1;
re.setShadeModel(context.shadeModel);
if (isLogDebugEnabled) {
log("sceGuShadeModel(" + ((context.shadeModel != 0) ? "smooth" : "flat") + ")");
}
break;
}
case RNORM: {
// This seems to be taked into account when calculating the lighting
// for the current normal.
context.faceNormalReverseFlag.setEnabled(normalArgument);
break;
}
/*
* Material setup
*/
case CMAT: {
int old_mat_flags = context.mat_flags;
context.mat_flags = normalArgument & 7;
if (old_mat_flags != context.mat_flags) {
materialChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuColorMaterial " + context.mat_flags);
}
break;
}
case EMC:
context.mat_emissive[0] = ((normalArgument) & 255) / 255.f;
context.mat_emissive[1] = ((normalArgument >> 8) & 255) / 255.f;
context.mat_emissive[2] = ((normalArgument >> 16) & 255) / 255.f;
context.mat_emissive[3] = 1.f;
materialChanged = true;
re.setMaterialEmissiveColor(context.mat_emissive);
if (isLogDebugEnabled) {
log("material emission " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
context.mat_emissive[0], context.mat_emissive[1], context.mat_emissive[2], normalArgument));
}
break;
case AMC:
context.mat_ambient[0] = ((normalArgument) & 255) / 255.f;
context.mat_ambient[1] = ((normalArgument >> 8) & 255) / 255.f;
context.mat_ambient[2] = ((normalArgument >> 16) & 255) / 255.f;
materialChanged = true;
if (isLogDebugEnabled) {
log(String.format("material ambient r=%.1f g=%.1f b=%.1f (%08X)",
context.mat_ambient[0], context.mat_ambient[1], context.mat_ambient[2], normalArgument));
}
break;
case DMC:
context.mat_diffuse[0] = ((normalArgument) & 255) / 255.f;
context.mat_diffuse[1] = ((normalArgument >> 8) & 255) / 255.f;
context.mat_diffuse[2] = ((normalArgument >> 16) & 255) / 255.f;
context.mat_diffuse[3] = 1.f;
materialChanged = true;
if (isLogDebugEnabled) {
log("material diffuse " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
context.mat_diffuse[0], context.mat_diffuse[1], context.mat_diffuse[2], normalArgument));
}
break;
case SMC:
context.mat_specular[0] = ((normalArgument) & 255) / 255.f;
context.mat_specular[1] = ((normalArgument >> 8) & 255) / 255.f;
context.mat_specular[2] = ((normalArgument >> 16) & 255) / 255.f;
context.mat_specular[3] = 1.f;
materialChanged = true;
if (isLogDebugEnabled) {
log("material specular " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
context.mat_specular[0], context.mat_specular[1], context.mat_specular[2], normalArgument));
}
break;
case AMA: {
context.mat_ambient[3] = ((normalArgument) & 255) / 255.f;
materialChanged = true;
if (isLogDebugEnabled) {
log(String.format("material ambient a=%.1f (%02X)",
context.mat_ambient[3], normalArgument & 255));
}
break;
}
case SPOW: {
context.materialShininess = floatArgument(normalArgument);
re.setMaterialShininess(context.materialShininess);
if (isLogDebugEnabled) {
log("material shininess " + context.materialShininess);
}
break;
}
case ALC:
context.ambient_light[0] = ((normalArgument) & 255) / 255.f;
context.ambient_light[1] = ((normalArgument >> 8) & 255) / 255.f;
context.ambient_light[2] = ((normalArgument >> 16) & 255) / 255.f;
re.setLightModelAmbientColor(context.ambient_light);
if (isLogDebugEnabled) {
log.debug(String.format("ambient light r=%.1f g=%.1f b=%.1f (%06X)",
context.ambient_light[0], context.ambient_light[1], context.ambient_light[2], normalArgument));
}
break;
case ALA:
context.ambient_light[3] = ((normalArgument) & 255) / 255.f;
re.setLightModelAmbientColor(context.ambient_light);
break;
case LMODE: {
context.lightMode = normalArgument & 1;
re.setLightMode(context.lightMode);
if (isLogDebugEnabled) {
log.debug("sceGuLightMode(" + ((context.lightMode != 0) ? "GU_SEPARATE_SPECULAR_COLOR" : "GU_SINGLE_COLOR") + ")");
}
// Check if other values than 0 and 1 are set
if ((normalArgument & ~1) != 0) {
log.warn(String.format("Unknown light mode sceGuLightMode(%06X)", normalArgument));
}
break;
}
/*
* Light types
*/
case LT0:
case LT1:
case LT2:
case LT3: {
int lnum = command - LT0;
int old_light_type = context.light_type[lnum];
int old_light_kind = context.light_kind[lnum];
context.light_type[lnum] = (normalArgument >> 8) & 3;
context.light_kind[lnum] = normalArgument & 3;
if (old_light_type != context.light_type[lnum] || old_light_kind != context.light_kind[lnum]) {
lightingChanged = true;
}
switch (context.light_type[lnum]) {
case LIGHT_DIRECTIONAL:
context.light_pos[lnum][3] = 0.f;
break;
case LIGHT_POINT:
re.setLightSpotCutoff(lnum, 180);
context.light_pos[lnum][3] = 1.f;
break;
case LIGHT_SPOT:
context.light_pos[lnum][3] = 1.f;
break;
default:
error("Unknown light type : " + normalArgument);
}
re.setLightType(lnum, context.light_type[lnum], context.light_kind[lnum]);
if (isLogDebugEnabled) {
log.debug("Light " + lnum + " type " + (normalArgument >> 8) + " kind " + (normalArgument & 3));
}
break;
}
/*
* Light attributes
*/
// Position
case LXP0:
case LXP1:
case LXP2:
case LXP3:
case LYP0:
case LYP1:
case LYP2:
case LYP3:
case LZP0:
case LZP1:
case LZP2:
case LZP3: {
int lnum = (command - LXP0) / 3;
int component = (command - LXP0) % 3;
float old_light_pos = context.light_pos[lnum][component];
context.light_pos[lnum][component] = floatArgument(normalArgument);
if (old_light_pos != context.light_pos[lnum][component]) {
lightingChanged = true;
}
if (isLogDebugEnabled) {
log.debug(String.format("Light %d position (%f, %f, %f)", lnum, context.light_pos[lnum][0], context.light_pos[lnum][1], context.light_pos[lnum][2]));
}
break;
}
case LXD0:
case LXD1:
case LXD2:
case LXD3:
case LYD0:
case LYD1:
case LYD2:
case LYD3:
case LZD0:
case LZD1:
case LZD2:
case LZD3: {
int lnum = (command - LXD0) / 3;
int component = (command - LXD0) % 3;
float old_light_dir = context.light_dir[lnum][component];
// OpenGL requires a normal in the opposite direction as the PSP
context.light_dir[lnum][component] = -floatArgument(normalArgument);
if (old_light_dir != context.light_dir[lnum][component]) {
lightingChanged = true;
}
if (isLogDebugEnabled) {
log.debug(String.format("Light %d direction (%f, %f, %f)", lnum, context.light_dir[lnum][0], context.light_dir[lnum][1], context.light_dir[lnum][2]));
}
// OpenGL parameter for light direction is set in initRendering
// because it depends on the model/view matrix
break;
}
// Light Attenuation
// Constant
case LCA0:
case LCA1:
case LCA2:
case LCA3: {
int lnum = (command - LCA0) / 3;
context.lightConstantAttenuation[lnum] = floatArgument(normalArgument);
re.setLightConstantAttenuation(lnum, context.lightConstantAttenuation[lnum]);
break;
}
// Linear
case LLA0:
case LLA1:
case LLA2:
case LLA3: {
int lnum = (command - LLA0) / 3;
context.lightLinearAttenuation[lnum] = floatArgument(normalArgument);
re.setLightLinearAttenuation(lnum, context.lightLinearAttenuation[lnum]);
break;
}
// Quadratic
case LQA0:
case LQA1:
case LQA2:
case LQA3: {
int lnum = (command - LQA0) / 3;
context.lightQuadraticAttenuation[lnum] = floatArgument(normalArgument);
re.setLightQuadraticAttenuation(lnum, context.lightQuadraticAttenuation[lnum]);
break;
}
/*
* Spot light exponent
*/
case SLE0:
case SLE1:
case SLE2:
case SLE3: {
int lnum = command - SLE0;
float old_spotLightExponent = context.spotLightExponent[lnum];
context.spotLightExponent[lnum] = floatArgument(normalArgument);
if (old_spotLightExponent != context.spotLightExponent[lnum]) {
lightingChanged = true;
}
if (isLogDebugEnabled) {
VideoEngine.log.debug("sceGuLightSpot(" + lnum + ",X," + context.spotLightExponent[lnum] + ",X)");
}
break;
}
/*
* Spot light cutoff angle
*/
case SLF0:
case SLF1:
case SLF2:
case SLF3: {
int lnum = command - SLF0;
float old_spotLightCutoff = context.spotLightCutoff[lnum];
// PSP Cutoff is cosine of angle, OpenGL expects degrees
float floatArgument = floatArgument(normalArgument);
float degreeCutoff = (float) Math.toDegrees(Math.acos(floatArgument));
if ((degreeCutoff >= 0 && degreeCutoff <= 90) || degreeCutoff == 180) {
context.spotLightCutoff[lnum] = degreeCutoff;
if (old_spotLightCutoff != context.spotLightCutoff[lnum]) {
lightingChanged = true;
}
if (isLogDebugEnabled) {
log.debug("sceGuLightSpot(" + lnum + ",X,X," + floatArgument + "=" + degreeCutoff + ")");
}
} else {
log.warn("sceGuLightSpot(" + lnum + ",X,X," + floatArgument + ") invalid argument value");
}
break;
}
// Color
// Ambient
case ALC0:
case ALC1:
case ALC2:
case ALC3: {
int lnum = (command - ALC0) / 3;
context.lightAmbientColor[lnum][0] = ((normalArgument) & 255) / 255.f;
context.lightAmbientColor[lnum][1] = ((normalArgument >> 8) & 255) / 255.f;
context.lightAmbientColor[lnum][2] = ((normalArgument >> 16) & 255) / 255.f;
context.lightAmbientColor[lnum][3] = 1.f;
re.setLightAmbientColor(lnum, context.lightAmbientColor[lnum]);
log("sceGuLightColor (GU_LIGHT0, GU_AMBIENT)");
break;
}
// Diffuse
case DLC0:
case DLC1:
case DLC2:
case DLC3: {
int lnum = (command - DLC0) / 3;
context.lightDiffuseColor[lnum][0] = ((normalArgument) & 255) / 255.f;
context.lightDiffuseColor[lnum][1] = ((normalArgument >> 8) & 255) / 255.f;
context.lightDiffuseColor[lnum][2] = ((normalArgument >> 16) & 255) / 255.f;
context.lightDiffuseColor[lnum][3] = 1.f;
re.setLightDiffuseColor(lnum, context.lightDiffuseColor[lnum]);
log("sceGuLightColor (GU_LIGHT0, GU_DIFFUSE)");
break;
}
// Specular
case SLC0:
case SLC1:
case SLC2:
case SLC3: {
int lnum = (command - SLC0) / 3;
float old_lightSpecularColor0 = context.lightSpecularColor[lnum][0];
float old_lightSpecularColor1 = context.lightSpecularColor[lnum][1];
float old_lightSpecularColor2 = context.lightSpecularColor[lnum][2];
context.lightSpecularColor[lnum][0] = ((normalArgument) & 255) / 255.f;
context.lightSpecularColor[lnum][1] = ((normalArgument >> 8) & 255) / 255.f;
context.lightSpecularColor[lnum][2] = ((normalArgument >> 16) & 255) / 255.f;
context.lightSpecularColor[lnum][3] = 1.f;
if (old_lightSpecularColor0 != context.lightSpecularColor[lnum][0] || old_lightSpecularColor1 != context.lightSpecularColor[lnum][1] || old_lightSpecularColor2 != context.lightSpecularColor[lnum][2]) {
lightingChanged = true;
}
re.setLightSpecularColor(lnum, context.lightDiffuseColor[lnum]);
log("sceGuLightColor (GU_LIGHT0, GU_SPECULAR)");
break;
}
case FFACE: {
context.frontFaceCw = normalArgument != 0;
re.setFrontFace(context.frontFaceCw);
if (isLogDebugEnabled) {
log(helper.getCommandString(FFACE) + " " + ((normalArgument != 0) ? "clockwise" : "counter-clockwise"));
}
break;
}
case FBP:
// FBP can be called before or after FBW
context.fbp = (context.fbp & 0xff000000) | normalArgument;
if (isLogDebugEnabled) {
log(helper.getCommandString(FBP) + " fbp=" + Integer.toHexString(context.fbp) + ", fbw=" + context.fbw);
}
geBufChanged = true;
break;
case FBW:
context.fbp = (context.fbp & 0x00ffffff) | ((normalArgument << 8) & 0xff000000);
context.fbw = normalArgument & 0xffff;
if (isLogDebugEnabled) {
log(helper.getCommandString(FBW) + " fbp=" + Integer.toHexString(context.fbp) + ", fbw=" + context.fbw);
}
geBufChanged = true;
break;
case ZBP:
context.zbp = (context.zbp & 0xff000000) | normalArgument;
if (isLogDebugEnabled) {
log("zbp=" + Integer.toHexString(context.zbp) + ", zbw=" +context. zbw);
}
break;
case ZBW:
context.zbp = (context.zbp & 0x00ffffff) | ((normalArgument << 8) & 0xff000000);
context.zbw = normalArgument & 0xffff;
if (isLogDebugEnabled) {
log("zbp=" + Integer.toHexString(context.zbp) + ", zbw=" + context.zbw);
}
break;
case TBP0:
case TBP1:
case TBP2:
case TBP3:
case TBP4:
case TBP5:
case TBP6:
case TBP7: {
int level = command - TBP0;
int old_texture_base_pointer = context.texture_base_pointer[level];
context.texture_base_pointer[level] = (context.texture_base_pointer[level] & 0xff000000) | normalArgument;
if (old_texture_base_pointer != context.texture_base_pointer[level]) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuTexImage(level=" + level + ", X, X, X, lo(pointer=0x" + Integer.toHexString(context.texture_base_pointer[level]) + "))");
}
break;
}
case TBW0:
case TBW1:
case TBW2:
case TBW3:
case TBW4:
case TBW5:
case TBW6:
case TBW7: {
int level = command - TBW0;
int old_texture_base_pointer = context.texture_base_pointer[level];
int old_texture_buffer_width = context.texture_buffer_width[level];
context.texture_base_pointer[level] = (context.texture_base_pointer[level] & 0x00ffffff) | ((normalArgument << 8) & 0xff000000);
context.texture_buffer_width[level] = normalArgument & 0xffff;
if (old_texture_base_pointer != context.texture_base_pointer[level] || old_texture_buffer_width != context.texture_buffer_width[level]) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuTexImage(level=" + level + ", X, X, texBufferWidth=" + context.texture_buffer_width[level] + ", hi(pointer=0x" + Integer.toHexString(context.texture_base_pointer[level]) + "))");
}
break;
}
case CBP: {
int old_tex_clut_addr = context.tex_clut_addr;
context.tex_clut_addr = (context.tex_clut_addr & 0xff000000) | normalArgument;
clutIsDirty = true;
if (old_tex_clut_addr != context.tex_clut_addr) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuClutLoad(X, lo(cbp=0x" + Integer.toHexString(context.tex_clut_addr) + "))");
}
break;
}
case CBPH: {
int old_tex_clut_addr = context.tex_clut_addr;
context.tex_clut_addr = (context.tex_clut_addr & 0x00ffffff) | ((normalArgument << 8) & 0x0f000000);
clutIsDirty = true;
if (old_tex_clut_addr != context.tex_clut_addr) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuClutLoad(X, hi(cbp=0x" + Integer.toHexString(context.tex_clut_addr) + "))");
}
break;
}
case TRXSBP:
context.textureTx_sourceAddress = (context.textureTx_sourceAddress & 0xFF000000) | normalArgument;
break;
case TRXSBW:
context.textureTx_sourceAddress = (context.textureTx_sourceAddress & 0x00FFFFFF) | ((normalArgument << 8) & 0xFF000000);
context.textureTx_sourceLineWidth = normalArgument & 0x0000FFFF;
// TODO Check when sx and sy are reset to 0. Here or after TRXKICK?
context.textureTx_sx = 0;
context.textureTx_sy = 0;
break;
case TRXDBP:
context.textureTx_destinationAddress = (context.textureTx_destinationAddress & 0xFF000000) | normalArgument;
break;
case TRXDBW:
context.textureTx_destinationAddress = (context.textureTx_destinationAddress & 0x00FFFFFF) | ((normalArgument << 8) & 0xFF000000);
context.textureTx_destinationLineWidth = normalArgument & 0x0000FFFF;
// TODO Check when dx and dy are reset to 0. Here or after TRXKICK?
context.textureTx_dx = 0;
context.textureTx_dy = 0;
break;
case TSIZE0:
case TSIZE1:
case TSIZE2:
case TSIZE3:
case TSIZE4:
case TSIZE5:
case TSIZE6:
case TSIZE7: {
int level = command - TSIZE0;
int old_texture_height = context.texture_height[level];
int old_texture_width = context.texture_width[level];
// Astonishia Story is using normalArgument = 0x1804
// -> use texture_height = 1 << 0x08 (and not 1 << 0x18)
// texture_width = 1 << 0x04
// The maximum texture size is 512x512: the exponent value must be [0..9]
int height_exp2 = Math.min((normalArgument >> 8) & 0x0F, 9);
int width_exp2 = Math.min((normalArgument) & 0x0F, 9);
context.texture_height[level] = 1 << height_exp2;
context.texture_width[level] = 1 << width_exp2;
if (old_texture_height != context.texture_height[level] || old_texture_width != context.texture_width[level]) {
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD && level == 0) {
textureMatrixUpload.setChanged(true);
}
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuTexImage(level=" + level + ", width=" + context.texture_width[level] + ", height=" + context.texture_height[level] + ", X, X)");
}
break;
}
case TMAP:
int old_tex_map_mode = context.tex_map_mode;
context.tex_map_mode = normalArgument & 3;
context.tex_proj_map_mode = (normalArgument >> 8) & 3;
if (old_tex_map_mode != context.tex_map_mode) {
textureMatrixUpload.setChanged(true);
}
if (isLogDebugEnabled) {
log("sceGuTexMapMode(mode=" + context.tex_map_mode + ", X, X)");
log("sceGuTexProjMapMode(mode=" + context.tex_proj_map_mode + ")");
}
break;
case TEXTURE_ENV_MAP_MATRIX: {
context.tex_shade_u = (normalArgument >> 0) & 0x3;
context.tex_shade_v = (normalArgument >> 8) & 0x3;
for (int i = 0; i < 3; i++) {
context.tex_envmap_matrix[i + 0] = context.light_pos[context.tex_shade_u][i];
context.tex_envmap_matrix[i + 4] = context.light_pos[context.tex_shade_v][i];
}
textureMatrixUpload.setChanged(true);
if (isLogDebugEnabled) {
log("sceGuTexMapMode(X, " + context.tex_shade_u + ", " + context.tex_shade_v + ")");
}
break;
}
case TMODE: {
int old_texture_num_mip_maps = context.texture_num_mip_maps;
boolean old_mipmapShareClut = context.mipmapShareClut;
boolean old_texture_swizzle = context.texture_swizzle;
context.texture_num_mip_maps = (normalArgument >> 16) & 0x7;
// This parameter has only a meaning when
// texture_storage == GU_PSM_T4 and texture_num_mip_maps > 0
// when parameter==0: all the mipmaps share the same clut entries (normal behavior)
// when parameter==1: each mipmap has its own clut table, 16 entries each, stored sequentially
context.mipmapShareClut = ((normalArgument >> 8) & 0x1) == 0;
context.texture_swizzle = ((normalArgument) & 0x1) != 0;
if (old_texture_num_mip_maps != context.texture_num_mip_maps || old_mipmapShareClut != context.mipmapShareClut || old_texture_swizzle != context.texture_swizzle) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuTexMode(X, mipmaps=" + context.texture_num_mip_maps + ", mipmapShareClut=" + context.mipmapShareClut + ", swizzle=" + context.texture_swizzle + ")");
}
break;
}
case TPSM: {
int old_texture_storage = context.texture_storage;
context.texture_storage = normalArgument & 0xF; // Lower four bits.
if (old_texture_storage != context.texture_storage) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuTexMode(tpsm=" + context.texture_storage + "(" + getPsmName(context.texture_storage) + "), X, X, X)");
}
break;
}
case CLOAD: {
int old_tex_clut_num_blocks = context.tex_clut_num_blocks;
context.tex_clut_num_blocks = normalArgument & 0x3F;
clutIsDirty = true;
if (old_tex_clut_num_blocks != context.tex_clut_num_blocks) {
textureChanged = true;
}
// Some games use the following sequence:
// - sceGuClutLoad(num_blocks=32, X)
// - sceGuClutLoad(num_blocks=1, X)
// - tflush
// - prim ... (texture data is referencing the clut entries from 32 blocks)
//
readClut();
if (isLogDebugEnabled) {
log("sceGuClutLoad(num_blocks=" + context.tex_clut_num_blocks + ", X)");
}
break;
}
case CMODE: {
int old_tex_clut_mode = context.tex_clut_mode;
int old_tex_clut_shift = context.tex_clut_shift;
int old_tex_clut_mask = context.tex_clut_mask;
int old_tex_clut_start = context.tex_clut_start;
context.tex_clut_mode = normalArgument & 0x03;
context.tex_clut_shift = (normalArgument >> 2) & 0x1F;
context.tex_clut_mask = (normalArgument >> 8) & 0xFF;
context.tex_clut_start = (normalArgument >> 16) & 0x1F;
clutIsDirty = true;
if (old_tex_clut_mode != context.tex_clut_mode || old_tex_clut_shift != context.tex_clut_shift || old_tex_clut_mask != context.tex_clut_mask || old_tex_clut_start != context.tex_clut_start) {
textureChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuClutMode(cpsm=" + context.tex_clut_mode + "(" + getPsmName(context.tex_clut_mode) + "), shift=" + context.tex_clut_shift + ", mask=0x" + Integer.toHexString(context.tex_clut_mask) + ", start=" + context.tex_clut_start + ")");
}
break;
}
case TFLT: {
int old_tex_mag_filter = context.tex_mag_filter;
int old_tex_min_filter = context.tex_min_filter;
context.tex_min_filter = normalArgument & 0x7;
context.tex_mag_filter = (normalArgument >> 8) & 0x1;
if (isLogDebugEnabled) {
log("sceGuTexFilter(min=" + context.tex_min_filter + ", mag=" + context.tex_mag_filter + ") (mm#" + context.texture_num_mip_maps + ")");
}
if (context.tex_min_filter == TFLT_UNKNOW1 || context.tex_min_filter == TFLT_UNKNOW2) {
log.warn("Unknown minimizing filter " + (normalArgument & 0xFF));
context.tex_min_filter = TFLT_NEAREST;
}
if (old_tex_mag_filter != context.tex_mag_filter || old_tex_min_filter != context.tex_min_filter) {
textureChanged = true;
}
break;
}
case TWRAP: {
context.tex_wrap_s = normalArgument & 0xFF;
context.tex_wrap_t = (normalArgument >> 8) & 0xFF;
if (context.tex_wrap_s > TWRAP_WRAP_MODE_CLAMP) {
log.warn(helper.getCommandString(TWRAP) + " unknown wrap mode " + context.tex_wrap_s);
context.tex_wrap_s = TWRAP_WRAP_MODE_REPEAT;
}
if (context.tex_wrap_t > TWRAP_WRAP_MODE_CLAMP) {
log.warn(helper.getCommandString(TWRAP) + " unknown wrap mode " + context.tex_wrap_t);
context.tex_wrap_t = TWRAP_WRAP_MODE_REPEAT;
}
break;
}
case TBIAS: {
context.tex_mipmap_mode = normalArgument & 0x3;
context.tex_mipmap_bias_int = (int) (byte) (normalArgument >> 16); // Signed 8-bit integer
context.tex_mipmap_bias = context.tex_mipmap_bias_int / 16.0f;
if (isLogDebugEnabled) {
log.debug("sceGuTexLevelMode(mode=" + context.tex_mipmap_mode + ", bias=" + context.tex_mipmap_bias + ")");
}
break;
}
case TFUNC:
executeCommandTFUNC(normalArgument);
break;
case TEC: {
context.tex_env_color[0] = ((normalArgument) & 255) / 255.f;
context.tex_env_color[1] = ((normalArgument >> 8) & 255) / 255.f;
context.tex_env_color[2] = ((normalArgument >> 16) & 255) / 255.f;
context.tex_env_color[3] = 1.f;
re.setTextureEnvColor(context.tex_env_color);
if (isLogDebugEnabled) {
log(String.format("sceGuTexEnvColor %08X (no alpha)", normalArgument));
}
break;
}
case TFLUSH: {
// Do not load the texture right now, clut parameters can still be
// defined after the TFLUSH and before the PRIM command.
// Delay the texture loading until the PRIM command.
if (isLogDebugEnabled) {
log("tflush (deferring to prim)");
}
break;
}
case TSYNC: {
// Probably synchronizing the GE when a drawing result
// is used as a texture. Currently ignored.
if (isLogDebugEnabled) {
log(helper.getCommandString(TSYNC) + " waiting for drawing.");
}
break;
}
case FFAR:
context.fog_far = floatArgument(normalArgument);
break;
case FDIST:
context.fog_dist = floatArgument(normalArgument);
if ((context.fog_far != 0.0f) && (context.fog_dist != 0.0f)) {
float end = context.fog_far;
float start = end - (1 / context.fog_dist);
re.setFogDist(start, end);
}
break;
case FCOL:
context.fog_color[0] = ((normalArgument) & 255) / 255.f;
context.fog_color[1] = ((normalArgument >> 8) & 255) / 255.f;
context.fog_color[2] = ((normalArgument >> 16) & 255) / 255.f;
context.fog_color[3] = 1.f;
re.setFogColor(context.fog_color);
if (isLogDebugEnabled) {
log(String.format("sceGuFog(X, X, color=%08X) (no alpha)", normalArgument));
}
break;
case TSLOPE: {
context.tslope_level = floatArgument(normalArgument);
if (isLogDebugEnabled) {
log(helper.getCommandString(TSLOPE) + " tslope_level=" + context.tslope_level);
}
break;
}
case PSM:
context.psm = normalArgument;
if (isLogDebugEnabled) {
log("psm=" + normalArgument + "(" + getPsmName(normalArgument) + ")");
}
geBufChanged = true;
break;
case CLEAR:
executeCommandCLEAR(normalArgument);
break;
case SCISSOR1:
context.scissor_x1 = normalArgument & 0x3ff;
context.scissor_y1 = (normalArgument >> 10) & 0x3ff;
scissorChanged = true;
break;
case SCISSOR2:
context.scissor_x2 = normalArgument & 0x3ff;
context.scissor_y2 = (normalArgument >> 10) & 0x3ff;
context.scissor_width = 1 + context.scissor_x2 - context.scissor_x1;
context.scissor_height = 1 + context.scissor_y2 - context.scissor_y1;
if (isLogDebugEnabled) {
log("sceGuScissor(" + context.scissor_x1 + "," + context.scissor_y1 + "," + context.scissor_width + "," + context.scissor_height + ")");
}
scissorChanged = true;
break;
case NEARZ: {
float old_nearZ = context.nearZ;
context.nearZ = (normalArgument & 0xFFFF) / (float) 0xFFFF;
if (old_nearZ != context.nearZ) {
depthChanged = true;
}
break;
}
case FARZ: {
float old_farZ = context.farZ;
context.farZ = (normalArgument & 0xFFFF) / (float) 0xFFFF;
if (old_farZ != context.farZ) {
// OpenGL requires the Depth parameters to be reloaded
depthChanged = true;
}
if (depthChanged) {
re.setDepthRange(context.zpos, context.zscale, context.nearZ, context.farZ);
}
if (isLogDebugEnabled) {
log.debug("sceGuDepthRange(" + context.nearZ + ", " + context.farZ + ")");
}
break;
}
case CTST: {
context.colorTestFunc = normalArgument & 3;
re.setColorTestFunc(context.colorTestFunc);
break;
}
case CREF: {
context.colorTestRef[0] = (normalArgument) & 0xFF;
context.colorTestRef[1] = (normalArgument >> 8) & 0xFF;
context.colorTestRef[2] = (normalArgument >> 16) & 0xFF;
re.setColorTestReference(context.colorTestRef);
break;
}
case CMSK: {
context.colorTestMsk[0] = (normalArgument) & 0xFF;
context.colorTestMsk[1] = (normalArgument >> 8) & 0xFF;
context.colorTestMsk[2] = (normalArgument >> 16) & 0xFF;
re.setColorTestMask(context.colorTestMsk);
break;
}
case ATST: {
context.alphaFunc = normalArgument & 0xFF;
if (context.alphaFunc > ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL) {
log.warn("sceGuAlphaFunc unhandled func " + context.alphaFunc);
context.alphaFunc = ATST_ALWAYS_PASS_PIXEL;
}
context.alphaRef = (normalArgument >> 8) & 0xFF;
re.setAlphaFunc(context.alphaFunc, context.alphaRef);
if (isLogDebugEnabled) {
log("sceGuAlphaFunc(" + context.alphaFunc + "," + context.alphaRef + ")");
}
break;
}
case STST: {
context.stencilFunc = normalArgument & 0xFF;
if (context.stencilFunc > STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL) {
log.warn("Unknown stencil function " + context.stencilFunc);
context.stencilFunc = STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST;
}
context.stencilRef = (normalArgument >> 8) & 0xff;
context.stencilMask = (normalArgument >> 16) & 0xff;
re.setStencilFunc(context.stencilFunc, context.stencilRef, context.stencilMask);
if (isLogDebugEnabled) {
log("sceGuStencilFunc(func=" + (normalArgument & 0xFF) + ", ref=" + context.stencilRef + ", mask=" + context.stencilMask + ")");
}
break;
}
case SOP: {
context.stencilOpFail = getStencilOp(normalArgument & 0xFF);
context.stencilOpZFail = getStencilOp((normalArgument >> 8) & 0xFF);
context.stencilOpZPass = getStencilOp((normalArgument >> 16) & 0xFF);
re.setStencilOp(context.stencilOpFail, context.stencilOpZFail, context.stencilOpZPass);
if (isLogDebugEnabled) {
log("sceGuStencilOp(fail=" + (normalArgument & 0xFF) + ", zfail=" + ((normalArgument >> 8) & 0xFF) + ", zpass=" + ((normalArgument >> 16) & 0xFF) + ")");
}
break;
}
case ZTST: {
int oldDepthFunc = context.depthFunc;
context.depthFunc = normalArgument & 0xFF;
if (context.depthFunc > ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL) {
error(String.format("%s unknown depth function %d", commandToString(ZTST), context.depthFunc));
context.depthFunc = ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS;
}
if (oldDepthFunc != context.depthFunc) {
depthChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuDepthFunc(" + normalArgument + ")");
}
break;
}
case ALPHA: {
int old_blend_src = context.blend_src;
int old_blend_dst = context.blend_dst;
context.blend_src = normalArgument & 0xF;
context.blend_dst = (normalArgument >> 4) & 0xF;
context.blendEquation = (normalArgument >> 8) & 0xF;
if (context.blendEquation > ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE) {
log.warn("Unhandled blend operation " + context.blendEquation);
context.blendEquation = ALPHA_SOURCE_BLEND_OPERATION_ADD;
}
re.setBlendEquation(context.blendEquation);
if (old_blend_src != context.blend_src || old_blend_dst != context.blend_dst) {
blendChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuBlendFunc(op=" + context.blendEquation + ", src=" + context.blend_src + ", dst=" + context.blend_dst + ")");
}
break;
}
case SFIX: {
float old_sfix_color0 = context.sfix_color[0];
float old_sfix_color1 = context.sfix_color[1];
float old_sfix_color2 = context.sfix_color[2];
context.sfix_color[0] = ((normalArgument) & 255) / 255.f;
context.sfix_color[1] = ((normalArgument >> 8) & 255) / 255.f;
context.sfix_color[2] = ((normalArgument >> 16) & 255) / 255.f;
context.sfix_color[3] = 1.f;
if (old_sfix_color0 != context.sfix_color[0] || old_sfix_color1 != context.sfix_color[1] || old_sfix_color2 != context.sfix_color[2]) {
blendChanged = true;
}
if (isLogDebugEnabled) {
log(String.format("%s : 0x%08X", helper.getCommandString(command), normalArgument));
}
break;
}
case DFIX: {
float old_dfix_color0 = context.dfix_color[0];
float old_dfix_color1 = context.dfix_color[1];
float old_dfix_color2 = context.dfix_color[2];
context.dfix_color[0] = ((normalArgument) & 255) / 255.f;
context.dfix_color[1] = ((normalArgument >> 8) & 255) / 255.f;
context.dfix_color[2] = ((normalArgument >> 16) & 255) / 255.f;
context.dfix_color[3] = 1.f;
if (old_dfix_color0 != context.dfix_color[0] || old_dfix_color1 != context.dfix_color[1] || old_dfix_color2 != context.dfix_color[2]) {
blendChanged = true;
}
if (isLogDebugEnabled) {
log(String.format("%s : 0x%08X", helper.getCommandString(command), normalArgument));
}
break;
}
case DTH0:
context.dither_matrix[0] = (normalArgument) & 0xF;
context.dither_matrix[1] = (normalArgument >> 4) & 0xF;
context.dither_matrix[2] = (normalArgument >> 8) & 0xF;
context.dither_matrix[3] = (normalArgument >> 12) & 0xF;
break;
case DTH1:
context.dither_matrix[4] = (normalArgument) & 0xF;
context.dither_matrix[5] = (normalArgument >> 4) & 0xF;
context.dither_matrix[6] = (normalArgument >> 8) & 0xF;
context.dither_matrix[7] = (normalArgument >> 12) & 0xF;
break;
case DTH2:
context.dither_matrix[8] = (normalArgument) & 0xF;
context.dither_matrix[9] = (normalArgument >> 4) & 0xF;
context.dither_matrix[10] = (normalArgument >> 8) & 0xF;
context.dither_matrix[11] = (normalArgument >> 12) & 0xF;
break;
case DTH3:
context.dither_matrix[12] = (normalArgument) & 0xF;
context.dither_matrix[13] = (normalArgument >> 4) & 0xF;
context.dither_matrix[14] = (normalArgument >> 8) & 0xF;
context.dither_matrix[15] = (normalArgument >> 12) & 0xF;
// The dither matrix's values can vary between -8 and 7.
// The most significant bit acts as sign bit.
// Translate and log only at the last command.
for (int i = 0; i < 16; i++) {
if (context.dither_matrix[i] > 7) {
context.dither_matrix[i] |= 0xFFFFFFF0;
}
}
if (isLogDebugEnabled) {
log.debug("DTH0:" + " " + context.dither_matrix[0] + " " + context.dither_matrix[1] + " " + context.dither_matrix[2] + " " + context.dither_matrix[3]);
log.debug("DTH1:" + " " + context.dither_matrix[4] + " " + context.dither_matrix[5] + " " + context.dither_matrix[6] + " " + context.dither_matrix[7]);
log.debug("DTH2:" + " " + context.dither_matrix[8] + " " + context.dither_matrix[9] + " " + context.dither_matrix[10] + " " + context.dither_matrix[11]);
log.debug("DTH3:" + " " + context.dither_matrix[12] + " " + context.dither_matrix[13] + " " + context.dither_matrix[14] + " " + context.dither_matrix[15]);
}
break;
case LOP: {
context.logicOp = normalArgument & 0xF;
re.setLogicOp(context.logicOp);
if (isLogDebugEnabled) {
log.debug("sceGuLogicalOp(LogicOp=" + context.logicOp + "(" + getLOpName(context.logicOp) + "))");
}
break;
}
case ZMSK: {
// NOTE: PSP depth mask as 1 is meant to avoid depth writes,
// with OpenGL it's the opposite
context.depthMask = (normalArgument == 0);
re.setDepthMask(context.depthMask);
if (context.depthMask) {
// OpenGL requires the Depth parameters to be reloaded
depthChanged = true;
}
if (isLogDebugEnabled) {
log("sceGuDepthMask(" + (normalArgument != 0 ? "disableWrites" : "enableWrites") + ")");
}
break;
}
case PMSKC: {
context.colorMask[0] = normalArgument & 0xFF;
context.colorMask[1] = (normalArgument >> 8) & 0xFF;
context.colorMask[2] = (normalArgument >> 16) & 0xFF;
re.setColorMask(context.colorMask[0], context.colorMask[1], context.colorMask[2], context.colorMask[3]);
if (isLogDebugEnabled) {
log(String.format("%s color mask=0x%06X", helper.getCommandString(PMSKC), normalArgument));
}
break;
}
case PMSKA: {
context.colorMask[3] = normalArgument & 0xFF;
re.setColorMask(context.colorMask[0], context.colorMask[1], context.colorMask[2], context.colorMask[3]);
if (isLogDebugEnabled) {
log(String.format("%s alpha mask=0x%02X", helper.getCommandString(PMSKA), normalArgument));
}
break;
}
case TRXKICK:
executeCommandTRXKICK(normalArgument);
break;
case TRXPOS:
context.textureTx_sx = normalArgument & 0x1FF;
context.textureTx_sy = (normalArgument >> 10) & 0x1FF;
break;
case TRXDPOS:
context.textureTx_dx = normalArgument & 0x1FF;
context.textureTx_dy = (normalArgument >> 10) & 0x1FF;
break;
case TRXSIZE:
context.textureTx_width = (normalArgument & 0x3FF) + 1;
context.textureTx_height = ((normalArgument >> 10) & 0x1FF) + 1;
break;
case VSCX:
int coordX = normalArgument & 0xFFFF;
log.warn("Unimplemented VSCX: coordX=" + coordX);
break;
case VSCY:
int coordY = normalArgument & 0xFFFF;
log.warn("Unimplemented VSCY: coordY=" + coordY);
break;
case VSCZ:
int coordZ = normalArgument & 0xFFFF;
log.warn("Unimplemented VSCZ: coordZ=" + coordZ);
break;
case VTCS:
float coordS = floatArgument(normalArgument);
log.warn("Unimplemented VTCS: coordS=" + coordS);
break;
case VTCT:
float coordT = floatArgument(normalArgument);
log.warn("Unimplemented VTCT: coordT=" + coordT);
break;
case VTCQ:
float coordQ = floatArgument(normalArgument);
log.warn("Unimplemented VTCQ: coordQ=" + coordQ);
break;
case VCV:
int colorR = normalArgument & 0xFF;
int colorG = (normalArgument >> 8) & 0xFF;
int colorB = (normalArgument >> 16) & 0xFF;
log.warn("Unimplemented VCV: colorR=" + colorR + ", colorG=" + colorG + ", colorB=" + colorB);
break;
case VAP:
int alpha = normalArgument & 0xFF;
int prim_type = (normalArgument >> 8) & 0x7;
log.warn("Unimplemented VAP: alpha=" + alpha + ", prim_type=" + prim_type);
break;
case VFC:
int fog = normalArgument & 0xFF;
log.warn("Unimplemented VFC: fog=" + fog);
break;
case VSCV:
int colorR2 = normalArgument & 0xFF;
int colorG2 = (normalArgument >> 8) & 0xFF;
int colorB2 = (normalArgument >> 16) & 0xFF;
log.warn("Unimplemented VSCV: colorR2=" + colorR2 + ", colorG2=" + colorG2 + ", colorB2=" + colorB2);
break;
case DUMMY: {
// This command always appears before a BOFS command and seems to have
// no special meaning.
// The command also appears sometimes after a PRIM command.
// Confirmed on PSP to be a dummy command and can be safely ignored.
// This commands' normalArgument may not be always 0, as it's totally
// discarded on the PSP.
if (isLogDebugEnabled) {
log.debug("Ignored DUMMY video command.");
}
break;
}
default:
if (isLogWarnEnabled) {
log.warn("Unknown/unimplemented video command [" + helper.getCommandString(command(instruction)) + "]" + getArgumentLog(normalArgument));
}
}
if (isLogInfoEnabled) {
commandStatistics[command].end();
}
}
private void executeCommandCLEAR(int normalArgument) {
if ((normalArgument & 1) == 0) {
re.endClearMode();
if (isLogDebugEnabled) {
log("clear mode end");
}
} else {
// TODO Add more disabling in clear mode, we also need to reflect the change to the internal GE registers
boolean color = (normalArgument & 0x100) != 0;
boolean alpha = (normalArgument & 0x200) != 0;
boolean depth = (normalArgument & 0x400) != 0;
updateGeBuf();
re.startClearMode(color, alpha, depth);
if (isLogDebugEnabled) {
log("clear mode : " + (normalArgument >> 8));
}
}
blendChanged = true;
lightingChanged = true;
projectionMatrixUpload.setChanged(true);
modelMatrixUpload.setChanged(true);
viewMatrixUpload.setChanged(true);
textureMatrixUpload.setChanged(true);
viewportChanged = true;
depthChanged = true;
materialChanged = true;
}
private void executeCommandTFUNC(int normalArgument) {
context.textureFunc = normalArgument & 0x7;
if (context.textureFunc >= TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_UNKNOW1) {
VideoEngine.log.warn("Unimplemented tfunc mode " + context.textureFunc);
context.textureFunc = TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE;
}
context.textureAlphaUsed = ((normalArgument >> 8) & 0x1) != TFUNC_FRAGMENT_DOUBLE_TEXTURE_COLOR_ALPHA_IS_IGNORED;
context.textureColorDoubled = ((normalArgument >> 16) & 0x1) != TFUNC_FRAGMENT_DOUBLE_ENABLE_COLOR_UNTOUCHED;
re.setTextureFunc(context.textureFunc, context.textureAlphaUsed, context.textureColorDoubled);
if (isLogDebugEnabled) {
log(String.format("sceGuTexFunc mode %06X", normalArgument)
+ (((normalArgument & 0x10000) != 0) ? " SCALE" : "")
+ (((normalArgument & 0x100) != 0) ? " ALPHA" : ""));
}
}
private void executeCommandPRIM(int normalArgument) {
int numberOfVertex = normalArgument & 0xFFFF;
int type = ((normalArgument >> 16) & 0x7);
Memory mem = Memory.getInstance();
if (!mem.isAddressGood(vinfo.ptr_vertex)) {
// Abort here to avoid a lot of useless memory read errors...
error(helper.getCommandString(PRIM) + " Invalid vertex address 0x" + Integer.toHexString(vinfo.ptr_vertex));
return;
}
if (type > PRIM_SPRITES) {
error(helper.getCommandString(PRIM) + " Type unhandled " + type);
return;
}
updateGeBuf();
somethingDisplayed = true;
primCount++;
loadTexture();
// Logging
if (isLogDebugEnabled) {
switch (type) {
case PRIM_POINT:
log("prim point " + numberOfVertex + "x");
break;
case PRIM_LINE:
log("prim line " + (numberOfVertex / 2) + "x");
break;
case PRIM_LINES_STRIPS:
log("prim lines_strips " + (numberOfVertex - 1) + "x");
break;
case PRIM_TRIANGLE:
log("prim triangle " + (numberOfVertex / 3) + "x");
break;
case PRIM_TRIANGLE_STRIPS:
log("prim triangle_strips " + (numberOfVertex - 2) + "x");
break;
case PRIM_TRIANGLE_FANS:
log("prim triangle_fans " + (numberOfVertex - 2) + "x");
break;
case PRIM_SPRITES:
log("prim sprites " + (numberOfVertex / 2) + "x");
break;
default:
VideoEngine.log.warn("prim unhandled " + type);
break;
}
}
boolean useVertexColor = initRendering();
int nTexCoord = 2;
int nColor = 4;
int nVertex = 3;
boolean useTexture = false;
boolean useTextureFromNormal = false;
boolean useTextureFromNormalizedNormal = false;
boolean useTextureFromPosition = false;
switch (context.tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (vinfo.texture != 0) {
useTexture = true;
}
break;
case TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX: {
switch (context.tex_proj_map_mode) {
case TMAP_TEXTURE_PROJECTION_MODE_POSITION:
if (vinfo.position != 0) {
useTexture = true;
useTextureFromPosition = true;
nTexCoord = nVertex;
}
break;
case TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
if (vinfo.texture != 0) {
useTexture = true;
}
break;
case TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
if (vinfo.normal != 0) {
useTexture = true;
useTextureFromNormal = true;
nTexCoord = 3;
}
break;
case TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
if (vinfo.normal != 0) {
useTexture = true;
useTextureFromNormalizedNormal = true;
nTexCoord = 3;
}
break;
}
break;
}
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
break;
default:
log("Unhandled texture matrix mode " + context.tex_map_mode);
break;
}
vertexStatistics.start();
vinfo.setMorphWeights(context.morph_weight);
vinfo.setDirty();
int numberOfWeightsForBuffer;
boolean mustComputeWeights;
if (vinfo.weight != 0) {
numberOfWeightsForBuffer = re.setBones(vinfo.skinningWeightCount, context.boneMatrixLinear);
mustComputeWeights = (numberOfWeightsForBuffer == 0);
} else {
numberOfWeightsForBuffer = re.setBones(0, null);
mustComputeWeights = false;
}
if (maxSpriteWidth == 0 || context.scissor_x2 < maxSpriteWidth) {
maxSpriteWidth = context.scissor_x2;
}
if (maxSpriteHeight == 0 || context.scissor_y2 < maxSpriteHeight) {
maxSpriteHeight = context.scissor_y2;
}
// Do not use optimized VertexInfo reading when
// - using Vertex Cache
// - the Vertex are indexed
// - the PRIM_SPRITE primitive is used where it is not supported natively
// - the normals have to be normalized for the texture mapping
// - the weights have to be computed and are not supported natively
// - the vertex address is invalid
// - tracing is enabled because it doesn't produce any trace information
if (!useVertexCache &&
vinfo.index == 0 &&
(type != PRIM_SPRITES || re.canNativeSpritesPrimitive()) &&
!useTextureFromNormalizedNormal &&
!mustComputeWeights &&
mem.isAddressGood(vinfo.ptr_vertex) &&
!isLogTraceEnabled) {
//
// Optimized VertexInfo reading:
// - do not copy the info already available in the OpenGL format
// (native format), load it into nativeBuffer (a direct buffer
// is required by OpenGL).
// - try to keep the info in "int" format when possible, convert
// to "float" only when necessary
// The best case is no reading and no conversion at all when all the
// vertex info are available in a format usable by OpenGL.
//
Buffer buffer = vertexInfoReader.read(vinfo, vinfo.ptr_vertex, numberOfVertex, re.canAllNativeVertexInfo());
enableClientState(useVertexColor, useTexture);
int stride = vertexInfoReader.getStride();
if (buffer != null) {
bufferManager.setBufferData(bufferId, stride * numberOfVertex, buffer, IRenderingEngine.RE_STREAM_DRAW);
}
if (vertexInfoReader.hasNative()) {
// Copy the VertexInfo from Memory to the nativeBuffer
// (a direct buffer is required by glXXXPointer())
int size = vinfo.vertexSize * numberOfVertex;
Buffer vertexData = mem.getBuffer(vinfo.ptr_vertex, size);
bufferManager.setBufferData(nativeBufferId, size, vertexData, IRenderingEngine.RE_STREAM_DRAW);
}
if (vinfo.texture != 0 || useTexture) {
boolean textureNative;
int textureOffset;
int textureType;
if (useTextureFromNormal) {
textureNative = vertexInfoReader.isNormalNative();
textureOffset = vertexInfoReader.getNormalOffset();
textureType = vertexInfoReader.getNormalType();
nTexCoord = vertexInfoReader.getNormalNumberValues();
} else if (useTextureFromPosition) {
textureNative = vertexInfoReader.isPositionNative();
textureOffset = vertexInfoReader.getPositionOffset();
textureType = vertexInfoReader.getPositionType();
nTexCoord = vertexInfoReader.getPositionNumberValues();
} else {
textureNative = vertexInfoReader.isTextureNative();
textureOffset = vertexInfoReader.getTextureOffset();
textureType = vertexInfoReader.getTextureType();
nTexCoord = vertexInfoReader.getTextureNumberValues();
}
setTexCoordPointer(useTexture, nTexCoord, textureType, stride, textureOffset, textureNative, true);
}
nVertex = vertexInfoReader.getPositionNumberValues();
nColor = vertexInfoReader.getColorNumberValues();
int nWeight = vertexInfoReader.getWeightNumberValues();
re.setVertexInfo(vinfo, re.canAllNativeVertexInfo(), useVertexColor);
setColorPointer(useVertexColor, nColor, vertexInfoReader.getColorType(), stride, vertexInfoReader.getColorOffset(), vertexInfoReader.isColorNative(), true);
setNormalPointer(vertexInfoReader.getNormalType(), stride, vertexInfoReader.getNormalOffset(), vertexInfoReader.isNormalNative(), true);
setWeightPointer(nWeight, vertexInfoReader.getWeightType(), stride, vertexInfoReader.getWeightOffset(), vertexInfoReader.isWeightNative(), true);
setVertexPointer(nVertex, vertexInfoReader.getPositionType(), stride, vertexInfoReader.getPositionOffset(), vertexInfoReader.isPositionNative(), true);
re.drawArrays(type, 0, numberOfVertex);
} else {
// Non-optimized VertexInfo reading
VertexInfo cachedVertexInfo = null;
if (useVertexCache) {
vertexCacheLookupStatistics.start();
cachedVertexInfo = VertexCache.getInstance().getVertex(vinfo, numberOfVertex, context.bone_uploaded_matrix, numberOfWeightsForBuffer);
vertexCacheLookupStatistics.end();
}
ByteBuffer byteBuffer = bufferManager.getBuffer(bufferId);
byteBuffer.clear();
FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
floatBuffer.clear();
re.setVertexInfo(vinfo, false, useVertexColor);
switch (type) {
case PRIM_POINT:
case PRIM_LINE:
case PRIM_LINES_STRIPS:
case PRIM_TRIANGLE:
case PRIM_TRIANGLE_STRIPS:
case PRIM_TRIANGLE_FANS:
float[] normalizedNormal = new float[3];
if (cachedVertexInfo == null) {
for (int i = 0; i < numberOfVertex; i++) {
int addr = vinfo.getAddress(mem, i);
VertexState v = vinfo.readVertex(mem, addr);
// Do skinning first as it modifies v.p and v.n
if (mustComputeWeights && vinfo.position != 0) {
doSkinning(vinfo, v);
}
if (useTextureFromNormal) {
floatBuffer.put(v.n, 0, 3);
} else if (useTextureFromNormalizedNormal) {
float normalLength = (float) Math.sqrt(v.n[0] * v.n[0] + v.n[1] * v.n[1] + v.n[2] * v.n[2]);
normalizedNormal[0] = v.n[0] / normalLength;
normalizedNormal[1] = v.n[1] / normalLength;
normalizedNormal[2] = v.n[2] / normalLength;
floatBuffer.put(normalizedNormal, 0, 3);
} else if (useTextureFromPosition) {
floatBuffer.put(v.p, 0, 3);
} else if (useTexture) {
floatBuffer.put(v.t);
}
if (useVertexColor) {
floatBuffer.put(v.c);
}
if (vinfo.normal != 0) {
floatBuffer.put(v.n);
}
if (vinfo.position != 0) {
floatBuffer.put(v.p);
}
if (numberOfWeightsForBuffer > 0) {
floatBuffer.put(v.boneWeights, 0, numberOfWeightsForBuffer);
}
if (isLogTraceEnabled) {
if (vinfo.texture != 0 && vinfo.position != 0) {
log.trace(" vertex#" + i + " (" + ((int) v.t[0]) + "," + ((int) v.t[1]) + ") at (" + ((int) v.p[0]) + "," + ((int) v.p[1]) + "," + ((int) v.p[2]) + ")");
}
}
}
if (useVertexCache) {
cachedVertexInfo = new VertexInfo(vinfo);
VertexCache.getInstance().addVertex(re, cachedVertexInfo, numberOfVertex, context.bone_uploaded_matrix, numberOfWeightsForBuffer);
int size = floatBuffer.position();
floatBuffer.rewind();
cachedVertexInfo.loadVertex(re, floatBuffer, size);
} else {
bufferManager.setBufferData(bufferId, floatBuffer.position() * SIZEOF_FLOAT, byteBuffer, IRenderingEngine.RE_STREAM_DRAW);
}
} else {
if (isLogDebugEnabled) {
log.debug("Reusing cached Vertex Data");
}
cachedVertexInfo.bindVertex(re);
}
setDataPointers(nVertex, useVertexColor, nColor, useTexture, nTexCoord, vinfo.normal != 0, numberOfWeightsForBuffer, cachedVertexInfo == null);
re.drawArrays(type, 0, numberOfVertex);
maxSpriteHeight = Integer.MAX_VALUE;
maxSpriteWidth = Integer.MAX_VALUE;
break;
case PRIM_SPRITES:
re.disableFlag(IRenderingEngine.GU_CULL_FACE);
float[] mvpMatrix = null;
if (!vinfo.transform2D) {
mvpMatrix = new float[4 * 4];
// pre-Compute the MVP (Model-View-Projection) matrix
matrixMult(mvpMatrix, context.model_uploaded_matrix, context.view_uploaded_matrix);
matrixMult(mvpMatrix, mvpMatrix, context.proj_uploaded_matrix);
}
if (cachedVertexInfo == null) {
for (int i = 0; i < numberOfVertex; i += 2) {
int addr1 = vinfo.getAddress(mem, i);
int addr2 = vinfo.getAddress(mem, i + 1);
VertexState v1 = vinfo.readVertex(mem, addr1);
VertexState v2 = vinfo.readVertex(mem, addr2);
v1.p[2] = v2.p[2];
if (v2.p[1] > maxSpriteHeight) {
maxSpriteHeight = (int) v2.p[1];
}
if (v2.p[1] > maxSpriteWidth) {
maxSpriteWidth = (int) v2.p[1];
}
//
// Texture flip tested using the GElist application:
// - it depends on the X and Y coordinates:
// GU_TRANSFORM_3D:
// X1 < X2 && Y1 < Y2 : flipped
// X1 > X2 && Y1 > Y2 : flipped
// X1 < X2 && Y1 > Y2 : not flipped
// X1 > X2 && Y1 < Y2 : not flipped
// GU_TRANSFORM_2D: opposite results because
// the Y-Axis is upside-down in 2D
// X1 < X2 && Y1 < Y2 : not flipped
// X1 > X2 && Y1 > Y2 : not flipped
// X1 < X2 && Y1 > Y2 : flipped
// X1 > X2 && Y1 < Y2 : flipped
// - the tests for GU_TRANSFORM_3D are based on the coordinates
// after the MVP (Model-View-Projection) transformation
// - texture coordinates are irrelevant
//
float x1, y1, x2, y2;
if (mvpMatrix == null) {
x1 = v1.p[0];
y1 = -v1.p[1]; // Y-Axis is upside-down in 2D
x2 = v2.p[0];
y2 = -v2.p[1]; // Y-Axis is upside-down in 2D
} else {
// Apply the MVP transformation to both position coordinates
float[] mvpPosition = new float[2];
vectorMult(mvpPosition, mvpMatrix, v1.p);
x1 = mvpPosition[0];
y1 = mvpPosition[1];
vectorMult(mvpPosition, mvpMatrix, v2.p);
x2 = mvpPosition[0];
y2 = mvpPosition[1];
}
boolean flippedTexture = (y1 < y2 && x1 < x2) ||
(y1 > y2 && x1 > x2);
if (isLogDebugEnabled) {
log(String.format(" sprite (%.0f,%.0f)-(%.0f,%.0f) at (%.0f,%.0f,%.0f)-(%.0f,%.0f,%.0f)%s", v1.t[0], v1.t[1], v2.t[0], v2.t[1], v1.p[0], v1.p[1], v1.p[2], v2.p[0], v2.p[1], v2.p[2], flippedTexture ? " flipped" : ""));
}
// V1
if (vinfo.texture != 0) {
floatBuffer.put(v1.t);
}
if (useVertexColor) {
floatBuffer.put(v2.c);
}
if (vinfo.normal != 0) {
floatBuffer.put(v2.n);
}
if (vinfo.position != 0) {
floatBuffer.put(v1.p);
}
if (vinfo.texture != 0) {
if (flippedTexture) {
floatBuffer.put(v2.t[0]).put(v1.t[1]);
} else {
floatBuffer.put(v1.t[0]).put(v2.t[1]);
}
}
if (useVertexColor) {
floatBuffer.put(v2.c);
}
if (vinfo.normal != 0) {
floatBuffer.put(v2.n);
}
if (vinfo.position != 0) {
floatBuffer.put(v1.p[0]).put(v2.p[1]).put(v2.p[2]);
}
// V2
if (vinfo.texture != 0) {
floatBuffer.put(v2.t);
}
if (useVertexColor) {
floatBuffer.put(v2.c);
}
if (vinfo.normal != 0) {
floatBuffer.put(v2.n);
}
if (vinfo.position != 0) {
floatBuffer.put(v2.p);
}
if (vinfo.texture != 0) {
if (flippedTexture) {
floatBuffer.put(v1.t[0]).put(v2.t[1]);
} else {
floatBuffer.put(v2.t[0]).put(v1.t[1]);
}
}
if (useVertexColor) {
floatBuffer.put(v2.c);
}
if (vinfo.normal != 0) {
floatBuffer.put(v2.n);
}
if (vinfo.position != 0) {
floatBuffer.put(v2.p[0]).put(v1.p[1]).put(v2.p[2]);
}
}
if (useVertexCache) {
cachedVertexInfo = new VertexInfo(vinfo);
VertexCache.getInstance().addVertex(re, cachedVertexInfo, numberOfVertex, context.bone_uploaded_matrix, numberOfWeightsForBuffer);
int size = floatBuffer.position();
floatBuffer.rewind();
cachedVertexInfo.loadVertex(re, floatBuffer, size);
} else {
bufferManager.setBufferData(bufferId, floatBuffer.position() * SIZEOF_FLOAT, byteBuffer, IRenderingEngine.RE_STREAM_DRAW);
}
} else {
if (isLogDebugEnabled) {
log.debug("Reusing cached Vertex Data");
}
cachedVertexInfo.bindVertex(re);
}
setDataPointers(nVertex, useVertexColor, nColor, useTexture, nTexCoord, vinfo.normal != 0, 0, cachedVertexInfo == null);
re.drawArrays(IRenderingEngine.RE_QUADS, 0, numberOfVertex * 2);
context.cullFaceFlag.updateEnabled();
break;
}
}
vertexStatistics.end();
// Don't capture the ram if the vertex list is embedded in the display list. TODO handle stall_addr == 0 better
// TODO may need to move inside the loop if indices are used, or find the largest index so we can calculate the size of the vertex list
if (State.captureGeNextFrame) {
if (!isVertexBufferEmbedded()) {
log.info("Capture PRIM");
CaptureManager.captureRAM(vinfo.ptr_vertex, vinfo.vertexSize * numberOfVertex);
}
display.captureGeImage();
textureChanged = true;
}
endRendering(useVertexColor, useTexture, numberOfVertex);
}
private void executeCommandTRXKICK(int normalArgument) {
context.textureTx_pixelSize = normalArgument & 0x1;
context.textureTx_sourceAddress &= Memory.addressMask;
context.textureTx_destinationAddress &= Memory.addressMask;
if (isLogDebugEnabled) {
log(String.format("%s from 0x%08X(%d,%d) to 0x%08X(%d,%d), width=%d, height=%d, pixelSize=%d",
helper.getCommandString(TRXKICK),
context.textureTx_sourceAddress,
context.textureTx_sx,
context.textureTx_sy,
context.textureTx_destinationAddress,
context.textureTx_dx,
context.textureTx_dy,
context.textureTx_width,
context.textureTx_height,
context.textureTx_pixelSize));
}
usingTRXKICK = true;
updateGeBuf();
int pixelFormatGe = context.psm;
int bpp = (context.textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) ? 2 : 4;
int bppGe = sceDisplay.getPixelFormatBytes(pixelFormatGe);
memoryForGEUpdated();
if (!display.isGeAddress(context.textureTx_destinationAddress) || bpp != bppGe) {
if (isLogDebugEnabled) {
if (bpp != bppGe) {
log(helper.getCommandString(TRXKICK) + " BPP not compatible with GE");
} else {
log(helper.getCommandString(TRXKICK) + " not in Ge Address space");
}
}
int width = context.textureTx_width;
int height = context.textureTx_height;
int srcAddress = context.textureTx_sourceAddress + (context.textureTx_sy * context.textureTx_sourceLineWidth + context.textureTx_sx) * bpp;
int dstAddress = context.textureTx_destinationAddress + (context.textureTx_dy * context.textureTx_destinationLineWidth + context.textureTx_dx) * bpp;
Memory memory = Memory.getInstance();
if (context.textureTx_sourceLineWidth == width && context.textureTx_destinationLineWidth == width) {
// All the lines are adjacent in memory,
// copy them all in a single memcpy operation.
int copyLength = height * width * bpp;
if (isLogDebugEnabled) {
log(String.format("%s memcpy(0x%08X-0x%08X, 0x%08X, 0x%X)", helper.getCommandString(TRXKICK), dstAddress, dstAddress + copyLength, srcAddress, copyLength));
}
memory.memcpy(dstAddress, srcAddress, copyLength);
} else {
// The lines are not adjacent in memory: copy line by line.
int copyLength = width * bpp;
int srcLineLength = context.textureTx_sourceLineWidth * bpp;
int dstLineLength = context.textureTx_destinationLineWidth * bpp;
for (int y = 0; y < height; y++) {
if (isLogDebugEnabled) {
log(String.format("%s memcpy(0x%08X-0x%08X, 0x%08X, 0x%X)", helper.getCommandString(TRXKICK), dstAddress, dstAddress + copyLength, srcAddress, copyLength));
}
memory.memcpy(dstAddress, srcAddress, copyLength);
srcAddress += srcLineLength;
dstAddress += dstLineLength;
}
}
if (State.captureGeNextFrame) {
log.warn("TRXKICK outside of Ge Address space not supported in capture yet");
}
} else {
int width = context.textureTx_width;
int height = context.textureTx_height;
int dx = context.textureTx_dx;
int dy = context.textureTx_dy;
int lineWidth = context.textureTx_sourceLineWidth;
int geAddr = display.getTopAddrGe();
dy += (context.textureTx_destinationAddress - geAddr) / (display.getBufferWidthGe() * bpp);
dx += ((context.textureTx_destinationAddress - geAddr) % (display.getBufferWidthGe() * bpp)) / bpp;
if (isLogDebugEnabled) {
log(helper.getCommandString(TRXKICK) + " in Ge Address space: dx=" + dx + ", dy=" + dy + ", width=" + width + ", height=" + height + ", lineWidth=" + lineWidth + ", bpp=" + bpp);
}
int texture = re.genTexture();
re.bindTexture(texture);
re.startDirectRendering(true, false, true, true, false, 480, 272);
re.setPixelStore(lineWidth, bpp);
int textureSize = lineWidth * height * bpp;
Buffer buffer = Memory.getInstance().getBuffer(context.textureTx_sourceAddress, textureSize);
if (State.captureGeNextFrame) {
log.info("Capture TRXKICK");
CaptureManager.captureRAM(context.textureTx_sourceAddress, lineWidth * height * bpp);
}
//
// glTexImage2D only supports
// width = (1 << n) for some integer n
// height = (1 << m) for some integer m
//
// This the reason why we are also using glTexSubImage2D.
//
int bufferHeight = Utilities.makePow2(height);
re.setTexImage(0,pixelFormatGe, lineWidth, bufferHeight, pixelFormatGe, pixelFormatGe, 0, null);
re.setTexSubImage(0, context.textureTx_sx, context.textureTx_sy, width, height, pixelFormatGe, pixelFormatGe, textureSize, buffer);
re.beginDraw(PRIM_SPRITES);
re.drawColor(1.0f, 1.0f, 1.0f, 1.0f);
float texCoordX = width / (float) lineWidth;
float texCoordY = height / (float) bufferHeight;
re.drawTexCoord(0.0f, 0.0f);
re.drawVertex(dx, dy);
re.drawTexCoord(texCoordX, 0.0f);
re.drawVertex(dx + width, dy);
re.drawTexCoord(texCoordX, texCoordY);
re.drawVertex(dx + width, dy + height);
re.drawTexCoord(0.0f, texCoordY);
re.drawVertex(dx, dy + height);
re.endDraw();
re.endDirectRendering();
re.deleteTexture(texture);
}
}
private void executeCommandBBOX(int normalArgument) {
Memory mem = Memory.getInstance();
int numberOfVertexBoundingBox = normalArgument & 0xFF;
if (!mem.isAddressGood(vinfo.ptr_vertex)) {
// Abort here to avoid a lot of useless memory read errors...
error(String.format("%s Invalid vertex address 0x%08X", helper.getCommandString(BBOX), vinfo.ptr_vertex));
return;
} else if (vinfo.position == 0) {
log.warn(helper.getCommandString(BBOX) + " no positions for vertex!");
return;
} else if (!re.hasBoundingBox()) {
if (!bboxWarningDisplayed) {
log.warn("Not supported by your OpenGL version (but can be ignored): " + helper.getCommandString(BBOX) + " numberOfVertex=" + numberOfVertexBoundingBox);
bboxWarningDisplayed = true;
}
return;
} else if ((numberOfVertexBoundingBox % 8) != 0) {
// How to interpret non-multiple of 8?
log.warn(helper.getCommandString(BBOX) + " unsupported numberOfVertex=" + numberOfVertexBoundingBox);
} else if (isLogDebugEnabled) {
log.debug(helper.getCommandString(BBOX) + " numberOfVertex=" + numberOfVertexBoundingBox);
}
boolean useVertexColor = initRendering();
re.setVertexInfo(vinfo, false, useVertexColor);
re.beginBoundingBox(numberOfVertexBoundingBox);
for (int i = 0; i < numberOfVertexBoundingBox; i++) {
int addr = vinfo.getAddress(mem, i);
VertexState v = vinfo.readVertex(mem, addr);
if (isLogDebugEnabled) {
log.debug(String.format("%s (%f,%f,%f)", helper.getCommandString(BBOX), v.p[0], v.p[1], v.p[2]));
}
int vertexIndex = i % 8;
bboxVertices[vertexIndex][0] = v.p[0];
bboxVertices[vertexIndex][1] = v.p[1];
bboxVertices[vertexIndex][2] = v.p[2];
if (vertexIndex == 7) {
re.drawBoundingBox(bboxVertices);
}
}
re.endBoundingBox();
endRendering(useVertexColor, false, numberOfVertexBoundingBox);
}
private void executeCommandBJUMP(int normalArgument) {
boolean takeConditionalJump = false;
if (re.hasBoundingBox()) {
takeConditionalJump = !re.isBoundingBoxVisible();
}
if (takeConditionalJump) {
int oldPc = currentList.pc;
currentList.jump(normalArgument);
int newPc = currentList.pc;
if (isLogDebugEnabled) {
log(String.format("%s old PC: 0x%08X, new PC: 0x%08X", helper.getCommandString(BJUMP), oldPc, newPc));
}
} else {
if (isLogDebugEnabled) {
log(String.format("%s not taking Conditional Jump", helper.getCommandString(BJUMP)));
}
}
}
private void executeCommandBONE(int normalArgument) {
// Multiple BONE matrix can be loaded in sequence
// without having to issue a BOFS for each matrix.
int matrixIndex = boneMatrixIndex / 12;
int elementIndex = boneMatrixIndex % 12;
if (matrixIndex >= 8) {
if(isLogDebugEnabled)
log("Ignoring BONE matrix element: boneMatrixIndex=" + boneMatrixIndex);
} else {
float floatArgument = floatArgument(normalArgument);
context.bone_uploaded_matrix[matrixIndex][elementIndex] = floatArgument;
context.boneMatrixLinear[(boneMatrixIndex / 3) * 4 + (boneMatrixIndex % 3)] = floatArgument;
if (matrixIndex >= boneMatrixLinearUpdatedMatrix) {
boneMatrixLinearUpdatedMatrix = matrixIndex + 1;
}
boneMatrixIndex++;
if (isLogDebugEnabled && (boneMatrixIndex % 12) == 0) {
for (int x = 0; x < 3; x++) {
log.debug(String.format("bone matrix %d %.2f %.2f %.2f %.2f",
matrixIndex,
context.bone_uploaded_matrix[matrixIndex][x + 0],
context.bone_uploaded_matrix[matrixIndex][x + 3],
context.bone_uploaded_matrix[matrixIndex][x + 6],
context.bone_uploaded_matrix[matrixIndex][x + 9]));
}
}
}
}
private void enableClientState(boolean useVertexColor, boolean useTexture) {
if (vinfo.texture != 0 || useTexture) {
re.enableClientState(IRenderingEngine.RE_TEXTURE);
} else {
re.disableClientState(IRenderingEngine.RE_TEXTURE);
}
if (useVertexColor) {
re.enableClientState(IRenderingEngine.RE_COLOR);
} else {
re.disableClientState(IRenderingEngine.RE_COLOR);
}
if (vinfo.normal != 0) {
re.enableClientState(IRenderingEngine.RE_NORMAL);
} else {
re.disableClientState(IRenderingEngine.RE_NORMAL);
}
re.enableClientState(IRenderingEngine.RE_VERTEX);
}
private void setTexCoordPointer(boolean useTexture, int nTexCoord, int type, int stride, int offset, boolean isNative, boolean useBufferManager) {
if (useTexture) {
if (!useBufferManager) {
re.setTexCoordPointer(nTexCoord, type, stride, offset);
} else if (isNative) {
bufferManager.setTexCoordPointer(nativeBufferId, nTexCoord, type, vinfo.vertexSize, offset);
} else {
bufferManager.setTexCoordPointer(bufferId, nTexCoord, type, stride, offset);
}
}
}
private void setColorPointer(boolean useVertexColor, int nColor, int type, int stride, int offset, boolean isNative, boolean useBufferManager) {
if (useVertexColor) {
if (!useBufferManager) {
re.setColorPointer(nColor, type, stride, offset);
} else if (isNative) {
bufferManager.setColorPointer(nativeBufferId, nColor, type, vinfo.vertexSize, offset);
} else {
bufferManager.setColorPointer(bufferId, nColor, type, stride, offset);
}
}
}
private void setVertexPointer(int nVertex, int type, int stride, int offset, boolean isNative, boolean useBufferManager) {
if (!useBufferManager) {
re.setVertexPointer(nVertex, type, stride, offset);
} else if (isNative) {
bufferManager.setVertexPointer(nativeBufferId, nVertex, type, vinfo.vertexSize, offset);
} else {
bufferManager.setVertexPointer(bufferId, nVertex, type, stride, offset);
}
}
private void setNormalPointer(int type, int stride, int offset, boolean isNative, boolean useBufferManager) {
if (vinfo.normal != 0) {
if (!useBufferManager) {
re.setNormalPointer(type, stride, offset);
} else if (isNative) {
bufferManager.setNormalPointer(nativeBufferId, type, vinfo.vertexSize, offset);
} else {
bufferManager.setNormalPointer(bufferId, type, stride, offset);
}
}
}
private void setWeightPointer(int numberOfWeightsForBuffer, int type, int stride, int offset, boolean isNative, boolean useBufferManager) {
if (numberOfWeightsForBuffer > 0) {
if (!useBufferManager) {
re.setWeightPointer(numberOfWeightsForBuffer, type, stride, offset);
} else if (isNative) {
re.setWeightPointer(numberOfWeightsForBuffer, type, vinfo.vertexSize, offset);
} else {
re.setWeightPointer(numberOfWeightsForBuffer, type, stride, offset);
}
}
}
private void setDataPointers(int nVertex, boolean useVertexColor, int nColor, boolean useTexture, int nTexCoord, boolean useNormal, int numberOfWeightsForBuffer, boolean useBufferManager) {
int stride = 0, cpos = 0, npos = 0, vpos = 0, wpos = 0;
if (vinfo.texture != 0 || useTexture) {
stride += SIZEOF_FLOAT * nTexCoord;
cpos = npos = vpos = stride;
}
if (useVertexColor) {
stride += SIZEOF_FLOAT * 4;
npos = vpos = stride;
}
if (useNormal) {
stride += SIZEOF_FLOAT * 3;
vpos = stride;
}
stride += SIZEOF_FLOAT * 3;
if (numberOfWeightsForBuffer > 0) {
wpos = stride;
stride += SIZEOF_FLOAT * numberOfWeightsForBuffer;
}
enableClientState(useVertexColor, useTexture);
setTexCoordPointer(useTexture, nTexCoord, IRenderingEngine.RE_FLOAT, stride, 0, false, useBufferManager);
setColorPointer(useVertexColor, nColor, IRenderingEngine.RE_FLOAT, stride, cpos, false, useBufferManager);
setNormalPointer(IRenderingEngine.RE_FLOAT, stride, npos, false, useBufferManager);
setWeightPointer(numberOfWeightsForBuffer, IRenderingEngine.RE_FLOAT, stride, wpos, false, useBufferManager);
setVertexPointer(nVertex, IRenderingEngine.RE_FLOAT, stride, vpos, false, useBufferManager);
}
public void doPositionSkinning(VertexInfo vinfo, float[] boneWeights, float[] position) {
float x = 0, y = 0, z = 0;
for (int i = 0; i < vinfo.skinningWeightCount; i++) {
if (boneWeights[i] != 0) {
x += (position[0] * context.bone_uploaded_matrix[i][0]
+ position[1] * context.bone_uploaded_matrix[i][3]
+ position[2] * context.bone_uploaded_matrix[i][6]
+ context.bone_uploaded_matrix[i][9]) * boneWeights[i];
y += (position[0] * context.bone_uploaded_matrix[i][1]
+ position[1] * context.bone_uploaded_matrix[i][4]
+ position[2] * context.bone_uploaded_matrix[i][7]
+ context.bone_uploaded_matrix[i][10]) * boneWeights[i];
z += (position[0] * context.bone_uploaded_matrix[i][2]
+ position[1] * context.bone_uploaded_matrix[i][5]
+ position[2] * context.bone_uploaded_matrix[i][8]
+ context.bone_uploaded_matrix[i][11]) * boneWeights[i];
}
}
position[0] = x;
position[1] = y;
position[2] = z;
}
public void doNormalSkinning(VertexInfo vinfo, float[] boneWeights, float[] normal) {
float nx = 0, ny = 0, nz = 0;
for (int i = 0; i < vinfo.skinningWeightCount; i++) {
if (boneWeights[i] != 0) {
// Normals shouldn't be translated :)
nx += (normal[0] * context.bone_uploaded_matrix[i][0]
+ normal[1] * context.bone_uploaded_matrix[i][3]
+ normal[2] * context.bone_uploaded_matrix[i][6]) * boneWeights[i];
ny += (normal[0] * context.bone_uploaded_matrix[i][1]
+ normal[1] * context.bone_uploaded_matrix[i][4]
+ normal[2] * context.bone_uploaded_matrix[i][7]) * boneWeights[i];
nz += (normal[0] * context.bone_uploaded_matrix[i][2]
+ normal[1] * context.bone_uploaded_matrix[i][5]
+ normal[2] * context.bone_uploaded_matrix[i][8]) * boneWeights[i];
}
}
/*
// TODO: I doubt psp hardware normalizes normals after skinning,
// but if it does, this should be uncommented :)
float length = nx*nx + ny*ny + nz*nz;
if (length > 0.f) {
length = 1.f / (float)Math.sqrt(length);
nx *= length;
ny *= length;
nz *= length;
}
*/
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
}
private void doSkinning(VertexInfo vinfo, VertexState v) {
float x = 0, y = 0, z = 0;
float nx = 0, ny = 0, nz = 0;
for (int i = 0; i < vinfo.skinningWeightCount; ++i) {
if (v.boneWeights[i] != 0.f) {
x += (v.p[0] * context.bone_uploaded_matrix[i][0]
+ v.p[1] * context.bone_uploaded_matrix[i][3]
+ v.p[2] * context.bone_uploaded_matrix[i][6]
+ context.bone_uploaded_matrix[i][9]) * v.boneWeights[i];
y += (v.p[0] * context.bone_uploaded_matrix[i][1]
+ v.p[1] * context.bone_uploaded_matrix[i][4]
+ v.p[2] * context.bone_uploaded_matrix[i][7]
+ context.bone_uploaded_matrix[i][10]) * v.boneWeights[i];
z += (v.p[0] * context.bone_uploaded_matrix[i][2]
+ v.p[1] * context.bone_uploaded_matrix[i][5]
+ v.p[2] * context.bone_uploaded_matrix[i][8]
+ context.bone_uploaded_matrix[i][11]) * v.boneWeights[i];
// Normals shouldn't be translated :)
nx += (v.n[0] * context.bone_uploaded_matrix[i][0]
+ v.n[1] * context.bone_uploaded_matrix[i][3]
+ v.n[2] * context.bone_uploaded_matrix[i][6]) * v.boneWeights[i];
ny += (v.n[0] * context.bone_uploaded_matrix[i][1]
+ v.n[1] * context.bone_uploaded_matrix[i][4]
+ v.n[2] * context.bone_uploaded_matrix[i][7]) * v.boneWeights[i];
nz += (v.n[0] * context.bone_uploaded_matrix[i][2]
+ v.n[1] * context.bone_uploaded_matrix[i][5]
+ v.n[2] * context.bone_uploaded_matrix[i][8]) * v.boneWeights[i];
}
}
v.p[0] = x;
v.p[1] = y;
v.p[2] = z;
/*
// TODO: I doubt psp hardware normalizes normals after skinning,
// but if it does, this should be uncommented :)
float length = nx*nx + ny*ny + nz*nz;
if (length > 0.f) {
length = 1.f / (float)Math.sqrt(length);
nx *= length;
ny *= length;
nz *= length;
}
*/
v.n[0] = nx;
v.n[1] = ny;
v.n[2] = nz;
}
private void log(String commandString, float floatArgument) {
if (isLogDebugEnabled) {
log(commandString + SPACE + floatArgument);
}
}
private void log(String commandString, int value) {
if (isLogDebugEnabled) {
log(commandString + SPACE + value);
}
}
private void log(String commandString, float[] matrix) {
if (isLogDebugEnabled) {
for (int y = 0; y < 4; y++) {
log(commandString + SPACE + String.format("%.1f %.1f %.1f %.1f", matrix[0 + y * 4], matrix[1 + y * 4], matrix[2 + y * 4], matrix[3 + y * 4]));
}
}
}
private boolean canCacheTexture(int tex_addr) {
if (!useTextureCache) {
return false;
}
// Some games are storing compressed textures in VRAM (e.g. Skate Park City).
// Force only a reload of textures that can be generated by the GE buffer,
// i.e. when texture_storage is one of
// BGR5650=0, ABGR5551=1, ABGR4444=2 or ABGR8888=3.
if (isVRAM(tex_addr) && context.texture_storage <= TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
return false;
}
if (!videoTextures.isEmpty() && videoTextures.contains(tex_addr)) {
return false;
}
return true;
}
private void loadTexture() {
// No need to reload or check the texture cache if no texture parameter
// has been changed since last call loadTexture()
if (!textureChanged) {
return;
}
// HACK: avoid texture uploads of null pointers
// This can come from Sony's GE init code (pspsdk GE init is ok)
if (context.texture_base_pointer[0] == 0) {
return;
}
// Texture not used when disabled (automatically disabled in clear mode).
if (!context.textureFlag.isEnabled()) {
return;
}
Texture texture;
int tex_addr = context.texture_base_pointer[0] & Memory.addressMask;
if (!canCacheTexture(tex_addr)) {
texture = null;
// Generate a texture id if we don't have one
if (textureId == -1) {
textureId = re.genTexture();
}
re.bindTexture(textureId);
} else {
TextureCache textureCache = TextureCache.getInstance();
boolean textureRequiresClut = context.texture_storage >= TPSM_PIXEL_STORAGE_MODE_4BIT_INDEXED && context.texture_storage <= TPSM_PIXEL_STORAGE_MODE_32BIT_INDEXED;
textureCacheLookupStatistics.start();
// Check if the texture is in the cache
if (textureRequiresClut) {
texture = textureCache.getTexture(context.texture_base_pointer[0], context.texture_buffer_width[0], context.texture_width[0], context.texture_height[0], context.texture_storage, context.tex_clut_addr, context.tex_clut_mode, context.tex_clut_start, context.tex_clut_shift, context.tex_clut_mask, context.tex_clut_num_blocks, context.texture_num_mip_maps, context.mipmapShareClut);
} else {
texture = textureCache.getTexture(context.texture_base_pointer[0], context.texture_buffer_width[0], context.texture_width[0], context.texture_height[0], context.texture_storage, 0, 0, 0, 0, 0, 0, context.texture_num_mip_maps, false);
}
textureCacheLookupStatistics.end();
// Create the texture if not yet in the cache
if (texture == null) {
if (textureRequiresClut) {
texture = new Texture(textureCache, context.texture_base_pointer[0], context.texture_buffer_width[0], context.texture_width[0], context.texture_height[0], context.texture_storage, context.tex_clut_addr, context.tex_clut_mode, context.tex_clut_start, context.tex_clut_shift, context.tex_clut_mask, context.tex_clut_num_blocks, context.texture_num_mip_maps, context.mipmapShareClut);
} else {
texture = new Texture(textureCache, context.texture_base_pointer[0], context.texture_buffer_width[0], context.texture_width[0], context.texture_height[0], context.texture_storage, 0, 0, 0, 0, 0, 0, context.texture_num_mip_maps, false);
}
textureCache.addTexture(re, texture);
}
texture.bindTexture(re);
}
// Load the texture if not yet loaded
if (texture == null || !texture.isLoaded() || State.captureGeNextFrame || State.replayGeNextFrame) {
if (isLogDebugEnabled) {
log(helper.getCommandString(TFLUSH)
+ " " + String.format("0x%08X", context.texture_base_pointer[0])
+ ", buffer_width=" + context.texture_buffer_width[0]
+ " (" + context.texture_width[0] + "," + context.texture_height[0] + ")");
log(helper.getCommandString(TFLUSH)
+ " texture_storage=0x" + Integer.toHexString(context.texture_storage)
+ "(" + getPsmName(context.texture_storage)
+ "), tex_clut_mode=0x" + Integer.toHexString(context.tex_clut_mode)
+ ", tex_clut_addr=" + String.format("0x%08X", context.tex_clut_addr)
+ ", texture_swizzle=" + context.texture_swizzle);
}
Buffer final_buffer = null;
int texclut = context.tex_clut_addr;
int texaddr;
int textureByteAlignment = 4; // 32 bits
boolean compressedTexture = false;
int numberMipmaps = context.texture_num_mip_maps;
Memory mem = Memory.getInstance();
for (int level = 0; level <= numberMipmaps; level++) {
// Extract texture information with the minor conversion possible
// TODO: Get rid of information copying, and implement all the available formats
texaddr = context.texture_base_pointer[level];
texaddr &= Memory.addressMask;
if (!mem.isAddressGood(texaddr)) {
error(String.format("Invalid texture address 0x%08X for texture level %d", texaddr, level));
break;
}
compressedTexture = false;
int compressedTextureSize = 0;
int buffer_storage = context.texture_storage;
switch (context.texture_storage) {
case TPSM_PIXEL_STORAGE_MODE_4BIT_INDEXED: {
if (texclut == 0) {
return;
}
buffer_storage = context.tex_clut_mode;
switch (context.tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
textureByteAlignment = 2; // 16 bits
short[] clut = readClut16(level);
int clutSharingOffset = context.mipmapShareClut ? 0 : level * 16;
if (!context.texture_swizzle) {
int length = context.texture_buffer_width[level] * context.texture_height[level];
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, length / 2, 1);
for (int i = 0; i < length; i += 2) {
int index = memoryReader.readNext();
tmp_texture_buffer16[i] = clut[getClutIndex(index & 0xF) + clutSharingOffset];
tmp_texture_buffer16[i + 1] = clut[getClutIndex((index >> 4) & 0xF) + clutSharingOffset];
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
if (State.captureGeNextFrame) {
log.info("Capture loadTexture clut 4/16 unswizzled");
CaptureManager.captureRAM(texaddr, length / 2);
}
} else {
unswizzleTextureFromMemory(texaddr, 0, level);
int pixels = context.texture_buffer_width[level] * context.texture_height[level];
for (int i = 0, j = 0; i < pixels; i += 8, j++) {
int n = tmp_texture_buffer32[j];
int index = n & 0xF;
tmp_texture_buffer16[i + 0] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 4) & 0xF;
tmp_texture_buffer16[i + 1] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 8) & 0xF;
tmp_texture_buffer16[i + 2] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 12) & 0xF;
tmp_texture_buffer16[i + 3] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 16) & 0xF;
tmp_texture_buffer16[i + 4] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 20) & 0xF;
tmp_texture_buffer16[i + 5] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 24) & 0xF;
tmp_texture_buffer16[i + 6] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 28) & 0xF;
tmp_texture_buffer16[i + 7] = clut[getClutIndex(index) + clutSharingOffset];
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
int[] clut = readClut32(level);
int clutSharingOffset = context.mipmapShareClut ? 0 : level * 16;
if (!context.texture_swizzle) {
int length = context.texture_buffer_width[level] * context.texture_height[level];
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, length / 2, 1);
for (int i = 0; i < length; i += 2) {
int index = memoryReader.readNext();
tmp_texture_buffer32[i + 1] = clut[getClutIndex((index >> 4) & 0xF) + clutSharingOffset];
tmp_texture_buffer32[i] = clut[getClutIndex(index & 0xF) + clutSharingOffset];
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
if (State.captureGeNextFrame) {
log.info("Capture loadTexture clut 4/32 unswizzled");
CaptureManager.captureRAM(texaddr, length / 2);
}
} else {
unswizzleTextureFromMemory(texaddr, 0, level);
int pixels = context.texture_buffer_width[level] * context.texture_height[level];
for (int i = pixels - 8, j = (pixels / 8) - 1; i >= 0; i -= 8, j--) {
int n = tmp_texture_buffer32[j];
int index = n & 0xF;
tmp_texture_buffer32[i + 0] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 4) & 0xF;
tmp_texture_buffer32[i + 1] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 8) & 0xF;
tmp_texture_buffer32[i + 2] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 12) & 0xF;
tmp_texture_buffer32[i + 3] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 16) & 0xF;
tmp_texture_buffer32[i + 4] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 20) & 0xF;
tmp_texture_buffer32[i + 5] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 24) & 0xF;
tmp_texture_buffer32[i + 6] = clut[getClutIndex(index) + clutSharingOffset];
index = (n >> 28) & 0xF;
tmp_texture_buffer32[i + 7] = clut[getClutIndex(index) + clutSharingOffset];
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
}
break;
}
default: {
error("Unhandled clut4 texture mode " + context.tex_clut_mode);
return;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_8BIT_INDEXED: {
final_buffer = readIndexedTexture(level, texaddr, texclut, 1);
buffer_storage = context.tex_clut_mode;
textureByteAlignment = textureByteAlignmentMapping[context.tex_clut_mode];
break;
}
case TPSM_PIXEL_STORAGE_MODE_16BIT_INDEXED: {
final_buffer = readIndexedTexture(level, texaddr, texclut, 2);
buffer_storage = context.tex_clut_mode;
textureByteAlignment = textureByteAlignmentMapping[context.tex_clut_mode];
break;
}
case TPSM_PIXEL_STORAGE_MODE_32BIT_INDEXED: {
final_buffer = readIndexedTexture(level, texaddr, texclut, 4);
buffer_storage = context.tex_clut_mode;
textureByteAlignment = textureByteAlignmentMapping[context.tex_clut_mode];
break;
}
case TPSM_PIXEL_STORAGE_MODE_16BIT_BGR5650:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR5551:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR4444: {
textureByteAlignment = 2; // 16 bits
if (!context.texture_swizzle) {
int length = Math.max(context.texture_buffer_width[level], context.texture_width[level]) * context.texture_height[level];
final_buffer = Memory.getInstance().getBuffer(texaddr, length * 2);
if (final_buffer == null) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, length * 2, 2);
for (int i = 0; i < length; i++) {
int pixel = memoryReader.readNext();
tmp_texture_buffer16[i] = (short) pixel;
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
}
if (State.captureGeNextFrame) {
log.info("Capture loadTexture 16 unswizzled");
CaptureManager.captureRAM(texaddr, length * 2);
}
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 2, level);
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888: {
final_buffer = getTexture32BitBuffer(texaddr, level);
break;
}
case TPSM_PIXEL_STORAGE_MODE_DXT1: {
if (isLogDebugEnabled) {
log.debug("Loading texture TPSM_PIXEL_STORAGE_MODE_DXT1 " + Integer.toHexString(texaddr));
}
compressedTexture = true;
compressedTextureSize = getCompressedTextureSize(level, 8);
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, compressedTextureSize, 4);
// PSP DXT1 hardware format reverses the colors and the per-pixel
// bits, and encodes the color in RGB 565 format
int i = 0;
for (int y = 0; y < context.texture_height[level]; y += 4) {
for (int x = 0; x < context.texture_buffer_width[level]; x += 4, i += 2) {
tmp_texture_buffer32[i + 1] = memoryReader.readNext();
tmp_texture_buffer32[i + 0] = memoryReader.readNext();
}
for (int x = context.texture_buffer_width[level]; x < context.texture_width[level]; x += 4, i += 2) {
tmp_texture_buffer32[i + 0] = 0;
tmp_texture_buffer32[i + 1] = 0;
}
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
break;
}
case TPSM_PIXEL_STORAGE_MODE_DXT3: {
if (isLogDebugEnabled) {
log.debug("Loading texture TPSM_PIXEL_STORAGE_MODE_DXT3 " + Integer.toHexString(texaddr));
}
compressedTexture = true;
compressedTextureSize = getCompressedTextureSize(level, 4);
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, compressedTextureSize, 4);
// PSP DXT3 format reverses the alpha and color parts of each block,
// and reverses the color and per-pixel terms in the color part.
int i = 0;
for (int y = 0; y < context.texture_height[level]; y += 4) {
for (int x = 0; x < context.texture_buffer_width[level]; x += 4, i += 4) {
// Color
tmp_texture_buffer32[i + 3] = memoryReader.readNext();
tmp_texture_buffer32[i + 2] = memoryReader.readNext();
// Alpha
tmp_texture_buffer32[i + 0] = memoryReader.readNext();
tmp_texture_buffer32[i + 1] = memoryReader.readNext();
}
for (int x = context.texture_buffer_width[level]; x < context.texture_width[level]; x += 4, i += 4) {
tmp_texture_buffer32[i + 0] = 0;
tmp_texture_buffer32[i + 1] = 0;
tmp_texture_buffer32[i + 2] = 0;
tmp_texture_buffer32[i + 3] = 0;
}
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
break;
}
case TPSM_PIXEL_STORAGE_MODE_DXT5: {
if (isLogDebugEnabled) {
log.debug("Loading texture TPSM_PIXEL_STORAGE_MODE_DXT5 " + Integer.toHexString(texaddr));
}
compressedTexture = true;
compressedTextureSize = getCompressedTextureSize(level, 4);
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, compressedTextureSize, 2);
// PSP DXT5 format reverses the alpha and color parts of each block,
// and reverses the color and per-pixel terms in the color part. In
// the alpha part, the 2 reference alpha values are swapped with the
// alpha interpolation values.
int i = 0;
for (int y = 0; y < context.texture_height[level]; y += 4) {
for (int x = 0; x < context.texture_buffer_width[level]; x += 4, i += 8) {
// Color
tmp_texture_buffer16[i + 6] = (short) memoryReader.readNext();
tmp_texture_buffer16[i + 7] = (short) memoryReader.readNext();
tmp_texture_buffer16[i + 4] = (short) memoryReader.readNext();
tmp_texture_buffer16[i + 5] = (short) memoryReader.readNext();
// Alpha
tmp_texture_buffer16[i + 1] = (short) memoryReader.readNext();
tmp_texture_buffer16[i + 2] = (short) memoryReader.readNext();
tmp_texture_buffer16[i + 3] = (short) memoryReader.readNext();
tmp_texture_buffer16[i + 0] = (short) memoryReader.readNext();
}
for (int x = context.texture_buffer_width[level]; x < context.texture_width[level]; x += 4, i += 8) {
tmp_texture_buffer16[i + 0] = 0;
tmp_texture_buffer16[i + 1] = 0;
tmp_texture_buffer16[i + 2] = 0;
tmp_texture_buffer16[i + 3] = 0;
tmp_texture_buffer16[i + 4] = 0;
tmp_texture_buffer16[i + 5] = 0;
tmp_texture_buffer16[i + 6] = 0;
tmp_texture_buffer16[i + 7] = 0;
}
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
break;
}
default: {
error("Unhandled texture storage " + context.texture_storage);
return;
}
}
// Upload texture to openGL.
re.setTextureMipmapMagFilter(context.tex_mag_filter);
re.setTextureMipmapMinFilter(context.tex_min_filter);
re.setPixelStore(context.texture_buffer_width[level], textureByteAlignment);
if (compressedTexture) {
re.setCompressedTexImage(
level,
buffer_storage,
context.texture_width[level], context.texture_height[level],
compressedTextureSize,
final_buffer);
} else {
int textureSize = Math.max(context.texture_buffer_width[level], context.texture_width[level]) * context.texture_height[level] * textureByteAlignment;
re.setTexImage(
level,
buffer_storage,
context.texture_width[level], context.texture_height[level],
buffer_storage,
buffer_storage,
textureSize,
final_buffer);
}
if (State.captureGeNextFrame) {
boolean vramImage = isVRAM(tex_addr);
boolean overwriteFile = !vramImage;
if (vramImage || !CaptureManager.isImageCaptured(texaddr)) {
CaptureManager.captureImage(texaddr, level, final_buffer, context.texture_width[level], context.texture_height[level], context.texture_buffer_width[level], buffer_storage, compressedTexture, compressedTextureSize, false, overwriteFile);
}
}
if (texture != null) {
texture.setIsLoaded();
if (isLogDebugEnabled) {
log(helper.getCommandString(TFLUSH) + " Loaded texture " + texture.getGlId());
}
}
}
checkTextureMinFilter(compressedTexture, numberMipmaps);
} else {
boolean compressedTexture = (context.texture_storage >= TPSM_PIXEL_STORAGE_MODE_DXT1 && context.texture_storage <= TPSM_PIXEL_STORAGE_MODE_DXT5);
re.setTextureMipmapMagFilter(context.tex_mag_filter);
re.setTextureMipmapMinFilter(context.tex_min_filter);
checkTextureMinFilter(compressedTexture, context.texture_num_mip_maps);
if (isLogDebugEnabled) {
log(helper.getCommandString(TFLUSH) + " Reusing cached texture " + texture.getGlId());
}
}
textureChanged = false;
}
private void checkTextureMinFilter(boolean compressedTexture, int numberMipmaps) {
// OpenGL/Hardware cannot interpolate between compressed textures;
// this restriction has been checked on NVIDIA GeForce 8500 GT and 9800 GT
if (compressedTexture) {
int new_tex_min_filter;
if (context.tex_min_filter == TFLT_NEAREST || context.tex_min_filter == TFLT_NEAREST_MIPMAP_LINEAR || context.tex_min_filter == TFLT_NEAREST_MIPMAP_NEAREST) {
new_tex_min_filter = TFLT_NEAREST;
} else {
new_tex_min_filter = TFLT_LINEAR;
}
if (new_tex_min_filter != context.tex_min_filter) {
re.setTextureMipmapMinFilter(new_tex_min_filter);
if (isLogDebugEnabled) {
log("Overwriting texture min filter, no mipmap was generated but filter was set to use mipmap");
}
}
}
}
private Buffer readIndexedTexture(int level, int texaddr, int texclut, int bytesPerIndex) {
Buffer buffer = null;
int length = context.texture_buffer_width[level] * context.texture_height[level];
switch (context.tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0) {
return null;
}
short[] clut = readClut16(level);
if (!context.texture_swizzle) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, length * bytesPerIndex, bytesPerIndex);
for (int i = 0; i < length; i++) {
int index = memoryReader.readNext();
tmp_texture_buffer16[i] = clut[getClutIndex(index)];
}
buffer = ShortBuffer.wrap(tmp_texture_buffer16);
if (State.captureGeNextFrame) {
log.info("Capture loadTexture clut 8/16 unswizzled");
CaptureManager.captureRAM(texaddr, length * bytesPerIndex);
}
} else {
unswizzleTextureFromMemory(texaddr, bytesPerIndex, level);
switch (bytesPerIndex) {
case 1: {
for (int i = 0, j = 0; i < length; i += 4, j++) {
int n = tmp_texture_buffer32[j];
int index = n & 0xFF;
tmp_texture_buffer16[i + 0] = clut[getClutIndex(index)];
index = (n >> 8) & 0xFF;
tmp_texture_buffer16[i + 1] = clut[getClutIndex(index)];
index = (n >> 16) & 0xFF;
tmp_texture_buffer16[i + 2] = clut[getClutIndex(index)];
index = (n >> 24) & 0xFF;
tmp_texture_buffer16[i + 3] = clut[getClutIndex(index)];
}
break;
}
case 2: {
for (int i = 0, j = 0; i < length; i += 2, j++) {
int n = tmp_texture_buffer32[j];
tmp_texture_buffer16[i + 0] = clut[getClutIndex(n & 0xFFFF)];
tmp_texture_buffer16[i + 1] = clut[getClutIndex(n >>> 16)];
}
break;
}
case 4: {
for (int i = 0; i < length; i++) {
int n = tmp_texture_buffer32[i];
tmp_texture_buffer16[i] = clut[getClutIndex(n)];
}
break;
}
}
buffer = ShortBuffer.wrap(tmp_texture_buffer16);
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0) {
return null;
}
int[] clut = readClut32(level);
if (!context.texture_swizzle) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, length * bytesPerIndex, bytesPerIndex);
for (int i = 0; i < length; i++) {
int index = memoryReader.readNext();
tmp_texture_buffer32[i] = clut[getClutIndex(index)];
}
buffer = IntBuffer.wrap(tmp_texture_buffer32);
if (State.captureGeNextFrame) {
log.info("Capture loadTexture clut 8/32 unswizzled");
CaptureManager.captureRAM(texaddr, length * bytesPerIndex);
}
} else {
unswizzleTextureFromMemory(texaddr, bytesPerIndex, level);
switch (bytesPerIndex) {
case 1: {
for (int i = length - 4, j = (length / 4) - 1; i >= 0; i -= 4, j--) {
int n = tmp_texture_buffer32[j];
int index = n & 0xFF;
tmp_texture_buffer32[i + 0] = clut[getClutIndex(index)];
index = (n >> 8) & 0xFF;
tmp_texture_buffer32[i + 1] = clut[getClutIndex(index)];
index = (n >> 16) & 0xFF;
tmp_texture_buffer32[i + 2] = clut[getClutIndex(index)];
index = (n >> 24) & 0xFF;
tmp_texture_buffer32[i + 3] = clut[getClutIndex(index)];
}
break;
}
case 2: {
for (int i = length - 2, j = (length / 2) - 1; i >= 0; i -= 2, j--) {
int n = tmp_texture_buffer32[j];
tmp_texture_buffer32[i + 0] = clut[getClutIndex(n & 0xFFFF)];
tmp_texture_buffer32[i + 1] = clut[getClutIndex(n >>> 16)];
}
break;
}
case 4: {
for (int i = 0; i < length; i++) {
int n = tmp_texture_buffer32[i];
tmp_texture_buffer32[i] = clut[getClutIndex(n)];
}
break;
}
}
buffer = IntBuffer.wrap(tmp_texture_buffer32);
}
break;
}
default: {
error("Unhandled clut8 texture mode " + context.tex_clut_mode);
break;
}
}
return buffer;
}
private void setScissor() {
if (context.scissor_x1 >= 0 && context.scissor_y1 >= 0 && context.scissor_width <= context.region_width && context.scissor_height <= context.region_height) {
int scissorX = context.scissor_x1;
int scissorY = context.scissor_y1;
int scissorWidth = context.scissor_width;
int scissorHeight = context.scissor_height;
if (scissorHeight < 272) {
scissorY = 272 - scissorHeight - scissorY;
}
re.setScissor(scissorX, scissorY, scissorWidth, scissorHeight);
context.scissorTestFlag.setEnabled(true);
} else {
context.scissorTestFlag.setEnabled(false);
}
}
private boolean initRendering() {
/*
* Defer transformations until primitive rendering
*/
/*
* Set Scissor
*/
if (scissorChanged) {
setScissor();
scissorChanged = false;
}
/*
* Apply Blending
*/
if (blendChanged) {
setBlendFunc();
blendChanged = false;
}
/*
* Apply projection matrix
*/
if (projectionMatrixUpload.isChanged()) {
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD) {
if (context.viewport_height <= 0 && context.viewport_width >= 0) {
re.setProjectionMatrix(context.proj_uploaded_matrix);
} else {
float[] flippedMatrix = new float[16];
System.arraycopy(context.proj_uploaded_matrix, 0, flippedMatrix, 0, flippedMatrix.length);
if (context.viewport_height > 0) {
// Flip upside-down
flippedMatrix[5] = -flippedMatrix[5];
}
if (context.viewport_width < 0) {
// Flip right-to-left
flippedMatrix[0] = -flippedMatrix[0];
}
re.setProjectionMatrix(flippedMatrix);
}
} else {
re.setProjectionMatrix(null);
}
projectionMatrixUpload.setChanged(false);
// The viewport has to be reloaded when the projection matrix has changed
viewportChanged = true;
}
/*
* Apply viewport
*/
boolean loadOrtho2D = false;
if (viewportChanged) {
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD) {
re.setViewport(0, 0, 480, 272);
// Load the ortho for 2D after the depth settings
loadOrtho2D = true;
} else {
if (context.viewport_cx == 0 && context.viewport_cy == 0 && context.viewport_height == 0 && context.viewport_width == 0) {
context.viewport_cx = 2048;
context.viewport_cy = 2048;
context.viewport_width = 480;
context.viewport_height = 272;
}
int halfHeight = Math.abs(context.viewport_height);
int haltWidth = Math.abs(context.viewport_width);
int viewportX = context.viewport_cx - haltWidth - context.offset_x;
int viewportY = context.viewport_cy - halfHeight - context.offset_y;
int viewportWidth = 2 * haltWidth;
int viewportHeight = 2 * halfHeight;
// Align the viewport to the top of the window
if (viewportHeight < 272) {
viewportY += 272 - viewportHeight;
}
if (viewportHeight <= 272) {
re.setViewport(viewportX, viewportY, viewportWidth, viewportHeight);
}
}
viewportChanged = false;
}
/*
* Apply depth handling
*/
if (depthChanged) {
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD) {
re.setDepthFunc(context.depthFunc);
re.setDepthRange(context.zpos, context.zscale, context.zpos - context.zscale, context.zpos + context.zscale);
} else {
re.setDepthFunc(context.depthFunc);
re.setDepthRange(0.5f, 0.5f, 0, 1);
}
depthChanged = false;
}
/*
* Load the 2D ortho (only after the depth settings
*/
if (loadOrtho2D) {
re.setProjectionMatrix(getOrthoMatrix(0, 480, 272, 0, 0, -0xFFFF));
}
/*
* 2D mode handling
*/
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD) {
// 2D mode shouldn't be affected by the lighting and fog
re.disableFlag(IRenderingEngine.GU_LIGHTING);
re.disableFlag(IRenderingEngine.GU_FOG);
// TODO I don't know why, but the GL_MODELVIEW matrix has to be reloaded
// each time in 2D mode... Otherwise textures are not displayed.
modelMatrixUpload.setChanged(true);
} else {
context.lightingFlag.update();
context.fogFlag.update();
}
/*
* Model-View matrix has to reloaded when
* - model matrix changed
* - view matrix changed
* - lighting has to be reloaded
*/
boolean loadLightingSettings = (viewMatrixUpload.isChanged() || lightingChanged) && context.lightingFlag.isEnabled() && context.transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD;
boolean modelViewMatrixChanged = modelMatrixUpload.isChanged() || viewMatrixUpload.isChanged() || loadLightingSettings;
/*
* Apply view matrix
*/
if (modelViewMatrixChanged) {
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD) {
re.setViewMatrix(context.view_uploaded_matrix);
} else {
re.setViewMatrix(null);
}
viewMatrixUpload.setChanged(false);
}
/*
* Setup lights on when view transformation is set up
*/
if (loadLightingSettings || context.tex_map_mode == TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP) {
for (int i = 0; i < NUM_LIGHTS; i++) {
if (context.lightFlags[i].isEnabled() || (context.tex_map_mode == TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP && (context.tex_shade_u == i || context.tex_shade_v == i))) {
re.setLightPosition(i, context.light_pos[i]);
re.setLightDirection(i, context.light_dir[i]);
if (context.light_type[i] == LIGHT_SPOT) {
re.setLightSpotExponent(i, context.spotLightExponent[i]);
re.setLightSpotCutoff(i, context.spotLightCutoff[i]);
} else {
// uniform light distribution
re.setLightSpotExponent(i, 0);
re.setLightSpotCutoff(i, 180);
}
// Light kind:
// LIGHT_DIFFUSE_SPECULAR: use ambient, diffuse and specular colors
// all other light kinds: use ambient and diffuse colors (not specular)
if (context.light_kind[i] != LIGHT_AMBIENT_DIFFUSE) {
re.setLightSpecularColor(i, context.lightSpecularColor[i]);
} else {
re.setLightSpecularColor(i, blackColor);
}
}
}
lightingChanged = false;
}
if (modelViewMatrixChanged) {
// Apply model matrix
if (context.transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD) {
re.setModelMatrix(context.model_uploaded_matrix);
} else {
re.setModelMatrix(null);
}
modelMatrixUpload.setChanged(false);
re.endModelViewMatrixUpdate();
}
/*
* Apply texture transforms
*/
if (textureMatrixUpload.isChanged()) {
if (context.transform_mode != VTYPE_TRANSFORM_PIPELINE_TRANS_COORD) {
re.setTextureMapMode(TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV, TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES);
float[] textureMatrix = new float[] {
1.f / context.texture_width[0], 0, 0, 0,
0, 1.f / context.texture_height[0], 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
re.setTextureMatrix(textureMatrix);
} else {
re.setTextureMapMode(context.tex_map_mode, context.tex_proj_map_mode);
switch (context.tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV: {
context.reTextureGenS.setEnabled(false);
context.reTextureGenT.setEnabled(false);
float[] textureMatrix = new float[] {
context.tex_scale_x, 0, 0, 0,
0, context.tex_scale_y, 0, 0,
0, 0, 1, 0,
context.tex_translate_x, context.tex_translate_y, 0, 1
};
re.setTextureMatrix(textureMatrix);
break;
}
case TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX: {
context.reTextureGenS.setEnabled(false);
context.reTextureGenT.setEnabled(false);
re.setTextureMatrix(context.texture_uploaded_matrix);
break;
}
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
re.setTextureEnvironmentMapping(context.tex_shade_u, context.tex_shade_v);
context.reTextureGenS.setEnabled(true);
context.reTextureGenT.setEnabled(true);
re.setTextureMatrix(context.tex_envmap_matrix);
break;
}
default:
log("Unhandled texture matrix mode " + context.tex_map_mode);
}
}
textureMatrixUpload.setChanged(false);
}
boolean useVertexColor = false;
if (!context.lightingFlag.isEnabled() || context.transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD) {
context.reColorMaterial.setEnabled(false);
if (vinfo.color != 0) {
useVertexColor = true;
} else {
if (materialChanged) {
re.setVertexColor(context.mat_ambient);
materialChanged = false;
}
}
} else if (vinfo.color != 0 && context.mat_flags != 0) {
useVertexColor = true;
if (materialChanged) {
boolean ambient = (context.mat_flags & 1) != 0;
boolean diffuse = (context.mat_flags & 2) != 0;
boolean specular = (context.mat_flags & 4) != 0;
if (!ambient) {
re.setMaterialAmbientColor(context.mat_ambient);
}
if (!diffuse) {
re.setMaterialDiffuseColor(context.mat_diffuse);
}
if (!specular) {
re.setMaterialSpecularColor(context.mat_specular);
}
re.setColorMaterial(ambient, diffuse, specular);
context.reColorMaterial.setEnabled(true);
materialChanged = false;
}
} else {
context.reColorMaterial.setEnabled(false);
if (materialChanged) {
re.setMaterialAmbientColor(context.mat_ambient);
re.setMaterialDiffuseColor(context.mat_diffuse);
re.setMaterialSpecularColor(context.mat_specular);
re.setColorMaterial(false, false, false);
materialChanged = false;
}
}
re.setTextureWrapMode(context.tex_wrap_s, context.tex_wrap_t);
int mipmapBaseLevel = 0;
int mipmapMaxLevel = context.texture_num_mip_maps;
if (context.tex_mipmap_mode == TBIAS_MODE_CONST) {
// TBIAS_MODE_CONST uses the tex_mipmap_bias_int level supplied by TBIAS.
mipmapBaseLevel = context.tex_mipmap_bias_int;
mipmapMaxLevel = context.tex_mipmap_bias_int;
if (isLogDebugEnabled) {
log.debug("TBIAS_MODE_CONST " + context.tex_mipmap_bias_int);
}
} else if (context.tex_mipmap_mode == TBIAS_MODE_AUTO) {
// TODO implement TBIAS_MODE_AUTO. The following is not correct
// TBIAS_MODE_AUTO performs a comparison between the texture's weight and height at level 0.
// int maxValue = Math.max(context.texture_width[0], context.texture_height[0]);
//
// if(maxValue <= 1) {
// mipmapBaseLevel = 0;
// } else {
// mipmapBaseLevel = (int) ((Math.log((Math.abs(maxValue) / Math.abs(context.zpos))) / Math.log(2)) + context.tex_mipmap_bias);
// }
// mipmapMaxLevel = mipmapBaseLevel;
// if (isLogDebugEnabled) {
// log.debug("TBIAS_MODE_AUTO " + context.tex_mipmap_bias + ", param=" + maxValue);
// }
} else if (context.tex_mipmap_mode == TBIAS_MODE_SLOPE) {
// TBIAS_MODE_SLOPE uses the tslope_level level supplied by TSLOPE.
mipmapBaseLevel = (int) ((Math.log(Math.abs(context.tslope_level) / Math.abs(context.zpos)) / Math.log(2)) + context.tex_mipmap_bias);
mipmapMaxLevel = mipmapBaseLevel;
if (isLogDebugEnabled) {
log.debug("TBIAS_MODE_SLOPE " + context.tex_mipmap_bias + ", slope=" + context.tslope_level);
}
}
// Clamp to [0..texture_num_mip_maps]
mipmapBaseLevel = Math.max(0, Math.min(mipmapBaseLevel, context.texture_num_mip_maps));
// Clamp to [mipmapBaseLevel..texture_num_mip_maps]
mipmapMaxLevel = Math.max(mipmapBaseLevel, Math.min(mipmapMaxLevel, context.texture_num_mip_maps));
if (isLogDebugEnabled) {
log.debug("Texture Mipmap base=" + mipmapBaseLevel + ", max=" + mipmapMaxLevel + ", textureNumMipmaps=" + context.texture_num_mip_maps);
}
re.setTextureMipmapMinLevel(mipmapBaseLevel);
re.setTextureMipmapMaxLevel(mipmapMaxLevel);
return useVertexColor;
}
private void endRendering(boolean useVertexColor, boolean useTexture, int numberOfVertex) {
Memory mem = Memory.getInstance();
// VADDR/IADDR are updated after vertex rendering
// (IADDR when indexed and VADDR when not).
// Some games rely on this and don't reload VADDR/IADDR between 2 PRIM/BBOX calls.
if (vinfo.index == 0) {
vinfo.ptr_vertex = vinfo.getAddress(mem, numberOfVertex);
} else {
vinfo.ptr_index += numberOfVertex * vinfo.index;
}
switch (context.tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
context.reTextureGenS.setEnabled(false);
context.reTextureGenT.setEnabled(false);
break;
}
}
}
public static float[] getOrthoMatrix(float left, float right, float bottom, float top, float near, float far) {
float dx = right - left;
float dy = top - bottom;
float dz = far - near;
float[] orthoMatrix = {
2.f / dx, 0, 0, 0,
0, 2.f / dy, 0, 0,
0, 0, -2.f / dz, 0,
-(right + left) / dx, -(top + bottom) / dy, -(far + near) / dz, 1
};
return orthoMatrix;
}
float spline_n(int i, int j, float u, int[] knot) {
if(j == 0) {
if(knot[i] <= u && u < knot[i + 1])
return 1;
return 0;
}
float res = 0;
if(knot[i + j] - knot[i] != 0)
res += (u - knot[i]) / (knot[i + j] - knot[i]) * spline_n(i, j - 1, u, knot);
if(knot[i + j + 1] - knot[i + 1] != 0)
res += (knot[i + j + 1] - u) / (knot[i + j + 1] - knot[i + 1]) * spline_n(i + 1, j - 1, u, knot);
return res;
}
int[] spline_knot(int n, int type) {
int[] knot = new int[n + 5];
for(int i = 0; i < n - 1; i++) {
knot[i + 3] = i;
}
if((type & 1) == 0) {
knot[0] = -3;
knot[1] = -2;
knot[2] = -1;
}
if((type & 2) == 0) {
knot[n + 2] = n - 1;
knot[n + 3] = n;
knot[n + 4] = n + 1;
} else {
knot[n + 2] = n - 2;
knot[n + 3] = n - 2;
knot[n + 4] = n - 2;
}
return knot;
}
private void drawSpline(int ucount, int vcount, int utype, int vtype) {
if (ucount < 4 || vcount < 4) {
log.warn("Unsupported spline parameters uc=" + ucount + " vc=" + vcount);
return;
}
boolean useVertexColor = initRendering();
boolean useTexture = vinfo.texture != 0 || context.textureFlag.isEnabled();
boolean useNormal = context.lightingFlag.isEnabled();
// Generate control points.
VertexState[][] ctrlpoints = getControlPoints(ucount, vcount);
// GE capture.
if (State.captureGeNextFrame && !isVertexBufferEmbedded()) {
log.info("Capture drawSpline");
CaptureManager.captureRAM(vinfo.ptr_vertex, vinfo.vertexSize * ucount * vcount);
}
// Generate patch VertexState.
VertexState[][] patch = new VertexState[context.patch_div_s + 1][context.patch_div_t + 1];
// Calculate knot arrays.
int n = ucount - 1;
int m = vcount - 1;
int[] knot_u = spline_knot(n, utype);
int[] knot_v = spline_knot(m, vtype);
// The spline grows to a limit defined by n - 2 for u and m - 2 for v.
// This limit is open, so we need to get a very close approximation of it.
float limit = 2.000001f;
// Process spline vertexes with Cox-deBoor's algorithm.
for(int j = 0; j <= context.patch_div_t; j++) {
float v = (float)j * (float)(m - limit) / (float)context.patch_div_t;
for(int i = 0; i <= context.patch_div_s; i++) {
float u = (float)i * (float)(n - limit) / (float)context.patch_div_s;
patch[i][j] = new VertexState();
VertexState p = patch[i][j];
for(int ii = 0; ii <= n; ii++) {
for(int jj = 0; jj <= m; jj++) {
float f = spline_n(ii, 3, u, knot_u) * spline_n(jj, 3, v, knot_v);
if(f != 0) {
pointMultAdd(p, ctrlpoints[ii][jj], f, useVertexColor, useTexture, useNormal);
}
}
}
if(useTexture && vinfo.texture == 0) {
p.t[0] = u;
p.t[1] = v;
}
}
}
drawCurvedSurface(patch, ucount, vcount, useVertexColor, useTexture, useNormal);
}
private void pointMultAdd(VertexState dest, VertexState src, float f, boolean useVertexColor, boolean useTexture, boolean useNormal) {
dest.p[0] += f * src.p[0];
dest.p[1] += f * src.p[1];
dest.p[2] += f * src.p[2];
if(useTexture) {
dest.t[0] += f * src.t[0];
dest.t[1] += f * src.t[1];
}
if(useVertexColor) {
dest.c[0] += f * src.c[0];
dest.c[1] += f * src.c[1];
dest.c[2] += f * src.c[2];
}
if(useNormal) {
dest.n[0] += f * src.n[0];
dest.n[1] += f * src.n[1];
dest.n[2] += f * src.n[2];
}
}
private void drawBezier(int ucount, int vcount) {
if ((ucount - 1) % 3 != 0 && (vcount - 1) % 3 != 0) {
log.warn("Unsupported bezier parameters ucount=" + ucount + " vcount=" + vcount);
return;
}
boolean useVertexColor = initRendering();
boolean useTexture = vinfo.texture != 0 || context.textureFlag.isEnabled();
boolean useNormal = context.lightingFlag.isEnabled();
VertexState[][] anchors = getControlPoints(ucount, vcount);
// Don't capture the ram if the vertex list is embedded in the display list. TODO handle stall_addr == 0 better
// TODO may need to move inside the loop if indices are used, or find the largest index so we can calculate the size of the vertex list
if (State.captureGeNextFrame && !isVertexBufferEmbedded()) {
log.info("Capture drawBezier");
CaptureManager.captureRAM(vinfo.ptr_vertex, vinfo.vertexSize * ucount * vcount);
}
// Generate patch VertexState.
VertexState[][] patch = new VertexState[context.patch_div_s + 1][context.patch_div_t + 1];
// Number of patches in the U and V directions
int upcount = ucount / 3;
int vpcount = vcount / 3;
float[][] ucoeff = new float[context.patch_div_s + 1][];
for(int j = 0; j <= context.patch_div_t; j++) {
float vglobal = (float)j * vpcount / (float)context.patch_div_t;
int vpatch = (int)vglobal; // Patch number
float v = vglobal - vpatch;
if(j == context.patch_div_t) {
vpatch--;
v = 1.f;
}
float[] vcoeff = BernsteinCoeff(v);
for(int i = 0; i <= context.patch_div_s; i++) {
float uglobal = (float)i * upcount / (float)context.patch_div_s;
int upatch = (int)uglobal;
float u = uglobal - upatch;
if(i == context.patch_div_s) {
upatch--;
u = 1.f;
}
ucoeff[i] = BernsteinCoeff(u);
patch[i][j] = new VertexState();
VertexState p = patch[i][j];
for(int ii = 0; ii < 4; ++ii) {
for(int jj = 0; jj < 4; ++jj) {
pointMultAdd(p,
anchors[3 * upatch + ii][3 * vpatch + jj],
ucoeff[i][ii] * vcoeff[jj],
useVertexColor, useTexture, useNormal);
}
}
if(useTexture && vinfo.texture == 0) {
p.t[0] = uglobal;
p.t[1] = vglobal;
}
}
}
drawCurvedSurface(patch, ucount, vcount, useVertexColor, useTexture, useNormal);
}
private void drawCurvedSurface(VertexState[][] patch, int ucount, int vcount,
boolean useVertexColor, boolean useTexture, boolean useNormal) {
// TODO: Compute the normals
setDataPointers(3, useVertexColor, 4, useTexture, 2, useNormal, 0, true);
re.setVertexInfo(vinfo, false, useVertexColor);
ByteBuffer drawByteBuffer = bufferManager.getBuffer(bufferId);
drawByteBuffer.clear();
FloatBuffer drawFloatBuffer = drawByteBuffer.asFloatBuffer();
for(int j = 0; j <= context.patch_div_t - 1; j++) {
drawFloatBuffer.clear();
for(int i = 0; i <= context.patch_div_s; i++) {
VertexState v1 = patch[i][j];
VertexState v2 = patch[i][j + 1];
if(useTexture) drawFloatBuffer.put(v1.t);
if(useVertexColor) drawFloatBuffer.put(v1.c);
if(useNormal) drawFloatBuffer.put(v1.n);
drawFloatBuffer.put(v1.p);
if(useTexture) drawFloatBuffer.put(v2.t);
if(useVertexColor) drawFloatBuffer.put(v2.c);
if(useNormal) drawFloatBuffer.put(v2.n);
drawFloatBuffer.put(v2.p);
}
bufferManager.setBufferData(bufferId, drawFloatBuffer.position() * SIZEOF_FLOAT, drawByteBuffer.rewind(), IRenderingEngine.RE_STREAM_DRAW);
re.drawArrays(patch_prim_types[context.patch_prim], 0, (context.patch_div_s + 1) * 2);
}
endRendering(useVertexColor, useTexture, ucount * vcount);
}
private VertexState[][] getControlPoints(int ucount, int vcount) {
VertexState[][] controlPoints = new VertexState[ucount][vcount];
Memory mem = Memory.getInstance();
for (int u = 0; u < ucount; u++) {
for (int v = 0; v < vcount; v++) {
int addr = vinfo.getAddress(mem, v * ucount + u);
VertexState vs = vinfo.readVertex(mem, addr);
if (isLogDebugEnabled) {
log(String.format("control point #%d,%d p(%f,%f,%f) t(%f,%f), c(%f,%f,%f)",
u, v,
vs.p[0], vs.p[1], vs.p[2],
vs.t[0], vs.t[1],
vs.c[0], vs.c[1], vs.c[2]));
}
controlPoints[u][v] = vs;
}
}
return controlPoints;
}
private float[] BernsteinCoeff(float u) {
float uPow2 = u * u;
float uPow3 = uPow2 * u;
float u1 = 1 - u;
float u1Pow2 = u1 * u1;
float u1Pow3 = u1Pow2 * u1;
return new float[] {u1Pow3, 3 * u * u1Pow2, 3 * uPow2 * u1, uPow3 };
}
private Buffer getTexture32BitBuffer(int texaddr, int level) {
Buffer final_buffer = null;
if (!context.texture_swizzle) {
// texture_width might be larger than texture_buffer_width
int bufferlen = Math.max(context.texture_buffer_width[level], context.texture_width[level]) * context.texture_height[level] * 4;
final_buffer = Memory.getInstance().getBuffer(texaddr, bufferlen);
if (final_buffer == null) {
int length = context.texture_buffer_width[level] * context.texture_height[level];
IMemoryReader memoryReader = MemoryReader.getMemoryReader(texaddr, length * 4, 4);
for (int i = 0; i < length; i++) {
tmp_texture_buffer32[i] = memoryReader.readNext();
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
}
if (State.captureGeNextFrame) {
log.info("Capture getTexture32BitBuffer unswizzled");
CaptureManager.captureRAM(texaddr, bufferlen);
}
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 4, level);
}
return final_buffer;
}
public final static String getPsmName(final int psm) {
return (psm >= 0 && psm < psm_names.length)
? psm_names[psm % psm_names.length]
: "PSM_UNKNOWN" + psm;
}
public final static String getLOpName(final int ops) {
return (ops >= 0 && ops < logical_ops_names.length)
? logical_ops_names[ops % logical_ops_names.length]
: "UNKNOWN_LOP" + ops;
}
private int getCompressedTextureSize(int level, int compressionRatio) {
return getCompressedTextureSize(context.texture_width[level], context.texture_height[level], compressionRatio);
}
public static int getCompressedTextureSize(int width, int height, int compressionRatio) {
int compressedTextureWidth = ((width + 3) / 4) * 4;
int compressedTextureHeight = ((height + 3) / 4) * 4;
int compressedTextureSize = compressedTextureWidth * compressedTextureHeight * 4 / compressionRatio;
return compressedTextureSize;
}
private void updateGeBuf() {
if (geBufChanged) {
display.hleDisplaySetGeBuf(context.fbp, context.fbw, context.psm, somethingDisplayed);
geBufChanged = false;
textureChanged = true;
maxSpriteHeight = 0;
maxSpriteWidth = 0;
projectionMatrixUpload.setChanged(true);
modelMatrixUpload.setChanged(true);
viewMatrixUpload.setChanged(true);
textureMatrixUpload.setChanged(true);
viewportChanged = true;
depthChanged = true;
materialChanged = true;
}
}
// For capture/replay
public int getFBP() {
return context.fbp;
}
public int getFBW() {
return context.fbw;
}
public int getZBP() {
return context.zbp;
}
public int getZBW() {
return context.zbw;
}
public int getPSM() {
return context.psm;
}
private boolean isVertexBufferEmbedded() {
// stall_addr may be 0
return (vinfo.ptr_vertex >= currentList.list_addr && vinfo.ptr_vertex < currentList.getStallAddr());
}
private boolean isVRAM(int addr) {
addr &= Memory.addressMask;
return addr >= MemoryMap.START_VRAM && addr <= MemoryMap.END_VRAM;
}
private void hlePerformAction(IAction action, Semaphore sync) {
hleAction = action;
while (true) {
try {
sync.acquire();
break;
} catch (InterruptedException e) {
// Retry again..
}
}
}
public void hleSaveContext(int addr) {
// If we are rendering, we have to wait for a consistent state
// before saving the context: let the display thread perform
// the save when appropriate.
if (hasDrawLists() || currentList != null) {
Semaphore sync = new Semaphore(0);
hlePerformAction(new SaveContextAction(addr, sync), sync);
} else {
saveContext(addr);
}
}
public void hleRestoreContext(int addr) {
// If we are rendering, we have to wait for a consistent state
// before restoring the context: let the display thread perform
// the restore when appropriate.
if (hasDrawLists() || currentList != null) {
Semaphore sync = new Semaphore(0);
hlePerformAction(new RestoreContextAction(addr, sync), sync);
} else {
restoreContext(addr);
}
}
private void saveContext(int addr) {
context.write(Memory.getInstance(), addr);
}
private void restoreContext(int addr) {
context.read(Memory.getInstance(), addr);
context.setDirty();
projectionMatrixUpload.setChanged(true);
modelMatrixUpload.setChanged(true);
viewMatrixUpload.setChanged(true);
textureMatrixUpload.setChanged(true);
lightingChanged = true;
blendChanged = true;
textureChanged = true;
geBufChanged = true;
viewportChanged = true;
depthChanged = true;
materialChanged = true;
}
public boolean isUsingTRXKICK() {
return usingTRXKICK;
}
public int getMaxSpriteHeight() {
return maxSpriteHeight;
}
public int getMaxSpriteWidth() {
return maxSpriteWidth;
}
public void setUseVertexCache(boolean useVertexCache) {
// VertexCache is relying on VBO
if (bufferManager != null && !bufferManager.useVBO()) {
useVertexCache = false;
}
this.useVertexCache = useVertexCache;
if (useVertexCache) {
VideoEngine.log.info("Using Vertex Cache");
}
}
public int getBase() {
return context.base;
}
public void setBase(int base) {
context.base = base;
}
public int getBaseOffset() {
return context.baseOffset;
}
public void setBaseOffset(int baseOffset) {
context.baseOffset = baseOffset;
}
public void addVideoTexture(int address) {
videoTextures.add(address);
}
public void resetVideoTextures() {
videoTextures.clear();
}
protected void matrixMult(float[] result, float[] m1, float[] m2) {
// If the result has to be stored into one of the input matrix,
// store the result in a temp array first.
float[] origResult = null;
if (result == m1 || result == m2) {
origResult = result;
result = new float[4 * 4];
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
float s = 0;
for (int k = 0; k < 4; k++) {
s += m1[k * 4 + j] * m2[i * 4 + k];
}
result[i * 4 + j] = s;
}
}
if (origResult != null) {
System.arraycopy(result, 0, origResult, 0, result.length);
}
}
protected void vectorMult(float[] result, float[] m, float[] v) {
for (int i = 0; i < result.length; i++) {
float s = 0;
for (int j = 0; j < v.length; j++) {
s += v[j] * m[j * 4 + i];
}
result[i] = s;
}
}
private class SaveContextAction implements IAction {
private int addr;
private Semaphore sync;
public SaveContextAction(int addr, Semaphore sync) {
this.addr = addr;
this.sync = sync;
}
@Override
public void execute() {
saveContext(addr);
sync.release();
}
}
private class RestoreContextAction implements IAction {
private int addr;
private Semaphore sync;
public RestoreContextAction(int addr, Semaphore sync) {
this.addr = addr;
this.sync = sync;
}
@Override
public void execute() {
restoreContext(addr);
context.update();
sync.release();
}
}
}
|
[
"[email protected]"
] | |
33786b8e0c254574505c302f56aa13e274a9c4b5
|
4d6f449339b36b8d4c25d8772212bf6cd339f087
|
/netreflected/src/Core/System.Private.CoreLib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=7cec85d7bea7798e/system/InsufficientMemoryException.java
|
6882aadb936b98da2e3802a1dfb5417fd1450e5b
|
[
"MIT"
] |
permissive
|
lvyitian/JCOReflector
|
299a64550394db3e663567efc6e1996754f6946e
|
7e420dca504090b817c2fe208e4649804df1c3e1
|
refs/heads/master
| 2022-12-07T21:13:06.208025 | 2020-08-28T09:49:29 | 2020-08-28T09:49:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,567 |
java
|
/*
* MIT License
*
* Copyright (c) 2020 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.OutOfMemoryException;
/**
* The base .NET class managing System.InsufficientMemoryException, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e. Extends {@link NetException}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.InsufficientMemoryException" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.InsufficientMemoryException</a>
*/
public class InsufficientMemoryException extends OutOfMemoryException {
/**
* Fully assembly qualified name: System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
*/
public static final String assemblyFullName = "System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e";
/**
* Assembly name: System.Private.CoreLib
*/
public static final String assemblyShortName = "System.Private.CoreLib";
/**
* Qualified class name: System.InsufficientMemoryException
*/
public static final String className = "System.InsufficientMemoryException";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
JCNativeException jcNativeException = null;
static JCType createType() {
try {
return bridge.GetType(className + ", " + (JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName));
} catch (JCException jce) {
if (JCOBridgeInstance.getDebug())
jce.printStackTrace();
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public InsufficientMemoryException() {
super();
}
public InsufficientMemoryException(Object instance) {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else if (instance instanceof JCNativeException) {
jcNativeException = (JCNativeException) instance;
classInstance = jcNativeException.getCLRException();
}
}
public InsufficientMemoryException(String message) {
super(message);
}
public InsufficientMemoryException(NetException cause) {
super(cause);
}
public InsufficientMemoryException(String message, NetException cause) {
super(message, cause);
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link InsufficientMemoryException}, a cast assert is made to check if types are compatible.
*/
public static InsufficientMemoryException cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new InsufficientMemoryException(from.getJCOInstance());
}
// Constructors section
// Methods section
// Properties section
}
|
[
"[email protected]"
] | |
ff171a4ae24eb25911f364d4104b1a709946fca0
|
e2456ec5b56bc0c50903425f9f63396bf28ab9d7
|
/src/main/java/com/uber/eats/authentication/ResourceServerConfiguration.java
|
f399d81a5748b79213db901012635aec87d31d0d
|
[] |
no_license
|
arubabai/uber_eats
|
1f3b0184138928f0dd1b6daf51037574a520664b
|
ec5cc59f47037a0d8437e1ed134a48da40678bce
|
refs/heads/main
| 2022-12-20T08:44:08.088078 | 2020-10-08T19:39:53 | 2020-10-08T19:39:53 | 302,444,291 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,198 |
java
|
package com.uber.eats.authentication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "resource-server-rest-api";
private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
private static final String SECURED_PATTERN = "/**";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers(SECURED_PATTERN).and().authorizeRequests()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/session-logout").permitAll()
.antMatchers("/user/country-list").permitAll()
.antMatchers("/user/city-list").permitAll()
.antMatchers("/user/state-list").permitAll()
.antMatchers("/user/sign-up").permitAll()
.antMatchers("/user/generate-password-reset-mail").permitAll()
.antMatchers("/user/password-reset").permitAll()
.antMatchers("/api-docs/swagger-config").permitAll()
.antMatchers("/api-docs").permitAll()
.antMatchers(HttpMethod.POST, SECURED_PATTERN)
.access(SECURED_WRITE_SCOPE)
.anyRequest().access(SECURED_READ_SCOPE)
.and()
.addFilterBefore(new SecurityContextRestorerFilter(), AbstractPreAuthenticatedProcessingFilter.class);
http.sessionManagement().sessionFixation().none();
}
}
|
[
"shadman@shadman"
] |
shadman@shadman
|
f4196c1e625c72fa2af4708c9666fe1ac4452bd0
|
a2bbd2ae2e9f83b1f06ca2dd71509c6febd35427
|
/LS_Client/src/main/java/blservice/goodsblservice/GoodsDeleteBLService.java
|
a9cfe2a915c080016c2a1099c64c30915e33fff5
|
[] |
no_license
|
disinuo/Logistics-System
|
0c15645d79881cc7c59bbe424de765d70ede9bc1
|
88de29f512d4a5a0acbbcc351407ac433175b035
|
refs/heads/master
| 2021-01-11T09:58:27.837194 | 2016-01-05T13:46:09 | 2016-01-05T13:46:09 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 310 |
java
|
package blservice.goodsblservice;
import util.enumData.ResultMessage;
import Exception.GoodsNotFound;
import VO.GoodsVO;
public interface GoodsDeleteBLService {
/**
* delete a list
* @param vo
* @return
* @throws GoodsNotFound
*/
public ResultMessage delete(GoodsVO vo) throws GoodsNotFound;
}
|
[
"[email protected]"
] | |
e7204a7ed79c726d72304db3111f43a0d10494a4
|
d13bb3049a58f756be8e45cdbdfa05353cb5a0d3
|
/decorator/Seelachs.java
|
e1b2e34dff44b8774298832ad8bfc1cbc817142b
|
[] |
no_license
|
SebSDev/design_patterns
|
517d740973cbf424a89ee4aa2be8b7ecf83106f1
|
ffc271c0d3c6c755691aa897224a60e41f9150f6
|
refs/heads/master
| 2020-04-14T18:59:12.635329 | 2019-01-28T18:11:07 | 2019-01-28T18:11:07 | 164,040,336 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 251 |
java
|
package prg.design_patterns.decorator;
/**
* @author Sebastian Schäffler
* created at 02.01.2019
* description: SomeComponent
*/
public class Seelachs extends Gericht
{
public String getDescription()
{
return "Seelachs";
}
}
|
[
"[email protected]"
] | |
39844a4487d54905e7997a51e2dd8e9daa2f2f1b
|
7439a2f954079c6ddc0394e9c2e1b550ea18ab57
|
/src/testenvironment/TestController.java
|
27d2acdbe3414478991f46065ca9802ddb223e96
|
[] |
no_license
|
TempestNite/Final-Gambit
|
b5e4154e93a28ecdb0fa8698129acc68d421e7ee
|
5b7a1455da63f415ed48f18d63973024297e75b6
|
refs/heads/master
| 2018-01-08T09:30:26.602473 | 2015-08-14T01:38:06 | 2015-08-14T01:38:06 | 36,632,744 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,731 |
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 testenvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* @author dasta
*/
public class TestController
{
private TestEnvironment Model = new TestEnvironment();
private TestApp View = new TestApp();
public TestController ()
{
//try
//{
IncrementListener biteMe = new IncrementListener();
DecrementListener ninjaLike = new DecrementListener();
this.View.addIncrementListener(biteMe);
this.View.addDecrementListener(ninjaLike);
//}
/*catch (NullPointerException e)
{
System.out.println("I Finally Gotcha.");
}*/
}
public void addModel(TestEnvironment m)
{
this.Model = m;
}
public void addView(TestApp v)
{
this.View = v;
}
class IncrementListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
int delta = 0;
delta = View.getAmountChange();
Model.incCount(delta);
View.setCount(Model.getCount());
}
}
class DecrementListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
int delta = 0;
delta = View.getAmountChange();
Model.decCount(delta);
View.setCount(Model.getCount());
}
}
}
|
[
"[email protected]"
] | |
2e1ceda659e493861230a31c6f160a3b94d97b6d
|
39439b61b8ddb53fb2962b2f26cb9153e555ef88
|
/app/src/main/java/net/nashlegend/sourcewall/request/interceptors/SupplierInterceptor.java
|
02de18dafc6e91156f3712201df7d64f30c9206f
|
[] |
no_license
|
joshuayingwhat/SourceWall
|
874e0dbe2cf5c0a088111d3921af570f89f90560
|
a90e2faf5ed67aede165bde3a60291062a57a444
|
refs/heads/master
| 2023-04-07T16:23:29.878727 | 2017-08-27T08:26:32 | 2017-08-27T08:26:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,068 |
java
|
package net.nashlegend.sourcewall.request.interceptors;
import net.nashlegend.sourcewall.request.RequestObject;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by NashLegend on 2016/10/31.
*/
public class SupplierInterceptor implements Interceptor {
RequestObject requestObject;
public SupplierInterceptor(RequestObject requestObject) {
this.requestObject = requestObject;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder newBuilder = chain.request().newBuilder();
if (requestObject.cacheControl != null) {
newBuilder.cacheControl(requestObject.cacheControl);
}
if (requestObject.headers != null) {
newBuilder.headers(requestObject.headers.build());
}
if (requestObject.requestBody != null) {
newBuilder.method(requestObject.method.value(), requestObject.requestBody);
}
return chain.proceed(newBuilder.build());
}
}
|
[
"[email protected]"
] | |
4b1049bcf282b53b460058eb54e856dd3efa9a16
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/15/15_af08c7fcab6ecd94def8e3c11fd00dd280c425ba/FileSystemAdapterTest/15_af08c7fcab6ecd94def8e3c11fd00dd280c425ba_FileSystemAdapterTest_s.java
|
be501a9a701f6c44c0035d3a06a5deee456fb529
|
[] |
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 | 851 |
java
|
package no.f12.agiledeploy.deployer;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Test;
public class FileSystemAdapterTest {
@Test(expected = IllegalStateException.class)
public void shouldThrowExceptionWhenUnableToCreateSymLink() {
FileSystemAdapterImpl adapter = new FileSystemAdapterImpl();
adapter.setSymLinkCommand("nothing");
adapter.createSymbolicLink(new File("."), new File("."));
}
@Test
public void shouldSucceedWithSimpleCommand() {
FileSystemAdapterImpl adapter = new FileSystemAdapterImpl();
adapter.setSymLinkCommand("echo");
}
@Test
public void shouldPerformExpectedSubstitution() {
assertEquals(String.format(FileSystemAdapterImpl.DEFAULT_SYMLINKCOMMAND, "hello1", "hello2"),
"ln -s hello1 hello2");
}
}
|
[
"[email protected]"
] | |
08d9eb36c157d72c93d24a07f28c18c8794aae84
|
f403abf4b3cea8eafbb75e2f2c484348dc2e4776
|
/src/trainning/BenQ.java
|
184a3e39ff788a1c4c2c021bab6c8749f43c38cf
|
[] |
no_license
|
javaobjects/demo_spring05_di_annotation
|
3e49848671bc08584de1e4f471cc67e712e5aef4
|
b9525e03d299d1a1a714b76369f8f9667c50aa66
|
refs/heads/master
| 2020-06-07T03:34:29.786756 | 2019-06-21T06:02:15 | 2019-06-21T06:02:15 | 192,912,055 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 122 |
java
|
package trainning;
import org.springframework.stereotype.Component;
@Component
public class BenQ implements Monitor{
}
|
[
"[email protected]"
] | |
2a8b4eeece1d870eebacfaa8d71c09d90220f388
|
16935ecd3e9029392feae94ac683b2b259150828
|
/aws-java-sdk-appconfig/src/main/java/com/amazonaws/services/appconfig/model/transform/StopDeploymentResultJsonUnmarshaller.java
|
585263987efb118fa6d27962cbf20c11dc8fa50b
|
[
"Apache-2.0"
] |
permissive
|
segfaultomatic/aws-sdk-java
|
c33b627d4172956cb219ceb706c4dfd040cb1e1f
|
7377e690a8be4de39068ba51226c4d8e0637f720
|
refs/heads/master
| 2022-06-18T03:22:43.141443 | 2022-05-27T20:39:37 | 2022-05-27T20:39:37 | 214,092,414 | 0 | 0 |
Apache-2.0
| 2019-10-10T05:14:48 | 2019-10-10T05:14:47 | null |
UTF-8
|
Java
| false | false | 7,311 |
java
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.appconfig.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.appconfig.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* StopDeploymentResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StopDeploymentResultJsonUnmarshaller implements Unmarshaller<StopDeploymentResult, JsonUnmarshallerContext> {
public StopDeploymentResult unmarshall(JsonUnmarshallerContext context) throws Exception {
StopDeploymentResult stopDeploymentResult = new StopDeploymentResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return stopDeploymentResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ApplicationId", targetDepth)) {
context.nextToken();
stopDeploymentResult.setApplicationId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("EnvironmentId", targetDepth)) {
context.nextToken();
stopDeploymentResult.setEnvironmentId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DeploymentStrategyId", targetDepth)) {
context.nextToken();
stopDeploymentResult.setDeploymentStrategyId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ConfigurationProfileId", targetDepth)) {
context.nextToken();
stopDeploymentResult.setConfigurationProfileId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DeploymentNumber", targetDepth)) {
context.nextToken();
stopDeploymentResult.setDeploymentNumber(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("ConfigurationName", targetDepth)) {
context.nextToken();
stopDeploymentResult.setConfigurationName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ConfigurationLocationUri", targetDepth)) {
context.nextToken();
stopDeploymentResult.setConfigurationLocationUri(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ConfigurationVersion", targetDepth)) {
context.nextToken();
stopDeploymentResult.setConfigurationVersion(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Description", targetDepth)) {
context.nextToken();
stopDeploymentResult.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DeploymentDurationInMinutes", targetDepth)) {
context.nextToken();
stopDeploymentResult.setDeploymentDurationInMinutes(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("GrowthType", targetDepth)) {
context.nextToken();
stopDeploymentResult.setGrowthType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("GrowthFactor", targetDepth)) {
context.nextToken();
stopDeploymentResult.setGrowthFactor(context.getUnmarshaller(Float.class).unmarshall(context));
}
if (context.testExpression("FinalBakeTimeInMinutes", targetDepth)) {
context.nextToken();
stopDeploymentResult.setFinalBakeTimeInMinutes(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("State", targetDepth)) {
context.nextToken();
stopDeploymentResult.setState(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("EventLog", targetDepth)) {
context.nextToken();
stopDeploymentResult.setEventLog(new ListUnmarshaller<DeploymentEvent>(DeploymentEventJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("PercentageComplete", targetDepth)) {
context.nextToken();
stopDeploymentResult.setPercentageComplete(context.getUnmarshaller(Float.class).unmarshall(context));
}
if (context.testExpression("StartedAt", targetDepth)) {
context.nextToken();
stopDeploymentResult.setStartedAt(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
}
if (context.testExpression("CompletedAt", targetDepth)) {
context.nextToken();
stopDeploymentResult.setCompletedAt(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return stopDeploymentResult;
}
private static StopDeploymentResultJsonUnmarshaller instance;
public static StopDeploymentResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new StopDeploymentResultJsonUnmarshaller();
return instance;
}
}
|
[
""
] | |
e8e3d54b7bc80a00f1207c3afbc436a4966f5026
|
eabd36fbad0ce4a017930356a79483f5fc5509ae
|
/src/com/domcafe/forms/SplashForm.java
|
82ee48a551e44da68bb883e3d9bd0e9de59c11b4
|
[] |
no_license
|
Akash0803/RestaurantManagment
|
908fa24367731c316cb099a4a149fdca08aec7a2
|
a2b08f2942394dd8548611ddfc25fbb006c8fda2
|
refs/heads/master
| 2023-07-31T19:53:18.588946 | 2021-09-26T17:04:13 | 2021-09-26T17:04:13 | 405,719,839 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 6,605 |
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 com.domcafe.forms;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
*
* @author admin
*/
public class SplashForm extends javax.swing.JFrame {
SplashPanel p1;
Timer t=null;
/**
* Creates new form SplashForm
*/
public SplashForm() {
initComponents();
t=new Timer(90, new ActionListener() {
int i=0;
@Override
public void actionPerformed(ActionEvent e) {
pb1.setValue(i);
i+=1;
if(i>110){
t.stop(); //stop timer
dispose();
LoginForm f=new LoginForm();
f.setVisible(true);
}
}
});
t.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
pb1 = new javax.swing.JProgressBar();
splashPanel1 = new com.domcafe.forms.SplashPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pb1, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pb1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Initialising Database...");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("<html>Domino's Pizza Restraurant Managment System Software<br>\n Version 6.0<br>\n Developed By Maria Inamdar & Shreya Shinde<br>\n<br> Contact:9028287210\nAll Copyrights Reserved Year 2020");
javax.swing.GroupLayout splashPanel1Layout = new javax.swing.GroupLayout(splashPanel1);
splashPanel1.setLayout(splashPanel1Layout);
splashPanel1Layout.setHorizontalGroup(
splashPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(splashPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 224, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))
);
splashPanel1Layout.setVerticalGroup(
splashPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(splashPanel1Layout.createSequentialGroup()
.addGap(0, 121, Short.MAX_VALUE)
.addGroup(splashPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
getContentPane().add(splashPanel1, java.awt.BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SplashForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SplashForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SplashForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SplashForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SplashForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JProgressBar pb1;
private com.domcafe.forms.SplashPanel splashPanel1;
// End of variables declaration//GEN-END:variables
}
|
[
"[email protected]"
] | |
99cf2e0921edb9486aa70e686671faf442162476
|
24c6b6c1b7850583b23f6ec5fbd0558596251803
|
/app/src/main/java/com/savedPhotos/utility/FileUtil.java
|
88d8458019d1e4b77b6caebc12950bb1d2bfacf4
|
[
"MIT"
] |
permissive
|
devman007/Instapic-master
|
2b072ce4184b2bbca1fe2f8b3d78066903b7bf3d
|
5de3af59e5244134c8796b9a6b103d5f680b77bf
|
refs/heads/master
| 2022-06-03T01:12:36.889464 | 2019-01-24T17:30:16 | 2019-01-24T17:30:16 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,034 |
java
|
package com.savedPhotos.utility;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by snowbean on 16-8-5.
*/
public class FileUtil {
private static final String TAG = "FileUtil";
// public static final String FOLDER_NAME = "Selfie With Celebrity";
public static final String FOLDER_NAME = com.rsmapps.selfieall.utility.FileUtil.FOLDER_NAME;
public static String getFolderName(String name) {
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
name);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return "";
}
}
return mediaStorageDir.getAbsolutePath();
}
/**
* 判断sd卡是否可以用
*/
private static boolean isSDAvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static File getNewFile(Context context, String folderName) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
String timeStamp = simpleDateFormat.format(new Date());
String path;
if (isSDAvailable()) {
path = getFolderName(folderName) + File.separator + timeStamp + ".jpg";
} else {
path = context.getFilesDir().getPath() + File.separator + timeStamp + ".jpg";
}
if (TextUtils.isEmpty(path)) {
return null;
}
return new File(path);
}
public static File[] getFileList(Context context) {
String path;
if (isSDAvailable()) {
path = getFolderName(FOLDER_NAME);
} else {
path = context.getFilesDir().getPath();
}
if (TextUtils.isEmpty(path)) {
return null;
}
File directory = new File(path);
File[] files = directory.listFiles();
if (files == null && files.length == 0) {
return null;
}
return files;
}
}
|
[
"[email protected]"
] | |
709edbb25f9c02a5a15c1eb542e0e4f7812c7e63
|
a753c693a9f85ab1bc70284d801f6403d403e21f
|
/app/src/main/java/com/moxi/agenttool/ui/bean/AddCollectionBean.java
|
cbf80562a10c29f4f33475f9b66cc54624930a20
|
[
"Apache-2.0"
] |
permissive
|
subenli115/AgentTool
|
ead6445fa26ee23bfc06fa45ef09c829954384d5
|
63ef76b0ce390331d7cdb863a6391920bc682fb9
|
refs/heads/main
| 2023-07-02T16:44:47.170475 | 2021-08-06T12:44:45 | 2021-08-06T12:44:45 | 392,252,432 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 855 |
java
|
package com.moxi.agenttool.ui.bean;
import java.util.List;
/**
* @ClassName: AddCollectionBean
* @Description: 添加收藏实体
* @Author: join_lu
* @CreateDate: 2021/7/28 14:19
*/
public class AddCollectionBean {
private String clientId;
private String clientUpdateTime;
private List<House> houseList;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientUpdateTime() {
return clientUpdateTime;
}
public void setClientUpdateTime(String clientUpdateTime) {
this.clientUpdateTime = clientUpdateTime;
}
public List<House> getHouseList() {
return houseList;
}
public void setHouseList(List<House> houseList) {
this.houseList = houseList;
}
}
|
[
"[email protected]"
] | |
a04cd80bc35abc6fa041c7c8aa75c674ea4c2f9f
|
c3c2ed58ba86ec3e1bf7ab4a28a1c64e809f8fc7
|
/day02-ControlFlow/src/control/ifstmt/PositiveNegative.java
|
7124bd5bef368f88442788c02b93bb8898dd513d
|
[] |
no_license
|
prosild/academy_java_basic
|
c485cf55b9a81e0eb0906ff12725483486a09c94
|
6e16eb9249923e8ea8c367c9da64b1fad984a0d4
|
refs/heads/master
| 2020-03-22T06:39:53.329096 | 2018-07-20T08:42:33 | 2018-07-20T08:42:33 | 139,649,320 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,228 |
java
|
package control.ifstmt;
import java.util.Scanner;
/**
* 하나의 정수를 입력받아서
* 음수인지, 0인지, 양수인지를
* 판단하는 클래스이다
* -------------------------------------------
* 값의 부호를 판단할 때
* if ~ else if ~ else 구문을 사용
* -------------------------------------------
* @author PC38218
*
*/
public class PositiveNegative {
public static void main(String[] args) {
// 1. 선언
// 입력받을 변수 선언
int input;
// 양수, 0, 음수 결과 판단을 저장할 변수
String result;
// 스캐너 변수 선언
Scanner scan;
// 2. 초기화
// 스캐너 변수 초기화
scan = new Scanner(System.in);
// 스캐너를 사용하여 입력 변수 초기화(입력)
System.out.println("정수 하나를 입력");
input = scan.nextInt();
// 3. 사용
// 입력 값이 저장된 input 변수를 if ~ else if ~ else
// 구문으로 부호 판단
if(input > 0) {
result = "양수";
} else if(input == 0) {
result = "0";
} else {
result = "음수";
}
// 출력
System.out.printf("입력 값 %d는 %s입니다%n", input, result);
}
}
|
[
"[email protected]"
] | |
e7dd6b215eefd149fd8566a1c146cd1d555f8ea1
|
99936ccd0479fc8219314b42a85b5e96d39dd80f
|
/src/main/java/com/subhash/controller/HelloWorldController.java
|
cd0448b46a8f8d90d2143c5ef03907c63426e89f
|
[] |
no_license
|
sanjava85/Helloworld
|
6b2f09c4fb5268e1584c1894937cb3262cf82c0f
|
fcdaf007b4f69f32aaff84797fe86123f242613b
|
refs/heads/master
| 2021-01-20T18:21:02.331132 | 2016-07-08T04:56:57 | 2016-07-08T04:56:57 | 62,859,297 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 691 |
java
|
package com.subhash.controller;
/**
* Created by m481262 on 12/18/15.
*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO SPRING MVC HOW R U";
return new ModelAndView("hellopage", "message", message);
}
@RequestMapping("/subhash")
public ModelAndView welcomeMessage(){
String message = "Hi Subhash Welcome to Spring";
return new ModelAndView("welcome","welcomeMessage",message);
}
}
|
[
"[email protected]"
] | |
c154e37c4ccc2534681501eaff90c5d71713d00c
|
74aadd89668f4fa25e349431f7176b0ecbc856cc
|
/app/src/main/java/com/techcourse/controller/LoginController.java
|
fce596628fc3445d178223a13790e1e0c8f7b4ae
|
[] |
no_license
|
ohjoohyung/jwp-dashboard-jdbc
|
446555f4da94f53a2ca982de737794f112910fe7
|
eef22fd6208591a7cf7033e49f668216dc1b4603
|
refs/heads/main
| 2023-08-22T19:21:29.530790 | 2021-09-16T06:06:06 | 2021-09-16T06:06:06 | 408,100,103 | 0 | 0 | null | 2021-09-19T10:47:30 | 2021-09-19T10:47:29 | null |
UTF-8
|
Java
| false | false | 2,198 |
java
|
package com.techcourse.controller;
import com.techcourse.domain.User;
import com.techcourse.repository.InMemoryUserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import nextstep.mvc.view.JspView;
import nextstep.mvc.view.ModelAndView;
import nextstep.web.annotation.Controller;
import nextstep.web.annotation.RequestMapping;
import nextstep.web.support.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Controller
public class LoginController {
private static final Logger log = LoggerFactory.getLogger(LoginController.class);
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView view(HttpServletRequest request, HttpServletResponse response) {
return UserSession.getUserFrom(request.getSession())
.map(user -> {
log.info("logged in {}", user.getAccount());
return redirect("/index.jsp");
})
.orElse(new ModelAndView(new JspView("/login.jsp")));
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
if (UserSession.isLoggedIn(request.getSession())) {
return redirect("/index.jsp");
}
return InMemoryUserRepository.findByAccount(request.getParameter("account"))
.map(user -> {
log.info("User : {}", user);
return login(request, user);
})
.orElse(redirect("/401.jsp"));
}
private ModelAndView login(HttpServletRequest request, User user) {
if (user.checkPassword(request.getParameter("password"))) {
final HttpSession session = request.getSession();
session.setAttribute(UserSession.SESSION_KEY, user);
return redirect("/index.jsp");
} else {
return redirect("/401.jsp");
}
}
private ModelAndView redirect(String path) {
return new ModelAndView(new JspView(JspView.REDIRECT_PREFIX + path));
}
}
|
[
"[email protected]"
] | |
adf752bf104923090a198338d976c6bfe0f12447
|
8ed0d44d50e0762669a309c4c9a5a3b6694aa128
|
/java/com/google/gerrit/elasticsearch/ElasticQueryAdapter.java
|
05fd7a7afc8d55d1475f719554fe3021bec5093b
|
[
"Apache-2.0"
] |
permissive
|
bbossola/gerrit
|
7b974c028c8278de137c62e34ccbab6dd5bab4e9
|
25828e08e098121c4825c938a8912b4367ede273
|
refs/heads/master
| 2020-04-05T12:57:29.940295 | 2018-11-09T13:59:30 | 2018-11-09T13:59:30 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,952 |
java
|
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.elasticsearch;
import com.google.gson.JsonObject;
public class ElasticQueryAdapter {
static final String POST_V5_TYPE = "_doc";
private final boolean ignoreUnmapped;
private final boolean usePostV5Type;
private final String searchFilteringName;
private final String indicesExistParam;
private final String exactFieldType;
private final String stringFieldType;
private final String indexProperty;
private final String rawFieldsKey;
private final String versionDiscoveryUrl;
ElasticQueryAdapter(ElasticVersion version) {
this.ignoreUnmapped = version == ElasticVersion.V2_4;
this.usePostV5Type = version.isV6();
this.versionDiscoveryUrl = version.isV6() ? "/%s*" : "/%s*/_aliases";
switch (version) {
case V5_6:
case V6_2:
case V6_3:
case V6_4:
this.searchFilteringName = "_source";
this.indicesExistParam = "?allow_no_indices=false";
this.exactFieldType = "keyword";
this.stringFieldType = "text";
this.indexProperty = "true";
this.rawFieldsKey = "_source";
break;
case V2_4:
default:
this.searchFilteringName = "fields";
this.indicesExistParam = "";
this.exactFieldType = "string";
this.stringFieldType = "string";
this.indexProperty = "not_analyzed";
this.rawFieldsKey = "fields";
break;
}
}
void setIgnoreUnmapped(JsonObject properties) {
if (ignoreUnmapped) {
properties.addProperty("ignore_unmapped", true);
}
}
public void setType(JsonObject properties, String type) {
if (!usePostV5Type) {
properties.addProperty("_type", type);
}
}
public String searchFilteringName() {
return searchFilteringName;
}
String indicesExistParam() {
return indicesExistParam;
}
String exactFieldType() {
return exactFieldType;
}
String stringFieldType() {
return stringFieldType;
}
String indexProperty() {
return indexProperty;
}
String rawFieldsKey() {
return rawFieldsKey;
}
boolean usePostV5Type() {
return usePostV5Type;
}
String getType(String preV6Type) {
return usePostV5Type() ? POST_V5_TYPE : preV6Type;
}
String getVersionDiscoveryUrl(String name) {
return String.format(versionDiscoveryUrl, name);
}
}
|
[
"[email protected]"
] | |
6452c07cc3be973931a6c6d54093df979a0bc103
|
6d4d184dda611169fada20f0fc4cf6d9e4fef064
|
/app/src/main/java/com/example/screening_time/Fitur/OrangTua/Sinkronisasi_Ponsel.java
|
45e2c8265b0e38dbf96c2243604c50fb54739380
|
[] |
no_license
|
mrromiardianto/TugasAkhir
|
49154ab258a75a872cac4240dc35d7aa3efde5a9
|
ce943d36bf230fe3c1f96faa20419ca21d14768e
|
refs/heads/master
| 2023-03-20T00:32:57.983382 | 2021-03-23T17:31:08 | 2021-03-23T17:31:08 | 325,998,487 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,385 |
java
|
package com.example.screening_time.Fitur.OrangTua;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.example.screening_time.Controller.Device;
import com.example.screening_time.Model.Model_Device;
import com.example.screening_time.Model.Model_laporantugas;
import com.example.screening_time.Model.Model_tugas;
import com.example.screening_time.R;
import com.example.screening_time.Session.SharedPrefManager;
import com.example.screening_time.Utils.Portrait;
import com.example.screening_time.View.MyDevice;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import java.util.List;
public class Sinkronisasi_Ponsel extends AppCompatActivity implements MyDevice {
SharedPrefManager sharedPrefManager;
ProgressDialog loading;
IntentIntegrator intentIntegrator;
private static final String TAG = Sinkronisasi_Ponsel.class.getSimpleName();
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private FusedLocationProviderClient mFusedLocationClient;
protected Location mLastLocation;
double Latitude;
double Longitude;
Device device;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sinkronisasi__ponsel);
sharedPrefManager=new SharedPrefManager(this);
loading=new ProgressDialog(this);
device=new Device(this);
// Toast.makeText(this, ""+sharedPrefManager.getSPEmail(), Toast.LENGTH_SHORT).show();
checkPermission();
scanow();
}
public void scanow() {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setCaptureActivity(Portrait.class);
integrator.setOrientationLocked(false);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan Barcode Device");
integrator.initiateScan();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Result Not Found", Toast.LENGTH_SHORT).show();
} else {
// formadddevice.setVisibility(View.VISIBLE);
// scanbarcode.setVisibility(View.GONE);
// No_Sn.setText(result.getContents());
Toast.makeText(this, result.getContents(), Toast.LENGTH_SHORT).show();
Sikron(result.getContents(),sharedPrefManager.getSPEmail());
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void Sikron(String contents, String spEmail) {
loading.setMessage("Loading.....");
loading.setCancelable(true);
loading.show();
device.sinkron(contents,spEmail);
}
private void checkPermission() {
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
if (!hasPermissions(Sinkronisasi_Ponsel.this, PERMISSIONS)) {
ActivityCompat.requestPermissions(Sinkronisasi_Ponsel.this, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
@Override
public void listlaporan(List<Model_laporantugas> laporan) {
}
@Override
public void truedata(List<Model_Device> devices) {
}
@Override
public void ImeiTerdaftar(String Message) {
loading.dismiss();
Toast.makeText(this, Message, Toast.LENGTH_SHORT).show();
back();
}
@Override
public void ImeiTidakTerdaftar(String Message) {
loading.dismiss();
Toast.makeText(this, Message, Toast.LENGTH_SHORT).show();
}
@Override
public void NoInternet(String Message) {
loading.dismiss();
Toast.makeText(this, Message, Toast.LENGTH_SHORT).show();
}
@Override
public void suksesgetdata(List<Model_tugas> tugases) {
}
// @Override
// public void suksesgetdata(List<Model_laporantugas> tugases) {
//
// }
@Override
public void onBackPressed() {
super.onBackPressed();
back();
}
private void back() {
Intent menuSebelumnya = new Intent(this, Daftar_Ponsel.class);
startActivity(menuSebelumnya);
finish();
}
}
|
[
"[email protected]"
] | |
7bd9c1c6b420d30dbf6cbbb0be523401aea9d0f2
|
89ae78c0168fcd2dde8698b5af1e37cbdd7f1801
|
/src/appcryptography/PemFileRead.java
|
8a440c91ea18007a9e02d11b798896a025a50c7a
|
[] |
no_license
|
NhanToThanh/AppCryptography
|
10abc6952783803ecc56e8e6ceb67be65142035d
|
e468d3fb8ef97b47214f3a93516e388ac9d77c89
|
refs/heads/master
| 2020-03-22T02:34:57.799574 | 2018-07-02T02:17:43 | 2018-07-02T02:17:43 | 139,379,943 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,188 |
java
|
package appcryptography;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class PemFileRead {
private PemObject pemObject;
public PemFileRead(String filename) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
} finally {
pemReader.close();
}
}
public void write(String filename) throws FileNotFoundException,
IOException {
PemWriter pemWriter = new PemWriter(new OutputStreamWriter(
new FileOutputStream(filename)));
try {
pemWriter.writeObject(this.pemObject);
} finally {
pemWriter.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
|
[
"[email protected]"
] | |
ac8739ba909e23169243d9dfa08bee972bc78602
|
e19cb51301a5be0f9c168260ae9e2d6c4aa57ad2
|
/src/test/java/com/choucair/automatizacion/steps/CambiarDeVentansSteps.java
|
c25e8b414f9ef65efcd1d520fdc721ccddf88fbf
|
[] |
no_license
|
jsandrea/Serenity-2-Web-Package-Utilities
|
2dbffa4473f59e6ddf6c36cc8937b82656f0e2a4
|
8f8ae548bea5b3eeb270b686b9028c7caf32b629
|
refs/heads/master
| 2023-06-02T09:39:36.639691 | 2019-10-19T17:50:32 | 2019-10-19T17:50:32 | 211,526,706 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,052 |
java
|
package com.choucair.automatizacion.steps;
import com.choucair.automatizacion.pages.PopupPage;
import com.choucair.automatizacion.util.web.window.WindowsHandler;
import net.serenitybdd.core.Serenity;
import net.thucydides.core.annotations.Step;
public class CambiarDeVentansSteps {
PopupPage popupPage;
WindowsHandler windowsHandler;
@Step("Cambiar Ventana Emergente")
public void abirVentanaEmergente() {
popupPage.clickHere();
popupPage.waitFor(2).second();
Serenity.takeScreenshot();
}
@Step("Ir a Ventana Principal")
public void irAVentanaPrincipal() {
windowsHandler.gotToMainWindow();
popupPage.waitFor(2).second();
Serenity.takeScreenshot();
}
@Step("Cambiar a Ventana Emergente por Indice")
public void irAVentanaEmergenteConIndice(int indice) {
windowsHandler.goToWindowsByIndex(indice);
popupPage.waitFor(2).second();
Serenity.takeScreenshot();
}
@Step("Cambio a la ultima Ventana")
public void cambioALaUltimaVentana() {
windowsHandler.goToLastWindow();
popupPage.waitFor(2).seconds();
}
}
|
[
"[email protected]"
] | |
f86841319d8ad74dd2e7cac066bdc70ebafef036
|
b83f809eda17821be046f05eee1125b4cf3c6033
|
/src/main/java/com/yqvod/vo/FilmDetailVo.java
|
4386a2f958e636391f8096cb2bd0ad07b869ff48
|
[] |
no_license
|
yqvodhappy/yqvod
|
303a646baaeae957bc303670b8543702cdf52329
|
5fc2ae0f13fc2251f8c8a884972efe3d5f4c3f36
|
refs/heads/master
| 2022-12-20T05:29:45.364632 | 2019-11-30T12:46:13 | 2019-11-30T12:46:13 | 214,388,268 | 0 | 0 | null | 2022-12-05T23:45:21 | 2019-10-11T08:48:30 |
Java
|
UTF-8
|
Java
| false | false | 2,937 |
java
|
package com.yqvod.vo;
import java.math.BigDecimal;
/**
* @ClassName $ {NAME}
* @Description TODO
* @Author fjw
* @Date 2019/10/21 4:30 PM
* @Version 1.0
**/
public class FilmDetailVo {
private Integer id;
private Integer categoryId;
private String name;
private String subtitle;
private String mainImage;
private String subImages;
private String filmUrl;
private String detail;
private String source;
private Integer count;
private Integer status;
private String createTime;
private String updateTime;
private String imageHost;
private Integer parentCategoryId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getMainImage() {
return mainImage;
}
public void setMainImage(String mainImage) {
this.mainImage = mainImage;
}
public String getSubImages() {
return subImages;
}
public void setSubImages(String subImages) {
this.subImages = subImages;
}
public String getFilmUrl() {
return filmUrl;
}
public void setFilmUrl(String filmUrl) {
this.filmUrl = filmUrl;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getImageHost() {
return imageHost;
}
public void setImageHost(String imageHost) {
this.imageHost = imageHost;
}
public Integer getParentCategoryId() {
return parentCategoryId;
}
public void setParentCategoryId(Integer parentCategoryId) {
this.parentCategoryId = parentCategoryId;
}
}
|
[
"[email protected]"
] | |
391bf29f3ca0df8a22cfb5ccf0b748fd42b270ed
|
54d5d44878fe8968feeb1311bf4c56830e6de15f
|
/src/main/java/co/com/ceiba/autocine/infraestructura/persistencia/repositorio/jpa/RepositorioUsuarioJPA.java
|
d46f6b9e062080b38b2e3663e522b255274703b1
|
[] |
no_license
|
rquirpa-csh/autocine
|
76d63acb79a9a60c3cd94885b2d9d40637cb7a5d
|
c365b6fb00558ad1476bd5a3710bd6af3ef85b4b
|
refs/heads/master
| 2022-12-27T05:37:57.698811 | 2020-10-13T16:30:41 | 2020-10-13T16:30:41 | 300,643,255 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 526 |
java
|
package co.com.ceiba.autocine.infraestructura.persistencia.repositorio.jpa;
import co.com.ceiba.autocine.infraestructura.persistencia.entidad.EntidadUsuario;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RepositorioUsuarioJPA extends CrudRepository<EntidadUsuario, Long> {
@Query("from usuarios x where x.correo = ?1")
EntidadUsuario obtenerPorCorreo(String correo);
}
|
[
"csh*736341"
] |
csh*736341
|
16a987f6c2362e3f464f77de62c25f651fc89321
|
67d2012905d2f2d9cc1be870241d871032dbb82f
|
/app/src/test/java/se/oakbright/modules/internalpoints/MiddlePointTest.java
|
c6aba14d71108b0ee92b0f80060b87313af1beca
|
[] |
no_license
|
Hampuse/PlanetWhite
|
f48fbdce3d41425a42a3e20f48ed164f64835478
|
de0ccd9671839ee78da2723956331e7cd8002e18
|
refs/heads/master
| 2020-04-16T09:55:08.437016 | 2015-08-12T16:52:45 | 2015-08-12T16:52:45 | 40,612,187 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,033 |
java
|
package se.oakbright.modules.internalpoints;
import org.junit.Before;
import org.junit.Test;
import se.oakbright.modules.internalpoints.MiddlePoint;
import se.oakbright.modules.helpers.Positioner;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Created by hampuse on 2015-07-08.
*/
public class MiddlePointTest {
MiddlePoint middlePoint;
@Before
public void setup(){
MiddlePoint.Builder middlePointBuilder = new MiddlePoint.Builder();
Positioner positioner = new Positioner();
positioner.setPosition(5,4);
middlePointBuilder.positionerBuilder = mock(Positioner.Builder.class);
when(middlePointBuilder.positionerBuilder.getBuilt()).thenReturn(positioner);
middlePoint = middlePointBuilder.getBuilt();
}
@Test
public void testX(){
assertEquals(5, middlePoint.x());
}
@Test
public void testY(){
assertEquals(4, middlePoint.y());
}
}
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.