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
4e947393b52dd93814acc82ad8023809230a8ea0
b4aaa7906e6d1d52e9d258e918f4788893c3ef40
/edu.udel.udse.jdt.astsimple/src/edu/udel/udse/jdt/astsimple/handlers/ASTViewerHandler.java
bc31567c7e86489f494658b25cd55cfb8376134c
[]
no_license
irenelizeth/jdt_practice
0a43e703b39f51ff2b4bbb7d90ab4f6981579dd0
b166c19f78267e667f05c2a43b1425d1cdc4fa95
refs/heads/master
2020-12-25T13:23:57.215727
2016-07-22T20:39:32
2016-07-22T20:39:32
63,981,716
0
0
null
null
null
null
UTF-8
Java
false
false
837
java
package edu.udel.udse.jdt.astsimple.handlers; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.jface.dialogs.MessageDialog; /** * Our sample handler extends AbstractHandler, an IHandler base class. * @see org.eclipse.core.commands.IHandler * @see org.eclipse.core.commands.AbstractHandler */ public class ASTViewerHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Astsimple", "AST viewer"); return null; } }
[ "imanotas@udel.edu" ]
imanotas@udel.edu
9ef68e549a7390159c634e04aaa062acb62b2c78
81ba543811bfffb16731c334793dc883c7d92e9f
/src/main/java/head_01/demo_db/Conn.java
aadabbfab6eb55bbb8ba5676065d2163e90993d5
[]
no_license
lrutivi/HeadFirstSQL-1
3a8d926d9630b4d5d50a788f048e31b7a8a76254
c96a9e978a6b55135e8c5cd85eb5e6eb1aa8f6d9
refs/heads/master
2020-06-24T15:29:57.989781
2017-09-11T17:57:16
2017-09-11T17:57:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,247
java
package head_01.demo_db; import java.sql.*; public class Conn { public static Connection conn; public static Statement statmt; public static ResultSet resSet; private static final String URL="jdbc:mysql://localhost:3306/headfirstsql"; private static final String USERNAME="root"; private static final String PASSWORD="root"; // --------ПОДКЛЮЧЕНИЕ К БАЗЕ ДАННЫХ-------- public static void Conn() throws ClassNotFoundException, SQLException { conn = null; conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); statmt = conn.createStatement(); System.out.println("База Подключена!"); } // --------Создание таблицы-------- public static void CreateDB() throws ClassNotFoundException, SQLException { statmt.execute("CREATE TABLE users (id INT(20), name VARCHAR(50), phone INT(20));"); System.out.println("Таблица создана или уже существует."); } // --------Заполнение таблицы-------- public static void WriteDB() throws SQLException { statmt.execute("INSERT INTO users (id, name, phone) VALUES (12,'Petya', 125453); "); System.out.println("Таблица заполнена"); } // -------- Вывод таблицы-------- public static void ReadDB() throws ClassNotFoundException, SQLException { resSet = statmt.executeQuery("SELECT * FROM users"); while(resSet.next()) { int id = resSet.getInt("id"); String name = resSet.getString("name"); String phone = resSet.getString("phone"); System.out.println( "ID = " + id ); System.out.println( "name = " + name ); System.out.println( "phone = " + phone ); System.out.println(); } System.out.println("Таблица выведена"); } // --------Закрытие-------- public static void CloseDB() throws ClassNotFoundException, SQLException { conn.close(); statmt.close(); resSet.close(); System.out.println("Соединения закрыты"); } }
[ "timon2@ukr.net" ]
timon2@ukr.net
5f0f885aa4cbcdf514d9cc805163fb18d0496e89
66bcb983f6ed34a6d742b2af4e0aa41e45c89fcc
/a/src/be/ac/kuleuven/cs/ttm/transformer/dataflow/analyzer/Switch.java
d3092a57285ba610662149c4e64760cb89388781
[]
no_license
vmram87/raytracempj
d3be7a4bb89a01746c0122d4154221a88d197351
b3f42c06afb459b4a49daaeeb1be8b37d0426879
refs/heads/master
2021-01-10T01:32:29.222948
2010-11-05T04:10:14
2010-11-05T04:10:14
48,790,897
0
0
null
null
null
null
UTF-8
Java
false
false
1,340
java
/** This file is part of the BRAKES framework v0.3 * Developed by: * Distributed Systems and Computer Networks Group (DistriNet) * Katholieke Universiteit Leuven * Department of Computer Science * Celestijnenlaan 200A * 3001 Leuven (Heverlee) * Belgium * Project Manager and Principal Investigator: * Pierre Verbaeten(pv@cs.kuleuven.ac.be) * Licensed under the Academic Free License version 1.1 (see COPYRIGHT) */ package be.ac.kuleuven.cs.ttm.transformer.dataflow.analyzer; import be.ac.kuleuven.cs.ttm.transformer.dataflow.Stack; import be.ac.kuleuven.cs.ttm.transformer.dataflow.Frame; import de.fub.bytecode.generic.Type; import de.fub.bytecode.generic.InstructionHandle; import de.fub.bytecode.generic.Select; import de.fub.bytecode.generic.MethodGen; import java.util.Vector; class Switch extends Branch { Switch() { super(new Type[] { Type.INT } ); } Vector execute(MethodGen mGen, InstructionHandle ins, Stack s, Frame f) { System.out.println("&&&&&&&& " + ins); System.out.println(s); System.out.println(f); Vector v = super.execute(mGen,ins,s,f); Select swIns = (Select) ins.getInstruction(); InstructionHandle[] targets = swIns.getTargets(); for (int i = 0; i < targets.length; i++) v.addElement(targets[i]); return v; } }
[ "jinqing808@190398b0-3e5a-db71-e392-7b5dfaa953ca" ]
jinqing808@190398b0-3e5a-db71-e392-7b5dfaa953ca
de9c8660a45505c5d3826bd15b5c14f829af85d1
55d75bfdb44754accd63e44c2d3af494e90c5e15
/src/com/cjn/proxy/demo2/Proxy.java
4f0fa1ce9ad6e3d0a134463b5633d5e8b3ef8f33
[]
no_license
cjn93/designPattern
b1033977877e451d6404c152ee49b6f8ee9d527c
b195fe2a739991872d6bae87056776efb66ac348
refs/heads/master
2020-03-18T19:06:37.455668
2018-05-28T08:44:31
2018-05-28T08:44:31
135,134,459
1
0
null
null
null
null
UTF-8
Java
false
false
452
java
package com.cjn.proxy.demo2; /** *@author cjn *@version 1.0 *@date 2018年5月24日 上午10:19:01 *@remark 只有代理的 追求者 * **/ public class Proxy implements GiveGift { Pursuit gg;//zhuojiayi SchoolGirl mm; public Proxy(SchoolGirl mm) { // TODO Auto-generated constructor stub gg = new Pursuit(mm); } @Override public void giveDolls(){ gg.giveDolls(); } @Override public void giveFlower(){ gg.giveFlower(); } }
[ "cjn93@qq.com" ]
cjn93@qq.com
90d82f108081023c07c1416b5f59fa239ebdf698
ba8ec6f1c97606011bcdcd0d44d31f6e22bf91fc
/Person.java
a0f339e4822d6c2277df12792fac835ea7c96c1e
[]
no_license
apoorvak1997/Employee-timesheet
4570ef1983f9f032c5ac72bf54d75cdeb41a8f48
2ad799d216b780a80a0531d73a38f1c930e06b0f
refs/heads/master
2022-12-19T01:50:05.752193
2020-09-15T06:02:01
2020-09-15T06:02:01
295,629,655
0
0
null
null
null
null
UTF-8
Java
false
false
93
java
package csye6200.neu.edu; public abstract class Person { private String Name; }
[ "noreply@github.com" ]
noreply@github.com
b4ab42e9dddc4a03b64f4f780c9d5a24626cd72a
d6eb6ec34d7945141de04743260aef9663a20d2f
/flow/modules/Skeletonize.java
5fa381f377d0623ad5fd5d34d75196ce0603d5b8
[ "Apache-2.0" ]
permissive
fourks/flow
62f982181ec8a620259f466f5d0fbba840846e78
6ad55314aba8ecbde80c1a7c9fb0a460b7b8ee7d
refs/heads/master
2020-05-15T14:49:35.375109
2019-03-16T21:02:14
2019-03-16T21:02:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,237
java
// Copyright 2018 by George Mason University // Licensed under the Apache 2.0 License package flow.modules; import flow.*; /** A Unit which strips out partials based on their distance from the nearest highest-amplitude partial. The further a partial is from the the nearest peak partial, the more its amplitude will be cut down, in an exponential distance fashion. CUT determines the strength of the cut-down: at its extreme, all partials other than the local peaks are eliminated entirely. <p>If you're wondering where this term came from, see <a href="https://en.wikipedia.org/wiki/Topological_skeleton">here</a>. */ public class Skeletonize extends Unit { private static final long serialVersionUID = 1; public static final int MOD_CUT = 0; public Skeletonize(Sound sound) { super(sound); defineInputs( new Unit[] { Unit.NIL }, new String[] { "Input" }); defineModulations(new Constant[] { Constant.ZERO }, new String[] { "Cut" }); } public void go() { super.go(); pushFrequencies(0); copyAmplitudes(0); double[] amplitudes = getAmplitudes(0); double cut = 1.0 - modulate(MOD_CUT); double[] upcuts = new double[amplitudes.length]; double[] downcuts = new double[amplitudes.length]; double c = 1.0; upcuts[0] = c; for(int i = 1; i < amplitudes.length; i++) { if (amplitudes[i] <= amplitudes[i - 1]) { c *= cut; } else { c = 1.0; } upcuts[i] = c; } c = 1.0; downcuts[amplitudes.length - 1] = c; for(int i = amplitudes.length - 2; i >= 0; i--) { if (amplitudes[i] <= amplitudes[i + 1]) { c *= cut; } else { c = 1.0; } downcuts[i] = c; } for(int i = 0; i < amplitudes.length; i++) { amplitudes[i] = amplitudes[i] * Math.min(upcuts[i], downcuts[i]); } constrain(); } }
[ "34138957+SeanLuke@users.noreply.github.com" ]
34138957+SeanLuke@users.noreply.github.com
8ecb2c620f5d2ba95bff09c2fbee7eb7e2bbb71c
59cdc79432a4a2ac315de09463c700f5508404a9
/app/src/androidTest/java/com/bwei/newhan/ExampleInstrumentedTest.java
bad6cae1e1ded1bb89d25b9acc597f1bfc094058
[]
no_license
Hanleixin/JiangNan
378774aab70fabecfefd7dc9d41b8d61f6d76cd1
c3bd5677ce6bb48b0e5a97e811fe87be17f4a2fd
refs/heads/master
2021-01-17T09:23:04.675396
2017-03-05T16:03:41
2017-03-05T16:03:41
83,983,068
0
0
null
null
null
null
UTF-8
Java
false
false
734
java
package com.bwei.newhan; 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("com.bwei.newhan", appContext.getPackageName()); } }
[ "leixinhan@foxmail.com" ]
leixinhan@foxmail.com
e1a84c6fc723d5142802340b8195942f6edc6951
2a66ed109c6b122166777c36cba2155a2a7cdf61
/src/main/java/pe/ventas2020/daoImpl/UsuarioDaoImpl.java
af89a0be06d0d9b557efa4375f761091113c1a54
[]
no_license
dreyna/ventas2020
422ea74e453160d9fb3cb0e78bb23c123f75fb54
2b16703d86b600aead5afdbed09f49859ea3299c
refs/heads/master
2022-12-24T15:31:14.709791
2020-10-13T19:45:03
2020-10-13T19:45:03
303,811,623
0
0
null
null
null
null
UTF-8
Java
false
false
670
java
package pe.ventas2020.daoImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import pe.ventas2020.dao.UsuarioDao; import pe.ventas2020.entity.Usuario; @Repository public class UsuarioDaoImpl implements UsuarioDao{ @Autowired private JdbcTemplate jdbcTemplate; @Override public Usuario read(String nomuser) { String SQL = "select *from usuario where nomuser=?"; return jdbcTemplate.queryForObject(SQL, new Object[] {nomuser}, new BeanPropertyRowMapper<Usuario>(Usuario.class)); } }
[ "dreyna@DESKTOP-JA7PVTB" ]
dreyna@DESKTOP-JA7PVTB
b94dab2dc4da40d5046747d588919a6b4619e634
b56e02d2aedf73ddd29187320532a292d7635560
/statemachine/src/main/java/com/polidea/statemachine/log/LogHandler.java
8c33b2671b6563a2127d8195dcc818ee9edaed11
[ "MIT" ]
permissive
kwoylie/state-machine-android
2c7f517a4de6ce8a9932251cf32e50879964c745
8db959075a9c9fd0965af9775e4dce995b948a3d
refs/heads/master
2021-01-14T14:01:48.891764
2016-07-29T13:33:12
2016-07-29T13:33:12
64,478,182
0
0
null
2016-07-29T12:17:05
2016-07-29T12:17:03
Java
UTF-8
Java
false
false
330
java
package com.polidea.statemachine.log; public interface LogHandler { void d(String tag, String message); void i(String tag, String message); void v(String tag, String message); void w(String tag, String message); void e(String tag, String message); void e(String tag, String message, Throwable e); }
[ "pawel.janeczek@polidea.com" ]
pawel.janeczek@polidea.com
4797f1c1e46cc26c2a4a3d0dbdc70242c8a7f485
ea6e3c324cf36d9b59a14598bb619a7a8f14329e
/workflow/automatiko-workflow-serverless/src/main/java/io/automatiko/engine/workflow/serverless/ServerlessProcessInstance.java
c0ca62aeffcff74344615733224db1cd7795174f
[ "Apache-2.0" ]
permissive
automatiko-io/automatiko-engine
9eaf3a8f5945e645ca704aa317c97c32ea4011da
af7e315d73895798b8b8bdd0fa5d7fcce64d289d
refs/heads/main
2023-08-24T21:25:17.045726
2023-08-16T08:20:56
2023-08-16T08:41:53
332,492,696
60
7
Apache-2.0
2023-09-14T00:44:40
2021-01-24T16:06:36
Java
UTF-8
Java
false
false
11,013
java
package io.automatiko.engine.workflow.serverless; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import io.automatiko.engine.api.Model; import io.automatiko.engine.api.auth.AccessPolicy; import io.automatiko.engine.api.runtime.process.ProcessRuntime; import io.automatiko.engine.api.runtime.process.WorkflowProcessInstance; import io.automatiko.engine.api.workflow.ArchiveBuilder; import io.automatiko.engine.api.workflow.ArchivedProcessInstance; import io.automatiko.engine.api.workflow.EndOfInstanceStrategy; import io.automatiko.engine.api.workflow.ExportedProcessInstance; import io.automatiko.engine.api.workflow.Process; import io.automatiko.engine.api.workflow.ProcessInstance; import io.automatiko.engine.api.workflow.ProcessInstanceReadMode; import io.automatiko.engine.api.workflow.ProcessInstances; import io.automatiko.engine.api.workflow.Signal; import io.automatiko.engine.api.workflow.Tags; import io.automatiko.engine.api.workflow.WorkItem; import io.automatiko.engine.api.workflow.workitem.Policy; import io.automatiko.engine.api.workflow.workitem.Transition; import io.automatiko.engine.workflow.AbstractProcess; import io.automatiko.engine.workflow.AbstractProcessInstance; import io.automatiko.engine.workflow.process.core.node.SubProcessNode; import io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl; import io.automatiko.engine.workflow.process.instance.node.LambdaSubProcessNodeInstance; public class ServerlessProcessInstance extends AbstractProcessInstance<ServerlessModel> { public ServerlessProcessInstance(AbstractProcess<ServerlessModel> process, ServerlessModel variables, ProcessRuntime rt) { super(process, variables, rt); } public ServerlessProcessInstance(AbstractProcess<ServerlessModel> process, ServerlessModel variables, String businessKey, ProcessRuntime rt) { super(process, variables, businessKey, rt); } public ServerlessProcessInstance(AbstractProcess<ServerlessModel> process, ServerlessModel variables, ProcessRuntime rt, WorkflowProcessInstance wpi, long versionTrack) { super(process, variables, rt, wpi, versionTrack); } public ServerlessProcessInstance(AbstractProcess<ServerlessModel> process, ServerlessModel variables, WorkflowProcessInstance wpi) { super(process, variables, wpi); } @Override protected Map<String, Object> bind(ServerlessModel variables) { if (variables == null) { return null; } return variables.toMap(); } @Override protected void unbind(ServerlessModel variables, Map<String, Object> vmap) { if (variables == null || vmap == null) { return; } variables.fromMap(vmap); } @Override protected void configureLock(String businessKey) { // do nothing on raw bpmn process instance - meaning it disables locking on process instance level } @Override public Collection<ProcessInstance<? extends Model>> subprocesses() { Collection<ProcessInstance<? extends Model>> subprocesses = ((WorkflowProcessInstanceImpl) processInstance()) .getNodeInstances(true) .stream() .filter(ni -> ni instanceof LambdaSubProcessNodeInstance) .map(ni -> new SubProcessInstanceMock<ServerlessModel>( ((LambdaSubProcessNodeInstance) ni).getProcessInstanceId(), ((SubProcessNode) ni.getNode()).getProcessId(), ((SubProcessNode) ni.getNode()).getProcessName(), ((LambdaSubProcessNodeInstance) ni).getTriggerTime())) .collect(Collectors.toList()); return subprocesses; } private static class SubProcessInstanceMock<ServerlessModel> implements ProcessInstance<ServerlessModel> { private String instanceId; private String processId; private String description; private Date startDate; public SubProcessInstanceMock(String instanceId, String processId, String description, Date startDate) { this.instanceId = instanceId; this.processId = processId; this.description = description == null ? "" : description; this.startDate = startDate; } @Override public Process process() { return new Process<ServerlessModel>() { @Override public ProcessInstance<ServerlessModel> createInstance(ServerlessModel workingMemory) { return null; } @Override public ProcessInstance<ServerlessModel> createInstance(String businessKey, ServerlessModel workingMemory) { return null; } @Override public ProcessInstances<ServerlessModel> instances() { return null; } @Override public <S> void send(Signal<S> sig) { } @Override public ProcessInstance<? extends Model> createInstance(Model m) { return null; } @Override public ProcessInstance<? extends Model> createInstance(String businessKey, Model m) { return null; } @Override public String id() { return processId; } @Override public String name() { return null; } @Override public String description() { return null; } @Override public String version() { return null; } @Override public void activate() { } @Override public void deactivate() { } @Override public ServerlessModel createModel() { return null; } @Override public AccessPolicy<? extends ProcessInstance<ServerlessModel>> accessPolicy() { return null; } @Override public ExportedProcessInstance exportInstance(String id, boolean abort) { return null; } @Override public ProcessInstance<ServerlessModel> importInstance(ExportedProcessInstance instance) { return null; } @Override public ArchivedProcessInstance archiveInstance(String id, ArchiveBuilder builder) { return null; } @Override public EndOfInstanceStrategy endOfInstanceStrategy() { return null; } }; } @Override public void start() { } @Override public void start(String trigger, String referenceId, Object data) { } @Override public void startFrom(String nodeId) { } @Override public void startFrom(String nodeId, String referenceId) { } @Override public void send(Signal signal) { } @Override public void abort() { } @Override public ServerlessModel variables() { return null; } @Override public void updateVariables(Object updates) { } @Override public int status() { return 1; } @Override public Collection subprocesses() { return null; } @Override public void completeWorkItem(String id, Map variables, Policy... policies) { } @Override public void abortWorkItem(String id, Policy... policies) { } @Override public void failWorkItem(String id, Throwable error) { } @Override public void transitionWorkItem(String id, Transition transition) { } @Override public WorkItem workItem(String workItemId, Policy... policies) { return null; } @Override public List workItems(Policy... policies) { return null; } @Override public String id() { return instanceId; } @Override public String businessKey() { return null; } @Override public String description() { return description; } @Override public String parentProcessInstanceId() { return null; } @Override public String rootProcessInstanceId() { return null; } @Override public String rootProcessId() { return null; } @Override public Date startDate() { return startDate; } @Override public Date endDate() { return null; } @Override public Date expiresAtDate() { return null; } @Override public Optional errors() { return null; } @Override public void triggerNode(String nodeId) { } @Override public void cancelNodeInstance(String nodeInstanceId) { } @Override public void retriggerNodeInstance(String nodeInstanceId) { } @Override public Set events() { return null; } @Override public Collection milestones() { return null; } @Override public Collection adHocFragments() { return null; } @Override public void disconnect() { } @Override public Tags tags() { return null; } @Override public Optional<String> initiator() { return null; } @Override public String image(String path) { return null; } @Override public ArchivedProcessInstance archive(ArchiveBuilder builder) { return null; } @Override public Collection<ProcessInstance<? extends Model>> subprocesses(ProcessInstanceReadMode mode) { return null; } @Override public String abortCode() { return null; } @Override public Object abortData() { return null; } } }
[ "swiderski.maciej@gmail.com" ]
swiderski.maciej@gmail.com
7c48285a9497a54d70e78f6c06e3210927240b46
50da4738f4f301a239858f02f8d5f4126cb4127f
/src/main/java/com/amazonaws/services/identitymanagement/model/CreateLoginProfileRequest.java
920958f078636d9153cfdf2abf255d30ed26402f
[ "JSON", "Apache-2.0" ]
permissive
scode/aws-sdk-for-java
f9e2d8ca181a1d56ba163c029ff90c52424f10a7
c0bbbf7e6a6c0953e67b925c0b0732b264e87c33
refs/heads/master
2021-01-18T05:50:03.373152
2011-08-30T20:03:45
2011-08-30T20:03:45
2,297,200
0
1
null
null
null
null
UTF-8
Java
false
false
5,800
java
/* * Copyright 2010-2011 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.identitymanagement.model; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.identitymanagement.AmazonIdentityManagement#createLoginProfile(CreateLoginProfileRequest) CreateLoginProfile operation}. * <p> * Creates a login profile for the specified User, giving the User the * ability to access AWS services such as the AWS Management Console. * For more information about login profiles, see <a * .com/IAM/latest/UserGuide/index.html?Using_ManagingLoginsAndMFA.html"> * Managing Login Profiles and MFA Devices </a> in <i>Using AWS Identity * and Access Management</i> . * </p> * * @see com.amazonaws.services.identitymanagement.AmazonIdentityManagement#createLoginProfile(CreateLoginProfileRequest) */ public class CreateLoginProfileRequest extends AmazonWebServiceRequest { /** * Name of the User to create a login profile for. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> */ private String userName; /** * The new password for the User name. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> */ private String password; /** * Default constructor for a new CreateLoginProfileRequest object. Callers should use the * setter or fluent setter (with...) methods to initialize this object after creating it. */ public CreateLoginProfileRequest() {} /** * Constructs a new CreateLoginProfileRequest object. * Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param userName Name of the User to create a login profile for. * @param password The new password for the User name. */ public CreateLoginProfileRequest(String userName, String password) { this.userName = userName; this.password = password; } /** * Name of the User to create a login profile for. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @return Name of the User to create a login profile for. */ public String getUserName() { return userName; } /** * Name of the User to create a login profile for. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param userName Name of the User to create a login profile for. */ public void setUserName(String userName) { this.userName = userName; } /** * Name of the User to create a login profile for. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param userName Name of the User to create a login profile for. * * @return A reference to this updated object so that method calls can be chained * together. */ public CreateLoginProfileRequest withUserName(String userName) { this.userName = userName; return this; } /** * The new password for the User name. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> * * @return The new password for the User name. */ public String getPassword() { return password; } /** * The new password for the User name. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> * * @param password The new password for the User name. */ public void setPassword(String password) { this.password = password; } /** * The new password for the User name. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/> * * @param password The new password for the User name. * * @return A reference to this updated object so that method calls can be chained * together. */ public CreateLoginProfileRequest withPassword(String password) { this.password = password; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("UserName: " + userName + ", "); sb.append("Password: " + password + ", "); sb.append("}"); return sb.toString(); } }
[ "aws-dr-tools@amazon.com" ]
aws-dr-tools@amazon.com
f5ba2aa0d204a7adacdab626fe6a2b744e115f07
3be69f34a096efa23378a4b25b66fe9dcd675cb2
/src/main/java/com/lmiky/cms/directory/pojo/CmsDirectory.java
fbcc51648a31d465d73b822930bc4ed7ff42efea
[]
no_license
linminqin/lmiky_hibernate
cf2a70cbc36857459ae1f3a844c8a35068a2094b
78e0a441455234034a291eaf73582d3100a4ebee
refs/heads/master
2021-01-23T09:52:36.129123
2014-09-13T04:08:43
2014-09-13T04:08:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
465
java
package com.lmiky.cms.directory.pojo; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.lmiky.jdp.tree.pojo.BaseTreePojo; /** * 目录 * @author lmiky * @date 2014-1-2 */ @Entity @Table(name="t_cms_directory") @PrimaryKeyJoinColumn(name="id") public class CmsDirectory extends BaseTreePojo { private static final long serialVersionUID = -2234133455649348507L; }
[ "flylmiky@gmail.com" ]
flylmiky@gmail.com
178a422ddbc4c56a95e6801d9702d39d09e65106
7dcb48de8406388e17f46911e4304f1e82cdaa52
/server2/src/main/java/com/evoupsight/monitorpass/server/cache/impl/ServerCacheImpl.java
50998ac6986980991858d9ea79b8eded252ddd94
[]
no_license
evoup/monitor_pass
eadd80d7bc3c6876310efb4fff43523019ab0a63
b7018a9357a7d71acd1cd5eb0b8e0f6dc8016a88
refs/heads/master
2022-06-24T11:20:38.248256
2019-10-21T04:30:45
2019-10-21T04:33:56
96,863,608
0
0
null
2022-06-21T01:46:32
2017-07-11T07:23:05
C
UTF-8
Java
false
false
5,311
java
package com.evoupsight.monitorpass.server.cache.impl; import com.evoupsight.monitorpass.server.cache.ServerCache; import com.evoupsight.monitorpass.server.constants.Constants; import com.evoupsight.monitorpass.server.dao.mapper.RelationServerServerGroupMapper; import com.evoupsight.monitorpass.server.dao.mapper.RelationTemplateServerGroupMapper; import com.evoupsight.monitorpass.server.dao.mapper.ServerMapper; import com.evoupsight.monitorpass.server.dao.mapper.TemplateMapper; import com.evoupsight.monitorpass.server.dao.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Repository; import java.util.*; import static com.evoupsight.monitorpass.server.constants.CacheConstants.CACHE_MANAGER_GUAVA; import static com.evoupsight.monitorpass.server.constants.CacheConstants.CACHE_MANAGER_GUAVA_EVENT; /** * @author evoup */ @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Repository public class ServerCacheImpl implements ServerCache { private static final String CACHE_NAME = "com.evoupsight.monitorpass.server.cache.impl.ServerCacheImpl"; private static final Logger LOG = LoggerFactory.getLogger(ServerCacheImpl.class); @Autowired ServerMapper serverMapper; @Autowired TemplateMapper templateMapper; @Autowired RelationTemplateServerGroupMapper relationTemplateServerGroupMapper; @Autowired RelationServerServerGroupMapper relationServerServerGroupMapper; @Override @Cacheable(value = CACHE_NAME, key = "#root.targetClass", unless = "#result == null", cacheManager = CACHE_MANAGER_GUAVA) public List<Server> fetchAll() { ServerExample serverExample = new ServerExample(); serverExample.createCriteria().andIdGreaterThan(0); return serverMapper.selectByExample(serverExample); } @Override @Cacheable(value = CACHE_NAME, key = "#root.targetClass+'-'+ #id", unless = "#result == null", condition = "#id != null", cacheManager = CACHE_MANAGER_GUAVA) public List<Server> getByTemplate(Long id) { TemplateExample templateExample = new TemplateExample(); templateExample.createCriteria().andIdEqualTo(id); List<Template> templates = templateMapper.selectByExample(templateExample); List<RelationTemplateServerGroup> relationTemplateServerGroups = new ArrayList<>(); templates.stream().filter(Objects::nonNull).forEach(t -> { // 根据templates找对应的服务器组 RelationTemplateServerGroupExample relationTemplateServerGroupExample = new RelationTemplateServerGroupExample(); relationTemplateServerGroupExample.createCriteria().andIdEqualTo(t.getId().intValue()); relationTemplateServerGroups.addAll(relationTemplateServerGroupMapper.selectByExample(relationTemplateServerGroupExample)); }); Set<Server> serverSets = new HashSet<>(); // 根据服务器组找服务器 relationTemplateServerGroups.stream().filter(Objects::nonNull).forEach(g -> { RelationServerServerGroupExample relationServerServerGroupExample = new RelationServerServerGroupExample(); relationServerServerGroupExample.createCriteria().andServergroupIdEqualTo(g.getId()); List<RelationServerServerGroup> relationServerServerGroups = relationServerServerGroupMapper.selectByExample(relationServerServerGroupExample); relationServerServerGroups.stream().filter(Objects::nonNull).forEach(r -> { Server server = serverMapper.selectByPrimaryKey(r.getServerId()); Optional.ofNullable(server).ifPresent(s -> { if (!new Integer(Constants.ServerStatus.NOT_MONITORING.ordinal()).equals(s.getId())) { serverSets.add(s); } }); }); }); return new ArrayList<>(serverSets); } /** * 设置在线 */ @Override @Cacheable(value = CACHE_NAME, key = "#root.targetClass+'-host_on-'+ #hostId", unless = "#result == null", condition = "#hostId != null", cacheManager = CACHE_MANAGER_GUAVA_EVENT) public String makeUp(Integer hostId) { Server server = new Server(); server.setId(hostId); server.setStatus(Constants.ServerStatus.ON.ordinal()); serverMapper.updateByPrimaryKeySelective(server); return "ok"; } /** * 设置宕机 */ @Override @Cacheable(value = CACHE_NAME, key = "#root.targetClass+'-host_down-'+ #hostId", unless = "#result == null", condition = "#hostId != null", cacheManager = CACHE_MANAGER_GUAVA_EVENT) public String makeDown(Integer hostId) { Server record = serverMapper.selectByPrimaryKey(hostId); if (record != null) { if (System.currentTimeMillis() - record.getLastOnline().getTime() > 300000) { Server server = new Server(); server.setId(hostId); server.setStatus(Constants.ServerStatus.DOWN.ordinal()); serverMapper.updateByPrimaryKeySelective(server); } } return "ok"; } }
[ "evoex123@gmail.com" ]
evoex123@gmail.com
7188c6cd260ebae4a37bdf7a327c0d03493dd971
78c166c4dc3b65c14f708a08a7eea35a18b8cbbd
/components/org.wso2.carbon.identity.api.dispatcher/src/main/java/org/wso2/carbon/identity/api/dispatcher/DefaultExceptionMapper.java
4b8c38d45ad8330205f96e5771d175be7f54c57a
[ "Apache-2.0" ]
permissive
somindatommy/identity-rest-dispatcher
405ee42272ad60b2aec26ce5c65980a591be86ea
8c282d45179b826eb01f8b75c01e8c9599119d57
refs/heads/master
2021-07-25T15:13:35.974221
2020-12-10T11:42:31
2020-12-10T11:42:31
229,014,924
0
0
Apache-2.0
2019-12-19T08:59:37
2019-12-19T08:59:36
null
UTF-8
Java
false
false
2,156
java
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.identity.api.dispatcher; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.api.server.common.error.ErrorDTO; import org.wso2.carbon.identity.api.server.common.error.ErrorResponse; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; /** * Handles all the unhandled server errors, (ex:NullPointer). * Sends a default error response. */ public class DefaultExceptionMapper implements ExceptionMapper<Throwable> { private static final Log log = LogFactory.getLog(DefaultExceptionMapper.class); public static final String PROCESSING_ERROR_CODE = "SE-50000"; public static final String PROCESSING_ERROR_MESSAGE = "Unexpected Processing Error."; public static final String PROCESSING_ERROR_DESCRIPTION = "Server encountered an error while serving the request."; @Override public Response toResponse(Throwable e) { log.error("Server encountered an error while serving the request.", e); ErrorDTO errorDTO = new ErrorResponse.Builder().withCode(PROCESSING_ERROR_CODE) .withMessage(PROCESSING_ERROR_MESSAGE) .withDescription(PROCESSING_ERROR_DESCRIPTION).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(errorDTO) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).build(); } }
[ "ayeshad.09@cse.mrt.ac.lk" ]
ayeshad.09@cse.mrt.ac.lk
f15bf1564006fb27de49425edae5425652329dc4
62533122cbbd8350a4ea0834987e262a4bda0a49
/app/src/test/java/com/example/minergame/ExampleUnitTest.java
475ca5c681c6c40bdca8ddd3cab1a63e75f41aba
[]
no_license
klok101/Miner_Game
231339b3cb5246efc38b31f5fcbc44ed44f59bb9
bb32d52fbf3c165e3b56c3bdb6c0fcee8e7147e3
refs/heads/master
2020-12-31T09:48:55.555681
2020-02-07T17:28:09
2020-02-07T17:28:09
238,985,817
0
0
null
null
null
null
UTF-8
Java
false
false
382
java
package com.example.minergame; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "blackhawks4447@gmail.com" ]
blackhawks4447@gmail.com
6a39c7f8921339c643c0a92547c6d9371f21d300
0ce26835ca89db1acf271cacc69d7b90fd8ecf3e
/SeleniumTraining/src/inhertenceConcept/Parent1111.java
5443d54de75b3c5b22eecfd121f274fb0a2b0ac1
[]
no_license
srinivaspatel8118/Office
5679567840bf6e646e338a326b6959fffb0186af
977c919e13943b0878aef1d4716a983a55c7beac
refs/heads/master
2020-06-21T23:47:58.865115
2019-09-18T12:41:28
2019-09-18T12:41:28
197,581,273
0
0
null
null
null
null
UTF-8
Java
false
false
315
java
package inhertenceConcept; /* * 7.a.Create a parent class (ex:Parent1) with two instance methods with return type String */ public class Parent1111 { String instnaceMethod1() { String str1="Srinivas"; return str1; } String instnaceMethod2() { String str2="Patel"; return str2; } }
[ "spatel@XVDT0253.xeno.com" ]
spatel@XVDT0253.xeno.com
e04d24a4b0e9638b22c405a798785cc650b54306
7a663b133d2f6b4d6af458f90cf66ab61c73d0f1
/CreateContact.java
db6b2a26743bf968e12bb059ea686b1fb8993266
[]
no_license
Benjamin2807/SeleniumAssignments
2ed1cf7d34b3add8ff73f0b7ca7f2abd6717c7fc
3a0db0f873fdc5923a8084ce30b07a09b396855f
refs/heads/main
2023-05-16T03:38:41.504252
2021-06-05T08:45:45
2021-06-05T08:45:45
360,655,380
0
0
null
null
null
null
UTF-8
Java
false
false
2,113
java
package week2.day2; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import io.github.bonigarcia.wdm.WebDriverManager; public class CreateContact { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); ChromeDriver driver = new ChromeDriver(); driver.get("http://leaftaps.com/opentaps"); driver.manage().window().maximize(); driver.findElement(By.id("username")).sendKeys("DemoSalesManager"); driver.findElement(By.id("password")).sendKeys("crmsfa"); driver.findElement(By.className("decorativeSubmit")).click(); driver.findElement(By.linkText("CRM/SFA")).click(); driver.findElement(By.xpath("//a[text()= 'Contacts']")).click(); driver.findElement(By.xpath("//a[text()= 'Create Contact']")).click(); driver.findElement(By.id("firstNameField")).sendKeys("Lionel"); driver.findElement(By.id("lastNameField")).sendKeys("Messi"); driver.findElement(By.id("createContactForm_firstNameLocal")).sendKeys("Goal"); driver.findElement(By.id("createContactForm_lastNameLocal")).sendKeys("Scorer"); driver.findElement(By.id("createContactForm_departmentName")).sendKeys("Football"); driver.findElement(By.id("createContactForm_description")).sendKeys("Main Contact"); driver.findElement(By.id("createContactForm_primaryEmail")).sendKeys("lionelmessi@gmail.com"); WebElement web = driver.findElement(By.id("createContactForm_generalStateProvinceGeoId")); Select select = new Select(web); select.selectByVisibleText("California"); driver.findElement(By.xpath("//input[@type='submit']")).click(); driver.findElement(By.xpath("//a[text()='Edit']")).click(); driver.findElement(By.id("updateContactForm_description")).clear(); driver.findElement(By.id("updateContactForm_importantNote")).sendKeys("Important contact"); driver.findElement(By.xpath("//input[@class='smallSubmit']")).click(); String title = driver.getTitle(); System.out.println(title); } }
[ "noreply@github.com" ]
noreply@github.com
8f4b5a3284834e4bed84b1b426135720e01f8577
063f5ea4fd94691069bbce6ddd93a649d34180f2
/src/main/java/com/soeasy/controller/mallController/ProductCategoryController.java
8ce1646f0116a6b7ed059bfdb58c160f3cee4cdb
[]
no_license
h188472r/SoEasyMall
c1f670166609d622cd12b82b4f5501427740f19e
dd87b0bc61ded0a02fdb0b5a410bcc25a84e7091
refs/heads/master
2023-06-24T16:40:06.563935
2021-07-27T08:38:56
2021-07-27T08:38:56
382,291,292
0
0
null
null
null
null
UTF-8
Java
false
false
4,864
java
package com.soeasy.controller.mallController; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.soeasy.model.ProductCategoryBean; import com.soeasy.service.mallService.ProductCategoryService; @Controller @RequestMapping("/mall/category") public class ProductCategoryController { @Autowired private ProductCategoryService productCategoryService; @GetMapping("") public String index(Model model) { model.addAttribute("categories",productCategoryService.findParentCategories()); return "/mall/category/productCategory"; } // ======================================================================================== @GetMapping("/add") public String add(Model model) { ProductCategoryBean category=new ProductCategoryBean(); category.setStatus(true); model.addAttribute("category",category); return "/mall/category/addProductCategory"; } @PostMapping("/add") public String addCategory(@ModelAttribute("category")ProductCategoryBean category) { //category.setCategories(null); //category.setCategory(new ProductCategoryBean(-1)); productCategoryService.save(category); return "redirect:/mall/category"; } // ======================================================================================== @GetMapping("/delete/{productCategoryId}") public String deleteCategory(@PathVariable("productCategoryId")int productCategoryId ,RedirectAttributes redirectAttributes) { try{ productCategoryService.delete(productCategoryId); }catch(Exception e) { redirectAttributes.addAttribute("error","Deleted Failed"); } return "redirect:/mall/category"; } // ======================================================================================== //修改跳轉出現資料 @GetMapping("/update/{productCategoryId}") public String editCategory(@PathVariable("productCategoryId")int productCategoryId,Model model) { model.addAttribute("category",productCategoryService.findByProductCategoryId(productCategoryId)); return "/mall/category/updateProductCategory"; } //更動可以保存 @PostMapping("/update/{productCategoryId}") public String editCategory( @ModelAttribute("category") ProductCategoryBean category, BindingResult result, Model model, @PathVariable int productCategoryId, HttpServletRequest request) { productCategoryService.save(category); return "redirect:/mall/category"; } // ======================================================================================== // =================================================================== // // 默認是10條 這裡改成5 // // 使用印出分頁內容的方式去取值 // @GetMapping("/category") // public String Category(@PageableDefault(size=10,sort= {"productCategoryId"},direction=Sort.Direction.DESC) // Pageable pageable,Model model) { // // List<ProductCategoryBean> list=productCategoryService.listCategory(pageable).getContent(); // model.addAttribute("page",list); // System.out.println(productCategoryService.listCategory(pageable)); // return"mall/ProductCategory"; // } // // //新增產品 使用Post請求 // //跳轉add提交頁 於新增時,送出空白的表單讓使用者輸入資料 // // @GetMapping("/addCategory") // public String addcategory(Model model) { // //ProductCategoryBean product = new ProductCategoryBean(); //// product.setProductCategoryName("海鮮套餐"); //// model.addAttribute("product", product); // // return "mall/addProductCategory"; // } // // // @PostMapping("/addcategory") // public String addProduct( // @ModelAttribute("category") /* @Valid */ ProductCategoryBean category, // BindingResult result, Model model) // //,HttpServletRequest request) // { // productCategoryService.saveCategory(category); // // 跳轉至查詢所有頁面 // return "redirect:/mall/category"; // } // // // // // 刪除一筆紀錄 // //送不出DELETE 先用POST // @PostMapping("/deletecategory/{productCategoryId}") // public String delete(@PathVariable("productCategoryId") Integer productCategoryId) { // productCategoryService.deleteCategory(productCategoryId); // System.out.println("刪除一條分類"); // return "redirect:/mall/category"; // } }
[ "senyaky@gmail.com" ]
senyaky@gmail.com
ae029ac19e6c96a17eca4e753427f775aed2cf7c
fc2ef923607747cbcba2a95ce0deb913aa0fb583
/Chapter8/src/template/Car.java
c13905a418e73d16a74e82d1ccf4bbf948064110
[]
no_license
easyspubjava/java_lesson
0aa04a859ca65273f7719a403fe8abd7bf39e3c3
09dc911b3bffffee1bcc6417badea761396f59a1
refs/heads/master
2020-05-19T06:27:13.363927
2020-02-28T02:32:56
2020-02-28T02:32:56
184,874,217
0
0
null
null
null
null
UHC
Java
false
false
348
java
package template; public abstract class Car { public abstract void drive(); public abstract void stop(); public void startCar() { System.out.println("시동을 켭니다"); } public void turnOff() { System.out.println("시동을 끕니다."); } final public void run() { startCar(); drive(); stop(); turnOff(); } }
[ "eunjong.park@gmail.com" ]
eunjong.park@gmail.com
4f8489c4c0786d46528de0c2ed35107bb1d78bc4
c21ed27cbb4b669141a07eb76128d7494de6893a
/app/src/main/java/metlife/lms/activity/MainActivity.java
e1c5b0125c128c7a342b007bdbea9604d0315e50
[]
no_license
ashishcubic/metlife
b5ccbaf78921a94c5a1cd6c061ea1b0ee9967734
ac5b1d624a3ea36f303466e451582200de5ccfee
refs/heads/master
2021-01-20T14:34:36.667649
2017-05-08T13:02:05
2017-05-08T13:02:05
90,628,653
0
0
null
null
null
null
UTF-8
Java
false
false
12,788
java
package metlife.lms.activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.HashMap; import me.leolin.shortcutbadger.ShortcutBadger; import metlife.lms.R; import metlife.lms.fragment.AppointmentLeadFragment; import metlife.lms.fragment.HomeFragment; import metlife.lms.fragment.NormalLeadFragment; import metlife.lms.helper.SQLiteHandler; import metlife.lms.helper.SessionManager; import metlife.lms.reminder.WatchList; public class MainActivity extends AppCompatActivity { private NavigationView navigationView; private DrawerLayout drawer; private View navHeader; private ImageView imgNavHeaderBg, imgProfile; private TextView txtName, txtWebsite; private Toolbar toolbar; // index to identify current nav menu item public static int navItemIndex = 0; // tags used to attach the fragments private static final String TAG_HOME = "home"; public static String CURRENT_TAG = TAG_HOME; private static final String TAG_NORMAL = "normal"; private static final String TAG_APOINTMENT = "appointment"; private String[] activityTitles; // flag to load home fragment when user presses back key private boolean shouldLoadHomeFragOnBackPress = true; private Handler mHandler; private SQLiteHandler db; private SessionManager session; String name; String role; private HomeFragment homeFragment; private NormalLeadFragment normalLeadFragment; private AppointmentLeadFragment appointmentLeadFragment; boolean flag_back=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); SharedPreferences preferences=getSharedPreferences("mycount",MODE_PRIVATE); preferences.edit().remove("count").commit(); activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles); db = new SQLiteHandler(getApplicationContext()); // session manager session = new SessionManager(getApplicationContext()); if (!session.isLoggedIn()) { logoutUser(); } HashMap<String, String> user = db.getUserDetails(); name = user.get("name"); role = user.get("email"); mHandler = new Handler(); drawer = (DrawerLayout) findViewById(R.id.drawer_layout); navigationView = (NavigationView) findViewById(R.id.nav_view); // Navigation view header navHeader = navigationView.getHeaderView(0); txtName = (TextView) navHeader.findViewById(R.id.name); txtWebsite = (TextView) navHeader.findViewById(R.id.website); imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg); imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile); // load toolbar titles from string resources // load nav menu header data loadNavHeader(); // initializing navigation menu setUpNavigationView(); if (savedInstanceState == null) { navItemIndex = 2; CURRENT_TAG = TAG_HOME; loadHomeFragment(); } } /*** * Load navigation menu header information * like background image, profile image * name, website, notifications action view (dot) */ private void loadNavHeader() { // name, website txtName.setText("Login as:"+" "+name); imgNavHeaderBg.setImageResource(R.drawable.nav_menu_header_bg); imgProfile.setImageResource(R.drawable.logo); // showing dot next to notifications label } /*** * Returns respected fragment that user * selected from navigation menu */ private void loadHomeFragment() { // selecting appropriate nav menu item selectNavMenu(); // set toolbar title setToolbarTitle(); // if user select the current navigation menu again, don't do anything // just close the navigation drawer if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) { drawer.closeDrawers(); // show or hide the fab button return; } // Sometimes, when fragment has huge data, screen seems hanging // when switching between navigation menus // So using runnable, the fragment is loaded with cross fade effect // This effect can be seen in GMail app Runnable mPendingRunnable = new Runnable() { @Override public void run() { // update the main content by replacing fragments Fragment fragment = getHomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG); fragmentTransaction.commitAllowingStateLoss(); } }; // If mPendingRunnable is not null, then add to the message queue if (mPendingRunnable != null) { mHandler.post(mPendingRunnable); } //Closing drawer on item click drawer.closeDrawers(); // refresh toolbar menu invalidateOptionsMenu(); } private Fragment getHomeFragment() { switch (navItemIndex) { case 0: // home homeFragment = new HomeFragment(); return homeFragment; case 1: // photos normalLeadFragment= new NormalLeadFragment(); return normalLeadFragment; case 2: // movies fragment appointmentLeadFragment = new AppointmentLeadFragment(); return appointmentLeadFragment; default: return new AppointmentLeadFragment(); } } private void setToolbarTitle() { getSupportActionBar().setTitle(activityTitles[navItemIndex]); } private void selectNavMenu() { navigationView.getMenu().getItem(navItemIndex).setChecked(true); } private void setUpNavigationView() { //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { // This method will trigger on item Click of navigation menu @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { //Replacing the main content with ContentFragment Which is our Inbox View; case R.id.home: navItemIndex = 0; CURRENT_TAG = TAG_HOME; break; case R.id.nav_normal_lead: navItemIndex = 1; CURRENT_TAG = TAG_NORMAL; break; case R.id.nav_appointment_lead: navItemIndex = 2; CURRENT_TAG = TAG_APOINTMENT; break; case R.id.nav_reminder: // launch new intent instead of loading fragment Intent favoriateIntent = new Intent(MainActivity.this,WatchList.class); startActivity(favoriateIntent); return true; case R.id.nav_logout: // launch new intent instead of loading fragment logoutUser(); drawer.closeDrawers(); return true; case R.id.nav_about_us: // launch new intent instead of loading fragment String url = "https://click2cover.in/why-us"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); drawer.closeDrawers(); return true; case R.id.nav_privacy_policy: // launch new intent instead of loading fragment String url1 = "https://click2cover.in/terms-conditions"; Intent i1 = new Intent(Intent.ACTION_VIEW); i1.setData(Uri.parse(url1)); startActivity(i1); drawer.closeDrawers(); return true; default: navItemIndex = 2; } //Checking if the item is in checked state or not, if not make it in checked state if (menuItem.isChecked()) { menuItem.setChecked(false); } else { menuItem.setChecked(true); } menuItem.setChecked(true); loadHomeFragment(); return true; } }); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) { @Override public void onDrawerClosed(View drawerView) { // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank super.onDrawerClosed(drawerView); } @Override public void onDrawerOpened(View drawerView) { // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank super.onDrawerOpened(drawerView); } }; //Setting the actionbarToggle to drawer layout drawer.setDrawerListener(actionBarDrawerToggle); //calling sync state is necessary or else your hamburger icon wont show up actionBarDrawerToggle.syncState(); } @Override public void onBackPressed() { if(flag_back==true) { super.onBackPressed(); } if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawers(); return; }else { // This code loads home fragment when back key is pressed // when user is in other fragment than home if (shouldLoadHomeFragOnBackPress) { // checking if user is on other navigation menu // rather than home if (navItemIndex != 2) { navItemIndex = 2; CURRENT_TAG = TAG_HOME; loadHomeFragment(); flag_back=true; return; } if (navItemIndex == 0) { homeFragment.onBackPressed(); flag_back=true; return; } if (navItemIndex == 1) { normalLeadFragment.onBackPressed(); flag_back=true; return; } if (navItemIndex == 2) { appointmentLeadFragment.onBackPressed(); flag_back=true; return; } } } } private void logoutUser() { session.setLogin(false); db.deleteUsers(); // Launching the login activity Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); } }
[ "info@techolex.com" ]
info@techolex.com
485029dbf29de53fec8edf811005b99849509b4c
eaa3ec46da67f73cbc1c578d75ba2fde53d83287
/collapsiblecalendarview/src/main/java/com/shrikanthravi/collapsiblecalendarview/widget/UICalendar.java
5d9f0321586b4dbd45b51d4ea83c863b71a0c5c5
[]
no_license
jmcoder1/Kama
996a22a5f35c2d2435d0280e7ab168d843d6a347
2c7d86d7060c389e032fb131d4687351a280d76f
refs/heads/master
2020-04-05T05:30:08.488165
2018-11-07T19:36:23
2018-11-07T19:36:23
156,598,416
0
0
null
null
null
null
UTF-8
Java
false
false
11,881
java
package com.shrikanthravi.collapsiblecalendarview.widget; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TableLayout; import android.widget.TextView; import com.shrikanthravi.collapsiblecalendarview.R; import com.shrikanthravi.collapsiblecalendarview.data.Day; import com.shrikanthravi.collapsiblecalendarview.listener.OnSwipeTouchListener; import com.shrikanthravi.collapsiblecalendarview.view.LockScrollView; public abstract class UICalendar extends LinearLayout { // Day of Week public static final int SUNDAY = 0; public static final int MONDAY = 1; public static final int TUESDAY = 2; public static final int WEDNESDAY = 3; public static final int THURSDAY = 4; public static final int FRIDAY = 5; public static final int SATURDAY = 6; // State public static final int STATE_EXPANDED = 0; public static final int STATE_COLLAPSED = 1; public static final int STATE_PROCESSING = 2; public static final int EVENT_DOT_BIG = 0; public static final int EVENT_DOT_SMALL = 1; protected Context mContext; protected LayoutInflater mInflater; // UI protected LinearLayout mLayoutRoot; protected TextView mTxtTitle; protected TableLayout mTableHead; protected LockScrollView mScrollViewBody; protected TableLayout mTableBody; protected RelativeLayout mLayoutBtnGroupMonth; protected RelativeLayout mLayoutBtnGroupWeek; protected ImageView mBtnPrevMonth; protected ImageView mBtnNextMonth; protected ImageView mBtnPrevWeek; protected ImageView mBtnNextWeek; // Attributes private boolean mShowWeek = true; private int mFirstDayOfWeek = SUNDAY; private int mState = STATE_COLLAPSED; private int mTextColor = Color.BLACK; private int mPrimaryColor = Color.WHITE; private int mTodayItemTextColor = Color.BLACK; private Drawable mTodayItemBackgroundDrawable = getResources().getDrawable(R.drawable.circle_black_stroke_background); private int mSelectedItemTextColor = Color.WHITE; private Drawable mSelectedItemBackgroundDrawable = getResources().getDrawable(R.drawable.circle_black_solid_background); private Drawable mButtonLeftDrawable = getResources().getDrawable(R.drawable.left_icon); private Drawable mButtonRightDrawable = getResources().getDrawable(R.drawable.right_icon); private Day mSelectedItem = null; private int mButtonLeftDrawableTintColor=Color.BLACK; private int mButtonRightDrawableTintColor=Color.BLACK; private int mEventColor=Color.BLACK; private int mEventDotSize=EVENT_DOT_BIG; public UICalendar(Context context) { this(context, null); } public UICalendar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public UICalendar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); TypedArray attributes = context.getTheme().obtainStyledAttributes( attrs, R.styleable.UICalendar, defStyleAttr, 0); setAttributes(attributes); attributes.recycle(); } protected abstract void redraw(); protected abstract void reload(); protected void init(Context context) { mContext = context; mInflater = LayoutInflater.from(mContext); // load rootView from xml View rootView = mInflater.inflate(R.layout.widget_collapsible_calendarview, this, true); // init UI mLayoutRoot = rootView.findViewById(R.id.layout_root); mTxtTitle = rootView.findViewById(R.id.txt_title); mTableHead = rootView.findViewById(R.id.table_head); mScrollViewBody = rootView.findViewById(R.id.scroll_view_body); mTableBody = rootView.findViewById(R.id.table_body); mLayoutBtnGroupMonth = rootView.findViewById(R.id.layout_btn_group_month); mLayoutBtnGroupWeek = rootView.findViewById(R.id.layout_btn_group_week); mBtnPrevMonth = rootView.findViewById(R.id.btn_prev_month); mBtnNextMonth = rootView.findViewById(R.id.btn_next_month); mBtnPrevWeek = rootView.findViewById(R.id.btn_prev_week); mBtnNextWeek = rootView.findViewById(R.id.btn_next_week); } protected void setAttributes(TypedArray attrs) { // set attributes by the values from XML //setStyle(attrs.getInt(R.styleable.UICalendar_style, mStyle)); setShowWeek(attrs.getBoolean(R.styleable.UICalendar_showWeek, mShowWeek)); setFirstDayOfWeek(attrs.getInt(R.styleable.UICalendar_firstDayOfWeek, mFirstDayOfWeek)); setState(attrs.getInt(R.styleable.UICalendar_state, mState)); setTextColor(attrs.getColor(R.styleable.UICalendar_textColor, mTextColor)); setPrimaryColor(attrs.getColor(R.styleable.UICalendar_primaryColor, mPrimaryColor)); setEventColor(attrs.getColor(R.styleable.UICalendar_eventColor, mEventColor)); setEventDotSize(attrs.getInt(R.styleable.UICalendar_eventDotSize, mEventDotSize)); setTodayItemTextColor(attrs.getColor( R.styleable.UICalendar_todayItem_textColor, mTodayItemTextColor)); Drawable todayItemBackgroundDrawable = attrs.getDrawable(R.styleable.UICalendar_todayItem_background); if (todayItemBackgroundDrawable != null) { setTodayItemBackgroundDrawable(todayItemBackgroundDrawable); } else { setTodayItemBackgroundDrawable(mTodayItemBackgroundDrawable); } setSelectedItemTextColor(attrs.getColor( R.styleable.UICalendar_selectedItem_textColor, mSelectedItemTextColor)); Drawable selectedItemBackgroundDrawable = attrs.getDrawable(R.styleable.UICalendar_selectedItem_background); if (selectedItemBackgroundDrawable != null) { setSelectedItemBackgroundDrawable(selectedItemBackgroundDrawable); } else { setSelectedItemBackgroundDrawable(mSelectedItemBackgroundDrawable); } Drawable buttonLeftDrawable = attrs.getDrawable(R.styleable.UICalendar_buttonLeft_drawable); if (buttonLeftDrawable != null) { setButtonLeftDrawable(buttonLeftDrawable); } else { setButtonLeftDrawable(mButtonLeftDrawable); } Drawable buttonRightDrawable = attrs.getDrawable(R.styleable.UICalendar_buttonRight_drawable); if (buttonRightDrawable != null) { setButtonRightDrawable(buttonRightDrawable); } else { setButtonRightDrawable(mButtonRightDrawable); } setButtonLeftDrawableTintColor(attrs.getColor(R.styleable.UICalendar_buttonLeft_drawableTintColor,mButtonLeftDrawableTintColor)); setButtonRightDrawableTintColor(attrs.getColor(R.styleable.UICalendar_buttonRight_drawableTintColor,mButtonRightDrawableTintColor)); Day selectedItem = null; } public void setButtonLeftDrawableTintColor(int color){ this.mButtonLeftDrawableTintColor = color; mBtnPrevMonth.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); mBtnPrevWeek.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); redraw(); } public void setButtonRightDrawableTintColor(int color){ this.mButtonRightDrawableTintColor = color; mBtnNextMonth.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); mBtnNextWeek.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); redraw(); } public boolean isShowWeek() { return mShowWeek; } public void setShowWeek(boolean showWeek) { this.mShowWeek = showWeek; if (showWeek) { mTableHead.setVisibility(VISIBLE); } else { mTableHead.setVisibility(GONE); } } public int getFirstDayOfWeek() { return mFirstDayOfWeek; } public void setFirstDayOfWeek(int firstDayOfWeek) { this.mFirstDayOfWeek = firstDayOfWeek; reload(); } public int getState() { return mState; } public void setState(int state) { this.mState = state; if (mState == STATE_EXPANDED) { mLayoutBtnGroupMonth.setVisibility(VISIBLE); mLayoutBtnGroupWeek.setVisibility(GONE); } if (mState == STATE_COLLAPSED) { mLayoutBtnGroupMonth.setVisibility(GONE); mLayoutBtnGroupWeek.setVisibility(VISIBLE); } } public int getTextColor() { return mTextColor; } public void setTextColor(int textColor) { this.mTextColor = textColor; redraw(); mTxtTitle.setTextColor(mTextColor); } public int getPrimaryColor() { return mPrimaryColor; } public void setPrimaryColor(int primaryColor) { this.mPrimaryColor = primaryColor; redraw(); mLayoutRoot.setBackgroundColor(mPrimaryColor); } private void setEventColor(int eventColor) { this.mEventColor = eventColor; redraw(); } private void setEventDotSize(int eventDotSize) { this.mEventDotSize = eventDotSize; redraw(); } public int getEventDotSize() { return mEventDotSize; } public int getEventColor() { return mEventColor; } public int getTodayItemTextColor() { return mTodayItemTextColor; } public void setTodayItemTextColor(int todayItemTextColor) { this.mTodayItemTextColor = todayItemTextColor; redraw(); } public Drawable getTodayItemBackgroundDrawable() { return mTodayItemBackgroundDrawable; } public void setTodayItemBackgroundDrawable(Drawable todayItemBackgroundDrawable) { this.mTodayItemBackgroundDrawable = todayItemBackgroundDrawable; redraw(); } public int getSelectedItemTextColor() { return mSelectedItemTextColor; } public void setSelectedItemTextColor(int selectedItemTextColor) { this.mSelectedItemTextColor = selectedItemTextColor; redraw(); } public Drawable getSelectedItemBackgroundDrawable() { return mSelectedItemBackgroundDrawable; } public void setSelectedItemBackgroundDrawable(Drawable selectedItemBackground) { this.mSelectedItemBackgroundDrawable = selectedItemBackground; redraw(); } public Drawable getButtonLeftDrawable() { return mButtonLeftDrawable; } public void setButtonLeftDrawable(Drawable buttonLeftDrawable) { this.mButtonLeftDrawable = buttonLeftDrawable; mBtnPrevMonth.setImageDrawable(buttonLeftDrawable); mBtnPrevWeek.setImageDrawable(buttonLeftDrawable); } public Drawable getButtonRightDrawable() { return mButtonRightDrawable; } public void setButtonRightDrawable(Drawable buttonRightDrawable) { this.mButtonRightDrawable = buttonRightDrawable; mBtnNextMonth.setImageDrawable(buttonRightDrawable); mBtnNextWeek.setImageDrawable(buttonRightDrawable); } public Day getSelectedItem() { return mSelectedItem; } public void setSelectedItem(Day selectedItem) { this.mSelectedItem = selectedItem; } }
[ "jojomasala@protonmail.com" ]
jojomasala@protonmail.com
e2802333eb57600e873b679d266ca294e191836f
5fbce2c9192f6cc5d6e2c0803fb5ec3cc640ba62
/cloud-api-common/src/main/java/com/tingyu/cloud/entity/CommonResult.java
c4a0d0dc8d1f2458a98b780c4d5738177d93dd02
[]
no_license
nameicc/cloud2020
9564c630723c86395457bde4e370d58c5ae93c0f
a6eb92fc6ea4ee88fbf14575839485a84909ef0d
refs/heads/master
2023-01-29T11:44:58.328525
2020-12-12T09:41:23
2020-12-12T09:41:23
293,507,805
2
0
null
null
null
null
UTF-8
Java
false
false
456
java
package com.tingyu.cloud.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @Description 统一返回值 * @Author tingyu * @Date 2020/9/8 18:20 **/ @Data @AllArgsConstructor @NoArgsConstructor public class CommonResult<T> { private Integer code; private String message; private T data; public CommonResult(Integer code, String message){ this(code, message, null); } }
[ "shichuanfeng@topscomm.com" ]
shichuanfeng@topscomm.com
67ebc6fc1be00460d150bb05e21981d10cb6a317
81ca49f20f71aa9451e140022a80dd681d96f056
/src/main/java/com/beiran/common/utils/transfer/DeptTransferUtils.java
88fdb63f09023cc83b3f247cb58ec704befa3f18
[ "MIT" ]
permissive
beiranc/erp-server
31abb98d38005697ac6f275a101014644d262279
67b97c91fd79bfd62f77eadb720687d4e36fb08d
refs/heads/master
2022-09-18T00:00:15.797691
2022-09-08T15:37:00
2022-09-08T15:37:00
247,779,774
0
0
null
null
null
null
UTF-8
Java
false
false
3,025
java
package com.beiran.common.utils.transfer; import com.beiran.common.utils.DateTimeUtils; import com.beiran.core.system.dto.DeptDto; import com.beiran.core.system.dto.DeptSmallDto; import com.beiran.core.system.entity.Dept; import com.beiran.core.system.vo.DeptVo; import lombok.extern.java.Log; import org.springframework.beans.BeanUtils; import org.springframework.util.StringUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; /** * 提供 DeptDto-Dept-DeptVo 相互转换的工具 */ @Log public class DeptTransferUtils { /** * 将 DeptDto 转换为 Dept * @param deptDto 需要转换的 DeptDto * @return Dept */ public static Dept dtoToDept(DeptDto deptDto) { Dept dept = new Dept(); if (!Objects.equals(deptDto, null)) { BeanUtils.copyProperties(deptDto, dept); } if (!Objects.equals(deptDto.getParent(), null)) { Dept parent = new Dept(); BeanUtils.copyProperties(deptDto.getParent(), parent); dept.setDeptParent(parent); } Date createTime = null; if (StringUtils.hasText(deptDto.getCreateTime())) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateTimeUtils.DATE_FORMAT_TIMESTAMP); try { createTime = simpleDateFormat.parse(deptDto.getCreateTime()); } catch (ParseException e) { log.info(" { 日期转换异常 } " + e.getLocalizedMessage()); } } dept.setDeptCreateTime(createTime); return dept; } /** * 将 Dept 转换为 DeptDto * @param dept 需要转换的 Dept * @return DeptDto */ public static DeptDto deptToDto(Dept dept) { DeptDto deptDto = new DeptDto(); if (!Objects.equals(dept, null)) { BeanUtils.copyProperties(dept, deptDto); } if (!Objects.equals(dept.getDeptParent(), null)) { DeptSmallDto parent = new DeptSmallDto(); BeanUtils.copyProperties(dept.getDeptParent(), parent); deptDto.setParent(parent); } if (!Objects.equals(dept.getDeptCreateTime(), null)) { deptDto.setCreateTime(DateTimeUtils.getDateTime(dept.getDeptCreateTime())); } return deptDto; } /** * 将 DeptVo 转换为 Dept * @param deptVo 需要转换的 DeptVo * @return Dept */ public static Dept voToDept(DeptVo deptVo) { Dept dept = new Dept(); if (!Objects.equals(deptVo, null)) { BeanUtils.copyProperties(deptVo, dept); } if (!Objects.equals(deptVo.getParent(), null)) { Dept parent = new Dept(); parent.setDeptId(deptVo.getParent().getDeptId()); parent.setDeptName(deptVo.getParent().getDeptName()); dept.setDeptParent(parent); } else { dept.setDeptParent(null); } return dept; } }
[ "beiranlp@gmail.com" ]
beiranlp@gmail.com
c23a8875531f0428f6df08b172705045128d7187
67ad6fd5ae2fe1905819110eb8d49ab2364f83c9
/other_src/param_3Dtopfast.java
dc8721c67a7460994a18783f9329350745078f9f
[]
no_license
pierrelhuissier/Analysis_3D
a80a94232c523982314900a482ddf75f13c37174
be9b58674283bbae91f0b9ed8a6fcb2528297bf1
refs/heads/master
2021-01-16T21:00:49.354590
2014-04-14T15:39:33
2014-04-14T15:39:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
37,548
java
import ij.*; import ij.plugin.filter.*; import ij.process.*; import ij.io.*; import java.io.*; import java.util.concurrent.atomic.AtomicInteger; public class param_3Dtopfast implements PlugInFilter { protected ImageStack stack; InputStream pin; int nb; int dimx,dimy,dimz; static int valPixel = 0; ImagePlus imp; protected final Thread[] threads= newThreadArray(); public int setup(String arg, ImagePlus imp) { stack=imp.getStack(); return DOES_16; } public void run(ImageProcessor ip) { dimz =stack.getSize(); dimy = stack.getWidth(); dimx = stack.getHeight(); SaveDialog sd = new SaveDialog("Save Measurements as Text...", "res", ".dat"); String name = sd.getFileName(); if (name == null) return; String directory = sd.getDirectory(); nb=calculnb(stack)-1; if(nb<1) { IJ.showMessage("volume must be labeled"); } else { double[] volume_m = new double[nb]; int[] volume_p = new int[nb]; double[] surface = new double[nb]; double[] surfacenb = new double[nb]; double[][][] I = new double[3][3][nb]; double[][] J = new double[3][nb]; double[][][] dir = new double[3][3][nb]; double[] xg = new double[nb]; double[] yg = new double[nb]; double[] zg = new double[nb]; byte[] bord = new byte[nb]; // double[] a = new double[nb]; // double[] b = new double[nb]; // double[] c = new double[nb]; // double[] Fab = new double[nb]; // double[] Fac = new double[nb]; // double[] Fbc = new double[nb]; // double[] sp = new double[nb]; double[][] lmin = new double[nb][3]; double[][] lmax = new double[nb][3]; calculmarchsurfstack(stack,nb,surface,volume_m); calculmarchsurfstacknb(stack,nb,surfacenb); //calculvolumestack(stack,nb,volume_p); calculcgstack(stack,nb,volume_p,xg, yg,zg); calculinertiestack(stack,nb,xg,yg,zg,I); inertie(nb,I,J,dir); boitestack(stack,nb,xg,yg,zg,dir,lmin,lmax); borderstack(stack, nb, bord); sauvegarde(volume_p,volume_m,surface,surfacenb,xg,yg,zg,J,dir,nb,bord,lmin,lmax,directory,name); volume_m = null; volume_p = null; surface = null; xg = null; yg = null; zg = null; } } public int calculnb(final ImageStack stack1) { final AtomicInteger ai = new AtomicInteger(1); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final int[] value = new int[dimZ]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi <= dimZ; superi = ai.getAndIncrement()) { int current = superi; ImageProcessor ip = stack1.getProcessor(current); for(int j=0;j<dimY;j++) { for(int i=0;i<dimX;i++) { int val =(int) (ip.getPixelValue(j,i)); if (val>value[current-1]) value[current-1]=val; } } } } }; } startAndJoin(threads); int val=0; for(int i=0; i<dimZ; i++) { if (val<value[i]) val=value[i]; } return val; } void calculmarchsurfstack(ImageStack stack,int nb, double s[], double v[]) { double[] cas = new double [22]; double[] tri = new double [256]; double[] cas2 = new double [22]; double[] tri2 = new double [256]; initcas_s2(cas); initincrement(tri,cas); initcas_v2_luc(cas2); initincrement(tri2,cas2); calculsurfacemarch2stack(stack,nb,tri,s,tri2,v); } void initcas_s2(double []cas) { cas[0]= 0.00000; cas[1] = 0.216506; cas[2] = 0.707106; cas[3] = 0.750000; cas[4] = 2.062500; cas[5] = 1.149519; cas[6] = 0.923613; cas[7] = 0.649519; cas[8] = 1.000000; cas[9] = 1.299039; cas[10] = 1.414214; cas[11] = 1.573132; cas[12] = 1.366026; cas[13] = 0.866026; cas[14] = 0.560250; cas[15] = 0.923613; cas[16] = 0.649519; cas[17] = 0.707106; cas[18] = 0.433013; cas[19] = 0.433013; cas[20] = 0.216506; cas[21] = 0.000000; } void initcas_v2_luc(double []cas) { cas[0] = 0.00000; cas[1] = 0.020833; cas[2] = 0.125; cas[3] =0.16666; cas[4] = 0.498102; cas[5] = 0.354166; cas[6] = 0.295047; cas[7] =0.479166; cas[8] = 0.500000; cas[9] = 0.500000; cas[10] = 0.750000; cas[11] = 0.437500; cas[12] =0.625; cas[13] = 0.91667; cas[14] = 0.75000; cas[15] = 0.8541667; cas[16] = 0.9375; cas[17] =0.875; cas[18] =0.958333; cas[19] = 0.958333; cas[20] = 0.9791667; cas[21] = 1.000000; } void initincrement(double []tri,double []cas) { tri[0] = cas[0]; tri[1] = cas[1]; tri[2] = cas[1]; tri[3] = cas[2]; tri[4] = cas[1]; tri[5] = cas[2]; tri[6] = cas[3]; tri[7] = cas[5]; tri[8] = cas[1]; tri[9] = cas[3]; tri[10] = cas[2]; tri[11] = cas[5]; tri[12] = cas[2]; tri[13] = cas[5]; tri[14] = cas[5]; tri[15] = cas[8]; tri[16] = cas[1]; tri[17] = cas[2]; tri[18] = cas[3]; tri[19] = cas[5]; tri[20] = cas[3]; tri[21] = cas[5]; tri[22] = cas[7]; tri[23] = cas[9]; tri[24] = cas[4]; tri[25] = cas[6]; tri[26] = cas[6]; tri[27] = cas[11]; tri[28] = cas[6]; tri[29] = cas[11]; tri[30] = cas[12]; tri[31] = cas[14]; tri[32] = cas[1]; tri[33] = cas[3]; tri[34] = cas[2]; tri[35] = cas[5]; tri[36] = cas[4]; tri[37] = cas[6]; tri[38] = cas[6]; tri[39] = cas[11]; tri[40] = cas[3]; tri[41] = cas[7]; tri[42] = cas[5]; tri[43] = cas[9]; tri[44] = cas[6]; tri[45] = cas[12]; tri[46] = cas[11]; tri[47] = cas[14]; tri[48] = cas[2]; tri[49] = cas[5]; tri[50] = cas[5]; tri[51] = cas[8]; tri[52] = cas[6]; tri[53] = cas[11]; tri[54] = cas[12]; tri[55] = cas[14]; tri[56] = cas[6]; tri[57] = cas[12]; tri[58] = cas[11]; tri[59] = cas[14]; tri[60] = cas[10]; tri[61] = cas[15]; tri[62] = cas[15]; tri[63] = cas[17]; tri[64] = cas[1]; tri[65] = cas[3]; tri[66] = cas[4]; tri[67] = cas[6]; tri[68] = cas[2]; tri[69] = cas[5]; tri[70] = cas[6]; tri[71] = cas[11]; tri[72] = cas[3]; tri[73] = cas[7]; tri[74] = cas[6]; tri[75] = cas[12]; tri[76] = cas[5]; tri[77] = cas[9]; tri[78] = cas[11]; tri[79] = cas[14]; tri[80] = cas[2]; tri[81] = cas[5]; tri[82] = cas[6]; tri[83] = cas[11]; tri[84] = cas[5]; tri[85] = cas[8]; tri[86] = cas[12]; tri[87] = cas[14]; tri[88] = cas[6]; tri[89] = cas[12]; tri[90] = cas[10]; tri[91] = cas[15]; tri[92] = cas[11]; tri[93] = cas[14]; tri[94] = cas[15]; tri[95] = cas[17]; tri[96] = cas[3]; tri[97] = cas[7]; tri[98] = cas[6]; tri[99] = cas[12]; tri[100] = cas[6]; tri[101] = cas[12]; tri[102] = cas[10]; tri[103] = cas[15]; tri[104] = cas[7]; tri[105] = cas[13]; tri[106] = cas[12]; tri[107] = cas[16]; tri[108] = cas[12]; tri[109] = cas[16]; tri[110] = cas[15]; tri[111] = cas[18]; tri[112] = cas[5]; tri[113] = cas[9]; tri[114] = cas[11]; tri[115] = cas[14]; tri[116] = cas[11]; tri[117] = cas[14]; tri[118] = cas[15]; tri[119] = cas[17]; tri[120] = cas[12]; tri[121] = cas[16]; tri[122] = cas[15]; tri[123] = cas[18]; tri[124] = cas[15]; tri[125] = cas[18]; tri[126] = cas[19]; tri[127] = cas[20]; tri[128] = cas[1]; tri[129] = cas[4]; tri[130] = cas[3]; tri[131] = cas[6]; tri[132] = cas[3]; tri[133] = cas[6]; tri[134] = cas[7]; tri[135] = cas[12]; tri[136] = cas[2]; tri[137] = cas[20]; tri[138] = cas[5]; tri[139] = cas[11]; tri[140] = cas[5]; tri[141] = cas[11]; tri[142] = cas[9]; tri[143] = cas[14]; tri[144] = cas[3]; tri[145] = cas[6]; tri[146] = cas[7]; tri[147] = cas[12]; tri[148] = cas[7]; tri[149] = cas[12]; tri[150] = cas[13]; tri[151] = cas[16]; tri[152] = cas[6]; tri[153] = cas[10]; tri[154] = cas[12]; tri[155] = cas[15]; tri[156] = cas[12]; tri[157] = cas[15]; tri[158] = cas[16]; tri[159] = cas[18]; tri[160] = cas[2]; tri[161] = cas[6]; tri[162] = cas[5]; tri[163] = cas[11]; tri[164] = cas[6]; tri[165] = cas[10]; tri[166] = cas[12]; tri[167] = cas[15]; tri[168] = cas[5]; tri[169] = cas[12]; tri[170] = cas[8]; tri[171] = cas[14]; tri[172] = cas[11]; tri[173] = cas[15]; tri[174] = cas[14]; tri[175] = cas[17]; tri[176] = cas[5]; tri[177] = cas[11]; tri[178] = cas[9]; tri[179] = cas[14]; tri[180] = cas[12]; tri[181] = cas[15]; tri[182] = cas[17]; tri[183] = cas[18]; tri[184] = cas[11]; tri[185] = cas[15]; tri[186] = cas[14]; tri[187] = cas[17]; tri[188] = cas[15]; tri[189] = cas[19]; tri[190] = cas[18]; tri[191] = cas[20]; tri[192] = cas[2]; tri[193] = cas[6]; tri[194] = cas[6]; tri[195] = cas[10]; tri[196] = cas[5]; tri[197] = cas[11]; tri[198] = cas[12]; tri[199] = cas[15]; tri[200] = cas[5]; tri[201] = cas[12]; tri[202] = cas[11]; tri[203] = cas[15]; tri[204] = cas[8]; tri[205] = cas[14]; tri[206] = cas[14]; tri[207] = cas[17]; tri[208] = cas[5]; tri[209] = cas[11]; tri[210] = cas[12]; tri[211] = cas[15]; tri[212] = cas[9]; tri[213] = cas[14]; tri[214] = cas[16]; tri[215] = cas[18]; tri[216] = cas[11]; tri[217] = cas[15]; tri[218] = cas[15]; tri[219] = cas[19]; tri[220] = cas[14]; tri[221] = cas[17]; tri[222] = cas[18]; tri[223] = cas[20]; tri[224] = cas[5]; tri[225] = cas[12]; tri[226] = cas[11]; tri[227] = cas[15]; tri[228] = cas[11]; tri[229] = cas[15]; tri[230] = cas[15]; tri[231] = cas[19]; tri[232] = cas[9]; tri[233] = cas[16]; tri[234] = cas[14]; tri[235] = cas[18]; tri[236] = cas[14]; tri[237] = cas[18]; tri[238] = cas[17]; tri[239] = cas[20]; tri[240] = cas[8]; tri[241] = cas[14]; tri[242] = cas[14]; tri[243] = cas[17]; tri[244] = cas[14]; tri[245] = cas[17]; tri[246] = cas[18]; tri[247] = cas[20]; tri[248] = cas[14]; tri[249] = cas[18]; tri[250] = cas[17]; tri[251] = cas[20]; tri[252] = cas[17]; tri[253] = cas[20]; tri[254] = cas[20]; tri[255] = cas[21]; } void calculsurfacemarch2stack(final ImageStack stack1, int nb, final double[] tri, double[] s, final double[] tri2, double[] v) { final AtomicInteger ai = new AtomicInteger(-1); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final double[][] vol = new double[dimZ][nb]; final double[][] surf = new double[dimZ][nb]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi <= dimZ; superi = ai.getAndIncrement()) { int k = superi; ImageProcessor ip1,ip2; if (k>=0) ip1 = stack1.getProcessor(k+1); else ip1 = stack1.getProcessor(10); if (k<=dimZ-2) ip2 = stack1.getProcessor(k+2); else ip2 = stack1.getProcessor(10); for(int j=-1;j<dimY;j++) { for(int i=-1;i<dimX;i++) { int [] p = new int[8]; int p1,p2,p3,p4,p5,p6,p7,p8,ptot; int [] nontab = new int[8]; ptot=(short)0; if (j<0 || i<0 || k<0) p[0]=(short)0; else p[0]=(int)ip1.getPixelValue(j,i); if (j==dimY-1 || i<0 || k<0) p[1]=(short)0; else p[1]=(int)ip1.getPixelValue(j+1,i); if(k==dimZ-1 || i<0 || j<0) p[2]=(short)0; else p[2]=(int)ip2.getPixelValue(j,i); if(k==dimZ-1 || j==dimY-1 || i<0) p[3]=(short)0; else p[3]=(int)ip2.getPixelValue(j+1,i); if(i==dimX-1 || k<0 || j<0) p[4]=(short)0; else p[4]=(int)ip1.getPixelValue(j,i+1); if(i==dimX-1 || j==dimY-1 || k<0) p[5]=(short)0; else p[5]=(int)ip1.getPixelValue(j+1,i+1); if(k==dimZ-1 || i==dimX-1 || j<0) p[6]=(short)0; else p[6]=(int)ip2.getPixelValue(j,i+1); if(k==dimZ-1 || j==dimY-1 || i==dimX-1) p[7]=(short)0; else p[7]=(int)ip2.getPixelValue(j+1,i+1); int pixcoul=0; for(int l=0;l<8;l++) nontab[l]=0; int cpt =0; // look for different colors for(int l=0;l<8;l++) { if (p[l]!=0 && appart(p[l],nontab,8)==1) { nontab[cpt]=p[l]; cpt++; } } for(int mm=0;mm<cpt;mm++) { p1=0; p2=0; p3=0; p4=0; p5=0; p6=0; p7=0; p8=0; if (p[0]!=0 && p[0] == nontab[mm]) { pixcoul=nontab[mm]; p1=1; } if (p[1]!=0 && p[1] == nontab[mm]) { pixcoul=nontab[mm]; p2=4; } if (p[2]!=0 && p[2] == nontab[mm]) { pixcoul=nontab[mm]; p3=2; } if (p[3]!=0 && p[3] == nontab[mm]) { pixcoul=nontab[mm]; p4=8; } if (p[4]!=0 && p[4] == nontab[mm]) { pixcoul=nontab[mm]; p5=16; } if (p[5]!=0 && p[5] == nontab[mm]) { pixcoul=nontab[mm]; p6=64; } if (p[6]!=0 && p[6] == nontab[mm]) { pixcoul=nontab[mm]; p7=32; } if (p[7]!=0 && p[7] == nontab[mm]) { pixcoul=nontab[mm]; p8=128; } ptot=(p1+p2+p3+p4+p5+p6+p7+p8); if (pixcoul!=0) { surf[k][(int)(pixcoul-2)]+=tri[(int)(ptot)]; vol[k][(int)(pixcoul-2)]+=tri2[(int)(ptot)]; } } } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=1; j<nb; j++) { v[j]+=vol[i][j]; s[j]+=surf[i][j]; } } } void calculmarchsurfstacknb(ImageStack stack, int nb,double s2[]) { double[] cas = new double [22]; double[] tri = new double [256]; initcas_s2(cas); initincrement(tri,cas); calculsurfacemarch3stack(stack,nb,tri,s2); } void calculsurfacemarch3stack(final ImageStack stack1, int nb, final double[] tri,double[] s2) { final AtomicInteger ai = new AtomicInteger(0); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final double[][] surf = new double[dimZ][nb]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi < dimZ-1; superi = ai.getAndIncrement()) { int k = superi; ImageProcessor ip1,ip2; ip1 = stack1.getProcessor(k+1); ip2 = stack1.getProcessor(k+2); for(int j=0;j<dimY-1;j++) { for(int i=0;i<dimX-1;i++) { int [] p = new int[8]; int p1,p2,p3,p4,p5,p6,p7,p8,ptot; int [] nontab = new int[8]; ptot=(short)0; p[0]=(int)ip1.getPixelValue(j,i); p[1]=(int)ip1.getPixelValue(j+1,i); p[2]=(int)ip2.getPixelValue(j,i); p[3]=(int)ip2.getPixelValue(j+1,i); p[4]=(int)ip1.getPixelValue(j,i+1); p[5]=(int)ip1.getPixelValue(j+1,i+1); p[6]=(int)ip2.getPixelValue(j,i+1); p[7]=(int)ip2.getPixelValue(j+1,i+1); int pixcoul=0; for(int l=0;l<8;l++) nontab[l]=0; int cpt =0; // look for different colors for(int l=0;l<8;l++) { if (p[l]!=0 && appart(p[l],nontab,8)==1) { nontab[cpt]=p[l]; cpt++; } } for(int mm=0;mm<cpt;mm++) { p1=0; p2=0; p3=0; p4=0; p5=0; p6=0; p7=0; p8=0; if (p[0]!=0 && p[0] == nontab[mm]) { pixcoul=nontab[mm]; p1=1; } if (p[1]!=0 && p[1] == nontab[mm]) { pixcoul=nontab[mm]; p2=4; } if (p[2]!=0 && p[2] == nontab[mm]) { pixcoul=nontab[mm]; p3=2; } if (p[3]!=0 && p[3] == nontab[mm]) { pixcoul=nontab[mm]; p4=8; } if (p[4]!=0 && p[4] == nontab[mm]) { pixcoul=nontab[mm]; p5=16; } if (p[5]!=0 && p[5] == nontab[mm]) { pixcoul=nontab[mm]; p6=64; } if (p[6]!=0 && p[6] == nontab[mm]) { pixcoul=nontab[mm]; p7=32; } if (p[7]!=0 && p[7] == nontab[mm]) { pixcoul=nontab[mm]; p8=128; } ptot=(p1+p2+p3+p4+p5+p6+p7+p8); if (pixcoul!=0) { surf[k][(int)(pixcoul-2)]+=tri[(int)(ptot)]; } } } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=1; j<nb; j++) { s2[j]+=surf[i][j]; } } } void calculvolumestack(final ImageStack stack1, int nb, int v[]) { final AtomicInteger ai = new AtomicInteger(1); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final int[][] vol = new int[dimZ][nb]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi <= dimZ; superi = ai.getAndIncrement()) { int current = superi; ImageProcessor ip = stack1.getProcessor(current); for(int j=0;j<dimY;j++) { for(int i=0;i<dimX;i++) { int val =(int) (ip.getPixelValue(j,i)); if (val!=0) vol[current-1][val-2]++; } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=1; j<nb; j++) { v[j]+=vol[i][j]; } } } void calculcgstack(final ImageStack stack1, int nb, final int[] v, final double[] xg, final double[] yg, final double[] zg) { final AtomicInteger ai = new AtomicInteger(0); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final int[][] vol = new int[dimZ][nb]; final int[][] tmpxg = new int[dimZ][nb]; final int[][] tmpyg = new int[dimZ][nb]; final int[][] tmpzg = new int[dimZ][nb]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi < dimZ; superi = ai.getAndIncrement()) { int k = superi; ImageProcessor ip = stack1.getProcessor(k+1); for(int j=0;j<dimY;j++) { for(int i=0;i<dimX;i++) { int pix =(int) (ip.getPixelValue(j,i)); if(pix!=0){ tmpxg[k][pix-2] += j; tmpyg[k][pix-2] += i; tmpzg[k][pix-2] += k; vol[k][pix-2]++; } } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=1; j<nb; j++) { v[j]+=vol[i][j]; xg[j]+=tmpxg[i][j]; yg[j]+=tmpyg[i][j]; zg[j]+=tmpzg[i][j]; } } for(int i=0;i<nb;i++) { xg[i]=(1.0*xg[i]/v[i]); yg[i]=(1.0*yg[i]/v[i]); zg[i]=(1.0*zg[i]/v[i]); } } void calculinertiestack(final ImageStack stack1, int nb, final double[] xg, final double[] yg, final double[] zg, double[][][] I) { final AtomicInteger ai = new AtomicInteger(0); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final double[][][][] inert = new double[dimZ][nb][3][3]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi < dimZ; superi = ai.getAndIncrement()) { int k = superi; ImageProcessor ip = stack1.getProcessor(k+1); for(int j=0;j<dimY;j++) { for(int i=0;i<dimX;i++) { int pix =(int) (ip.getPixelValue(j,i)); if(pix!=0){ inert[k][pix-2][0][0]+=(i-yg[pix-2])*(i-yg[pix-2])+(k-zg[pix-2])*(k-zg[pix-2])+1.0/6.0; inert[k][pix-2][0][1]-=(j-xg[pix-2])*(i-yg[pix-2]); inert[k][pix-2][0][2]-=(j-xg[pix-2])*(k-zg[pix-2]); inert[k][pix-2][1][1]+=(j-xg[pix-2])*(j-xg[pix-2])+(k-zg[pix-2])*(k-zg[pix-2])+1.0/6.0; inert[k][pix-2][1][2]-=(i-yg[pix-2])*(k-zg[pix-2]); inert[k][pix-2][2][2]+=(j-xg[pix-2])*(j-xg[pix-2])+(i-yg[pix-2])*(i-yg[pix-2])+1.0/6.0; } } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=0; j<nb; j++) { for(int l=0;l<3;l++) { for(int m=0; m<=l; m++) { I[l][m][j]+=inert[i][j][l][m]; } } } } for(int j=1; j<nb; j++) { I[1][0][j]=I[0][1][j]; I[2][0][j]=I[0][2][j]; I[2][1][j]=I[1][2][j]; } } void boitestack(final ImageStack stack1, final int nb, final double[] xg, final double[] yg, final double[] zg, final double[][][] dir, double[][] lmin, double[][] lmax) { final AtomicInteger ai = new AtomicInteger(0); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final double[][][] lmint = new double[dimZ][nb][3]; final double[][][] lmaxt = new double[dimZ][nb][3]; for(int k=0; k<nb; k++) { lmin[k][0]= 100000; lmin[k][1]= 100000; lmin[k][2]= 100000; lmax[k][0]= -100000; lmax[k][1]= -100000; lmax[k][2]= -100000; } for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi < dimZ; superi = ai.getAndIncrement()) { int k = superi; ImageProcessor ip = stack1.getProcessor(k+1); for(int l=0; l<nb; l++) { lmint[l][k][0]= 100000; lmint[l][k][1]= 100000; lmint[l][k][2]= 100000; lmaxt[l][k][0]= -100000; lmaxt[l][k][1]= -100000; lmaxt[l][k][2]= -100000; } for(int j=0;j<dimY;j++) { for(int i=0;i<dimX;i++) { int pix =(int) (ip.getPixelValue(j,i)); if(pix!=0){ double v1 = (i-xg[pix-2])*dir[0][0][pix-2]+(j-yg[pix-2])*dir[1][0][pix-2]+(k-zg[pix-2])*dir[2][0][pix-2]; double v2 = (i-xg[pix-2])*dir[0][1][pix-2]+(j-yg[pix-2])*dir[1][1][pix-2]+(k-zg[pix-2])*dir[2][1][pix-2]; double v3 = (i-xg[pix-2])*dir[0][2][pix-2]+(j-yg[pix-2])*dir[1][2][pix-2]+(k-zg[pix-2])*dir[2][2][pix-2]; if (v1<lmint[k][pix-2][0]) lmint[k][pix-2][0]=v1; if (v1>lmaxt[k][pix-2][0]) lmaxt[k][pix-2][0]=v1; if (v2<lmint[k][pix-2][1]) lmint[k][pix-2][1]=v2; if (v2>lmaxt[k][pix-2][1]) lmaxt[k][pix-2][1]=v2; if (v3<lmint[k][pix-2][2]) lmint[k][pix-2][2]=v3; if (v3>lmaxt[k][pix-2][2]) lmaxt[k][pix-2][2]=v3; } } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=0; j<nb; j++) { for(int l=0;l<3;l++) { if(lmint[i][j][l]<lmin[j][l]) lmin[j][l]=lmint[i][j][l]; if(lmaxt[i][j][l]>lmax[j][l]) lmax[j][l]=lmaxt[i][j][l]; } } } } void borderstack(final ImageStack stack1, int nb, byte []b) { final AtomicInteger ai = new AtomicInteger(0); final int dimX = stack1.getWidth(); final int dimY = stack1.getHeight(); final int dimZ = stack1.getSize(); final byte[][] bord = new byte[dimZ][nb]; for (int ithread = 0; ithread < threads.length; ithread++) { // Concurrently run in as many threads as CPUs threads[ithread] = new Thread() { public void run() { for (int superi = ai.getAndIncrement(); superi < dimZ; superi = ai.getAndIncrement()) { int k = superi; ImageProcessor ip = stack1.getProcessor(k+1); for(int j=0;j<dimY;j++) { for(int i=0;i<dimX;i++) { int val =(int) (ip.getPixelValue(j,i)); if ((val != 0) && ( i==0 || j==0 || k==0 || i==dimX-1 || j==dimY-1 || k==dimZ-1)) bord[k][val-2]=1; } } } } }; } startAndJoin(threads); for(int i=0; i<dimZ; i++) { for(int j=0; j<nb; j++) { b[j]*=(1-bord[i][j]); } } for(int j=0; j<nb; j++) { b[j]=(byte)(1-b[j]); } } void sauvegarde(int v1[],double v2[],double s[],double s2[],double xg[],double yg[],double zg[],double [][]J, double [][][] dir, int n,byte[]bord,double[][] lmin,double[][] lmax,String directory, String name) { double sp; PrintWriter pw = null; try { FileOutputStream fos = new FileOutputStream(directory+name); BufferedOutputStream bos = new BufferedOutputStream(fos); pw = new PrintWriter(bos); } catch (IOException e) { return; } pw.println("nb xg yg zg volpix volmarch surfacemarch surfacemarchnb sphericity I1 I2 I3 vI1x vI1y vI1z vI2x vI2y vI2z vI3x vI3y vI3z a b c Fab Fac Fbc xmin xmax ymin ymax zmin zmax dx dy dz border"); for (int i=0;i<n;i++) { pw.print(i+2); pw.print(" "); pw.print(xg[i]); pw.print(" "); pw.print(yg[i]); pw.print(" "); pw.print(zg[i]); pw.print(" "); pw.print(v1[i]); pw.print(" "); pw.print(v2[i]); pw.print(" "); pw.print(s[i]); pw.print(" "); pw.print(s2[i]); sp = 6*v2[i]*Math.sqrt(3.14159265/(s2[i]*s2[i]*s2[i])); pw.print(" "); pw.print(sp); pw.print(" "); pw.print(J[0][i]); pw.print(" "); pw.print(J[1][i]); pw.print(" "); pw.print(J[2][i]); pw.print(" "); pw.print(dir[0][0][i]); pw.print(" "); pw.print(dir[1][0][i]); pw.print(" "); pw.print(dir[2][0][i]); pw.print(" "); pw.print(dir[0][1][i]); pw.print(" "); pw.print(dir[1][1][i]); pw.print(" "); pw.print(dir[2][1][i]); pw.print(" "); pw.print(dir[0][2][i]); pw.print(" "); pw.print(dir[1][2][i]); pw.print(" "); pw.print(dir[2][2][i]); pw.print(" "); double ma =(J[0][i]+J[1][i]-J[2][i]); double mb = (J[0][i]-J[1][i]+J[2][i]); double mc = (-J[0][i]+J[1][i]+J[2][i]); double b1 = (3*mb*mb/(16*Math.sqrt(ma*mc))); b1 = Math.pow(b1,0.2); double a = b1*Math.sqrt(ma/mb); double b = b1; double c=b*Math.sqrt(mc/mb); double Fab =Math.sqrt((J[0][i]+J[1][i]-J[2][i])/(J[0][i]-J[1][i]+J[2][i])); double Fac = Math.sqrt((J[0][i]+J[1][i]-J[2][i])/(-J[0][i]+J[1][i]+J[2][i])); double Fbc = Math.sqrt((J[0][i]-J[1][i]+J[2][i])/(-J[0][i]+J[1][i]+J[2][i])); pw.print(a); pw.print(" "); pw.print(b); pw.print(" "); pw.print(c); pw.print(" "); pw.print(Fab); pw.print(" "); pw.print(Fac); pw.print(" "); pw.print(Fbc); pw.print(" "); pw.print(lmin[i][0]-0.5); pw.print(" "); pw.print(lmax[i][0]+0.5); pw.print(" "); pw.print(lmin[i][1]-0.5); pw.print(" "); pw.print(lmax[i][1]+0.5); pw.print(" "); pw.print(lmin[i][2]-0.5); pw.print(" "); pw.print(lmax[i][2]+0.5); pw.print(" "); double dx=lmax[i][0]-lmin[i][0]+1; double dy=lmax[i][1]-lmin[i][1]+1; double dz=lmax[i][2]-lmin[i][2]+1; double a1 = dx; if (dy<a1) a1=dy; if (dz<a1) a1=dz; double a3 = dx; if (dy>a3) a3=dy; if (dz>a3) a3=dz; double a2=dx; if (dx!=a1 && dx !=a3) a2=dx; if (dy!=a1 && dy !=a3) a2=dy; if (dz!=a1 && dz !=a3) a2=dz; pw.print(" "); pw.print(a1); pw.print(" "); pw.print(a2); pw.print(" "); pw.print(a3); pw.print(" "); pw.println(bord[i]); } pw.close(); } int appart(int v,int []tab, int n) { int val; val =1; for(int i=0;i<n;i++) { if (v==tab[i]) val =val*0; else val =val*1; } return val ; } void ROTATE(double [][]a, int i, int j, int k, int l, double tau,double s) { double g,h; g=a[i][j]; h=a[k][l]; a[i][j]=g-s*(h+g*tau); a[k][l]=h+s*(g-h*tau); } void jacobi(double [][]a ,int n,double [] d,double [][] v) /* a matrice de depart, n taille du systeme, d valeurs propres v matrice de passage : vecteur propre normalises */ { int j,iq,ip,i,nrot; double tresh,theta,tau,t,sm,s,h,g,c; double []b=new double[3]; double []z=new double[3]; for (ip=0;ip<n;ip++) { for (iq=0;iq<n;iq++) v[ip][iq]=0.0; v[ip][ip]=1.0; } for (ip=0;ip<n;ip++) { b[ip]=d[ip]=a[ip][ip]; z[ip]=0.0; } nrot =0; for (i=1;i<=50;i++) { sm=0.0; for (ip=0;ip<n-1;ip++) { for (iq=ip+1;iq<n;iq++) sm += Math.abs(a[ip][iq]); } if (sm == 0.0) { return; } if (i < 4) tresh=0.2*sm/(n*n); else tresh=0.0; for (ip=0;ip<n-1;ip++) { for (iq=ip+1;iq<n;iq++) { g=100.0*Math.abs(a[ip][iq]); if (i > 4 && Math.abs(d[ip])+g == Math.abs(d[ip]) && Math.abs(d[iq])+g == Math.abs(d[iq])) a[ip][iq]=0.0; else if (Math.abs(a[ip][iq]) > tresh) { h=d[iq]-d[ip]; if (Math.abs(h)+g == Math.abs(h)) t=(a[ip][iq])/h; else { theta=0.5*h/(a[ip][iq]); t=1.0/(Math.abs(theta)+Math.sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; } c=1.0/Math.sqrt(1+t*t); s=t*c; tau=s/(1.0+c); h=t*a[ip][iq]; z[ip] -= h; z[iq] += h; d[ip] -= h; d[iq] += h; a[ip][iq]=0.0; for (j=0;j<=ip-1;j++) { ROTATE(a,j,ip,j,iq,tau,s); } for (j=ip+1;j<=iq-1;j++) { ROTATE(a,ip,j,j,iq,tau,s); } for (j=iq+1;j<n;j++) { ROTATE(a,ip,j,iq,j,tau,s); } for (j=0;j<n;j++) { ROTATE(v,j,ip,j,iq,tau,s); } ++(nrot); } } } for (ip=0;ip<n;ip++) { b[ip] += z[ip]; d[ip]=b[ip]; z[ip]=0.0; } } } void eigsrt(double []d,double [][] v,int n) { int k,j,i; double p; for (i=0;i<(n-1);i++) { p=d[k=i]; for (j=i+1;j<n;j++) if (d[j] >= p) p=d[k=j]; if (k != i) { d[k]=d[i]; d[i]=p; for (j=0;j<n;j++) { p=v[j][i]; v[j][i]=v[j][k]; v[j][k]=p; } } } } void transfert1(double[][][] I,int i,double [][] A) { int k,j; for(k=0;k<3;k++) for(j=0;j<3;j++) { A[k][j]=I[k][j][i]; } } void transfert2(double [][] sol ,int i,double [][][]dir ) { int k,j; for(k=0;k<3;k++) for(j=0;j<3;j++) dir[k][j][i]=sol[k][j]; } void inertie(int n,double[][][] I, double[][] J, double dir [][][]) { double[][] A = new double [3][3]; double[][] SOL = new double [3][3]; double[]B = new double [3]; for(int i=0;i<n;i++) { //IJ.showStatus("Inertia calculation ...: "+i+"/"+n); transfert1(I,i,A); jacobi(A,3,B,SOL); eigsrt(B,SOL,3); J[0][i]=B[2]; J[1][i]=B[1]; J[2][i]=B[0]; transfert2(SOL,i,dir); } } /** Create a Thread[] array as large as the number of processors available. * From Stephan Preibisch's Multithreading.java class. See: * http://repo.or.cz/w/trakem2.git?a=blob;f=mpi/fruitfly/general/MultiThreading.java;hb=HEAD */ private Thread[] newThreadArray() { int n_cpus = Runtime.getRuntime().availableProcessors(); return new Thread[n_cpus]; } /** Start all given threads and wait on each of them until all are done. * From Stephan Preibisch's Multithreading.java class. See: * http://repo.or.cz/w/trakem2.git?a=blob;f=mpi/fruitfly/general/MultiThreading.java;hb=HEAD */ private static void startAndJoin(Thread[] threads) { for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread].setPriority(Thread.NORM_PRIORITY); threads[ithread].start(); } try { for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread].join(); } catch (InterruptedException ie) { throw new RuntimeException(ie); } } }
[ "pl@PLPL.(none)" ]
pl@PLPL.(none)
e28a95c985f6f8e7ae5374f5628cf688481af68c
59b9e11d12551e56ccabaf22a5a8581c000720c9
/src/test/java/creational/factoryMethod/FactoryMethodTest.java
ded7c23ff6ce56d2ae3ce1b1db7c2f9ea0df429e
[]
no_license
symeonn/design-patterns
c6300fdb654d42c20adfdc4fadab80acb8baefec
5a3925d7f1085f66739e14771a050850c0d63492
refs/heads/master
2020-04-18T07:16:34.889717
2019-03-04T19:22:42
2019-03-04T19:22:42
167,354,377
0
0
null
null
null
null
UTF-8
Java
false
false
535
java
package creational.factoryMethod; import static org.junit.Assert.*; import org.hamcrest.core.IsInstanceOf; import org.junit.Test; public class FactoryMethodTest { @Test public void test() { AbsFactory fmA = new FactoryA(); assertNotNull(fmA); IProduct prodA = fmA.createProduct(); assertThat(prodA, IsInstanceOf.instanceOf(ProductA.class)); AbsFactory fmB = new FactoryB(); assertNotNull(fmA); IProduct prodB = fmB.createProduct(); assertThat(prodB, IsInstanceOf.instanceOf(ProductB.class)); } }
[ "m.lewandowski@nuadu.com" ]
m.lewandowski@nuadu.com
a8973fc2bcdd03d9369ce4e3439664bed3580d8b
5ac2fb4db63c9383abad7931025d5ac9bc7259d3
/Tama_app/src/main/java/com/tama/chat/utils/KeyboardUtils.java
7fa8e99c0a4c6b4a0e532ec8eca07532b144b6b0
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Testtaccount/TamaAndroid
097f48f913c23449c983fa1260a1696b06742cc8
82912bd3cb80c9fc274c0c23adc005bba85b7fb7
refs/heads/master
2021-09-19T08:26:09.108350
2018-07-25T12:33:20
2018-07-25T12:35:42
139,688,915
0
0
null
null
null
null
UTF-8
Java
false
false
1,195
java
package com.tama.chat.utils; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; public class KeyboardUtils { public static void showKeyboard(Activity activity) { InputMethodManager inputManager = (InputMethodManager) activity. getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager != null) { inputManager.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT); } } public static void hideKeyboard(Activity activity) { InputMethodManager inputManager = (InputMethodManager) activity. getSystemService(Context.INPUT_METHOD_SERVICE); if (activity.getCurrentFocus() != null) { inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } public static void hideKeyboard(View view) { InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } }
[ "avetik.avetik@gmail.com" ]
avetik.avetik@gmail.com
fecc27489fb26cd85ee82e9bf1326db3df88606b
a484a3994e079fc2f340470a658e1797cd44e8de
/app/src/main/java/shangri/example/com/shangri/ui/adapter/NewHeadLinesAdapter.java
c1517b3cd56f87553a66be4cdd64e5f312693d25
[]
no_license
nmbwq/newLiveHome
2c4bef9b2bc0b83038dd91c7bf7a6a6a2c987437
fde0011f14e17ade627426935cd514fcead5096c
refs/heads/master
2020-07-12T20:33:23.502494
2019-08-28T09:55:52
2019-08-28T09:55:52
204,899,192
0
0
null
null
null
null
UTF-8
Java
false
false
6,688
java
package shangri.example.com.shangri.ui.adapter; import android.content.Context; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; import shangri.example.com.shangri.R; import shangri.example.com.shangri.base.BaseListAdapter; import shangri.example.com.shangri.model.bean.response.CollectBean; import shangri.example.com.shangri.model.bean.response.HeadLinesData; import shangri.example.com.shangri.ui.listener.NewsListListener; import shangri.example.com.shangri.ui.listener.PraiseListener; import shangri.example.com.shangri.util.ViewHolder; /** * 咨询 adapter * Created by chengaofu on 2017/6/22. */ public class NewHeadLinesAdapter extends BaseListAdapter<CollectBean.CollectsBean> { private Context mContext; private Animation mLikeAnim; private PraiseListener mPraiseListener; private NewsListListener mNewsListListener; public NewHeadLinesAdapter(Context context, int layoutId, List<CollectBean.CollectsBean> datas) { super(context, layoutId, datas); mContext = context; mLikeAnim = AnimationUtils.loadAnimation(context, R.anim.anim_like); } @Override public void convert(final ViewHolder helper, CollectBean.CollectsBean data) { //, List<Object> payloads ImageView iv_consulation_item = helper.getView(R.id.iv_consulation_item); TextView tv_consultaton_titel = helper.getView(R.id.tv_consultaton_titel); TextView entertain_news_like_num = helper.getView(R.id.entertain_news_like_num); TextView entertain_news_view_count = helper.getView(R.id.entertain_news_view_count); TextView tv_increase = helper.getView(R.id.tv_increase); ImageView iv_dian = helper.getView(R.id.iv_dian); Glide.with(mContext) .load(data.getCover_url()) .placeholder(R.mipmap.bg_touxiang) .crossFade() .into(iv_consulation_item); tv_consultaton_titel.setText(data.getTitle()); entertain_news_like_num.setText(data.getBrowse_amount()); entertain_news_view_count.setText(data.getGood_amount()); String myString = data.getKeywords().replace("|", " "); tv_increase.setText(myString); if (data.getRegister_good() == 0) { //未点赞 iv_dian.setImageResource(R.mipmap.icon_good); entertain_news_view_count.setTextColor(mContext.getResources().getColor(R.color.text_color_light_black)); } else if (data.getRegister_good() == 1) { //已点赞 iv_dian.setImageResource(R.mipmap.icon_good4); entertain_news_view_count.setTextColor(mContext.getResources().getColor(R.color.text_color_light_yellow)); } helper.getView(R.id.ll_dian).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mPraiseListener != null) { mPraiseListener.onPraise(getPosition(helper)); } } }); helper.getView(R.id.video_news_item).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mNewsListListener.onItemClickListener(helper.getAdapterPosition()); } }); } @Override public void convert(ViewHolder helper, CollectBean.CollectsBean data, List<Object> payloads) { //item局部刷新 ImageView iv_dian = helper.getView(R.id.iv_dian); TextView entertain_news_like_num = helper.getView(R.id.entertain_news_like_num); TextView entertain_news_view_count = helper.getView(R.id.entertain_news_view_count); entertain_news_like_num.setText(data.getBrowse_amount()); entertain_news_view_count.setText(data.getGood_amount()); if (data.getRegister_good() == 0) { //未点赞 iv_dian.setImageResource(R.mipmap.icon_good); entertain_news_view_count.setTextColor(mContext.getResources().getColor(R.color.text_color_light_black)); } else if (data.getRegister_collect() == 1) { //已点赞 iv_dian.setImageResource(R.mipmap.icon_good4); entertain_news_view_count.setTextColor(mContext.getResources().getColor(R.color.text_color_light_yellow)); } } // entertain_news_view_count.setText(String.valueOf(data.getGood_amount())); // final TextView like = helper.getView(R.id.addOne_like); //点赞动画 // if (like.getVisibility() == View.GONE) { // like.setVisibility(View.VISIBLE); // like.startAnimation(mLikeAnim); // new Handler().postDelayed(new Runnable() { // public void run() { // like.setVisibility(View.GONE); // } // }, 1000); // } // ImageView likeFinger = helper.getView(R.id.video_news_like_click); // TextView likeNum = helper.getView(R.id.video_news_like_num); // TextView playCount = helper.getView(R.id.video_news_play_count); // playCount.setText(data.getBrowseCount()); // TextView browseCount = helper.getView(R.id.video_news_view_count); // browseCount.setText(data.getBrowseCount()); // if (data.getIsPraise() == 0) { //未点赞 // likeFinger.setImageResource(R.mipmap.ic_zx_dianzan2); // likeNum.setTextColor(mContext.getResources().getColor(R.color.text_color_little_black)); // } else if (data.getIsPraise() == 1) { //已点赞 // likeFinger.setImageResource(R.mipmap.ic_zx_dianzan4); // likeNum.setTextColor(mContext.getResources().getColor(R.color.text_color_light_yellow)); // final TextView like = helper.getView(R.id.addOne_like); //点赞动画 // if (like.getVisibility() == View.GONE) { // like.setVisibility(View.VISIBLE); // like.startAnimation(mLikeAnim); // new Handler().postDelayed(new Runnable() { // public void run() { // like.setVisibility(View.GONE); // } // }, 1000); // } // } // likeNum.setText(String.valueOf(data.getPraiseCount())); public void setPraiseListener(PraiseListener praiseListener) { this.mPraiseListener = praiseListener; } public void setNewsListListener(NewsListListener newsListListener) { //列表点击 this.mNewsListListener = newsListListener; } }
[ "1763312610@qq.com" ]
1763312610@qq.com
7f7a72e9ed461ea156c3a2a209ed9d4bf6414f8a
dd72f7faf3b93ce0a0867df4c34b692032a7f0d9
/src/microsoft_100/ListClass.java
0e48fd6e2f82d7d06044eb03adcf3516209179ef
[]
no_license
dndxxiangyu/Test_java
0bb2214c6764bd8afdedbc16b0b352da652b2c38
b432f491db2d4c440ccafe0da1339a9ca0b7ff21
refs/heads/master
2021-01-10T18:31:19.101710
2017-08-02T02:04:29
2017-08-02T02:04:29
45,538,986
0
0
null
null
null
null
UTF-8
Java
false
false
6,249
java
package microsoft_100; import java.util.LinkedList; import java.util.Queue; import yeheya.List; public class ListClass{ public static void main(String[] args) { SingleLinkedList<Integer> sl = new SingleLinkedList<Integer>(); for(int i = 0; i < 10; i++){ sl.add(i); } System.out.println(sl); sl.reverse(); System.out.println(sl); sl.get(sl.head); // sl.add(100); // System.out.println(sl); // sl.remove(0); // System.out.println(sl); // sl.add(0, 10); // System.out.println(sl); // sl.reverse(); // System.out.println(sl); // sl.clear(); } } /** * * 线性表的顺序表示 */ class ArrayList<E> implements List<E>{ private Object[] elements; private int len; public ArrayList(){ this(10); } public ArrayList(int size){ //if(size ==0) ?? if(size < 0){ throw new IllegalArgumentException("Illegal Capacity: " + size); } this.elements = new Object[size]; this.len = 0; } public ArrayList(ArrayList<E> arr){ } public boolean add(int index, E element) { if(element == null)return false; if(index < 0 || index > this.len){ throw new IndexOutOfBoundsException("index:" + index + ", size:" + this.len); } if(len == elements.length){ Object[] temp = this.elements; elements = new Object[2*temp.length+1]; for(int i = 0; i < temp.length; i++){ elements[i] = temp[i]; } for(int i = 0; i < temp.length; i++){ temp[i] = null; }//clear } for( int i = len; i > index; i--){ elements[i] = elements[i-1]; } elements[index] = element; len++; return true; } public boolean add(E element) { return this.add(len, element); } public void clear() { for(int i = 0; i< this.len; i++){ this.elements[i] = null; } this.len = 0; } public E get(int index) { if(index < 0 || index >= this.len){ throw new IndexOutOfBoundsException("index:" + index + " , size:" + this.len); } return (E) this.elements[index]; } public boolean isEmpty() { return this.len == 0; } public E remove(int index) { if( index < 0 || index >= this.len){ throw new IndexOutOfBoundsException("index:"+index+" , size:"+this.len); } E temp = (E) elements[index]; for(int i = index; i < this.len-1; i++){ elements[index] = elements[index+1]; } elements[len-1] = null; len--; return temp; } public E set(int index, E element) { if(element == null)return null; if(index < 0 || index >= this.len){ throw new IndexOutOfBoundsException("index:" + index + " , size:" + this.len); } E old = (E) elements[index]; elements[index] = element; return old; } public int size() { return this.len; } @Override public String toString() { if(len == 0)return "[]"; StringBuilder sb = new StringBuilder(); sb.append("["); for(int i = 0; i < len; i++){ sb.append(elements[i].toString()); if( i != len - 1)sb.append(","); } sb.append("]"); return sb.toString(); } } /** * * 线性表的链式表示 */ //单链表 class Node<E>{ public E data; public Node<E> next; public Node(E data, Node<E> next){ this.data = data; this.next = next; } public Node(E data){ this(data, null); } public Node(){ this(null,null); } @Override public String toString() { // TODO Auto-generated method stub return data.toString(); } } //带头结点的单链表 class SingleLinkedList<E> implements List<E>{ public Node<E> head; private int len; public SingleLinkedList(){ this.head = new Node<E>(); this.len = 0; } public SingleLinkedList(E[] elements){ this(); Node<E> temp = this.head; for(int i = 0; i < elements.length; i++){ temp.next = new Node<E>(elements[i],null); temp = temp.next; } } public boolean add(int index, E element) { //需要两个指针来表示插入的地方的前后位置 if(element == null)return false; if(index < 0 || index > this.len){ throw new IndexOutOfBoundsException("index: " + index + ", size:" + len); } Node<E> temp = head; Node<E> node = new Node<E>(element); if(len == 0){ head.next = node; }else{ for(int i = 0; i < index; i++){ temp = temp.next; }// find the place to insert node.next = temp.next; temp.next = node; } len++; return true; } public boolean add(E element) { return this.add(len, element); } public void clear() { Node<E> temp = head; Node<E> p = head; for(int i = 0; i < len; i++){ p = temp.next; temp.next = null; temp = p; } temp = null; p = null; len = 0; } public E set(int index, E element) { if(element == null)return null; if(index < 0 || index >= len){ throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + len); } Node<E> temp = head; for(int i = 0; i < index; i++){ temp = temp.next; } E old = temp.next.data; temp.next.data = element; return old; } public E get(int index) { if(index < 0 || index >= len){ throw new IndexOutOfBoundsException("Index:" + index + ", Size: " + len); } Node<E> temp = head; for(int i = 0; i < index; i++){ temp = temp.next; } return temp.next.data; } public boolean isEmpty() { return this.len == 0; } public E remove(int index) { E old = null; if(index < 0 || index >= len){ throw new IndexOutOfBoundsException("Index:" + index + ", Size: " + len); } Node<E> temp = head; for(int i = 0; i < index; i++){ temp = temp.next; } old = temp.next.data; temp.next = temp.next.next; len--; return old; } public int size() { return this.len; } public void reverse(){ if(len > 0){ Node<E> now = head.next; Node<E> front = null; Node<E> after = null; while(now != null){ after = now.next; now.next = front; front = now; now = after; } head.next = front; } } public Node<E> get(Node<E> head){ Node<E> p = head; if(p==null||p.next==null)return p; Node<E> temp = get(p.next); System.out.println(temp); return temp; } @Override public String toString() { if(head.next == null)return "[]"; Node<E> temp = head; StringBuilder sb = new StringBuilder(); sb.append("["); for(int i = 0; i < len; i++){ sb.append(temp.next.data); if(i != len-1)sb.append(","); temp = temp.next; } sb.append("]"); return sb.toString(); } }
[ "wuyu012@126.com" ]
wuyu012@126.com
0bde8ff893bd6b356d230b51d2780676da106318
6a06bc79163c892646a89d0fafe3e46968d8e126
/app/src/main/java/com/example/tchl/liaomei/data/LiaomeiData.java
5577388a58d51d6c8213114665eda3be3f9043da
[]
no_license
whtchl/Liaomei
3126e79e1aa5cf5be75ae44884c589bd12c8087f
c651d46372497a989d559f023d6e9576e4ecd596
refs/heads/master
2021-01-17T17:20:15.983095
2017-01-13T03:22:45
2017-01-13T03:22:45
61,127,288
0
0
null
null
null
null
UTF-8
Java
false
false
242
java
package com.example.tchl.liaomei.data; import com.example.tchl.liaomei.data.entity.Liaomei; import java.util.List; /** * Created by happen on 2016/6/3. */ public class LiaomeiData extends BaseData { public List<Liaomei> results; }
[ "whtchl@126.com" ]
whtchl@126.com
7fea04f7a3e0bcfc8df4f7ef0cf0296ca4f664b1
9afc47389be6c423da2dffb5f37935fd1edb66f2
/src/oca/chapter5/mushfiginkitabi/interfaces/Supervore.java
def40bf1689cbfe756f793d8abe4bd4b803a3c78
[]
no_license
polad1997/Training
8153ae34b1867d23c5025670873ea806f1cca337
62941ed4b3b9065c3b835f0cf5c3e5f8034cef3a
refs/heads/master
2023-05-09T18:45:20.453766
2021-06-13T18:47:33
2021-06-13T18:47:33
167,844,377
0
0
null
null
null
null
UTF-8
Java
false
false
127
java
package oca.chapter5.mushfiginkitabi.interfaces; public interface Supervore extends Herbivore, Omnivore { int a = 2; }
[ "alqayev1997@gmail.com" ]
alqayev1997@gmail.com
c8900af3dff64265391e1e732705a3e369bb4e1c
6ac298dc92c77548c33cc7378b6921836fe56eea
/app/src/main/java/za/co/thamserios/basilread/utils/DateUtil.java
afd279bc15079fcc86f929a2c24eddd3266404e1
[]
no_license
rmukubvu/BasilRead
06287a0c7b80553f86a1ec46ef2d6c8b1053115f
07e42029081af5c228a739b6df79ce5d071aca2e
refs/heads/master
2020-05-19T23:49:30.369801
2019-05-06T21:33:48
2019-05-06T21:33:48
185,275,332
0
0
null
null
null
null
UTF-8
Java
false
false
1,398
java
package za.co.thamserios.basilread.utils; import org.joda.time.DateTime; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by robson on 2017/03/01. */ public class DateUtil { // long unixTime = System.currentTimeMillis() / 1000L; public static java.sql.Timestamp getCurrentTimeStamp() { Date today = new Date(); return new java.sql.Timestamp(today.getTime()); } public static String getFormattedTime(long diff){ long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000); return String.format("%d h %d min(s)",diffHours,diffMinutes); } public static String getFormattedDateFromLong(long date){ Date d = new Date(date); SimpleDateFormat df2 = new SimpleDateFormat("dd MMMM yyyy"); return df2.format(d); } public static String getTimeFromLong(long date){ Date d = new Date(date); SimpleDateFormat df2 = new SimpleDateFormat("HH:mm"); return df2.format(d); } public static int getCurrentDay(){ DateTime dt = new DateTime(); DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Date dateNew = dt.toDate(); return Integer.parseInt(dateFormat.format(dateNew)); } public static long getTimeStamp(){ return new Date().getTime(); } }
[ "rmukubvu@gmail.com" ]
rmukubvu@gmail.com
5ab1a0ff1f1cceb798a2eef432cc1ca4ee56ae66
17d24c22bac343e473df79451e1a12ad803860b2
/pinyougou_git/pinyougou_sellergoods_interface/src/main/java/com/pinyougou/sellergoods/service/GoodsService.java
864fc7bf0ab5973341de652bab42b947b462e7af
[]
no_license
liujianguo90/pinyougou2
0e2492198c299cf36df2cd5f416d9ca9f924821e
a087598cae7d8541a52532536458f978145b12d0
refs/heads/master
2022-07-24T03:15:18.186327
2019-06-29T07:45:56
2019-06-29T07:45:56
194,355,278
0
0
null
2021-08-09T21:01:21
2019-06-29T02:23:50
JavaScript
UTF-8
Java
false
false
731
java
package com.pinyougou.sellergoods.service; import java.util.List; import com.pinyougou.pojo.TbGoods; import entity.PageResult; /** * 业务逻辑接口 * @author Steven * */ public interface GoodsService { /** * 返回全部列表 * @return */ public List<TbGoods> findAll(); /** * 分页查询列表 * @return */ public PageResult<TbGoods> findPage(int pageNum, int pageSize, TbGoods goods); /** * 增加 */ public void add(TbGoods goods); /** * 修改 */ public void update(TbGoods goods); /** * 根据ID获取实体 * @param id * @return */ public TbGoods getById(Long id); /** * 批量删除 * @param ids */ public void delete(Long[] ids); }
[ "2383214764@qq.com" ]
2383214764@qq.com
74836a0d55a85cac44f572c6074c3aad36e940b8
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Lang/8/org/apache/commons/lang3/builder/HashCodeBuilder_append_763.java
4de71986b10ae4e1903442054b37468ccd783d10
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
2,404
java
org apach common lang3 builder assist implement link object hash code hashcod method enabl good code hash code hashcod code method built rule laid book href http java sun doc book effect index html effect java joshua bloch write good code hash code hashcod code method difficult aim simplifi process approach append data field current total multipli multipli relev data type ad current hash code hashcod multipli append integ creat hashcod relev field object includ code hash code hashcod code method deriv field exclud gener field code equal code method code hash code hashcod code method write code pre person string ag smoker hash code hashcod pick hard code randomli chosen odd number ideal hash code builder hashcodebuild append append ag append smoker hash code tohashcod pre requir superclass code hash code hashcod code ad link append super appendsup altern method reflect determin field test field method code reflect hash code reflectionhashcod code code access object accessibleobject set access setaccess code chang visibl field fail secur manag permiss set correctli slower test explicitli typic invoc method pre hash code hashcod hash code builder hashcodebuild reflect hash code reflectionhashcod pre version hash code builder hashcodebuild builder integ append code hash code hashcod code code code arrai param arrai arrai add code hash code hashcod code hash code builder hashcodebuild append arrai arrai total itot total itot constant iconst element arrai append element
[ "hvdthong@gmail.com" ]
hvdthong@gmail.com
11444e4b74a2d3fc023696854639057d61d417a7
95cb1bd066b584348fd3c6f2f17d24cc71f4e52b
/src/main/java/itao/workspace/spring/aop/annotation/Action.java
06573b103fd8c04e79fe57e166c87c683fea02cc
[]
no_license
itaoboy/spring
141b44f7c2b24adbe012e425b5420f0c29169544
12e3ee3481d35ee6b29eb113472c1c5465f993c0
refs/heads/master
2020-04-27T23:33:26.245238
2019-03-10T07:27:59
2019-03-10T07:27:59
174,780,521
0
0
null
null
null
null
UTF-8
Java
false
false
254
java
package itao.workspace.spring.aop.annotation; import java.lang.annotation.*; /** * @author itao * @since 2019-03-09 15:47 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { String name(); }
[ "1716367679@qq.com" ]
1716367679@qq.com
5bf0e024ae1fee9bb1f399974e4fbf19e2ee9bf1
a04c5edcd59bbd65e3b8ef55b4f1a0ef3c4eba89
/src/main/java/by/htp/cinema/web/controllers/crudControllers/CrudTicketController.java
71a3268607bd97882935c027471a4ebde122f13e
[]
no_license
PatskoArkadzi/HTP_JD02_finalProject
6f558f2a6eb5ae8546743143d003c1efd9a6eaf6
abeb446392fc4245433a5900730cf2eb735ebaf6
refs/heads/master
2021-08-16T21:04:19.629179
2018-07-05T14:40:16
2018-07-05T14:40:16
130,855,042
0
0
null
null
null
null
UTF-8
Java
false
false
4,201
java
package by.htp.cinema.web.controllers.crudControllers; import static by.htp.cinema.web.util.ConstantDeclaration.*; import static by.htp.cinema.web.util.HttpRequestParamValidator.*; import static by.htp.cinema.web.util.HttpRequestParamFormatter.*; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import by.htp.cinema.domain.Film; import by.htp.cinema.domain.Genre; import by.htp.cinema.domain.Role; import by.htp.cinema.domain.Ticket; import by.htp.cinema.domain.User; import by.htp.cinema.service.FilmService; import by.htp.cinema.service.FilmSessionService; import by.htp.cinema.service.GenreService; import by.htp.cinema.service.RoleService; import by.htp.cinema.service.SeatService; import by.htp.cinema.service.TicketService; import by.htp.cinema.service.TicketsOrderService; import by.htp.cinema.service.UserService; @Controller @RequestMapping(value = "/newapp/admin/crud/ticket") public class CrudTicketController { @Autowired TicketService ticketService; @Autowired FilmSessionService filmSessionService; @Autowired SeatService seatService; @Autowired @Qualifier("ticketOrderService") TicketsOrderService ticketsOrderService; private static final Logger logger = LogManager.getLogger(); @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView main() { ModelAndView mav = new ModelAndView(); mav.addObject(REQUEST_PARAM_FILM_TICKET_LIST, ticketService.getTicketList()); mav.addObject(REQUEST_PARAM_FILM_SESSION_LIST, filmSessionService.getFilmSessionList()); mav.addObject(REQUEST_PARAM_SEAT_LIST, seatService.getSeatList()); mav.addObject(REQUEST_PARAM_FILM_TICKETS_ORDER_LIST, ticketsOrderService.getTicketsOrderList()); mav.addObject(REQUEST_PARAM_COMMAND_NAME_CRUD_TICKET, new Ticket()); mav.setViewName("springMvcPages/admin/crud_ticket"); return mav; } @RequestMapping(value = "/create", method = RequestMethod.POST) public String create(@ModelAttribute(REQUEST_PARAM_COMMAND_NAME_CRUD_TICKET) Ticket ticket) { validateRequestParamNotNull(ticket.getFilmSession(), ticket.getSeat(), ticket.getOrder()); ticketService.createTicket(ticket); return "redirect:/newapp/admin/crud/ticket/"; } @RequestMapping(value = "/read", method = RequestMethod.GET, produces = { "application/json; charset=UTF-8" }) public @ResponseBody String read(@RequestParam String id) throws UnsupportedEncodingException { validateRequestParamIdnotNull(getInt(id)); Ticket foundTicket = ticketService.readTicket(getInt(id)); return "{\"foundTicket\" : \"" + foundTicket + "\"}"; } @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(@ModelAttribute(REQUEST_PARAM_COMMAND_NAME_CRUD_TICKET) Ticket ticket) { validateRequestParamNotNull(ticket.getId(), ticket.getFilmSession(), ticket.getSeat(), ticket.getOrder()); ticketService.updateTicket(ticket); return "redirect:/newapp/admin/crud/ticket/"; } @RequestMapping(value = "/delete", method = RequestMethod.POST) public String delete(@ModelAttribute(REQUEST_PARAM_COMMAND_NAME_CRUD_TICKET) Ticket ticket) { validateRequestParamIdnotNull(ticket.getId()); ticketService.deleteTicket(ticket); return "redirect:/newapp/admin/crud/ticket/"; } }
[ "arkpatsko@gmail.com" ]
arkpatsko@gmail.com
ce6603b444f4f745a3362836fd7078fe7b562200
fbfc3daa65d0526fca9be38c13117231a2bcb292
/small-framework/src/main/java/code/heitao/small/framework/entity/FormParam.java
5da369a901f70852cef015c0f531e8a8ccfa1eaf
[]
no_license
Aimintao/lightFrame
ab352b7e38ffa41c467b733c573f420c25aaf8d6
093f304f9a012ac5b691be87e29d1044c5f7e8c4
refs/heads/master
2020-03-20T04:25:00.835488
2018-06-28T08:18:30
2018-06-28T08:18:30
137,181,537
0
0
null
null
null
null
UTF-8
Java
false
false
552
java
package code.heitao.small.framework.entity; /** * @author Aimin * @Title: FormParam * @ProjectName lightFrame架构 * @Description: 封装表单参数 * @date 2018/6/26 16:30 */ public class FormParam { private String fieldName; private Object fieldValue; public FormParam(String fieldName, Object fieldValue) { this.fieldName = fieldName; this.fieldValue = fieldValue; } public String getFieldName() { return fieldName; } public Object getFieldValue() { return fieldValue; } }
[ "wb_taoaimin@zhongan.com" ]
wb_taoaimin@zhongan.com
cad2356d1105596cf3b8151944723c38203e840e
a0dfd5c1ac53014855cbdb6c5baf34ee96923b79
/acs/tabbychat/settings/TCSettingEnum.java
ecddd8a465c9e28ceac8e4b4350f0941d199c768
[]
no_license
a3535ed54a5ee6917a46cfa6c3f12679/5ab07bac_orizia_v1
13b0d93ea8cd77e82f0d2e151b00fa41559fe145
1b7507aabd17dea3981a765a18f0798f20815cd7
refs/heads/master
2021-05-08T16:41:38.684821
2018-02-12T14:56:34
2018-02-12T14:56:34
120,166,619
0
0
null
null
null
null
UTF-8
Java
false
false
7,760
java
package acs.tabbychat.settings; import acs.tabbychat.util.TabbyChatUtils; import java.util.Properties; import net.minecraft.client.Minecraft; public class TCSettingEnum extends TCSetting implements ITCSetting { public TCSettingEnum(Object theSetting, String theProperty, String theCategory, int theID) { super(theSetting, theProperty, theCategory, theID); this.type = "enum"; this.width(30); this.height(11); } public TCSettingEnum(Object theSetting, String theProperty, String theCategory, int theID, FormatCodeEnum theFormat) { super(theSetting, theProperty, theCategory, theID, theFormat); this.type = "enum"; } /** * Draws this button to the screen. */ public void drawButton(Minecraft par1, int cursorX, int cursorY) { int centerX = this.x() + this.width() / 2; int fgcolor = -1717526368; if (!this.enabled) { fgcolor = 1721802912; } else if (this.hovered(cursorX, cursorY).booleanValue()) { fgcolor = -1711276128; } int labelColor = this.enabled ? 16777215 : 6710886; drawRect(this.x() + 1, this.y(), this.x() + this.width() - 1, this.y() + 1, fgcolor); drawRect(this.x() + 1, this.y() + this.height() - 1, this.x() + this.width() - 1, this.y() + this.height(), fgcolor); drawRect(this.x(), this.y() + 1, this.x() + 1, this.y() + this.height() - 1, fgcolor); drawRect(this.x() + this.width() - 1, this.y() + 1, this.x() + this.width(), this.y() + this.height() - 1, fgcolor); drawRect(this.x() + 1, this.y() + 1, this.x() + this.width() - 1, this.y() + this.height() - 1, -16777216); this.drawCenteredString(mc.fontRenderer, this.tempValue.toString(), centerX, this.y() + 2, labelColor); this.drawCenteredString(mc.fontRenderer, this.description, this.labelX + mc.fontRenderer.getStringWidth(this.description) / 2, this.y() + (this.height() - 6) / 2, labelColor); } public Enum<?> getTempValue() { return (Enum)this.tempValue; } public Enum<?> getValue() { return (Enum)this.value; } public void loadSelfFromProps(Properties readProps) { String found = (String)readProps.get(this.propertyName); if (found == null) { this.clear(); } else { if (this.propertyName.contains("Color")) { this.value = TabbyChatUtils.parseColor(found); } else if (this.propertyName.contains("Format")) { this.value = TabbyChatUtils.parseFormat(found); } else if (this.propertyName.contains("Sound")) { this.value = TabbyChatUtils.parseSound(found); } else if (this.propertyName.contains("delim")) { this.value = TabbyChatUtils.parseDelimiters(found); } else if (this.propertyName.contains("Stamp")) { this.value = TabbyChatUtils.parseTimestamp(found); } } } public void mouseClicked(int par1, int par2, int par3) { if (this.hovered(par1, par2).booleanValue() && this.enabled) { if (par3 == 1) { this.previous(); } else if (par3 == 0) { this.next(); } } } public void next() { Enum eCast = (Enum)this.tempValue; Enum[] E = (Enum[])eCast.getClass().getEnumConstants(); Enum tmp; if (eCast.ordinal() == E.length - 1) { tmp = Enum.valueOf(eCast.getClass(), E[0].name()); } else { tmp = Enum.valueOf(eCast.getClass(), E[eCast.ordinal() + 1].name()); } this.tempValue = tmp; } public void previous() { Enum eCast = (Enum)this.tempValue; Enum[] E = (Enum[])eCast.getClass().getEnumConstants(); if (eCast.ordinal() == 0) { this.tempValue = Enum.valueOf(eCast.getClass(), E[E.length - 1].name()); } else { this.tempValue = Enum.valueOf(eCast.getClass(), E[eCast.ordinal() - 1].name()); } } public void setTempValueFromProps(Properties readProps) { String found = (String)readProps.get(this.propertyName); if (found == null) { this.tempValue = this.theDefault; } else { if (this.propertyName.contains("Color")) { this.tempValue = TabbyChatUtils.parseColor(found); } else if (this.propertyName.contains("Format")) { this.tempValue = TabbyChatUtils.parseFormat(found); } else if (this.propertyName.contains("Sound")) { this.tempValue = TabbyChatUtils.parseSound(found); } else if (this.propertyName.contains("delim")) { this.tempValue = TabbyChatUtils.parseDelimiters(found); } else if (this.propertyName.contains("Stamp")) { this.tempValue = TabbyChatUtils.parseTimestamp(found); } } } public void setValue(Object var1) { super.setValue(var1); } public void setCleanValue(Object var1) { super.setCleanValue(var1); } public void setTempValue(Object var1) { super.setTempValue(var1); } public void setLabelLoc(int var1) { super.setLabelLoc(var1); } public void setButtonLoc(int var1, int var2) { super.setButtonLoc(var1, var2); } public void setButtonDims(int var1, int var2) { super.setButtonDims(var1, var2); } public void saveSelfToProps(Properties var1) { super.saveSelfToProps(var1); } public void save() { super.save(); } public void resetDescription() { super.resetDescription(); } public void reset() { super.reset(); } public Boolean hovered(int var1, int var2) { return super.hovered(var1, var2); } public String getType() { return super.getType(); } public String getProperty() { return super.getProperty(); } public Object getDefault() { return super.getDefault(); } public boolean enabled() { return super.enabled(); } public void enable() { super.enable(); } public void disable() { super.disable(); } public void clear() { super.clear(); } public void y(int var1) { super.y(var1); } public int y() { return super.y(); } public void x(int var1) { super.x(var1); } public int x() { return super.x(); } public void height(int var1) { super.height(var1); } public int height() { return super.height(); } public void width(int var1) { super.width(var1); } public int width() { return super.width(); } public void actionPerformed() { super.actionPerformed(); } }
[ "unknowlk@tuta.io" ]
unknowlk@tuta.io
76acd97cbdf69054733b2b71042996dbf4f36ecc
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_e7a58a123eae2cec2eb7fc8a2676de0ed432b67d/SqlQuery/2_e7a58a123eae2cec2eb7fc8a2676de0ed432b67d_SqlQuery_s.java
22bde6dc622796de241597ab4fb04c4a28856e57
[]
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
93,372
java
package com.psddev.dari.db; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.joda.time.DateTime; import com.psddev.dari.util.ObjectUtils; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; /** Internal representation of an SQL query based on a Dari one. */ class SqlQuery { private static final Pattern QUERY_KEY_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}"); //private static final Logger LOGGER = LoggerFactory.getLogger(SqlQuery.class); private final SqlDatabase database; private final Query<?> query; private final String aliasPrefix; private final SqlVendor vendor; private final String recordIdField; private final String recordTypeIdField; private final String recordInRowIndexField; private final Map<String, Query.MappedKey> mappedKeys; private final Map<String, ObjectIndex> selectedIndexes; private String selectClause; private String fromClause; private String whereClause; private String groupByClause; private String havingClause; private String orderByClause; private String extraSourceColumns; private final List<String> orderBySelectColumns = new ArrayList<String>(); private final Map<String, String> groupBySelectColumnAliases = new LinkedHashMap<String, String>(); private final List<Join> joins = new ArrayList<Join>(); private final Map<Query<?>, String> subQueries = new LinkedHashMap<Query<?>, String>(); private final Map<Query<?>, SqlQuery> subSqlQueries = new HashMap<Query<?>, SqlQuery>(); private boolean needsDistinct; private Join mysqlIndexHint; private boolean forceLeftJoins; private boolean needsRecordTable; private final List<Predicate> recordMetricDatePredicates = new ArrayList<Predicate>(); private final List<Predicate> recordMetricParentDatePredicates = new ArrayList<Predicate>(); private final List<Predicate> recordMetricDimensionPredicates = new ArrayList<Predicate>(); private final List<Predicate> recordMetricParentDimensionPredicates = new ArrayList<Predicate>(); private final List<Predicate> recordMetricHavingPredicates = new ArrayList<Predicate>(); private final List<Predicate> recordMetricParentHavingPredicates = new ArrayList<Predicate>(); private final List<Sorter> recordMetricSorters = new ArrayList<Sorter>(); private ObjectField recordMetricField; private final Map<String, String> reverseAliasSql = new HashMap<String, String>(); private final List<Predicate> havingPredicates = new ArrayList<Predicate>(); private final List<Predicate> parentHavingPredicates = new ArrayList<Predicate>(); /** * Creates an instance that can translate the given {@code query} * with the given {@code database}. */ public SqlQuery( SqlDatabase initialDatabase, Query<?> initialQuery, String initialAliasPrefix) { database = initialDatabase; query = initialQuery; aliasPrefix = initialAliasPrefix; needsRecordTable = true; vendor = database.getVendor(); recordIdField = aliasedField("r", SqlDatabase.ID_COLUMN); recordTypeIdField = aliasedField("r", SqlDatabase.TYPE_ID_COLUMN); recordInRowIndexField = aliasedField("r", SqlDatabase.IN_ROW_INDEX_COLUMN); mappedKeys = query.mapEmbeddedKeys(database.getEnvironment()); selectedIndexes = new HashMap<String, ObjectIndex>(); for (Map.Entry<String, Query.MappedKey> entry : mappedKeys.entrySet()) { selectIndex(entry.getKey(), entry.getValue()); } } private void selectIndex(String queryKey, Query.MappedKey mappedKey) { ObjectIndex selectedIndex = null; int maxMatchCount = 0; for (ObjectIndex index : mappedKey.getIndexes()) { List<String> indexFields = index.getFields(); int matchCount = 0; for (Query.MappedKey mk : mappedKeys.values()) { ObjectField mkf = mk.getField(); if (mkf != null && indexFields.contains(mkf.getInternalName())) { ++ matchCount; } } if (matchCount > maxMatchCount) { selectedIndex = index; maxMatchCount = matchCount; } } if (selectedIndex != null) { if (maxMatchCount == 1) { for (ObjectIndex index : mappedKey.getIndexes()) { if (index.getFields().size() == 1) { selectedIndex = index; break; } } } selectedIndexes.put(queryKey, selectedIndex); } } public SqlQuery(SqlDatabase initialDatabase, Query<?> initialQuery) { this(initialDatabase, initialQuery, ""); } private String aliasedField(String alias, String field) { StringBuilder fieldBuilder = new StringBuilder(); fieldBuilder.append(aliasPrefix); fieldBuilder.append(alias); fieldBuilder.append('.'); vendor.appendIdentifier(fieldBuilder, field); return fieldBuilder.toString(); } private SqlQuery getOrCreateSubSqlQuery(Query<?> subQuery, boolean forceLeftJoins) { SqlQuery subSqlQuery = subSqlQueries.get(subQuery); if (subSqlQuery == null) { subSqlQuery = new SqlQuery(database, subQuery, aliasPrefix + "s" + subSqlQueries.size()); subSqlQuery.forceLeftJoins = forceLeftJoins; subSqlQuery.initializeClauses(); subSqlQueries.put(subQuery, subSqlQuery); } return subSqlQuery; } /** Initializes FROM, WHERE, and ORDER BY clauses. */ private void initializeClauses() { // Determine whether any of the fields are sourced somewhere else. Set<ObjectField> sourceTables = new HashSet<ObjectField>(); Set<ObjectType> queryTypes = query.getConcreteTypes(database.getEnvironment()); for (ObjectType type : queryTypes) { for (ObjectField field : type.getFields()) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); if (fieldData.isIndexTableSource() && fieldData.getIndexTable() != null && !field.isMetric()) { // TODO/performance: if this is a count(), don't join to this table. // if this is a groupBy() and they don't want to group by // a field in this table, don't join to this table. sourceTables.add(field); } } } @SuppressWarnings("unchecked") Set<UUID> unresolvedTypeIds = (Set<UUID>) query.getOptions().get(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION); if (unresolvedTypeIds != null) { DatabaseEnvironment environment = database.getEnvironment(); for (UUID typeId : unresolvedTypeIds) { ObjectType type = environment.getTypeById(typeId); if (type != null) { for (ObjectField field : type.getFields()) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); if (fieldData.isIndexTableSource() && fieldData.getIndexTable() != null && !field.isMetric()) { sourceTables.add(field); } } } } } String extraJoins = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_JOINS_QUERY_OPTION)); if (extraJoins != null) { Matcher queryKeyMatcher = QUERY_KEY_PATTERN.matcher(extraJoins); int lastEnd = 0; StringBuilder newExtraJoinsBuilder = new StringBuilder(); while (queryKeyMatcher.find()) { newExtraJoinsBuilder.append(extraJoins.substring(lastEnd, queryKeyMatcher.start())); lastEnd = queryKeyMatcher.end(); String queryKey = queryKeyMatcher.group(1); Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), queryKey); mappedKeys.put(queryKey, mappedKey); selectIndex(queryKey, mappedKey); Join join = getJoin(queryKey); join.type = JoinType.LEFT_OUTER; newExtraJoinsBuilder.append(join.getValueField(queryKey, null)); } newExtraJoinsBuilder.append(extraJoins.substring(lastEnd)); extraJoins = newExtraJoinsBuilder.toString(); } // Builds the WHERE clause. StringBuilder whereBuilder = new StringBuilder(); whereBuilder.append("\nWHERE "); String extraWhere = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_WHERE_QUERY_OPTION)); if (!ObjectUtils.isBlank(extraWhere)) { whereBuilder.append('('); } whereBuilder.append("1 = 1"); if (!query.isFromAll()) { Set<UUID> typeIds = query.getConcreteTypeIds(database); whereBuilder.append("\nAND "); if (typeIds.isEmpty()) { whereBuilder.append("0 = 1"); } else { whereBuilder.append(recordTypeIdField); whereBuilder.append(" IN ("); for (UUID typeId : typeIds) { vendor.appendValue(whereBuilder, typeId); whereBuilder.append(", "); } whereBuilder.setLength(whereBuilder.length() - 2); whereBuilder.append(')'); } } Predicate predicate = query.getPredicate(); if (predicate != null) { StringBuilder childBuilder = new StringBuilder(); addWherePredicate(childBuilder, predicate, null, false, true); if (childBuilder.length() > 0) { whereBuilder.append("\nAND ("); whereBuilder.append(childBuilder); whereBuilder.append(')'); } } if (!ObjectUtils.isBlank(extraWhere)) { whereBuilder.append(") "); whereBuilder.append(extraWhere); } // Builds the ORDER BY clause. StringBuilder orderByBuilder = new StringBuilder(); for (Sorter sorter : query.getSorters()) { addOrderByClause(orderByBuilder, sorter, true, false); } if (orderByBuilder.length() > 0) { orderByBuilder.setLength(orderByBuilder.length() - 2); orderByBuilder.insert(0, "\nORDER BY "); } // Builds the FROM clause. StringBuilder fromBuilder = new StringBuilder(); HashMap<String, String> joinTableAliases = new HashMap<String, String>(); boolean didJoin = false; for (Join join : joins) { if (join.indexKeys.isEmpty()) { continue; } didJoin = true; for (String indexKey : join.indexKeys) { joinTableAliases.put(join.getTableName().toLowerCase(Locale.ENGLISH) + join.quoteIndexKey(indexKey), join.getAlias()); } // e.g. JOIN RecordIndex AS i# fromBuilder.append('\n'); if (join.position == 0 && ! needsRecordTable) { fromBuilder.append("FROM "); } else { fromBuilder.append((forceLeftJoins ? JoinType.LEFT_OUTER : join.type).token); fromBuilder.append(' '); } fromBuilder.append(join.getTable()); if (join.type == JoinType.INNER && join.equals(mysqlIndexHint)) { fromBuilder.append(" /*! USE INDEX (k_name_value) */"); } else if (join.sqlIndex == SqlIndex.LOCATION && join.sqlIndexTable.getVersion() >= 2) { fromBuilder.append(" /*! IGNORE INDEX (PRIMARY) */"); } // e.g. ON i#.recordId = r.id if (join.position == 0 && ! needsRecordTable) { // almost all of this is done in the WHERE clause already whereBuilder.append(" AND "); whereBuilder.append(join.getKeyField()); whereBuilder.append(" IN ("); for (String indexKey : join.indexKeys) { whereBuilder.append(join.quoteIndexKey(indexKey)); whereBuilder.append(", "); } whereBuilder.setLength(whereBuilder.length() - 2); whereBuilder.append(")"); } else { fromBuilder.append(" ON "); if (join.getTypeIdField() != null) { fromBuilder.append(join.getTypeIdField()); fromBuilder.append(" = "); fromBuilder.append(aliasPrefix); fromBuilder.append("r"); fromBuilder.append("."); vendor.appendIdentifier(fromBuilder, "typeId"); fromBuilder.append(" AND "); } // AND i#.recordId = r.id fromBuilder.append(join.getIdField()); fromBuilder.append(" = "); fromBuilder.append(aliasPrefix); fromBuilder.append("r"); fromBuilder.append("."); vendor.appendIdentifier(fromBuilder, "id"); // AND i#.symbolId in (...) fromBuilder.append(" AND "); fromBuilder.append(join.getKeyField()); fromBuilder.append(" IN ("); for (String indexKey : join.indexKeys) { fromBuilder.append(join.quoteIndexKey(indexKey)); fromBuilder.append(", "); } fromBuilder.setLength(fromBuilder.length() - 2); fromBuilder.append(")"); } } if (!didJoin) { needsRecordTable = true; } StringBuilder extraColumnsBuilder = new StringBuilder(); Set<String> sourceTableColumns = new HashSet<String>(); for (ObjectField field: sourceTables) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); StringBuilder sourceTableNameBuilder = new StringBuilder(); vendor.appendIdentifier(sourceTableNameBuilder, fieldData.getIndexTable()); String sourceTableName = sourceTableNameBuilder.toString(); String sourceTableAlias; StringBuilder keyNameBuilder = new StringBuilder(field.getParentType().getInternalName()); keyNameBuilder.append('/'); keyNameBuilder.append(field.getInternalName()); Query.MappedKey key = query.mapEmbeddedKey(database.getEnvironment(), keyNameBuilder.toString()); ObjectIndex useIndex = null; for (ObjectIndex index : key.getIndexes()) { if (field.getInternalName().equals(index.getFields().get(0))) { useIndex = index; break; } } if (useIndex == null) { continue; } int symbolId = database.getSymbolId(key.getIndexKey(useIndex)); String sourceTableAndSymbol = fieldData.getIndexTable().toLowerCase(Locale.ENGLISH) + symbolId; SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex); SqlIndex.Table indexTable = useSqlIndex.getReadTable(database, useIndex); // This table hasn't been joined to for this symbol yet. if (!joinTableAliases.containsKey(sourceTableAndSymbol)) { sourceTableAlias = sourceTableAndSymbol; fromBuilder.append(" LEFT OUTER JOIN "); fromBuilder.append(sourceTableName); fromBuilder.append(" AS "); vendor.appendIdentifier(fromBuilder, sourceTableAlias); fromBuilder.append(" ON "); vendor.appendIdentifier(fromBuilder, sourceTableAlias); fromBuilder.append('.'); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(" = "); fromBuilder.append(aliasPrefix); fromBuilder.append("r."); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(" AND "); vendor.appendIdentifier(fromBuilder, sourceTableAlias); fromBuilder.append('.'); vendor.appendIdentifier(fromBuilder, "symbolId"); fromBuilder.append(" = "); fromBuilder.append(symbolId); joinTableAliases.put(sourceTableAndSymbol, sourceTableAlias); } else { sourceTableAlias = joinTableAliases.get(sourceTableAndSymbol); } // Add columns to select. int fieldIndex = 0; for (String indexFieldName : useIndex.getFields()) { if (sourceTableColumns.contains(indexFieldName)) { continue; } sourceTableColumns.add(indexFieldName); String indexColumnName = indexTable.getValueField(database, useIndex, fieldIndex); ++ fieldIndex; query.getExtraSourceColumns().put(indexFieldName, indexFieldName); extraColumnsBuilder.append(sourceTableAlias); extraColumnsBuilder.append('.'); vendor.appendIdentifier(extraColumnsBuilder, indexColumnName); extraColumnsBuilder.append(" AS "); vendor.appendIdentifier(extraColumnsBuilder, indexFieldName); extraColumnsBuilder.append(", "); } } if (extraColumnsBuilder.length() > 0) { extraColumnsBuilder.setLength(extraColumnsBuilder.length() - 2); this.extraSourceColumns = extraColumnsBuilder.toString(); } for (Map.Entry<Query<?>, String> entry : subQueries.entrySet()) { Query<?> subQuery = entry.getKey(); SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, false); if (subSqlQuery.needsDistinct) { needsDistinct = true; } fromBuilder.append("\nINNER JOIN "); vendor.appendIdentifier(fromBuilder, "Record"); fromBuilder.append(' '); fromBuilder.append(subSqlQuery.aliasPrefix); fromBuilder.append("r ON "); fromBuilder.append(entry.getValue()); fromBuilder.append(subSqlQuery.aliasPrefix); fromBuilder.append("r."); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(subSqlQuery.fromClause); } if (extraJoins != null) { fromBuilder.append(' '); fromBuilder.append(extraJoins); } this.whereClause = whereBuilder.toString(); StringBuilder havingBuilder = new StringBuilder(); if (hasDeferredHavingPredicates()) { StringBuilder childBuilder = new StringBuilder(); int i = 0; for (Predicate havingPredicate : havingPredicates) { addWherePredicate(childBuilder, havingPredicate, parentHavingPredicates.get(i++), false, false); } if (childBuilder.length() > 0) { havingBuilder.append(" \nHAVING "); havingBuilder.append(childBuilder); } } String extraHaving = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_HAVING_QUERY_OPTION)); havingBuilder.append(ObjectUtils.isBlank(extraHaving) ? "" : ("\n"+(ObjectUtils.isBlank(this.havingClause) ? "HAVING" : "AND")+" " + extraHaving)); this.havingClause = havingBuilder.toString(); this.orderByClause = orderByBuilder.toString(); this.fromClause = fromBuilder.toString(); } /** Adds the given {@code predicate} to the {@code WHERE} clause. */ private void addWherePredicate( StringBuilder whereBuilder, Predicate predicate, Predicate parentPredicate, boolean usesLeftJoin, boolean deferMetricAndHavingPredicates) { if (predicate instanceof CompoundPredicate) { CompoundPredicate compoundPredicate = (CompoundPredicate) predicate; String operator = compoundPredicate.getOperator(); boolean isNot = PredicateParser.NOT_OPERATOR.equals(operator); // e.g. (child1) OR (child2) OR ... (child#) if (isNot || PredicateParser.OR_OPERATOR.equals(operator)) { StringBuilder compoundBuilder = new StringBuilder(); List<Predicate> children = compoundPredicate.getChildren(); boolean usesLeftJoinChildren; if (children.size() > 1) { usesLeftJoinChildren = true; needsDistinct = true; } else { usesLeftJoinChildren = isNot; } for (Predicate child : children) { StringBuilder childBuilder = new StringBuilder(); addWherePredicate(childBuilder, child, predicate, usesLeftJoinChildren, deferMetricAndHavingPredicates); if (childBuilder.length() > 0) { compoundBuilder.append('('); compoundBuilder.append(childBuilder); compoundBuilder.append(")\nOR "); } } if (compoundBuilder.length() > 0) { compoundBuilder.setLength(compoundBuilder.length() - 4); // e.g. NOT ((child1) OR (child2) OR ... (child#)) if (isNot) { whereBuilder.append("NOT ("); whereBuilder.append(compoundBuilder); whereBuilder.append(')'); } else { whereBuilder.append(compoundBuilder); } } return; // e.g. (child1) AND (child2) AND .... (child#) } else if (PredicateParser.AND_OPERATOR.equals(operator)) { StringBuilder compoundBuilder = new StringBuilder(); for (Predicate child : compoundPredicate.getChildren()) { StringBuilder childBuilder = new StringBuilder(); addWherePredicate(childBuilder, child, predicate, usesLeftJoin, deferMetricAndHavingPredicates); if (childBuilder.length() > 0) { compoundBuilder.append('('); compoundBuilder.append(childBuilder); compoundBuilder.append(")\nAND "); } } if (compoundBuilder.length() > 0) { compoundBuilder.setLength(compoundBuilder.length() - 5); whereBuilder.append(compoundBuilder); } return; } } else if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate; String queryKey = comparisonPredicate.getKey(); Query.MappedKey mappedKey = mappedKeys.get(queryKey); boolean isFieldCollection = mappedKey.isInternalCollectionType(); Join join = null; if (mappedKey.getField() != null && parentPredicate instanceof CompoundPredicate && PredicateParser.OR_OPERATOR.equals(((CompoundPredicate) parentPredicate).getOperator())) { for (Join j : joins) { if (j.parent == parentPredicate && j.sqlIndex.equals(SqlIndex.Static.getByType(mappedKeys.get(queryKey).getInternalType()))) { join = j; join.addIndexKey(queryKey); needsDistinct = true; break; } } if (join == null) { join = getJoin(queryKey); join.parent = parentPredicate; } } else if (isFieldCollection) { join = createJoin(queryKey); } else { join = getJoin(queryKey); } if (usesLeftJoin) { join.type = JoinType.LEFT_OUTER; } if (isFieldCollection && (join.sqlIndexTable == null || join.sqlIndexTable.getVersion() < 2)) { needsDistinct = true; } if (deferMetricAndHavingPredicates) { if (mappedKey.getField() != null) { if (mappedKey.getField().isMetric()) { if (recordMetricField == null) { recordMetricField = mappedKey.getField(); } else if (! recordMetricField.equals(mappedKey.getField())) { throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName() + " AND " + mappedKey.getField().getInternalName()); } if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { recordMetricDatePredicates.add(predicate); recordMetricParentDatePredicates.add(parentPredicate); } else if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { recordMetricDimensionPredicates.add(predicate); recordMetricParentDimensionPredicates.add(parentPredicate); } else { recordMetricHavingPredicates.add(predicate); recordMetricParentHavingPredicates.add(parentPredicate); } return; } } if (join.isHaving) { // pass for now; we'll get called again later. havingPredicates.add(predicate); parentHavingPredicates.add(parentPredicate); return; } } String joinValueField = join.getValueField(queryKey, comparisonPredicate); if (reverseAliasSql.containsKey(joinValueField)) { joinValueField = reverseAliasSql.get(joinValueField); } String operator = comparisonPredicate.getOperator(); StringBuilder comparisonBuilder = new StringBuilder(); boolean hasMissing = false; int subClauseCount = 0; boolean isNotEqualsAll = PredicateParser.NOT_EQUALS_ALL_OPERATOR.equals(operator); if (isNotEqualsAll || PredicateParser.EQUALS_ANY_OPERATOR.equals(operator)) { Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate); // e.g. field IN (SELECT ...) if (valueQuery != null) { if (isNotEqualsAll || isFieldCollection) { needsDistinct = true; } if (findSimilarComparison(mappedKey.getField(), query.getPredicate())) { whereBuilder.append(joinValueField); if (isNotEqualsAll) { whereBuilder.append(" NOT"); } whereBuilder.append(" IN ("); whereBuilder.append(new SqlQuery(database, valueQuery).subQueryStatement()); whereBuilder.append(')'); } else { SqlQuery subSqlQuery = getOrCreateSubSqlQuery(valueQuery, join.type == JoinType.LEFT_OUTER); subQueries.put(valueQuery, joinValueField + (isNotEqualsAll ? " != " : " = ")); whereBuilder.append(subSqlQuery.whereClause.substring(7)); } return; } for (Object value : comparisonPredicate.resolveValues(database)) { if (value == null) { ++ subClauseCount; comparisonBuilder.append("0 = 1"); } else if (value == Query.MISSING_VALUE) { ++ subClauseCount; hasMissing = true; comparisonBuilder.append(joinValueField); if (isNotEqualsAll) { if (isFieldCollection) { needsDistinct = true; } comparisonBuilder.append(" IS NOT NULL"); } else { join.type = JoinType.LEFT_OUTER; comparisonBuilder.append(" IS NULL"); } } else if (value instanceof Region) { List<Location> locations = ((Region) value).getLocations(); if (!locations.isEmpty()) { ++ subClauseCount; if (isNotEqualsAll) { comparisonBuilder.append("NOT "); } try { vendor.appendWhereRegion(comparisonBuilder, (Region) value, joinValueField); } catch (UnsupportedIndexException uie) { throw new UnsupportedIndexException(vendor, queryKey); } } } else { ++ subClauseCount; if (isNotEqualsAll) { join.type = JoinType.LEFT_OUTER; needsDistinct = true; hasMissing = true; comparisonBuilder.append('('); comparisonBuilder.append(joinValueField); comparisonBuilder.append(" IS NULL OR "); comparisonBuilder.append(joinValueField); if (join.likeValuePrefix != null) { comparisonBuilder.append(" NOT LIKE "); join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%"); } else { comparisonBuilder.append(" != "); join.appendValue(comparisonBuilder, comparisonPredicate, value); } comparisonBuilder.append(')'); } else { comparisonBuilder.append(joinValueField); if (join.likeValuePrefix != null) { comparisonBuilder.append(" LIKE "); join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%"); } else { comparisonBuilder.append(" = "); join.appendValue(comparisonBuilder, comparisonPredicate, value); } } } comparisonBuilder.append(isNotEqualsAll ? " AND " : " OR "); } if (comparisonBuilder.length() == 0) { whereBuilder.append(isNotEqualsAll ? "1 = 1" : "0 = 1"); return; } } else { boolean isStartsWith = PredicateParser.STARTS_WITH_OPERATOR.equals(operator); boolean isContains = PredicateParser.CONTAINS_OPERATOR.equals(operator); String sqlOperator = isStartsWith ? "LIKE" : isContains ? "LIKE" : PredicateParser.LESS_THAN_OPERATOR.equals(operator) ? "<" : PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR.equals(operator) ? "<=" : PredicateParser.GREATER_THAN_OPERATOR.equals(operator) ? ">" : PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(operator) ? ">=" : null; // e.g. field OP value1 OR field OP value2 OR ... field OP value# if (sqlOperator != null) { for (Object value : comparisonPredicate.resolveValues(database)) { ++ subClauseCount; if (value == null) { comparisonBuilder.append("0 = 1"); } else if (value instanceof Location) { ++ subClauseCount; if (isNotEqualsAll) { comparisonBuilder.append("NOT "); } try { vendor.appendWhereLocation(comparisonBuilder, (Location) value, joinValueField); } catch (UnsupportedIndexException uie) { throw new UnsupportedIndexException(vendor, queryKey); } } else if (value == Query.MISSING_VALUE) { hasMissing = true; join.type = JoinType.LEFT_OUTER; comparisonBuilder.append(joinValueField); comparisonBuilder.append(" IS NULL"); } else { comparisonBuilder.append(joinValueField); comparisonBuilder.append(' '); comparisonBuilder.append(sqlOperator); comparisonBuilder.append(' '); if (isStartsWith) { value = value.toString() + "%"; } else if (isContains) { value = "%" + value.toString() + "%"; } join.appendValue(comparisonBuilder, comparisonPredicate, value); } comparisonBuilder.append(" OR "); } if (comparisonBuilder.length() == 0) { whereBuilder.append("0 = 1"); return; } } } if (comparisonBuilder.length() > 0) { comparisonBuilder.setLength(comparisonBuilder.length() - 5); if (!hasMissing) { if (join.needsIndexTable) { String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey)); if (indexKey != null) { whereBuilder.append(join.getKeyField()); whereBuilder.append(" = "); whereBuilder.append(join.quoteIndexKey(indexKey)); whereBuilder.append(" AND "); } } if (join.needsIsNotNull) { whereBuilder.append(joinValueField); whereBuilder.append(" IS NOT NULL AND "); } if (subClauseCount > 1) { needsDistinct = true; whereBuilder.append('('); comparisonBuilder.append(')'); } } whereBuilder.append(comparisonBuilder); return; } } throw new UnsupportedPredicateException(this, predicate); } private void addOrderByClause(StringBuilder orderByBuilder, Sorter sorter, boolean deferMetricPredicates, boolean useGroupBySelectAliases) { String operator = sorter.getOperator(); boolean ascending = Sorter.ASCENDING_OPERATOR.equals(operator); boolean descending = Sorter.DESCENDING_OPERATOR.equals(operator); boolean closest = Sorter.CLOSEST_OPERATOR.equals(operator); boolean farthest = Sorter.CLOSEST_OPERATOR.equals(operator); if (ascending || descending || closest || farthest) { String queryKey = (String) sorter.getOptions().get(0); if (deferMetricPredicates) { ObjectField sortField = mappedKeys.get(queryKey).getField(); if (sortField != null && sortField.isMetric()) { if (recordMetricField == null) { recordMetricField = sortField; } else if (! recordMetricField.equals(sortField)) { throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName() + " AND " + sortField.getInternalName()); } recordMetricSorters.add(sorter); return; } } Join join = getSortFieldJoin(queryKey); String joinValueField = join.getValueField(queryKey, null); if (useGroupBySelectAliases && groupBySelectColumnAliases.containsKey(joinValueField)) { joinValueField = groupBySelectColumnAliases.get(joinValueField); } Query<?> subQuery = mappedKeys.get(queryKey).getSubQueryWithSorter(sorter, 0); if (subQuery != null) { SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, true); subQueries.put(subQuery, joinValueField + " = "); orderByBuilder.append(subSqlQuery.orderByClause.substring(9)); orderByBuilder.append(", "); return; } if (ascending || descending) { orderByBuilder.append(joinValueField); if (! join.isHaving) { orderBySelectColumns.add(joinValueField); } } else if (closest || farthest) { Location location = (Location) sorter.getOptions().get(1); StringBuilder selectBuilder = new StringBuilder(); try { vendor.appendNearestLocation(orderByBuilder, selectBuilder, location, joinValueField); if (!join.isHaving) { orderBySelectColumns.add(selectBuilder.toString()); } } catch(UnsupportedIndexException uie) { throw new UnsupportedIndexException(vendor, queryKey); } } orderByBuilder.append(' '); orderByBuilder.append(ascending || closest ? "ASC" : "DESC"); orderByBuilder.append(", "); return; } throw new UnsupportedSorterException(database, sorter); } private boolean findSimilarComparison(ObjectField field, Predicate predicate) { if (field != null) { if (predicate instanceof CompoundPredicate) { for (Predicate child : ((CompoundPredicate) predicate).getChildren()) { if (findSimilarComparison(field, child)) { return true; } } } else if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparison = (ComparisonPredicate) predicate; Query.MappedKey mappedKey = mappedKeys.get(comparison.getKey()); if (field.equals(mappedKey.getField()) && mappedKey.getSubQueryWithComparison(comparison) == null) { return true; } } } return false; } private boolean hasDeferredHavingPredicates() { if (! havingPredicates.isEmpty()) { return true; } else { return false; } } private boolean hasAnyDeferredMetricPredicates() { if (! recordMetricDatePredicates.isEmpty() || ! recordMetricDimensionPredicates.isEmpty() || ! recordMetricHavingPredicates.isEmpty() || ! recordMetricSorters.isEmpty()) { return true; } else { return false; } } /** * Returns an SQL statement that can be used to get a count * of all rows matching the query. */ public String countStatement() { StringBuilder statementBuilder = new StringBuilder(); needsRecordTable = false; initializeClauses(); statementBuilder.append("SELECT COUNT("); if (needsDistinct) { statementBuilder.append("DISTINCT "); } statementBuilder.append(recordIdField); statementBuilder.append(')'); if (needsRecordTable) { statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(' '); statementBuilder.append(aliasPrefix); statementBuilder.append('r'); } statementBuilder.append(fromClause.replace(" /*! USE INDEX (k_name_value) */", "")); if (! recordMetricHavingPredicates.isEmpty()) { statementBuilder.append(" \nJOIN ("); appendSubqueryMetricSql(statementBuilder, recordMetricField); statementBuilder.append(") m \nON ("); appendSimpleOnClause(statementBuilder, vendor, "r", "id", "=", "m", "id"); statementBuilder.append(" AND "); appendSimpleOnClause(statementBuilder, vendor, "r", "typeId", "=", "m", "typeId"); statementBuilder.append(')'); statementBuilder.append(whereClause); StringBuilder havingChildBuilder = new StringBuilder(); for (int i = 0; i < recordMetricHavingPredicates.size(); i++) { addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false); havingChildBuilder.append(" AND "); } if (havingChildBuilder.length() > 0) { havingChildBuilder.setLength(havingChildBuilder.length()-5); // " AND " statementBuilder.append(" AND "); statementBuilder.append(havingChildBuilder); } } else { statementBuilder.append(whereClause); } return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to delete all rows * matching the query. */ public String deleteStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); if (hasAnyDeferredMetricPredicates()) { throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName()); } statementBuilder.append("DELETE r\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(' '); statementBuilder.append(aliasPrefix); statementBuilder.append('r'); statementBuilder.append(fromClause); statementBuilder.append(whereClause); statementBuilder.append(havingClause); statementBuilder.append(orderByClause); return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to get all objects * grouped by the values of the given {@code groupFields}. */ public String groupStatement(String[] groupFields) { Map<String, Join> groupJoins = new LinkedHashMap<String, Join>(); Map<String, SqlQuery> groupSubSqlQueries = new HashMap<String, SqlQuery>(); needsRecordTable = false; if (groupFields != null) { for (String groupField : groupFields) { Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), groupField); if (mappedKey.getField() != null) { if (mappedKey.getField().isMetric()) { if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { // TODO: this one has to work eventually . . . } else if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { // TODO: this one has to work eventually . . . throw new Query.NoFieldException(query.getGroup(), groupField); } else { throw new RuntimeException("Unable to group by @MetricValue: " + groupField); } } } mappedKeys.put(groupField, mappedKey); Iterator<ObjectIndex> indexesIterator = mappedKey.getIndexes().iterator(); if (indexesIterator.hasNext()) { ObjectIndex selectedIndex = indexesIterator.next(); while (indexesIterator.hasNext()) { ObjectIndex index = indexesIterator.next(); if (selectedIndex.getFields().size() < index.getFields().size()) { selectedIndex = index; } } selectedIndexes.put(groupField, selectedIndex); } Join join = getJoin(groupField); Query<?> subQuery = mappedKey.getSubQueryWithGroupBy(); if (subQuery != null) { SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, true); groupSubSqlQueries.put(groupField, subSqlQuery); subQueries.put(subQuery, join.getValueField(groupField, null) + " = "); } groupJoins.put(groupField, join); } } StringBuilder statementBuilder = new StringBuilder(); StringBuilder groupBy = new StringBuilder(); initializeClauses(); if (hasAnyDeferredMetricPredicates()) { // add "id" and "dimensionId" to groupJoins mappedKeys.put(Query.ID_KEY, query.mapEmbeddedKey(database.getEnvironment(), Query.ID_KEY)); groupJoins.put(Query.ID_KEY, getJoin(Query.ID_KEY)); mappedKeys.put(Query.DIMENSION_KEY, query.mapEmbeddedKey(database.getEnvironment(), Query.DIMENSION_KEY)); groupJoins.put(Query.DIMENSION_KEY, getJoin(Query.DIMENSION_KEY)); } statementBuilder.append("SELECT COUNT("); if (needsDistinct) { statementBuilder.append("DISTINCT "); } statementBuilder.append(recordIdField); statementBuilder.append(')'); statementBuilder.append(' '); vendor.appendIdentifier(statementBuilder, "_count"); int columnNum = 0; for (Map.Entry<String, Join> entry : groupJoins.entrySet()) { statementBuilder.append(", "); if (groupSubSqlQueries.containsKey(entry.getKey())) { for (String subSqlSelectField : groupSubSqlQueries.get(entry.getKey()).orderBySelectColumns) { statementBuilder.append(subSqlSelectField); } } else { statementBuilder.append(entry.getValue().getValueField(entry.getKey(), null)); } statementBuilder.append(' '); String columnAlias = null; if (! entry.getValue().queryKey.equals(Query.ID_KEY) && ! entry.getValue().queryKey.equals(Query.DIMENSION_KEY)) { // Special case for id and dimensionId // These column names just need to be unique if we put this statement in a subquery columnAlias = "value" + columnNum; groupBySelectColumnAliases.put(entry.getValue().getValueField(entry.getKey(), null), columnAlias); } ++columnNum; if (columnAlias != null) { vendor.appendIdentifier(statementBuilder, columnAlias); } } selectClause = statementBuilder.toString(); for (String field : orderBySelectColumns) { statementBuilder.append(", "); statementBuilder.append(field); } if (needsRecordTable) { statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); } statementBuilder.append(fromClause.replace(" /*! USE INDEX (k_name_value) */", "")); statementBuilder.append(whereClause); for (Map.Entry<String, Join> entry : groupJoins.entrySet()) { if (groupSubSqlQueries.containsKey(entry.getKey())) { for (String subSqlSelectField : groupSubSqlQueries.get(entry.getKey()).orderBySelectColumns) { groupBy.append(subSqlSelectField); } } else { groupBy.append(entry.getValue().getValueField(entry.getKey(), null)); } groupBy.append(", "); } for (String field : orderBySelectColumns) { groupBy.append(field); groupBy.append(", "); } if (groupBy.length() > 0) { groupBy.setLength(groupBy.length() - 2); groupBy.insert(0, " GROUP BY "); } groupByClause = groupBy.toString(); statementBuilder.append(groupByClause); statementBuilder.append(havingClause); if (!orderBySelectColumns.isEmpty()) { if (orderByClause.length() > 0) { statementBuilder.append(orderByClause); statementBuilder.append(", "); } else { statementBuilder.append(" ORDER BY "); } int i = 0; for (Map.Entry<String, Join> entry : groupJoins.entrySet()) { if (i++ > 0) { statementBuilder.append(", "); } statementBuilder.append(entry.getValue().getValueField(entry.getKey(), null)); } } else { statementBuilder.append(orderByClause); } if (hasAnyDeferredMetricPredicates()) { // If there are deferred HAVING predicates, we need to go ahead and execute the metric query // TODO: there might be a way to filter on more than 1 metric simultaneously. return buildGroupedMetricSql(recordMetricField.getInternalName(), groupFields, selectClause, fromClause, whereClause, groupByClause, orderByClause); } else { return statementBuilder.toString(); } } /** * Returns an SQL statement that can be used to get the sum * of the specified Metric {@code metricFieldName} grouped by the values * of the given {@code groupFields}. */ public String groupedMetricSql(String metricFieldName, String[] groupFields) { int addFields = 2; boolean addIdField = true; boolean addDimField = true; for (int i = 0; i < groupFields.length; i++) { if (Query.ID_KEY.equals(groupFields[i])) { addFields--; addIdField = false; } if (Query.DIMENSION_KEY.equals(groupFields[i])) { addFields--; addDimField = false; } } String[] innerGroupByFields = Arrays.copyOf(groupFields, groupFields.length+addFields); if (addIdField) { innerGroupByFields[groupFields.length] = Query.ID_KEY; } if (addDimField) { innerGroupByFields[groupFields.length+1] = Query.DIMENSION_KEY; } // This prepares selectClause, et al. groupStatement(innerGroupByFields); return buildGroupedMetricSql(metricFieldName, groupFields, selectClause, fromClause, whereClause, groupByClause, orderByClause); } private String buildGroupedMetricSql(String metricFieldName, String[] groupFields, String selectClause, String fromClause, String whereClause, String groupByClause, String orderByClause) { StringBuilder selectBuilder = new StringBuilder(selectClause); StringBuilder fromBuilder = new StringBuilder(fromClause); StringBuilder whereBuilder = new StringBuilder(whereClause); StringBuilder groupByBuilder = new StringBuilder(groupByClause); StringBuilder havingBuilder = new StringBuilder(orderByClause); StringBuilder orderByBuilder = new StringBuilder(orderByClause); Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), metricFieldName); if (mappedKey.getField() == null) { throw new Query.NoFieldException(query.getGroup(), metricFieldName); } ObjectField metricField = mappedKey.getField(); String actionSymbol = metricField.getUniqueName(); // JavaDeclaringClassName() + "/" + metricField.getInternalName(); selectBuilder.insert(7, "MIN(r.data) minData, MAX(r.data) maxData, "); // Right after "SELECT " (7 chars) fromBuilder.insert(0, "FROM "+MetricAccess.METRIC_TABLE+" r "); whereBuilder.append(" AND r."+MetricAccess.METRIC_SYMBOL_FIELD+" = "); vendor.appendValue(whereBuilder, database.getSymbolId(actionSymbol)); // If a dimensionId is not specified, we will append dimensionId = 00000000000000000000000000000000 if (recordMetricDimensionPredicates.isEmpty()) { whereBuilder.append(" AND "); appendSimpleWhereClause(whereBuilder, vendor, "r", MetricAccess.METRIC_DIMENSION_FIELD, "=", MetricAccess.getDimensionIdByValue(database, null)); } // Apply deferred WHERE predicates (eventDates and dimensionIds) for (int i = 0; i < recordMetricDatePredicates.size(); i++) { whereBuilder.append(" AND "); addWherePredicate(whereBuilder, recordMetricDatePredicates.get(i), recordMetricParentDatePredicates.get(i), false, false); } for (int i = 0; i < recordMetricDimensionPredicates.size(); i++) { whereBuilder.append(" AND "); addWherePredicate(whereBuilder, recordMetricDimensionPredicates.get(i), recordMetricParentDimensionPredicates.get(i), false, false); } String innerSql = selectBuilder.toString() + " " + fromBuilder.toString() + " " + whereBuilder.toString() + " " + groupByBuilder.toString() + " " + havingBuilder.toString() + " " + orderByBuilder.toString(); selectBuilder = new StringBuilder(); fromBuilder = new StringBuilder(); whereBuilder = new StringBuilder(); groupByBuilder = new StringBuilder(); havingBuilder = new StringBuilder(); orderByBuilder = new StringBuilder(); selectBuilder.append("SELECT "); StringBuilder amountBuilder = new StringBuilder(); MetricAccess.Static.appendSelectCalculatedAmountSql(amountBuilder, vendor, "minData", "maxData", true); selectBuilder.append(amountBuilder); reverseAliasSql.put(metricField.getInternalName(), amountBuilder.toString()); vendor.appendAlias(selectBuilder, metricField.getInternalName()); selectBuilder.append(", COUNT("); vendor.appendIdentifier(selectBuilder, "id"); selectBuilder.append(") "); vendor.appendIdentifier(selectBuilder, "_count"); List<String> groupBySelectColumns = new ArrayList<String>(); for (String field : groupBySelectColumnAliases.values()) { groupBySelectColumns.add(field); } // Special case for id and dimensionId for (int i = 0; i < groupFields.length; i++) { if (Query.ID_KEY.equals(groupFields[i])) { groupBySelectColumns.add("id"); } if (Query.DIMENSION_KEY.equals(groupFields[i])) { groupBySelectColumns.add("dimensionId"); } } for (String field : groupBySelectColumns) { selectBuilder.append(", "); vendor.appendIdentifier(selectBuilder, field); } fromBuilder.append(" \nFROM ("); fromBuilder.append(innerSql); fromBuilder.append(" ) x "); if (!groupBySelectColumns.isEmpty()) { groupByBuilder.append(" GROUP BY "); for (String field : groupBySelectColumns) { if (groupByBuilder.length() > 10) { // " GROUP BY ".length() groupByBuilder.append(", "); } vendor.appendIdentifier(groupByBuilder, field); } } // Apply deferred HAVING predicates (sums) StringBuilder havingChildBuilder = new StringBuilder(); for (int i = 0; i < recordMetricHavingPredicates.size(); i++) { addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false); havingChildBuilder.append(" AND "); } if (havingChildBuilder.length() > 0) { havingChildBuilder.setLength(havingChildBuilder.length()-5); // " AND " havingBuilder.append(" HAVING "); havingBuilder.append(havingChildBuilder); } // Apply all ORDER BY (deferred and original) for (Sorter sorter : query.getSorters()) { addOrderByClause(orderByBuilder, sorter, false, true); } if (orderByBuilder.length() > 0) { orderByBuilder.setLength(orderByBuilder.length() - 2); orderByBuilder.insert(0, "\nORDER BY "); } return selectBuilder + " " + fromBuilder + " " + whereBuilder + " " + groupByBuilder + " " + havingBuilder + " " + orderByBuilder; } private void appendSubqueryMetricSql(StringBuilder sql, ObjectField metricField) { String actionSymbol = metricField.getUniqueName(); // JavaDeclaringClassName() + "/" + metricField.getInternalName(); StringBuilder minData = new StringBuilder("MIN("); vendor.appendIdentifier(minData, "m2"); minData.append('.'); vendor.appendIdentifier(minData, MetricAccess.METRIC_DATA_FIELD); minData.append(')'); StringBuilder maxData = new StringBuilder("MAX("); vendor.appendIdentifier(maxData, "m2"); maxData.append('.'); vendor.appendIdentifier(maxData, MetricAccess.METRIC_DATA_FIELD); maxData.append(')'); sql.append("SELECT "); appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.ID_COLUMN); sql.append(", "); appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.TYPE_ID_COLUMN); sql.append(", "); MetricAccess.Static.appendSelectCalculatedAmountSql(sql, vendor, minData.toString(), maxData.toString(), false); sql.append(' '); vendor.appendAlias(sql, metricField.getInternalName()); sql.append(" FROM "); vendor.appendIdentifier(sql, SqlDatabase.RECORD_TABLE); sql.append(" "); vendor.appendIdentifier(sql, "r"); // Left joins if we're only sorting, not filtering. if (recordMetricHavingPredicates.isEmpty()) { sql.append(" \nLEFT OUTER JOIN "); } else { sql.append(" \nINNER JOIN "); } vendor.appendIdentifier(sql, MetricAccess.METRIC_TABLE); sql.append(" "); vendor.appendIdentifier(sql, "m2"); sql.append(" ON (\n"); appendSimpleOnClause(sql, vendor, "r", SqlDatabase.ID_COLUMN, "=", "m2", MetricAccess.METRIC_ID_FIELD); sql.append(" AND \n"); appendSimpleOnClause(sql, vendor, "r", SqlDatabase.TYPE_ID_COLUMN, "=", "m2", MetricAccess.METRIC_TYPE_FIELD); sql.append(" AND \n"); appendSimpleWhereClause(sql, vendor, "m2", MetricAccess.METRIC_SYMBOL_FIELD, "=", database.getSymbolId(actionSymbol)); // If a dimensionId is not specified, we will append dimensionId = 00000000000000000000000000000000 if (recordMetricDimensionPredicates.isEmpty()) { sql.append(" AND "); appendSimpleWhereClause(sql, vendor, "m2", MetricAccess.METRIC_DIMENSION_FIELD, "=", MetricAccess.getDimensionIdByValue(database, null)); } // Apply deferred WHERE predicates (eventDates and metric Dimensions) for (int i = 0; i < recordMetricDatePredicates.size(); i++) { sql.append(" AND "); vendor.appendIdentifier(sql, "m2"); sql.append("."); addWherePredicate(sql, recordMetricDatePredicates.get(i), recordMetricParentDatePredicates.get(i), false, false); } for (int i = 0; i < recordMetricDimensionPredicates.size(); i++) { sql.append(" AND "); vendor.appendIdentifier(sql, "m2"); sql.append("."); addWherePredicate(sql, recordMetricDimensionPredicates.get(i), recordMetricParentDimensionPredicates.get(i), false, false); } sql.append(")"); // Apply the "main" JOINs sql.append(fromClause); // Apply the "main" WHERE clause sql.append(whereClause); sql.append(" GROUP BY "); appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.ID_COLUMN); sql.append(", "); appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.TYPE_ID_COLUMN); sql.append(", "); appendSimpleAliasedColumn(sql, vendor, "m2", MetricAccess.METRIC_DIMENSION_FIELD); sql.append(orderByClause); if (! recordMetricSorters.isEmpty()) { StringBuilder orderByBuilder = new StringBuilder(); for (Sorter sorter : recordMetricSorters) { addOrderByClause(orderByBuilder, sorter, false, true); } if (orderByBuilder.length() > 0) { orderByBuilder.setLength(orderByBuilder.length() - 2); orderByBuilder.insert(0, "\nORDER BY "); sql.append(orderByBuilder); } } // Add placeholder for LIMIT/OFFSET sql injected by SqlDatabase sql.append(vendor.getLimitOffsetPlaceholder()); } /** * Returns an SQL statement that can be used to get when the rows * matching the query were last updated. */ public String lastUpdateStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT MAX(r."); vendor.appendIdentifier(statementBuilder, "updateDate"); statementBuilder.append(")\nFROM "); vendor.appendIdentifier(statementBuilder, "RecordUpdate"); statementBuilder.append(' '); statementBuilder.append(aliasPrefix); statementBuilder.append('r'); statementBuilder.append(fromClause); statementBuilder.append(whereClause); return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to list all rows * matching the query. */ public String selectStatement() { StringBuilder statementBuilder = new StringBuilder(); if (query.getOptions().get(State.DISABLE_SECONDARY_FETCH_QUERY_OPTION) == null) { if (query.getOptions().get(State.FORCE_SECONDARY_FETCH_QUERY_OPTION) != null || !query.getSorters().isEmpty()) { needsRecordTable = false; } } initializeClauses(); statementBuilder.append("SELECT"); if (needsDistinct && vendor.supportsDistinctBlob()) { statementBuilder.append(" DISTINCT"); } statementBuilder.append(" r."); vendor.appendIdentifier(statementBuilder, "id"); statementBuilder.append(", r."); vendor.appendIdentifier(statementBuilder, "typeId"); List<String> fields = query.getFields(); boolean cacheData = database.isCacheData(); if (fields == null) { if (!needsDistinct || vendor.supportsDistinctBlob()) { if (cacheData) { statementBuilder.append(", ru."); vendor.appendIdentifier(statementBuilder, "updateDate"); } else { if (needsRecordTable) { statementBuilder.append(", r."); vendor.appendIdentifier(statementBuilder, "data"); } else { query.getOptions().put(SqlDatabase.NEEDS_SECONDARY_FETCH, true); } } } } else if (!fields.isEmpty()) { statementBuilder.append(", "); vendor.appendSelectFields(statementBuilder, fields); } if (hasAnyDeferredMetricPredicates()) { statementBuilder.append(", "); vendor.appendAlias(statementBuilder, recordMetricField.getInternalName()); statementBuilder.append(' '); query.getExtraSourceColumns().put(recordMetricField.getInternalName(), recordMetricField.getInternalName()); } if (!orderBySelectColumns.isEmpty()) { for (String joinValueField : orderBySelectColumns) { statementBuilder.append(", "); statementBuilder.append(joinValueField); } } String extraColumns = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_COLUMNS_QUERY_OPTION)); if (extraColumns != null) { statementBuilder.append(", "); statementBuilder.append(extraColumns); } if (extraSourceColumns != null) { statementBuilder.append(", "); statementBuilder.append(extraSourceColumns); } if (!needsDistinct && ! subSqlQueries.isEmpty()) { for (Map.Entry<Query<?>, SqlQuery> entry : subSqlQueries.entrySet()) { SqlQuery subSqlQuery = entry.getValue(); statementBuilder.append(", " + subSqlQuery.aliasPrefix + "r."+SqlDatabase.ID_COLUMN+" AS "+SqlDatabase.SUB_DATA_COLUMN_ALIAS_PREFIX + subSqlQuery.aliasPrefix + "_" + SqlDatabase.ID_COLUMN); statementBuilder.append(", " + subSqlQuery.aliasPrefix + "r."+SqlDatabase.TYPE_ID_COLUMN+" AS "+SqlDatabase.SUB_DATA_COLUMN_ALIAS_PREFIX + subSqlQuery.aliasPrefix + "_" + SqlDatabase.TYPE_ID_COLUMN); statementBuilder.append(", " + subSqlQuery.aliasPrefix + "r."+SqlDatabase.DATA_COLUMN+" AS "+SqlDatabase.SUB_DATA_COLUMN_ALIAS_PREFIX + subSqlQuery.aliasPrefix + "_" + SqlDatabase.DATA_COLUMN); } } if (needsRecordTable) { statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(' '); statementBuilder.append(aliasPrefix); statementBuilder.append('r'); if (cacheData) { statementBuilder.append("\nLEFT OUTER JOIN "); vendor.appendIdentifier(statementBuilder, "RecordUpdate"); statementBuilder.append(' '); statementBuilder.append(aliasPrefix); statementBuilder.append("ru"); statementBuilder.append(" ON r."); vendor.appendIdentifier(statementBuilder, "id"); statementBuilder.append(" = ru."); vendor.appendIdentifier(statementBuilder, "id"); } } statementBuilder.append(fromClause); if (hasAnyDeferredMetricPredicates()) { statementBuilder.append(" \nJOIN ("); appendSubqueryMetricSql(statementBuilder, recordMetricField); statementBuilder.append(") m \nON ("); appendSimpleOnClause(statementBuilder, vendor, "r", "id", "=", "m", "id"); statementBuilder.append(" AND "); appendSimpleOnClause(statementBuilder, vendor, "r", "typeId", "=", "m", "typeId"); statementBuilder.append(')'); } statementBuilder.append(whereClause); statementBuilder.append(havingClause); statementBuilder.append(orderByClause); if (needsDistinct && !vendor.supportsDistinctBlob()) { StringBuilder distinctBuilder = new StringBuilder(); distinctBuilder.append("SELECT"); distinctBuilder.append(" r."); vendor.appendIdentifier(distinctBuilder, "id"); distinctBuilder.append(", r."); vendor.appendIdentifier(distinctBuilder, "typeId"); if (fields == null) { if (needsRecordTable) { distinctBuilder.append(", r."); vendor.appendIdentifier(distinctBuilder, "data"); } } else if (!fields.isEmpty()) { distinctBuilder.append(", "); vendor.appendSelectFields(distinctBuilder, fields); } if (! query.getExtraSourceColumns().isEmpty()) { for (String extraSourceColumn : query.getExtraSourceColumns().keySet()) { distinctBuilder.append(", "); vendor.appendIdentifier(distinctBuilder, "d0"); distinctBuilder.append('.'); vendor.appendIdentifier(distinctBuilder, extraSourceColumn); } } distinctBuilder.append(" FROM "); vendor.appendIdentifier(distinctBuilder, SqlDatabase.RECORD_TABLE); distinctBuilder.append(" r INNER JOIN ("); distinctBuilder.append(statementBuilder.toString()); distinctBuilder.append(") d0 ON (r.id = d0.id)"); statementBuilder = distinctBuilder; } else if (! recordMetricHavingPredicates.isEmpty()) { StringBuilder wrapperStatementBuilder = new StringBuilder(); wrapperStatementBuilder.append("SELECT * FROM ("); wrapperStatementBuilder.append(statementBuilder); wrapperStatementBuilder.append(") d0 "); statementBuilder = wrapperStatementBuilder; } if (! recordMetricHavingPredicates.isEmpty()) { // the whole query is already aliased to d0 due to one of the above //statementBuilder.append(" WHERE "); StringBuilder havingChildBuilder = new StringBuilder(); for (int i = 0; i < recordMetricHavingPredicates.size(); i++) { addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false); havingChildBuilder.append(" AND "); } if (havingChildBuilder.length() > 0) { havingChildBuilder.setLength(havingChildBuilder.length()-5); // " AND " statementBuilder.append(" WHERE "); statementBuilder.append(havingChildBuilder); } StringBuilder orderByBuilder = new StringBuilder(); // Apply all ORDER BY (deferred and original) for (Sorter sorter : query.getSorters()) { addOrderByClause(orderByBuilder, sorter, false, true); } if (orderByBuilder.length() > 0) { orderByBuilder.setLength(orderByBuilder.length() - 2); orderByBuilder.insert(0, "\nORDER BY "); statementBuilder.append(orderByBuilder); } } else if (! recordMetricSorters.isEmpty()) { StringBuilder orderByBuilder = new StringBuilder(); for (Sorter sorter : recordMetricSorters) { addOrderByClause(orderByBuilder, sorter, false, true); } if (orderByBuilder.length() > 0) { orderByBuilder.setLength(orderByBuilder.length() - 2); orderByBuilder.insert(0, "\nORDER BY "); statementBuilder.append(orderByBuilder); } } return statementBuilder.toString(); } /** Returns an SQL statement that can be used as a sub-query. */ public String subQueryStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT"); if (needsDistinct) { statementBuilder.append(" DISTINCT"); } statementBuilder.append(" r."); vendor.appendIdentifier(statementBuilder, "id"); statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(' '); statementBuilder.append(aliasPrefix); statementBuilder.append('r'); statementBuilder.append(fromClause); statementBuilder.append(whereClause); statementBuilder.append(havingClause); statementBuilder.append(orderByClause); return statementBuilder.toString(); } private enum JoinType { INNER("INNER JOIN"), LEFT_OUTER("LEFT OUTER JOIN"); public final String token; private JoinType(String token) { this.token = token; } } private Join createJoin(String queryKey) { String alias; int position = joins.size(); if (! needsRecordTable && position == 0) { alias = "r"; } else { alias = "i" + position; } Join join = new Join(alias, queryKey); join.position = position; joins.add(join); if (queryKey.equals(query.getOptions().get(SqlDatabase.MYSQL_INDEX_HINT_QUERY_OPTION))) { mysqlIndexHint = join; } return join; } /** Returns the column alias for the given {@code queryKey}. */ private Join getJoin(String queryKey) { ObjectIndex index = selectedIndexes.get(queryKey); for (Join join : joins) { if (queryKey.equals(join.queryKey)) { return join; } else { String indexKey = mappedKeys.get(queryKey).getIndexKey(index); if (indexKey != null && indexKey.equals(mappedKeys.get(join.queryKey).getIndexKey(join.index)) && ((mappedKeys.get(queryKey).getHashAttribute() != null && mappedKeys.get(queryKey).getHashAttribute().equals(join.hashAttribute)) || (mappedKeys.get(queryKey).getHashAttribute() == null && join.hashAttribute == null))) { // If there's a #attribute on the mapped key, make sure we are returning the matching join. return join; } } } return createJoin(queryKey); } /** Returns the column alias for the given field-based {@code sorter}. */ private Join getSortFieldJoin(String queryKey) { ObjectIndex index = selectedIndexes.get(queryKey); for (Join join : joins) { if (queryKey.equals(join.queryKey)) { return join; } else { String indexKey = mappedKeys.get(queryKey).getIndexKey(index); if (indexKey != null && indexKey.equals(mappedKeys.get(join.queryKey).getIndexKey(join.index)) && ((mappedKeys.get(queryKey).getHashAttribute() != null && mappedKeys.get(queryKey).getHashAttribute().equals(join.hashAttribute)) || (mappedKeys.get(queryKey).getHashAttribute() == null && join.hashAttribute == null))) { // If there's a #attribute on the mapped key, make sure we are returning the matching join. return join; } } } Join join = createJoin(queryKey); join.type = JoinType.LEFT_OUTER; return join; } public String getAliasPrefix() { return aliasPrefix; } private void appendSimpleOnClause(StringBuilder sql, SqlVendor vendor, String leftTableAlias, String leftColumnName, String operator, String rightTableAlias, String rightColumnName) { appendSimpleAliasedColumn(sql, vendor, leftTableAlias, leftColumnName); sql.append(' '); sql.append(operator); sql.append(' '); appendSimpleAliasedColumn(sql, vendor, rightTableAlias, rightColumnName); } private void appendSimpleWhereClause(StringBuilder sql, SqlVendor vendor, String leftTableAlias, String leftColumnName, String operator, Object value) { appendSimpleAliasedColumn(sql, vendor, leftTableAlias, leftColumnName); sql.append(' '); sql.append(operator); sql.append(' '); vendor.appendValue(sql, value); } private void appendSimpleAliasedColumn(StringBuilder sql, SqlVendor vendor, String tableAlias, String columnName) { vendor.appendIdentifier(sql, tableAlias); sql.append('.'); vendor.appendIdentifier(sql, columnName); } private class Join { public Predicate parent; public JoinType type = JoinType.INNER; public int position; private String alias; public final boolean needsIndexTable; public final boolean needsIsNotNull; public final String likeValuePrefix; public final String queryKey; public final String indexType; public final List<String> indexKeys = new ArrayList<String>(); private final String tableName; private final ObjectIndex index; private final SqlIndex sqlIndex; private final SqlIndex.Table sqlIndexTable; private final String idField; private final String keyField; private final String typeIdField; private final String valueField; private final String hashAttribute; private final boolean isHaving; public Join(String alias, String queryKey) { this.alias = alias; this.queryKey = queryKey; Query.MappedKey mappedKey = mappedKeys.get(queryKey); this.hashAttribute = mappedKey.getHashAttribute(); this.index = selectedIndexes.get(queryKey); this.indexType = mappedKey.getInternalType(); this.sqlIndex = this.index != null ? SqlIndex.Static.getByIndex(this.index) : SqlIndex.Static.getByType(this.indexType); ObjectField joinField = null; if (this.index != null) { joinField = this.index.getParent().getField(this.index.getField()); } if (Query.ID_KEY.equals(queryKey)) { needsIndexTable = false; likeValuePrefix = null; valueField = recordIdField; sqlIndexTable = null; tableName = null; idField = null; typeIdField = null; keyField = null; needsIsNotNull = true; isHaving = false; } else if (Query.TYPE_KEY.equals(queryKey)) { needsIndexTable = false; likeValuePrefix = null; valueField = recordTypeIdField; sqlIndexTable = null; tableName = null; idField = null; typeIdField = null; keyField = null; needsIsNotNull = true; isHaving = false; } else if (Query.DIMENSION_KEY.equals(queryKey)) { needsIndexTable = false; likeValuePrefix = null; //valueField = MetricAccess.METRIC_DIMENSION_FIELD; StringBuilder fieldBuilder = new StringBuilder(); vendor.appendIdentifier(fieldBuilder, "r"); fieldBuilder.append('.'); vendor.appendIdentifier(fieldBuilder, MetricAccess.METRIC_DIMENSION_FIELD); valueField = fieldBuilder.toString(); sqlIndexTable = null; tableName = null; idField = null; typeIdField = null; keyField = null; needsIsNotNull = true; isHaving = false; } else if (Query.COUNT_KEY.equals(queryKey)) { needsIndexTable = false; likeValuePrefix = null; StringBuilder fieldBuilder = new StringBuilder(); fieldBuilder.append("COUNT("); vendor.appendIdentifier(fieldBuilder, "r"); fieldBuilder.append('.'); vendor.appendIdentifier(fieldBuilder, "id"); fieldBuilder.append(')'); valueField = fieldBuilder.toString(); // "count(r.id)"; sqlIndexTable = null; tableName = null; idField = null; typeIdField = null; keyField = null; needsIsNotNull = false; isHaving = true; } else if (Query.ANY_KEY.equals(queryKey)) { throw new UnsupportedIndexException(database, queryKey); } else if (database.hasInRowIndex() && index.isShortConstant()) { needsIndexTable = false; likeValuePrefix = "%;" + database.getSymbolId(mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey))) + "="; valueField = recordInRowIndexField; sqlIndexTable = this.sqlIndex.getReadTable(database, index); tableName = null; idField = null; typeIdField = null; keyField = null; needsIsNotNull = true; isHaving = false; } else if (joinField != null && joinField.isMetric()) { needsIndexTable = false; likeValuePrefix = null; //addIndexKey(queryKey); sqlIndexTable = this.sqlIndex.getReadTable(database, index); tableName = sqlIndexTable.getName(database, index); alias = "r"; idField = null; typeIdField = null; keyField = null; needsIsNotNull = false; if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { // for metricField#dimension, use dimensionId valueField = MetricAccess.METRIC_DIMENSION_FIELD; isHaving = false; } else if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { // for metricField#date, use "data" valueField = MetricAccess.METRIC_DATA_FIELD; isHaving = false; } else { // for metricField, use internalName StringBuilder fieldBuilder = new StringBuilder(); vendor.appendAlias(fieldBuilder, joinField.getInternalName()); valueField = fieldBuilder.toString(); isHaving = true; } } else { needsIndexTable = true; likeValuePrefix = null; addIndexKey(queryKey); valueField = null; sqlIndexTable = this.sqlIndex.getReadTable(database, index); tableName = sqlIndexTable.getName(database, index); idField = sqlIndexTable.getIdField(database, index); typeIdField = sqlIndexTable.getTypeIdField(database, index); keyField = sqlIndexTable.getKeyField(database, index); if (position == 0 && !needsRecordTable && (!needsIndexTable || typeIdField == null)) { /* if we're not capable of running this query without Record, reset it here. */ needsRecordTable = true; } needsIsNotNull = true; isHaving = false; } } private void checkAlias() { if (alias.equals("i0") && !needsRecordTable) { alias = "r"; } else if (alias.equals("r") && needsRecordTable) { alias = "i0"; } } public String getTable() { if (tableName == null) { return null; } checkAlias(); StringBuilder tableBuilder = new StringBuilder(); vendor.appendIdentifier(tableBuilder, tableName); tableBuilder.append(" "); tableBuilder.append(aliasPrefix); tableBuilder.append(alias); return tableBuilder.toString(); } public String getIdField() { if (idField == null) { return null; } checkAlias(); return aliasedField(alias, idField); } public String getTypeIdField() { if (typeIdField == null) { return null; } checkAlias(); return aliasedField(alias, typeIdField); } public String getKeyField() { if (keyField == null) { return null; } checkAlias(); return aliasedField(alias, keyField); } public String getAlias() { return this.alias; } public String toString() { return this.tableName + " (" + this.alias + ") ." + this.valueField; } public String getTableName() { return this.tableName; } public void addIndexKey(String queryKey) { String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey)); if (ObjectUtils.isBlank(indexKey)) { throw new UnsupportedIndexException(database, indexKey); } if (needsIndexTable) { indexKeys.add(indexKey); } } public Object quoteIndexKey(String indexKey) { return SqlDatabase.quoteValue(sqlIndexTable.convertKey(database, index, indexKey)); } public void appendValue(StringBuilder builder, ComparisonPredicate comparison, Object value) { Query.MappedKey mappedKey = mappedKeys.get(comparison.getKey()); ObjectField field = mappedKey.getField(); SqlIndex fieldSqlIndex = field != null ? SqlIndex.Static.getByType(field.getInternalItemType()) : sqlIndex; if (field != null && field.isMetric()) { if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { String stringValue = null; if (value != null) { stringValue = String.valueOf(value); } value = MetricAccess.getDimensionIdByValue(database, stringValue); } else if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) { // EventDates in MetricAccess are smaller than long Character padChar = 'F'; if (PredicateParser.LESS_THAN_OPERATOR.equals(comparison.getOperator()) || PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(comparison.getOperator())) { padChar = '0'; } if (value instanceof DateTime) { value = ((DateTime) value).getMillis(); } if (value instanceof Date) { value = ((Date) value).getTime(); } vendor.appendMetricEncodeTimestampSql(builder, null, (Long) value, padChar); // Taking care of the appending since it is raw SQL; return here so it isn't appended again return; } else { value = ObjectUtils.to(Double.class, value); } } else if (fieldSqlIndex == SqlIndex.UUID) { value = ObjectUtils.to(UUID.class, value); } else if (fieldSqlIndex == SqlIndex.NUMBER && !PredicateParser.STARTS_WITH_OPERATOR.equals(comparison.getOperator())) { if (value != null) { Long valueLong = ObjectUtils.to(Long.class, value); if (valueLong != null) { value = valueLong; } else { value = ObjectUtils.to(Double.class, value); } } } else if (fieldSqlIndex == SqlIndex.STRING) { if (comparison.isIgnoreCase()) { value = value.toString().toLowerCase(Locale.ENGLISH); } else if (database.comparesIgnoreCase()) { String valueString = value.toString().trim(); if (!index.isCaseSensitive()) { valueString = valueString.toLowerCase(Locale.ENGLISH); } value = valueString; } } vendor.appendValue(builder, value); } public String getValueField(String queryKey, ComparisonPredicate comparison) { String field; checkAlias(); if (valueField != null) { field = valueField; } else if (sqlIndex != SqlIndex.CUSTOM) { field = aliasedField(alias, sqlIndexTable.getValueField(database, index, 0)); } else { String valueFieldName = mappedKeys.get(queryKey).getField().getInternalName(); List<String> fieldNames = index.getFields(); int fieldIndex = 0; for (int size = fieldNames.size(); fieldIndex < size; ++ fieldIndex) { if (valueFieldName.equals(fieldNames.get(fieldIndex))) { break; } } field = aliasedField(alias, sqlIndexTable.getValueField(database, index, fieldIndex)); } if (comparison != null && comparison.isIgnoreCase()) { field = "LOWER(" + vendor.convertRawToStringSql(field) + ")"; } return field; } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
e2b331e55c2b27bd57e1d4bc6551bbb8a32b6448
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/9/9_108f7e5b718aeae5b16f99e3f228b23dd4a6cf51/MainActivity/9_108f7e5b718aeae5b16f99e3f228b23dd4a6cf51_MainActivity_s.java
4d8714690d2a2b20aa1c0f218460bbc62e8510e2
[]
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
52,003
java
/* * This file is part of Fluid Nexus. * * Fluid Nexus 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. * * Fluid Nexus 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 Fluid Nexus. If not, see <http://www.gnu.org/licenses/>. * */ package net.fluidnexus.FluidNexusAndroid; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ListActivity; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.os.Vibrator; import android.preference.PreferenceManager; import android.text.format.Time; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.SimpleCursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.TreeSet; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.client.HttpClient; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import oauth.signpost.OAuth; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.http.HttpParameters; import net.fluidnexus.FluidNexusAndroid.provider.MessagesProvider; import net.fluidnexus.FluidNexusAndroid.provider.MessagesProviderHelper; import net.fluidnexus.FluidNexusAndroid.services.NetworkService; /* * TODO * * deal with new binding to the service when clicking on the notification; this shouldn't happen */ public class MainActivity extends ListActivity { private Cursor c = null; private MessagesProviderHelper messagesProviderHelper = null; private Toast toast; private SharedPreferences prefs; private Editor prefsEditor; private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener; // just for testing private BroadcastReceiver iReceiver; private IntentFilter iFilter; private static Logger log = Logger.getLogger("FluidNexus"); private static final int ACTIVITY_HOME = 0; private static final int ACTIVITY_VIEW_OUTGOING = 1; private static final int ACTIVITY_ADD_OUTGOING = 2; private static final int ACTIVITY_PREFERENCES= 3; private static final int ACTIVITY_VIEW_MESSAGE = 4; private static final int ACTIVITY_HELP = 5; private static final int REQUEST_ENABLE_BT = 6; private static final int ACTIVITY_EDIT_MESSAGE = 7; private static final int ACTIVITY_ABOUT = 8; private static final int REQUEST_DISCOVERABLE_RESULT = 9; private static final int VIEW_ALL = 0; private static final int VIEW_PUBLIC = 1; private static final int VIEW_OUTGOING = 2; private static final int VIEW_BLACKLIST = 3; private static final int VIEW_HIGH_PRIORITY = 4; private static int VIEW_MODE = VIEW_ALL; private static final int MESSAGE_VIEW_LENGTH = 300; private long currentRowID = -1; private static final int DIALOG_REALLY_DELETE = 0; private static final int DIALOG_REALLY_BLACKLIST = 1; private static final int DIALOG_REALLY_UNBLACKLIST = 2; private static final int DIALOG_NO_KEY = 3; private static final int DIALOG_DISCLAIMER = 4; private static final int MENU_ADD_ID = Menu.FIRST; private static final int MENU_VIEW_ID = Menu.FIRST + 1; private static final int MENU_SETTINGS_ID = Menu.FIRST + 2; private static final int MENU_ALL_ID = Menu.FIRST + 3; private static final int MENU_DELETE_ID = Menu.FIRST + 4; private static final int MENU_HELP_ID = Menu.FIRST + 5; private static final int MENU_BLACKLIST_ID = Menu.FIRST + 5; // messages to/from bluetooth service Messenger networkService = null; final Messenger messenger = new Messenger(new IncomingHandler()); private boolean bound = false; // Messages to the bluetooth service public static final int MSG_NEW_MESSAGE_CREATED = 0xF0; public static final int MSG_MESSAGE_DELETED = 0xF1; private boolean showMessages = true; private boolean sendBlacklist = true; private BluetoothAdapter bluetoothAdapter = null; private boolean askedBluetooth = false; private boolean enableBluetoothServicePref = true; private boolean vibratePref = false; private Vibrator vibrator = null; private File attachmentsDir = null; // oauth constants private static final String API_BASE = "http://fluidnexus.net/api/01/"; private static final String REQUEST_URL = API_BASE + "request_token/android"; private static final String ACCESS_URL = API_BASE + "access_token"; private static final String AUTH_URL = API_BASE + "authorize_token/android"; private static final String CALLBACK_URL = "fluidnexus://access_token"; private static CommonsHttpOAuthConsumer consumer = null; private static CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider(REQUEST_URL, ACCESS_URL, AUTH_URL); /** * Our handler for incoming messages */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case NetworkService.MSG_NEW_MESSAGE_RECEIVED: Toast.makeText(getApplicationContext(), R.string.toast_new_message_received, Toast.LENGTH_LONG).show(); if (vibratePref) { ((Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE)).vibrate(500); } fillListView(VIEW_MODE); break; default: super.handleMessage(msg); } } } public class MessagesListAdapter extends SimpleCursorAdapter { private Context context = null; private int layout; private Cursor c = null; private LayoutInflater inflater = null; public MessagesListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context; this.layout = layout; this.c = c; this.inflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = super.getView(position, convertView, parent); if (c.moveToPosition(position)) { if (convertView == null) { convertView = inflater.inflate(layout, parent, false); } this.setMessageItemValues(convertView, c); } return convertView; } private void setMessageItemValues(View v, Cursor cursor) { int i = 0; TextView tv = null; ImageView iv = null; Float s_float = null; Long s = null; Time t = null; String formattedTime = null; // Set title i = cursor.getColumnIndex(MessagesProvider.KEY_TITLE); String title = cursor.getString(i); tv = (TextView) v.findViewById(R.id.message_list_item); tv.setText(title); // Set content i = cursor.getColumnIndex(MessagesProvider.KEY_CONTENT); String fullMessage = cursor.getString(i); tv = (TextView) v.findViewById(R.id.message_list_data); int stringLen = fullMessage.length(); if (stringLen < MESSAGE_VIEW_LENGTH) { tv.setText(fullMessage); } else { tv.setText(fullMessage.substring(0, MESSAGE_VIEW_LENGTH) + " ..."); } // Set icons i = cursor.getColumnIndex(MessagesProvider.KEY_MINE); iv = (ImageView) v.findViewById(R.id.message_list_item_icon); int mine = cursor.getInt(i); boolean publicMessage = cursor.getInt(cursor.getColumnIndex(MessagesProvider.KEY_PUBLIC)) > 0; if (mine == 0) { if (publicMessage) { iv.setImageResource(R.drawable.menu_public_other); } else { iv.setImageResource(R.drawable.menu_all); } } else if (mine == 1) { if (publicMessage) { iv.setImageResource(R.drawable.menu_public); } else { iv.setImageResource(R.drawable.menu_outgoing); } } // set created time i = cursor.getColumnIndex(MessagesProvider.KEY_TIME); s_float = cursor.getFloat(i); s = s_float.longValue() * 1000; t = new Time(); t.set(s); tv = (TextView) v.findViewById(R.id.message_list_created_time); formattedTime = t.format(getString(R.string.message_list_created_time) + " %c"); tv.setText(formattedTime); // set received time i = cursor.getColumnIndex(MessagesProvider.KEY_RECEIVED_TIME); s_float = cursor.getFloat(i); s = s_float.longValue() * 1000; t = new Time(); t.set(s); tv = (TextView) v.findViewById(R.id.message_list_received_time); formattedTime = t.format(getString(R.string.message_list_received_time) + " %c"); tv.setText(formattedTime); // set attachment infos i = cursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME); final String attachmentFilename = cursor.getString(i); final String attachmentPath = cursor.getString(cursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_PATH)); tv = (TextView) v.findViewById(R.id.message_list_attachment); if (attachmentFilename.equals("")) { tv.setVisibility(View.GONE); } else { tv.setVisibility(View.VISIBLE); tv.setText("Has attachment: " + attachmentFilename); } // Set priority i = cursor.getColumnIndex(MessagesProvider.KEY_PRIORITY); int priority = cursor.getInt(i); if (priority == MessagesProvider.HIGH_PRIORITY) { v.setBackgroundResource(R.drawable.message_list_item_high_priority_gradient); } else { v.setBackgroundResource(R.drawable.message_list_item_gradient); } } } private ServiceConnection networkServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { networkService = new Messenger(service); try { Message msg = Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT); msg.replyTo = messenger; networkService.send(msg); log.debug("Connected to service"); // Send send_blacklist flag // This needs to be sent before all others msg = Message.obtain(null, NetworkService.MSG_SEND_BLACKLISTED); msg.arg1 = (prefs.getBoolean("sendBlacklistPref", false))? 1 : 0; msg.replyTo = messenger; networkService.send(msg); // Send bluetooth enabled bit on start msg = Message.obtain(null, NetworkService.MSG_BLUETOOTH_ENABLED); msg.arg1 = (prefs.getBoolean("enableBluetoothServicePref", true))? 1 : 0; msg.arg2 = Integer.parseInt(prefs.getString("bluetoothScanFrequency", "120")); msg.replyTo = messenger; networkService.send(msg); // Send bonded only flag msg = Message.obtain(null, NetworkService.MSG_BLUETOOTH_BONDED_ONLY_FLAG); msg.arg1 = (prefs.getBoolean("bluetoothBondedOnlyFlag", false))? 1 : 0; msg.replyTo = messenger; networkService.send(msg); // Send zeroconf enabled bit on start msg = Message.obtain(null, NetworkService.MSG_ZEROCONF_ENABLED); msg.arg1 = (prefs.getBoolean("enableZeroconfServicePref", true)) ? 1 : 0; msg.arg2 = Integer.parseInt(prefs.getString("zeroconfScanFrequency", "120")); msg.replyTo = messenger; networkService.send(msg); // Send bit for starting nexus service msg = Message.obtain(null, NetworkService.MSG_NEXUS_START); msg.arg1 = (prefs.getBoolean("enableNexusServicePref", true)) ? 1 : 0; // TODO // Make this configurable? msg.arg2 = 120; Bundle bundle = new Bundle(); bundle.putString("key", prefs.getString("nexusKeyPref", "")); bundle.putString("secret", prefs.getString("nexusSecretPref", "")); bundle.putString("token", prefs.getString("nexusTokenPref", "")); bundle.putString("token_secret", prefs.getString("nexusTokenSecretPref", "")); msg.setData(bundle); msg.replyTo = messenger; networkService.send(msg); } catch (RemoteException e) { // Here, the service has crashed even before we were able to connect } } public void onServiceDisconnected(ComponentName className) { // Called when the connection to the service has been unexpectedly closed networkService = null; log.debug("Disconnected from service"); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); log.verbose("unfreezing..."); if (messagesProviderHelper == null) { messagesProviderHelper = new MessagesProviderHelper(this); } setContentView(R.layout.message_list); registerForContextMenu(getListView()); // setup bluetooth adapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // if it's not available, let user know if (bluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available; sending and receiving messages will not be possible", Toast.LENGTH_LONG).show(); } // Create our attachments dir // TODO // Make this configurable to SD card File dataDir = Environment.getExternalStorageDirectory(); attachmentsDir = new File(dataDir.getAbsolutePath() + "/FluidNexusAttachments"); attachmentsDir.mkdirs(); } /** * Method of creating dialogs for this activity * @param id ID of the dialog to create */ protected Dialog onCreateDialog(int id) { Dialog dialog; switch (id) { case DIALOG_REALLY_DELETE: dialog = reallyDeleteDialog(); break; case DIALOG_REALLY_BLACKLIST: dialog = reallyBlacklistDialog(); break; case DIALOG_REALLY_UNBLACKLIST: dialog = reallyUnblacklistDialog(); break; case DIALOG_NO_KEY: dialog = noKeyDialog(); break; case DIALOG_DISCLAIMER: dialog = disclaimerDialog(); break; default: dialog = null; } return dialog; } /** * Method to create our really delete dialog */ private AlertDialog reallyDeleteDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to delete this message?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Cursor localCursor = messagesProviderHelper.returnItemByID(currentRowID); String attachmentPath = localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_PATH)); boolean mine = localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_MINE)) > 0; localCursor.close(); if ((!(attachmentPath.equals(""))) && (!mine)) { File f = new File(attachmentPath); f.delete(); } messagesProviderHelper.deleteById(currentRowID); try { // Send message to service to note that a new message has been created Message msg = Message.obtain(null, MSG_MESSAGE_DELETED); networkService.send(msg); } catch (RemoteException e) { // Here, the service has crashed even before we were able to connect } currentRowID = -1; fillListView(VIEW_MODE); toast = Toast.makeText(getApplicationContext(), R.string.toast_message_deleted, Toast.LENGTH_SHORT); toast.show(); } }) .setNegativeButton("No", null); return builder.create(); } /** * Method to create our really blacklist dialog */ private AlertDialog reallyBlacklistDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.really_blacklist_dialog) .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ContentValues values = new ContentValues(); values.put(MessagesProvider.KEY_BLACKLIST, 1); messagesProviderHelper.updateItemByID(currentRowID, values); currentRowID = -1; fillListView(VIEW_MODE); toast = Toast.makeText(getApplicationContext(), R.string.toast_message_blacklisted, Toast.LENGTH_SHORT); toast.show(); } }) .setNegativeButton("No", null); return builder.create(); } /** * Method to create our really blacklist dialog */ private AlertDialog reallyUnblacklistDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.really_unblacklist_dialog) .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ContentValues values = new ContentValues(); values.put(MessagesProvider.KEY_BLACKLIST, 0); messagesProviderHelper.updateItemByID(currentRowID, values); currentRowID = -1; fillListView(VIEW_MODE); toast = Toast.makeText(getApplicationContext(), R.string.toast_message_unblacklisted, Toast.LENGTH_SHORT); toast.show(); } }) .setNegativeButton("No", null); return builder.create(); } /** * Method to create our lack of nexus key or secret dialog */ private AlertDialog noKeyDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.no_key_dialog) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); return builder.create(); } /** * Method to create our lack of nexus key or secret dialog */ private AlertDialog disclaimerDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.disclaimer_dialog) .setCancelable(false) .setPositiveButton(R.string.understand_answer, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); return builder.create(); } @Override public void onStart() { super.onStart(); fillListView(VIEW_MODE); Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); setupPreferences(); if ((bluetoothAdapter != null) && (askedBluetooth == false)) { if (!bluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else { /* if (networkService == null) { setupFluidNexusBluetoothService(); } */ } } // Bind to the network service doBindService(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); ListView lv; lv = (ListView) getListView(); int scrollPos = lv.getFirstVisiblePosition(); outState.putInt("position", scrollPos); } @Override public void onRestoreInstanceState(Bundle inState) { super.onRestoreInstanceState(inState); ListView lv; lv = (ListView) getListView(); int scrollPos = inState.getInt("position"); lv.setSelection(scrollPos); } @Override protected void onPause() { super.onPause(); /* ListView lv; lv = (ListView) getListView(); int scroll = lv.getScrollY(); log.debug("ON PAUSE: " + scroll); SharedPreferences p = getSharedPreferences("SCROLL", 0); SharedPreferences.Editor e = p.edit(); e.putInt("ScrollValue", scroll); e.commit(); */ } @Override protected void onResume() { super.onResume(); /* SharedPreferences p = getSharedPreferences("SCROLL", 0); int scroll = p.getInt("ScrollValue", 0); log.debug("ON RESUME: " + scroll); ListView lv; lv = (ListView) getListView(); lv.scrollTo(0, scroll); */ // Parse a URI result as sent from the browser on Nexus confirmation Uri uri = this.getIntent().getData(); if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { String token = uri.getQueryParameter("oauth_token"); String token_secret = uri.getQueryParameter("oauth_token_secret"); prefsEditor = prefs.edit(); if ((token != null) && (token_secret != null)) { prefsEditor.putString("nexusTokenPref", token); prefsEditor.putString("nexusTokenSecretPref", token_secret); prefsEditor.commit(); Toast.makeText(this, R.string.toast_tokens_updated, Toast.LENGTH_LONG).show(); } else { log.error("Unable to parse token or token_secret from the uri: " + uri); } } } @Override protected void onDestroy() { super.onDestroy(); prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener); c.close(); try { if (bound) { doUnbindService(); } } catch (Throwable t) { log.error("Failed to unbind from the service"); } } /* * Context menu code from: * http://stackoverflow.com/questions/6205808/how-to-handle-long-tap-on-listview-item */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; currentRowID = info.id; Cursor localCursor = messagesProviderHelper.returnItemByID(currentRowID); menu.setHeaderTitle(localCursor.getString(localCursor.getColumnIndexOrThrow(MessagesProvider.KEY_TITLE))); int mine = localCursor.getInt(localCursor.getColumnIndexOrThrow(MessagesProvider.KEY_MINE)); if (VIEW_MODE == VIEW_BLACKLIST) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.message_list_context_unblacklist, menu); } else { if (mine == 0) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.message_list_context_noedit, menu); } else { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.message_list_context, menu); } } localCursor.close(); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.delete_message: showDialog(DIALOG_REALLY_DELETE); return true; case R.id.blacklist_message: showDialog(DIALOG_REALLY_BLACKLIST); return true; case R.id.unblacklist_message: showDialog(DIALOG_REALLY_UNBLACKLIST); return true; case R.id.edit_message: editMessage(); return true; default: return super.onContextItemSelected(item); } } /** * Bind to the service */ private void doBindService() { if (bound == false) { log.info("Binding to Fluid Nexus Network Service"); Intent i = new Intent(this, NetworkService.class); startService(i); bindService(i, networkServiceConnection, Context.BIND_AUTO_CREATE); bound = true; } } /** * Unbind to the service */ private void doUnbindService() { if (networkService != null) { try { Message msg = Message.obtain(null, NetworkService.MSG_UNREGISTER_CLIENT); msg.replyTo = messenger; networkService.send(msg); } catch (RemoteException e) { // nothing special to do if the service has already stopped for some reason } unbindService(networkServiceConnection); log.info("Unbound to the Fluid Nexus Bluetooth Service"); } } /** * Open up a new activity to edit the message */ private void editMessage() { Cursor localCursor = messagesProviderHelper.returnItemByID(currentRowID); Intent i = new Intent(this, EditMessage.class); i.putExtra(MessagesProvider._ID, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider._ID))); i.putExtra(MessagesProvider.KEY_TYPE, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_TYPE))); i.putExtra(MessagesProvider.KEY_PRIORITY, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_PRIORITY))); i.putExtra(MessagesProvider.KEY_TITLE, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_TITLE))); i.putExtra(MessagesProvider.KEY_CONTENT, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_CONTENT))); i.putExtra(MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME))); i.putExtra(MessagesProvider.KEY_ATTACHMENT_PATH, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_PATH))); i.putExtra(MessagesProvider.KEY_PUBLIC, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_PUBLIC)) > 0); localCursor.close(); startActivityForResult(i, ACTIVITY_EDIT_MESSAGE); } private void setupPreferences() { prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); boolean firstRun = prefs.getBoolean("FirstRun", true); if (firstRun == true) { prefsEditor = prefs.edit(); prefsEditor.putBoolean("FirstRun", false); prefsEditor.commit(); messagesProviderHelper.initialPopulate(); fillListView(VIEW_MODE); showDialog(DIALOG_DISCLAIMER); } showMessages = prefs.getBoolean("showMessagesPref", true); sendBlacklist = prefs.getBoolean("sendBlacklistPref", false); vibratePref = prefs.getBoolean("vibratePref", false); // Setup a listener for when preferences change preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences pref, String key) { if (key.equals("enableBluetoothServicePref")) { boolean tmp = prefs.getBoolean("enableBluetoothServicePref", true); try { // Send bluetooth enabled bit Message msg = Message.obtain(null, NetworkService.MSG_BLUETOOTH_ENABLED); msg.arg1 = (prefs.getBoolean("enableBluetoothServicePref", false))? 1 : 0; msg.replyTo = messenger; networkService.send(msg); enableBluetoothServicePref = tmp; } catch (RemoteException e) { log.error("Unable to send MSG_BLUETOOTH_ENABLED"); } } else if (key.equals("bluetoothScanFrequency")) { try { Message msg = Message.obtain(null, NetworkService.MSG_BLUETOOTH_SCAN_FREQUENCY); msg.arg1 = Integer.parseInt(prefs.getString("bluetoothScanFrequency", "120")); msg.replyTo = messenger; networkService.send(msg); } catch (RemoteException e) { log.error("Unable to send scan frequency message: " + e); } } else if (key.equals("bluetoothBondedOnlyFlag")) { try { Message msg = Message.obtain(null, NetworkService.MSG_BLUETOOTH_BONDED_ONLY_FLAG); msg.arg1 = (prefs.getBoolean("bluetoothBondedOnlyFlag", false) ? 1:0); msg.replyTo = messenger; networkService.send(msg); } catch (RemoteException e) { log.error("Unable to send bonded only flag message: " + e); } } else if (key.equals("zeroconfScanFrequency")) { try { Message msg = Message.obtain(null, NetworkService.MSG_ZEROCONF_SCAN_FREQUENCY); msg.arg1 = Integer.parseInt(prefs.getString("zeroconfScanFrequency", "120")); msg.replyTo = messenger; networkService.send(msg); } catch (RemoteException e) { log.error("Unable to send scan frequency message: " + e); } } else if (key.equals("vibratePref")) { vibratePref = prefs.getBoolean("vibratePref", false); } else if (key.equals("showMessagesPref")) { showMessages = prefs.getBoolean("showMessagesPref", true); fillListView(VIEW_MODE); } else if (key.equals("sendBlacklistPref")) { sendBlacklist = prefs.getBoolean("sendBlacklistPref", false); try { Message msg = Message.obtain(null, NetworkService.MSG_SEND_BLACKLISTED); msg.arg1 = (prefs.getBoolean("sendBlacklistPref", false) ? 1:0); msg.replyTo = messenger; networkService.send(msg); } catch (RemoteException e) { log.error("Unable to send bonded only flag message: " + e); } } } }; prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.message_list_options, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { TextView tv; Intent i = null; switch (item.getItemId()) { case R.id.menu_add: addOutgoingMessage(); return true; case R.id.menu_view_all: VIEW_MODE = VIEW_ALL; fillListView(VIEW_MODE); // Update our header text view tv = (TextView) findViewById(R.id.message_list_header_text); tv.setText(R.string.message_list_header_text_all); return true; case R.id.menu_view_public: VIEW_MODE = VIEW_PUBLIC; fillListView(VIEW_MODE); // Update our header text view tv = (TextView) findViewById(R.id.message_list_header_text); tv.setText(R.string.message_list_header_text_public); return true; case R.id.menu_view_outgoing: VIEW_MODE = VIEW_OUTGOING; fillListView(VIEW_MODE); // Update our header text view tv = (TextView) findViewById(R.id.message_list_header_text); tv.setText(R.string.message_list_header_text_outgoing); return true; case R.id.menu_view_high_priority: VIEW_MODE = VIEW_HIGH_PRIORITY; fillListView(VIEW_MODE); // Update our header text view tv = (TextView) findViewById(R.id.message_list_header_text); tv.setText(R.string.message_list_header_text_high_priority); return true; case R.id.menu_view_blacklist: VIEW_MODE = VIEW_BLACKLIST; fillListView(VIEW_MODE); // Update our header text view tv = (TextView) findViewById(R.id.message_list_header_text); tv.setText(R.string.message_list_header_text_blacklist); return true; case R.id.menu_request_authorization: String key = prefs.getString("nexusKeyPref", ""); String secret = prefs.getString("nexusSecretPref", ""); if (key.equals("")) { showDialog(DIALOG_NO_KEY); return true; } else { consumer = new CommonsHttpOAuthConsumer(key, secret); HttpParameters p = new HttpParameters(); TreeSet<String> s = new TreeSet<String>(); s.add(CALLBACK_URL); p.put("oauth_callback", s); //consumer.setAdditionalParameters(p); try { //HttpPost request = new HttpPost(REQUEST_URL); //consumer.sign(request); //HttpClient httpClient = new DefaultHttpClient(); //HttpResponse response = httpClient.execute(request); //log.debug(EntityUtils.toString(response.getEntity())); provider.setOAuth10a(true); String authURL = provider.retrieveRequestToken(consumer, CALLBACK_URL); log.debug("URL: " + authURL); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL))); } catch (OAuthMessageSignerException e) { log.debug("OAuthMessageSignerException: " + e); } catch (OAuthExpectationFailedException e) { log.debug("OAuthExpectationFailedException: " + e); } catch (OAuthCommunicationException e) { log.debug("OAuthCommunicationException: " + e); } catch (OAuthNotAuthorizedException e) { log.debug("OAuthNotAuthorizedException: " + e); } /*catch (IOException e) { log.debug("Some sort of error trying to parse result" + e); }*/ return true; } case R.id.menu_preferences: editPreferences(); return true; case R.id.menu_discoverable: if (bluetoothAdapter != null) { i = new Intent(); i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivityForResult(i, REQUEST_DISCOVERABLE_RESULT); } return true; case R.id.menu_help: i = new Intent(this, Help.class); /*startSubActivity(i, ACTIVITY_HELP);*/ startActivityForResult(i, ACTIVITY_HELP); return true; case R.id.menu_about: i = new Intent(this, About.class); /*startSubActivity(i, ACTIVITY_HELP);*/ startActivityForResult(i, ACTIVITY_ABOUT); return true; } return super.onOptionsItemSelected(item); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // We will need to be careful later here about the different uses of position and rowID super.onListItemClick(l, v, position, id); Cursor localCursor = messagesProviderHelper.returnItemByID(id); //localCursor.moveToPosition(position); Intent i = new Intent(this, ViewMessage.class); i.putExtra(MessagesProvider._ID, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider._ID))); i.putExtra(MessagesProvider.KEY_TITLE, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_TITLE))); i.putExtra(MessagesProvider.KEY_CONTENT, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_CONTENT))); i.putExtra(MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME))); i.putExtra(MessagesProvider.KEY_MINE, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_MINE)) > 0); i.putExtra(MessagesProvider.KEY_PUBLIC, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_PUBLIC)) > 0); i.putExtra(MessagesProvider.KEY_ATTACHMENT_PATH, localCursor.getString(localCursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_PATH))); i.putExtra(MessagesProvider.KEY_TIME, localCursor.getFloat(localCursor.getColumnIndex(MessagesProvider.KEY_TIME))); i.putExtra(MessagesProvider.KEY_RECEIVED_TIME, localCursor.getFloat(localCursor.getColumnIndex(MessagesProvider.KEY_RECEIVED_TIME))); i.putExtra(MessagesProvider.KEY_PRIORITY, localCursor.getInt(localCursor.getColumnIndex(MessagesProvider.KEY_PRIORITY))); c.close(); startActivityForResult(i, ACTIVITY_VIEW_MESSAGE); localCursor.close(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(ACTIVITY_VIEW_MESSAGE): fillListView(VIEW_MODE); break; case(ACTIVITY_ADD_OUTGOING): try { // Send message to service to note that a new message has been created Message msg = Message.obtain(null, MSG_NEW_MESSAGE_CREATED); networkService.send(msg); } catch (RemoteException e) { // Here, the service has crashed even before we were able to connect } fillListView(VIEW_MODE); break; case(REQUEST_DISCOVERABLE_RESULT): // Do something on request discoverable result String s = ""; if (resultCode < 0) { s = getString(R.string.toast_discoverable_notok); } else { s = getString(R.string.toast_discoverable_ok, resultCode); } Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); break; case(ACTIVITY_PREFERENCES): break; case(REQUEST_ENABLE_BT): if (resultCode == ListActivity.RESULT_OK) { toast = Toast.makeText(this, R.string.toast_bluetooth_request_ok, Toast.LENGTH_LONG); toast.show(); // setup services here } else { log.warn("Bluetooth not enabled"); Toast.makeText(this, R.string.toast_bluetooth_request_notok, Toast.LENGTH_SHORT).show(); askedBluetooth = true; enableBluetoothServicePref = false; if (prefsEditor != null) { prefsEditor.putBoolean("enableBluetoothServicePref", false); } } } } private void editPreferences() { Intent intent = new Intent(this, Preferences.class); startActivityForResult(intent, ACTIVITY_PREFERENCES); } private void addOutgoingMessage() { Intent intent = new Intent(this, AddOutgoing.class); startActivityForResult(intent, ACTIVITY_ADD_OUTGOING); } private void fillListView(int viewType) { if (!(showMessages)) { log.debug("We shouldn't be showing messages..."); return; } String[] from = new String[] {MessagesProvider.KEY_TITLE, MessagesProvider.KEY_CONTENT, MessagesProvider.KEY_MINE, MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME, MessagesProvider.KEY_TIME, MessagesProvider.KEY_RECEIVED_TIME, MessagesProvider.KEY_PRIORITY}; //String[] projection = new String[] {MessagesProvider._ID, MessagesProvider.KEY_TITLE, MessagesProvider.KEY_CONTENT, MessagesProvider.KEY_MINE, MessagesProvider.KEY_ATTACHMENT_PATH, MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME, MessagesProvider.KEY_PUBLIC}; int[] to = new int[] {R.id.message_list_item, R.id.message_list_data, R.id.message_list_item_icon, R.id.message_list_attachment, R.id.message_list_created_time, R.id.message_list_received_time, R.id.message_list_item}; if (viewType == VIEW_ALL) { // Get the non-blacklisted messages c = messagesProviderHelper.allNoBlacklist(); } else if (viewType == VIEW_PUBLIC) { c = messagesProviderHelper.publicMessages(); } else if (viewType == VIEW_OUTGOING) { c = messagesProviderHelper.outgoing(); } else if (viewType == VIEW_BLACKLIST) { c = messagesProviderHelper.blacklist(); } else if (viewType == VIEW_HIGH_PRIORITY) { c = messagesProviderHelper.highPriority(); } //SimpleCursorAdapter messagesAdapter = new SimpleCursorAdapter(this, R.layout.message_list_item, c, from, to); MessagesListAdapter messagesAdapter = new MessagesListAdapter(this, R.layout.message_list_item, c, from, to); ListView lv; lv = (ListView) getListView(); //lv.setSelection(0); /* messagesAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { public boolean setViewValue(View view, Cursor cursor, int i) { if (i == cursor.getColumnIndex(MessagesProvider.KEY_CONTENT)) { String fullMessage = cursor.getString(i); TextView tv = (TextView) view; int stringLen = fullMessage.length(); if (stringLen < MESSAGE_VIEW_LENGTH) { tv.setText(fullMessage); } else { tv.setText(fullMessage.substring(0, MESSAGE_VIEW_LENGTH) + " ..."); } return true; } if (i == cursor.getColumnIndex(MessagesProvider.KEY_PRIORITY)) { TextView tv = (TextView) view; int priority = cursor.getInt(cursor.getColumnIndex(MessagesProvider.KEY_PRIORITY)); if (priority == MessagesProvider.NORMAL_PRIORITY) { tv.setVisibility(View.GONE); } else if (priority == MessagesProvider.HIGH_PRIORITY) { tv.setVisibility(View.VISIBLE); tv.setText("!!!!!"); } return true; } if (i == cursor.getColumnIndex(MessagesProvider.KEY_MINE)) { ImageView iv = (ImageView) view; int mine = cursor.getInt(i); boolean publicMessage = cursor.getInt(cursor.getColumnIndex(MessagesProvider.KEY_PUBLIC)) > 0; if (mine == 0) { if (publicMessage) { iv.setImageResource(R.drawable.menu_public_other); } else { iv.setImageResource(R.drawable.menu_all); } } else if (mine == 1) { if (publicMessage) { iv.setImageResource(R.drawable.menu_public); } else { iv.setImageResource(R.drawable.menu_outgoing); } } return true; } if (i == cursor.getColumnIndex(MessagesProvider.KEY_TIME)) { Float s_float = cursor.getFloat(i); Long s = s_float.longValue() * 1000; Time t = new Time(); t.set(s); TextView timeView = (TextView) view; String formattedTime = t.format(getString(R.string.message_list_created_time) + " %c"); timeView.setText(formattedTime); return true; } if (i == cursor.getColumnIndex(MessagesProvider.KEY_RECEIVED_TIME)) { Float s_float = cursor.getFloat(i); Long s = s_float.longValue() * 1000; Time t = new Time(); t.set(s); TextView timeView = (TextView) view; String formattedTime = t.format(getString(R.string.message_list_received_time) + " %c"); timeView.setText(formattedTime); return true; } if (i == cursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_ORIGINAL_FILENAME)) { final String attachmentFilename = cursor.getString(i); final String attachmentPath = cursor.getString(cursor.getColumnIndex(MessagesProvider.KEY_ATTACHMENT_PATH)); TextView viewAttachment = (TextView) view; if (attachmentFilename.equals("")) { viewAttachment.setVisibility(View.GONE); } else { viewAttachment.setVisibility(View.VISIBLE); viewAttachment.setText("Has attachment: " + attachmentFilename); } return true; } return false; } }); */ setListAdapter(messagesAdapter); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
ffc005601b53b0a039446c63d3817d6d4cfd9a95
70008cdb8f11cbc57ca2596492c00d753824e3b0
/app/src/main/java/com/mobile/mtrader/di/qualifier/ApplicationContext.java
281ab25e822edded9d6bbdc37f89979fe9527076
[]
no_license
olukayodepaul/mobiletreaderv3
7ecf4056cf6546ff39887c453f9ec3160808a979
d785dba13b8a47e09f65b6795cdf812aa2c700b5
refs/heads/master
2020-05-03T20:17:04.587375
2019-07-30T19:16:47
2019-07-30T19:16:47
178,799,674
0
0
null
null
null
null
UTF-8
Java
false
false
126
java
package com.mobile.mtrader.di.qualifier; import javax.inject.Qualifier; @Qualifier public @interface ApplicationContext { }
[ "paul.olukayode.pro@gmail.com" ]
paul.olukayode.pro@gmail.com
991fc1798d30f9ad2f1c79db05c5a901f6b5e79c
1a12a0dba28b1f054f530442687dff07b6ffe419
/src/main/java/vn/com/vsii/service/impl/AccountServiceImpl.java
0af39e88a18c0bf05824624b438afdc892a4cc36
[]
no_license
anhtuan9/vsii_test
635b67650a8319780d6bf0ef57548160799fb2e5
5ddcb454ff56efb30973b76deb9ed77657d14304
refs/heads/master
2020-04-17T21:28:39.707730
2019-01-23T03:40:38
2019-01-23T03:40:38
166,951,499
0
1
null
null
null
null
UTF-8
Java
false
false
1,714
java
package vn.com.vsii.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import vn.com.vsii.model.Account; import vn.com.vsii.model.Role; import vn.com.vsii.repository.AccountRepository; import vn.com.vsii.repository.RoleRepository; import vn.com.vsii.service.AccountService; import java.util.HashSet; import java.util.Set; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountRepository accountRepository; @Autowired private RoleRepository roleRepository; @Override public Page<Account> findAll(Pageable pageable) { return accountRepository.findAll(pageable); } @Override public Account findById(Long id) { return accountRepository.findById(id).orElse(null); } @Override public void save(Account user) { accountRepository.save(user); } @Override public void remove(Long id) { accountRepository.deleteById(id); } @Override public void setupRole(String role, Account account) { Set<Role> roles = new HashSet<>(); roles.add(roleRepository.findByName(account.getRole())); account.setRoles(roles); accountRepository.save(account); } @Override public Page<Account> findAllByStudentName(String nickname, Pageable pageable) { return null; } @Override public Account findByUserName(String username) { return accountRepository.findByUserName(username); } }
[ "batmanlate@gmail.com" ]
batmanlate@gmail.com
0c525727de16ba804c9f5f6c506316b531187263
bdcd46f5f1ebf0a333b50ad48f4bae6909359a66
/src/controllers/NodeServiceSingelton.java
063b11f431b462404c6e34d1fb12d5bab7de8b53
[]
no_license
Michael-Raafat/Circus-Of-Plates
4b5c29b1d9f0e15d74ff187cd1712efc85efb427
d924dd877d49549d65aa68a99b8e35504dbd41a2
refs/heads/master
2020-07-29T06:29:20.723675
2019-09-20T03:39:26
2019-09-20T03:39:26
89,272,253
0
0
null
null
null
null
UTF-8
Java
false
false
2,439
java
package controllers; import java.util.ArrayList; import java.util.List; import javafx.scene.Node; import logs.LogService; /** * Singelton node service implementation. * @author Amr * */ public final class NodeServiceSingelton implements NodeService { /**. * Node service. */ private static NodeService service; /**. * controller to update the javaFX UI */ private GUIController guiController; /** * Unregister node buffer list. */ private List<Node> unregisterBuffer; /** * register node buffer list. */ private List<Node> registerBuffer; /**. * Private constructor to prevent creating new instance. */ private NodeServiceSingelton() { LogService.printTrace(this.getClass(), "private Construction of" + " NodeServiceSingleton Class which implements" + " NodeService interface."); unregisterBuffer = new ArrayList<Node>(); registerBuffer = new ArrayList<Node>(); } /**. * * @return a service object that is shared between all classes */ public static NodeService getInstance() { if (service == null) { service = new NodeServiceSingelton(); } LogService.printTrace(service.getClass(), "NodeService Method" + " getInstance is called"); return service; } @Override public void registerController(final GUIController controller) { LogService.printTrace(this.getClass(), "void Method" + " registerController(GUIController)" + " is called"); this.guiController = controller; } @Override public void bufferRegisterNode(final Node node) { LogService.printTrace(this.getClass(), "void Method" + " bufferRegisterNode(Node) is called"); if (unregisterBuffer.contains(node)) { unregisterBuffer.remove(node); } else { registerBuffer.add(node); } } @Override public void bufferUnregisterNode(final Node node) { LogService.printTrace(this.getClass(), "void Method" + " bufferUnregisterNode(Node) is called"); unregisterBuffer.add(node); } @Override public void clearBuffer() { LogService.printTrace(this.getClass(), "void Method" + " ClearBuffer is called"); if (registerBuffer.size() > 0 || unregisterBuffer.size() > 0) { guiController.updateNodes( registerBuffer, unregisterBuffer); } } @Override public void clearScreen() { LogService.printTrace(this.getClass(), "void Method" + " ClearScreen is called"); registerBuffer.clear(); unregisterBuffer.clear(); guiController.clearNodes(); } }
[ "micoraafat96@gmail.com" ]
micoraafat96@gmail.com
0b06bd3c4e9ca1b4df35aca190eb8724bc36bfc9
84b38ea2f96a9d9b7d6142a73fbf0b03db41a4a6
/src/main/java/com/athena/chameleon/web/login/service/LoginService.java
39cfc40d5b76d317f109406e681de88199b7df61
[ "Apache-2.0" ]
permissive
OpenSourceConsulting/playce-chameleon
06916eae62ba0bdf3088c5364544ae1f6acbe69b
356a75674495d2946aaf2c2b40f78ecf388fefd0
refs/heads/master
2022-12-04T10:06:02.135611
2020-08-11T04:27:17
2020-08-11T04:27:17
5,478,313
4
1
null
null
null
null
UTF-8
Java
false
false
1,171
java
/* * Copyright 2012 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. * * Revision History * Author Date Description * --------------- ---------------- ------------ * Hyo-jeong Lee 2012. 9. 12. First Draft. */ package com.athena.chameleon.web.login.service; import com.athena.chameleon.web.login.vo.Login; /** * This LoginService class is an Interface class to Login. * * @author Hyo-jeong Lee * @version 1.0 */ public interface LoginService { /** * 로그인 체크 Service * * @param login * @return * @throws Exception */ boolean login(Login login) throws Exception; }
[ "hjlee@osci.kr" ]
hjlee@osci.kr
c669d9a4b355474e85a7e6a48e3227aa1eda1d61
d75cc19e1535622621c624b1ecdb896ded18c4ed
/commonLib/src/main/java/com/officego/commonlib/base/recycle/BaseRecyclerAdapter.java
5a5b98d08a15a5500e12b1edaa11b03c3011003a
[]
no_license
ysj0227/officego2006
7cbbc2b806c8abb4c5bff88f20e9077cd6fb148c
128bef26a24c58f494143b02b16f3f886320e3ca
refs/heads/master
2023-05-03T20:40:44.585329
2021-05-26T01:24:05
2021-05-26T01:24:05
273,682,946
0
0
null
2020-10-13T02:52:16
2020-06-20T10:03:59
Java
UTF-8
Java
false
false
2,807
java
package com.officego.commonlib.base.recycle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.Collection; /** * Common base class of common implementation for an {@link RecyclerView.Adapter Adapter} * that can be used in {@link RecyclerView RecyclerView}. * <p> * * @author yinhui * @since 17-12-22 */ public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseViewHolder<T>> { private TypePool mTypePool; BaseRecyclerAdapter() { this.mTypePool = new TypePool(); } @NonNull @Override @SuppressWarnings("unchecked") public BaseViewHolder<T> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { ItemType type = mTypePool.getType(viewType); View view = LayoutInflater.from(parent.getContext()) .inflate(type.getLayoutId(viewType), parent, false); return type.onCreateViewHolder(view, type); } @Override public void onBindViewHolder(@NonNull BaseViewHolder<T> holder, int position) { ItemType<T, BaseViewHolder<T>> type = mTypePool.getType(holder.getItemViewType()); T item = getItem(position); type.onBindViewHolder(holder, item, position); holder.setup(item, position); } @Override public int getItemViewType(int position) { return mTypePool.getIndexOfType(getItem(position).getClass()); } public <Type, VH extends BaseViewHolder<Type>> ItemType<Type, VH> getItemType(int position) { return mTypePool.getType(getItemViewType(position)); } public <Type, VH extends BaseViewHolder<Type>> ItemType<Type, VH> getItemType(Class<Type> itemClass) { return mTypePool.getType(itemClass); } public <Type> void register(@NonNull ItemType<Type, ?> itemType) { register(null, itemType); } @SuppressWarnings("unchecked") public <Type> void register(Class<? extends Type> clazz, @NonNull ItemType<Type, ?> itemType) { mTypePool.register(clazz, itemType); itemType.setAdapter((BaseRecyclerAdapter<Type>) this); } public void clearTypes() { mTypePool.clear(); } public abstract T getItem(int position); public abstract void add(@NonNull T data); public abstract void add(@IntRange(from = 0) int position, @NonNull T data); public abstract void add(@NonNull Collection<? extends T> data); public abstract void add(@IntRange(from = 0) int position, @NonNull Collection<? extends T> data); public abstract void remove(@IntRange(from = 0) int position); public abstract void clear(); }
[ "1976290043@qq.com" ]
1976290043@qq.com
77cd7e50659f8cc37e335b0707542020d405d33b
c9eae5f5116e60cef12dcf26ef47bcb93e5dd3a8
/src/day16_Scanner/Scanner_NextLine.java
780479d490b8d24bdf9ef0ca3530980f09c38cf0
[]
no_license
A1myra/JavaProgramming2020_B21
871bb5630f92db3a6c211b28b8f8c872a373e972
0e23000c9aac88c8cb66d75dfc09aada896b46ce
refs/heads/master
2023-02-26T07:51:03.634622
2021-02-01T20:33:26
2021-02-01T20:33:26
312,080,251
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package day16_Scanner; import java.util.Scanner; public class Scanner_NextLine { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your address"); String address = input.nextLine(); // nextLine allow us to enter multiple words System.out.println("Address: "+address); } }
[ "amiraa1225@gmail.com" ]
amiraa1225@gmail.com
2e669f31fde75868b58fe4aabe03c9566cc40fdb
23cc963092bb93e4b0b6531747a40bbcfaea20fb
/Server/src/main/java/ar/com/adriabe/web/controllers/adapters/ProductFamilyJSONAdapter.java
b51e908c538b5c40076d05554d050bfb175d7887
[]
no_license
MildoCentaur/billing
819927d1695fde31b26451b4223fcf513d35e376
6c37bf3f476d326404cf70f4fd72740028eb3d01
refs/heads/master
2021-01-11T04:18:26.568172
2017-02-10T03:44:12
2017-02-10T03:44:12
71,210,731
0
0
null
null
null
null
UTF-8
Java
false
false
1,387
java
package ar.com.adriabe.web.controllers.adapters; import ar.com.adriabe.model.ProductFamily; import ar.com.adriabe.web.model.json.ProductFamilyJSON; import java.util.ArrayList; import java.util.List; /** * Created by Mildo on 1/23/15. */ public class ProductFamilyJSONAdapter { public List<ProductFamilyJSON> buildProductFamilyJSONListFromProductList(List<ProductFamily> all) { List<ProductFamilyJSON> result = new ArrayList<ProductFamilyJSON>(); for (ProductFamily family : all) { result.add(buildProductFamilyJSONFromProduct(family)); } return result; } public ProductFamilyJSON buildProductFamilyJSONFromProduct(ProductFamily family) { ProductFamilyJSON result = new ProductFamilyJSON(); if(family!=null){ result.setColorType(family.getColorType().getLabel()); result.setFabricId(family.getFabric().getId()); result.setFabricName(family.getFabric().getCode() + " " + family.getFabric().getShortname()); result.setId(family.getId()); result.setName(family.getName()); result.setPrice(family.getPrice()); if(family.getStripe()!=null){ result.setStripeId(family.getStripe().getId()); result.setStripeName(family.getStripe().getName()); } } return result; } }
[ "alejandro.mildiner@gmail.com" ]
alejandro.mildiner@gmail.com
04772b316457c86ade61855083687e52ce125f0d
2843ca9ef3979ae681b026c66eddd1c6fd2b0f51
/app/src/main/java/com/android/mvpp2p/injector/PerService.java
4c8d29284925c811240efbc73f85a49b9acdbb3a
[]
no_license
rensw/P2PMVP
5cd55ba34e374e567f734f7a8a8142e957a3f268
976695e4cf9235a0b733d746b628e529386aaddd
refs/heads/master
2020-04-02T05:41:00.849627
2016-07-07T09:23:40
2016-07-07T09:23:40
62,623,724
1
0
null
null
null
null
UTF-8
Java
false
false
266
java
package com.android.mvpp2p.injector; import java.lang.annotation.Retention; import javax.inject.Scope; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Created by sll on 15/11/22. */ @Scope @Retention(RUNTIME) public @interface PerService { }
[ "rsw1992@163.com" ]
rsw1992@163.com
f800b6739cd1f849d7d7ce60f717ba5e30fa2858
9b32140410ba1c063114daa5af25d8739d507703
/distance/SquaredEuclidean.java
25ba2bd7d1fd519d8a0421e9ce3c14d342a9a768
[]
no_license
Abelarm/AlignmentFree-Hadoop
12c7415dbf68053d22345919b799dfea8e7befd5
ecfb2145c7bdf38fae00da4a502fb5688d16eb05
refs/heads/master
2021-01-21T12:40:21.272528
2016-03-10T11:30:43
2016-03-10T11:30:43
34,841,044
1
1
null
null
null
null
UTF-8
Java
false
false
1,036
java
package distance; /** * * @author Gianluca Roscigno - email: giroscigno@unisa.it - http://www.di.unisa.it/~roscigno/ * * @version 1.3 * * Date: January, 30 2015 */ public class SquaredEuclidean implements DistanceMeasure { public SquaredEuclidean() { super(); } @Override public double computePartialDistance(Parameters param) { return Math.pow((param.getC1()-param.getC2()), 2); } @Override public double distanceOperator(double partialResult, double addResult) { return partialResult + addResult; } @Override public double initDistance() { return 0.0; } @Override public boolean hasInternalProduct() { return false; } @Override public double finalizeDistance(double dist, int numEl) { return dist; } @Override public boolean isSymmetricMeasure() { return true; } @Override public String toString() { return getName(); } @Override public String getName() { return "SquaredEuclidean"; } public boolean isCompatibile(String pattern){ return true; } }
[ "luigi3000@gmail.com" ]
luigi3000@gmail.com
0912385ab36f83c5a4c73d4318cc7e9e0b138ee6
6629ab1ed6ad36db65816056d2a63d86bda17b89
/ClaseSabado302/src/com/example/clasesabado302/ListViewDemo.java
605edcc49dec15fb9a64daace79d219bd588c2b6
[]
no_license
Eddyjim/MAEOCS
52802e5f506a9fb36661c2cec06797be37426315
f3d5b775fbba59db21de319bb62f68e6dba62e2b
refs/heads/master
2016-09-06T03:53:03.041891
2013-05-14T07:11:49
2013-05-14T07:11:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,065
java
package com.example.clasesabado302; import android.app.ListActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class ListViewDemo extends ListActivity { TextView selection; String[] items = { "Lorem", "ipsum", "dolor", "sit" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view_demo); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1)); selection = (TextView) findViewById(R.id.selection); } public void onListItemClick(ListView parent, View v, int position, long id) { selection.setText(items[position]); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_list_view_demo, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return true; } }
[ "edward.jimenez.m@gmail.com" ]
edward.jimenez.m@gmail.com
4611695c4b6e44ca3adea4010e8d0f53c6ff732b
ff30350502b71d97d19e8e0f9d66325be2ad8800
/src/main/java/com/mavha/personascrud/config/DatabaseConfig.java
42c31037f01ea16522c4e1d77f2cb12995f4e81a
[]
no_license
ayarde/personascrud
24af691b01402b732b7116fb8dd4b0172eee07a5
1326e99f4b790c519a81c7a55e93d7abed9815d2
refs/heads/master
2020-03-18T03:06:30.555188
2018-05-21T20:12:04
2018-05-21T20:12:04
134,223,031
0
0
null
null
null
null
UTF-8
Java
false
false
557
java
package com.mavha.personascrud.config; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; @Configuration public class DatabaseConfig { public DataSource dataSource(){ final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:mem:testdb"); dataSource.setUsername("sa"); return dataSource; } }
[ "adrian.ayarde@gmail.com" ]
adrian.ayarde@gmail.com
d55c3609a92fc583ad1834e91e254161b571fc11
8b84f3a7aa72d302a19da00ac8b844921e32c81a
/src/main/java/org/jyu/web/service/question/QuestionBlankService.java
2364db4764310a6697af39e6e6b8f44024854f9d
[]
no_license
unclesky4/Learnease
f8c8e946a445d82371fb2c78d44964581d6415bc
88e0eacd712fe4ed05459a8e5434a5c7025dd86b
refs/heads/master
2020-03-11T08:56:53.029686
2018-07-03T12:50:46
2018-07-03T12:50:46
129,896,962
0
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package org.jyu.web.service.question; import java.util.List; import java.util.Map; import org.jyu.web.dto.Result; import org.jyu.web.entity.question.QuestionBlank; public interface QuestionBlankService { Result save(String shortName, String content, Integer difficulty, String userId, List<String> labelIds, String answerContent, String analyse); Result update(String id, String shortName, String content, Integer difficulty, List<String> labelIds, String answerContent, String analyse); Result deleteById(String id); QuestionBlank findById(String id); Map<String, Object> list(int pageNumber, int pageSize, String sortOrder); Result judgeResult(String qid, String solution); /** * 分页查询某个用户提交的填空题 * @param pageNumber 页码 * @param pageSize 分页大小 * @param sortOrder 排序 * @param userId 用户主键 * @return Map集合 */ Map<String, Object> getPageByUser(int pageNumber, int pageSize, String sortOrder, String userId); }
[ "1292931210@qq.com" ]
1292931210@qq.com
eda35d34caa3c0b8f6fe7d6542899e0caad0128e
6255f6adcfaa9b5a2fb25598655492aa2cf9478e
/src/main/java/com/faype/security/core/service/GenericService.java
7c5af9c8e8e20fa231a5b591005c69432bfee3c4
[]
no_license
silveiraSoftware/faype-security-model-java
71d82624236f19386a8cd05ba3f92f01fc9e1f83
a1be2a11daa0af46fc470f8d8fb878c5071364d8
refs/heads/master
2021-06-25T02:44:21.476329
2017-07-04T21:40:41
2017-07-04T21:40:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,672
java
package com.faype.security.core.service; import com.faype.security.core.domain.GenericDomain; import com.faype.security.core.domain.QueryObject; import com.faype.security.core.domain.SearchResponse; import com.faype.security.core.exception.DomainExistenceException; import com.faype.security.core.repository.GenericRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; /** * @param <D> Id * @param <E> WDomain * @author wmfsystem */ @Service @Scope(value = "prototype") public abstract class GenericService<F extends GenericRepository, E extends GenericDomain, D extends Serializable> { @Autowired protected F repository; @Transactional public SearchResponse<List<E>> findAll(QueryObject queryObject) { Page page = repository.findAll(new PageRequest(queryObject.getStart(), queryObject.getPageSize())); SearchResponse searchResponse = new SearchResponse(); searchResponse.setCount(page.getTotalElements()); searchResponse.setPageSize(queryObject.getPageSize()); searchResponse.setStart(queryObject.getStart()); searchResponse.setValues(page.getContent()); return searchResponse; } @Transactional public SearchResponse<List<E>> findAll() { QueryObject queryObject = new QueryObject(); Page page = repository.findAll(new PageRequest(queryObject.getStart(), queryObject.getPageSize())); SearchResponse searchResponse = new SearchResponse(); searchResponse.setCount(page.getTotalElements()); searchResponse.setPageSize(queryObject.getPageSize()); searchResponse.setStart(queryObject.getStart()); searchResponse.setValues(page.getContent()); return searchResponse; } public E save(E obj) { boolean isUpdate = false; if (obj.getId() != null) { E verifyId = (E) repository.findOne(obj.getId()); if (verifyId != null) { throw new DomainExistenceException("This Domain exists!"); } isUpdate = true; this.beforeUpdate(obj); } else { this.beforeSave(obj); } obj.setCreatedAt(LocalDateTime.now()); Object object = repository.save(obj); if (isUpdate) { afterUpdate((E) object); } else { afterSave((E) object); } return (E) object; } public void beforeSave(E obj) { } public void afterSave(E obj) { } public void beforeUpdate(E obj) { } public void afterUpdate(E obj) { } public E findOne(Serializable id) { E object = (E) repository.findOne(id); return object; } public void delete(Serializable id) { try { repository.delete(id); } catch (EmptyResultDataAccessException e) { throw new DataIntegrityViolationException("Erro ao deletar!"); } } public E update(E object) { E actualObject = (E) verifyExists(object); Object after = repository.save(object); return (E) after; } public Object verifyExists(E object) { return findOne(object.getId()); } }
[ "willianmarquesfreire@gmail.com" ]
willianmarquesfreire@gmail.com
1cdce7c44b6d4545fd0fdd0ca08d2b370057c5ef
16a0cfd5667dc5c1eeaaac85366888a8854ce62b
/src/com/esri/gpt/catalog/schema/InputSelectWithOther.java
fe001237ae60b3d58c37c5284e4afb8ae8d77e5d
[ "Apache-2.0" ]
permissive
usgin/usgin-geoportal
d9d0e635963e4af63ce923ee0fbc81f6047e4530
d23f0a8fa96c855f01c8b30be80fb8031d122188
refs/heads/master
2021-01-22T10:12:44.792482
2014-12-01T19:15:53
2014-12-01T19:15:53
3,076,342
0
0
null
null
null
null
UTF-8
Java
false
false
8,757
java
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.catalog.schema; import com.esri.gpt.framework.util.Val; import com.esri.gpt.framework.xml.DomUtil; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.html.HtmlInputText; import javax.faces.component.html.HtmlPanelGroup; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Select one menu input component with an "Other" option for inputing text. * <p/> * The drop down choices are based upon the codes defined for the parameter. * <p/> * The component is configured from a node with a schema configuration * XML document. */ public class InputSelectWithOther extends InputSelectOneMenu { // class variables ============================================================= // instance variables ========================================================== private String _otherCodeKey = ""; private InputText _otherComponent; // constructors ================================================================ /** Default constructor. */ public InputSelectWithOther() { this(null); } /** * Construct by duplicating an existing object. * @param objectToDuplicate the object to duplicate */ public InputSelectWithOther(InputSelectWithOther objectToDuplicate) { super(objectToDuplicate); if (objectToDuplicate == null) { setOtherComponent(new InputText()); } else { setOtherCodeKey(objectToDuplicate.getOtherCodeKey()); setOtherComponent(objectToDuplicate.getOtherComponent().duplicate()); setFacesId(objectToDuplicate.getFacesId()); } } // properties ================================================================== /** * Sets the Faces ID for the component. * <br/> The '.' character will be replaced with the '.' character. * @param id Faces ID */ @Override public void setFacesId(String id) { super.setFacesId(id); if (getOtherComponent() != null) { getOtherComponent().setFacesId(getFacesId()+"_other"); } } /** * Gets the code key associated with the "Other" option. * @return the key */ public String getOtherCodeKey() { return _otherCodeKey; } /** * Sets the code key associated with the "Other" option. * @param key the key */ public void setOtherCodeKey(String key) { _otherCodeKey = Val.chkStr(key); } /** * Gets the component for inputting "Other" text. * @return the InputText component associated with the "Other" option */ public InputText getOtherComponent() { return _otherComponent; } /** * Sets the component for inputting "Other" text. * @param otherComponent the InputText component associated with the "Other" option */ public void setOtherComponent(InputText otherComponent) { _otherComponent = otherComponent; if (_otherComponent == null) _otherComponent = new InputText(); } // methods ===================================================================== /** * Configures the object based upon a node loaded from a * schema configuration XML. * <br/>The super.configure method should be invoked prior to any * sub-class configuration. * <p/> * The following attributes are configured: * <br/>otherCodeKey * <p/> * The InputText component associated with the "Other" option is also configured * from this node. * @param context the configuration context * @param node the configuration node * @param attributes the attributes of the configuration node */ @Override public void configure(CfgContext context, Node node, NamedNodeMap attributes) { super.configure(context,node,attributes); setOtherCodeKey(DomUtil.getAttributeValue(attributes,"otherCodeKey")); getOtherComponent().configure(context,node,attributes); } /** * Produces a deep clone of the object. * <br/>The duplication constructor is invoked. * <br/>return new InputSelectWithOther(this); */ @Override public InputSelectWithOther duplicate() { return new InputSelectWithOther(this); } /** * Appends property information for the component to a StringBuffer. * <br/>The method is intended to support "FINEST" logging. * <br/>super.echo should be invoked prior appending any local information. * @param sb the StringBuffer to use when appending information */ @Override public void echo(StringBuffer sb) { super.echo(sb); sb.append(" otherCodeKey=\"").append(getOtherCodeKey()).append("\""); sb.append("\n").append(getOtherComponent()); } /** * Makes a Faces HtmlSelectOneMenu and an HtmlInputText (for "Other" option) * components for a parameter. * <p/> * The menu items are based upon the defined codes for the parameter. * @param context the UI context * @param section the parent section * @param parameter the associated parameter * @return the UI component */ @Override public UIComponent makeInputComponent(UiContext context, Section section, Parameter parameter) { // determine values String sValue = parameter.getContent().getSingleValue().getValue(); String sMenuValue = sValue; String sTextValue = ""; boolean bIsOther = false; if (!parameter.getContent().getCodes().containsKey(sValue)) { bIsOther = true; } else if (sValue.equalsIgnoreCase(getOtherCodeKey())) { bIsOther = true; } if (bIsOther) { sMenuValue = getOtherCodeKey(); sTextValue = sValue; } // make the input text for the "Other" option InputText other = getOtherComponent(); HtmlInputText text = new HtmlInputText(); text.setId(other.getFacesId()); text.setMaxlength(other.getMaxlength()); text.setSize(other.getSize()); text.setDisabled(!getEditable()); text.setValue(sTextValue); if (!bIsOther) { text.setStyle("visibility:hidden;"); } // make the script for the onchange event StringBuffer sbOnchange = new StringBuffer(); sbOnchange.append("mdeToggleVisibility(this,"); sbOnchange.append("'").append(other.getFacesId()).append("',"); sbOnchange.append("this.options[this.selectedIndex].value=="); sbOnchange.append("'").append(getOtherCodeKey()).append("')"); // make the select one menu parameter.getContent().getSingleValue().setValue(sMenuValue); UIComponent menu = makeSelectOneMenu(context,section,parameter,sbOnchange.toString()); parameter.getContent().getSingleValue().setValue(sValue); // group the components HtmlPanelGroup panel = new HtmlPanelGroup(); panel.getChildren().add(menu); panel.getChildren().add(makeNBSP()); panel.getChildren().add(text); return panel; } /** * Triggered on the save event from the metadata editor. * <p/> * On this event, either HtmlSelectOneMenu input value or the HtmlInputText * value is propagated to the parameter's singleValue (depending on the * whether or not the user has selected the "Other" option). * @param context the UI context * @param editorForm the Faces HtmlForm for the metadata editor * @param parameter the associated parameter * @throws SchemaException if an associated Faces UIComponent cannot be located */ @Override public void unBind(UiContext context, UIComponent editorForm, Parameter parameter) throws SchemaException { UIInput menu = findInputComponent(context,editorForm); UIInput text = getOtherComponent().findInputComponent(context,editorForm); String sMenuValue = getInputValue(menu); String sTextValue = Val.chkStr(getInputValue(text)); text.setValue(sTextValue); if (sMenuValue.equalsIgnoreCase(getOtherCodeKey())) { parameter.getContent().getSingleValue().setValue(sTextValue); if (text instanceof HtmlInputText) { ((HtmlInputText)text).setStyle("visibility:visible;"); } } else { parameter.getContent().getSingleValue().setValue(sMenuValue); if (text instanceof HtmlInputText) { ((HtmlInputText)text).setStyle("visibility:hidden;"); } } } }
[ "urbanm@67efa443-47dd-41b6-99b9-72c5c247b029" ]
urbanm@67efa443-47dd-41b6-99b9-72c5c247b029
4831f37a361bd4b95c92cd39cc908659160bbe02
b5b15968fb086b406ac98699916d04baeb21c97e
/Group1/src/lesson150922/HW/OOM/ConstructionHW.java
5c54e006358bd83ca12b99672862cc3c290558c6
[]
no_license
Shukman/HWJava_Fall
7517ca0b9f83b4b6b290c5897156e251549e2187
6807320b5d2a91906dfc147ffc8ba2ac206c4a7c
refs/heads/master
2021-01-10T15:43:04.490035
2016-04-24T12:24:01
2016-04-24T12:24:01
54,334,520
0
0
null
null
null
null
UTF-8
Java
false
false
74
java
package lesson150922.HW.OOM; public class ConstructionHW { }
[ "Shukmanv@inbox.ru" ]
Shukmanv@inbox.ru
d0b0b9d35ab6812be454971d2924ba2b4c7f568a
171b90e6d3eb5f623caacb3be29a586d6a8cb6a8
/src/main/java/com/leadsdc/webserver/dto/MailDTO.java
ef6fdacb88bed974538cac0c32ce46fecb72cc86
[]
no_license
usaselmo/leadsdc-webserver
1aa9ad6f78463fbbafa67eaf85593b014521b682
867371efcac04a8e6135396c2813f36163159f86
refs/heads/main
2023-02-24T02:38:39.232881
2021-01-15T18:38:41
2021-01-15T18:38:41
329,982,005
0
0
null
null
null
null
UTF-8
Java
false
false
402
java
package com.leadsdc.webserver.dto; import java.util.List; import lombok.Getter; import lombok.RequiredArgsConstructor; @Getter @RequiredArgsConstructor public class MailDTO { private final List<PersonDTO> to; private final List<PersonDTO> bcc; private final String text; private final List<MediaDTO> attachments; private final String type; private final String subject; }
[ "anselmo.sr@gmail.com" ]
anselmo.sr@gmail.com
983c3e4b78b62aa60c89b865c7ccc28e42fcfc63
0ef8ce3db76289db5f9478f8771ee3ee6d024387
/src/geektime/15_binary/BinaryFind.java
6b1b8ca967741ebe9695367ffad0212b4b7604bc
[]
no_license
WarriorYu/Algorithm-Best-Practice
aac5fb454e879aa2fdd87351b5b6f4fcb3c5c862
185fa64ad8eadc8e2c5ad5ef06db4d3d90960e85
refs/heads/master
2021-08-31T11:49:29.787889
2021-08-17T02:27:17
2021-08-17T02:27:17
183,173,452
0
0
null
null
null
null
UTF-8
Java
false
false
1,252
java
/** * Author : soldieryu.dev@gmail.com * Create : 2019/6/3 * Describe : 二分查找 (数组必须有序,不存在重复) */ public class BinaryFind { public static void main(String[] args) { int[] arr = {1, 3, 4, 5, 7, 9, 10, 12}; int index = bsearch(arr, arr.length, 9); System.out.print(index); } //mid=(low+high)/2 这种写法是有问题的。 // 因为如果 low 和 high 比较大的话,两者之和就有可能会溢出。 // 改进的方法是将 mid 的计算方式写成 low+(high-low)/2。 // 更进一步,如果要将性能优化到极致的话,我们可以将这里的除以 2 操作转化成位运算 low+((high-low)>>1)。 // 因为相比除法运算来说,计算机处理位运算要快得多。 public static int bsearch(int[] a, int n, int value) { if (n == 0) return -1; int low = 0; int high = n - 1; while (low <= high) { int mid = low + ((high - low) >> 1); if (a[mid] == value) { return mid; } else if (a[mid] < value) { low = mid + 1; } else { high = mid - 1; } } return -1; } }
[ "soldieryu.dev@gmail.com" ]
soldieryu.dev@gmail.com
343b45df67499bc12a36ccc275af22929460f388
879c90816b90232b224389f144725aaf4dc3939f
/WsIntegration/src/com/integration/ws/soap/SOAPUtil.java
d652d7500579bed9fa83aa06ffc73cd3a9c2a08b
[]
no_license
munditoro/wsintegracion
12b7467519bd713ca42270da4ef8b203876532ba
fd764b4eb535cb24fdad4fb4b6dd11dd703843b4
refs/heads/master
2021-01-23T08:43:54.663464
2016-11-14T17:43:57
2016-11-14T17:43:57
73,729,327
0
0
null
null
null
null
UTF-8
Java
false
false
2,897
java
package com.integration.ws.soap; import java.util.HashMap; import javax.naming.Context; import com.integracion.ws.security.SecConstants; import com.integracion.ws.security.SecCrypto; import com.integracion.ws.security.SecCryptoParams; public class SOAPUtil { public static SOAPMessage createSOAPMessage() { return new SOAPMessage(); } /** * This method supports signing, and encrypting & signing of * a certain SOAP message; * * @param message SOAP message to be secured * @param params Configuration parameters to enable encryption / signature * @param credentials User Credentials used to sign a SOAP message * @param crypto Crypto Data used to encrypt a SOAP Message * @return * @throws Exception */ public static SOAPMessage secureSOAPMessage(SOAPMessage message, HashMap<String,String> params, SecCrypto sigCrypto, SecCrypto encCrypto) throws Exception { if (params.containsKey(SecConstants.REQ_SIGN) && params.get(SecConstants.REQ_SIGN).equals("yes")) { if (sigCrypto == null) throw new Exception("[SOAPMessenger] No credential information provided."); message.sign(sigCrypto); } else if (params.containsKey(SecConstants.REQ_ENCRYPT_SIGN) && params.get(SecConstants.REQ_ENCRYPT_SIGN).equals("yes")) { if ((sigCrypto == null) || (encCrypto == null)) throw new Exception("[SOAPMessenger] No credential or crypto information provided."); message.encryptAndSign(sigCrypto, encCrypto); } return message; } /** * @param message * @param params * @param crypto * @return * @throws Exception */ public static SOAPMessage validateSOAPMessage(SOAPMessage message, HashMap<String,String> params, SecCrypto decCrypto) throws Exception { if (params.containsKey(SecConstants.RES_VERIFY) && params.get(SecConstants.RES_VERIFY).equals("yes")) { message.verify(); } else if (params.containsKey(SecConstants.RES_DECRYPT_VERIFY) && params.get(SecConstants.RES_DECRYPT_VERIFY).equals("yes")) { if (decCrypto == null) throw new Exception("[SOAPMessenger] No crypto information provided."); message.verifyAndDecrypt(decCrypto); } return message; } /** * @param context * @param message * @param endpoint * @param cryptoParams * @return * @throws Exception */ public static SOAPMessage sendSOAPMessage(Context context, SOAPMessage message, String endpoint, SecCryptoParams cryptoParams) throws Exception { SOAPMessenger messenger = SOAPMessenger.getInstance(); // the messenger is initialized only once messenger.init(context, cryptoParams); return messenger.sendRequest(message, endpoint); } }
[ "noreply@github.com" ]
noreply@github.com
480f46759bbb9d6639bc235c71687e3808de10d2
cce34cb0a6fd6eeca32dbfea349af887143fa112
/CustomerListStats.java
2b150f0d0db609a742cb3786d2eb692d8fc4c339
[]
no_license
eozmen410/CustomerAnalytics
3159791a86aaa6961d0704915b24500a9f26378c
795295026ee95da60bc1eb391ea280c5cb8705c9
refs/heads/master
2020-04-02T01:25:09.176751
2018-10-20T00:59:13
2018-10-20T00:59:13
153,854,602
0
0
null
null
null
null
UTF-8
Java
false
false
1,877
java
public class CustomerListStats implements CustomerAnalytics { private int numberOfFemaleCustomers, numberOfMaleCustomers, numberOfSeniorCustomers, numberOfAdultCustomers, numberOfYoungCustomers; public CustomerListStats() { numberOfAdultCustomers = 0; numberOfFemaleCustomers = 0; numberOfMaleCustomers = 0; numberOfSeniorCustomers = 0; numberOfYoungCustomers = 0; } public void addCustomer(Customer customer) { checkGender(customer); checkAge(customer); } private void checkGender(Customer customer) { if(customer.isFemale()) { numberOfFemaleCustomers++; } else if(customer.isMale()) { numberOfMaleCustomers++; } } private void checkAge(Customer customer) { if(customer.isSenior()) { numberOfSeniorCustomers++; } else if (customer.isAdult()) { numberOfAdultCustomers++; } else { numberOfYoungCustomers++; } } public int numberOfFemaleCustomers() { return numberOfFemaleCustomers; } public int numberOfMaleCustomers() { return numberOfMaleCustomers; } public int numberOfSeniorCustomers() { return numberOfSeniorCustomers; } public int numberOfAdultCustomers() { return numberOfAdultCustomers; } public int numberOfYoungCustomers() { return numberOfYoungCustomers; } public String toString() { return "Number of Female Customers: " + numberOfFemaleCustomers + "\nNumber of Male Customers: " + numberOfMaleCustomers + "\nNumber of Senior Customers: " + numberOfSeniorCustomers +"\nNumber of Adult Customers: " + numberOfAdultCustomers + "\nNumber of Young Customers: " + numberOfYoungCustomers; } }
[ "ecenaz@dyn-209-2-234-196.dyn.columbia.edu" ]
ecenaz@dyn-209-2-234-196.dyn.columbia.edu
4d179be5365e39d41497c7a681acb57b4c12fd25
d105f7d16b745d69dd9a7ac64ed631a92b628027
/src/test/java/edu/bzu/soa/demo/DemoApplicationTests.java
cc132794acf1c911f1178fb07ac893f5c1605971
[]
no_license
BZUmaster/Demo
dfc246e11de281290d49fb09039dcbef37788f0d
fab8f6897cf03f7b037dc8cc401d0bf488c0e91a
refs/heads/master
2021-01-20T15:42:03.035062
2017-05-09T20:37:42
2017-05-09T20:37:42
90,788,533
0
0
null
null
null
null
UTF-8
Java
false
false
331
java
package edu.bzu.soa.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Test public void contextLoads() { } }
[ "eliasdkh@gmail.com" ]
eliasdkh@gmail.com
516e5ede3cc4563fdc5294aaeccb7c1553632207
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-large-project/src/test/java/org/gradle/test/performancenull_151/Testnull_15012.java
9088a0823416b5ca56df9f1411ea9260fb04cd10
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
308
java
package org.gradle.test.performancenull_151; import static org.junit.Assert.*; public class Testnull_15012 { private final Productionnull_15012 production = new Productionnull_15012("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
[ "cedric.champeau@gmail.com" ]
cedric.champeau@gmail.com
087ce77a36e498d6ca5290f91a11c225a34ec6a3
38ca4442311ce8d2a92ebd2c3eab69d4bae50c63
/SpringCore/shop/src/main/java/org/shop/api/impl/UserServiceImpl.java
498e3cf674c74ebd1c6a538de632ec0969a84b04
[]
no_license
VGand/JMP2016
89757096d29a0ecceedaf85680b37858255507a3
d0c53f2c71c36e842bdbb956bec8cfa52bb138a8
refs/heads/master
2020-05-21T16:40:24.728223
2016-10-22T18:49:34
2016-10-22T18:49:34
63,398,444
0
1
null
2016-08-26T05:27:30
2016-07-15T06:44:37
Java
UTF-8
Java
false
false
1,280
java
package org.shop.api.impl; import java.util.List; import org.shop.api.UserService; import org.shop.data.User; import org.shop.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class UserServiceImpl implements UserService { @Autowired private UserRepository repository; /* (non-Javadoc) * @see org.shop.api.UserService#registerUser(org.shop.data.User) */ @Override public Long registerUser(User user) { return repository.createUser(user); } /* (non-Javadoc) * @see org.shop.api.UserService#getUserById(java.lang.Long) */ @Override public User getUserById(Long userId) { return repository.getUserById(userId); } /* (non-Javadoc) * @see org.shop.api.UserService#updateUserProfile(org.shop.data.User) */ @Override public void updateUserProfile(User user) { repository.updateUser(user); } /* (non-Javadoc) * @see org.shop.api.UserService#getUsers() */ @Override public List<User> getUsers() { return repository.getUsers(); } public void populate(UserRepository repository) { this.repository = repository; } }
[ "andreivv@list.ru" ]
andreivv@list.ru
fb2982bd22c6d1e793d721184cc989871daf4208
a4e8fc07df596bc17418869fc75a2ad5097dd3ea
/src/oop/inheritence/demo/Animal.java
3dad7f53d23466a72b9268069910c1c20c7368f6
[]
no_license
dimaTsaruk/Fall2020
439ce42eeb76c8252d34d3a96f627f5833d3d5cb
b63a3d91174e0a8402a6da2190237eca47adcc0b
refs/heads/master
2023-03-07T02:43:12.853007
2021-02-17T02:02:08
2021-02-17T02:02:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
162
java
package oop.inheritence.demo; public class Animal { public String name = "ANIMAL"; public void printName(){ System.out.println(name); } }
[ "askarmusakunov@Askars-MacBook-Pro.local" ]
askarmusakunov@Askars-MacBook-Pro.local
79f313f8d0473d6ab3d4ee39e5817e21311faa20
216407b9625b01491175fb95b14653b9fb586fab
/src/main/java/com/fmsh/blockchain/core/redis/MessageConfiguration.java
b5c45f34bfff0bea7fb34bc61f0d185e69d429ab
[]
no_license
clozeblur/blockchain
7edb19c689bf47f24515448e366e3caf2811d41d
032e556e2010b659a8b9d0e37bdfc130f18e38a5
refs/heads/master
2020-03-22T05:19:40.420801
2018-08-22T08:51:04
2018-08-22T08:51:04
139,558,052
0
0
null
null
null
null
UTF-8
Java
false
false
1,444
java
package com.fmsh.blockchain.core.redis; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import java.util.Collections; import java.util.List; /** * @Author: yuanjiaxin * @Date: 2018/7/23 14:53 * @Description: */ @Configuration public class MessageConfiguration { @Bean public RedisMessageListenerContainer leaderRedisMessageListenerContainer(RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); List<PatternTopic> topics = Collections.singletonList(new PatternTopic("manager")); container.addMessageListener(messageListenerAdapter, topics); return container; } @Bean public Receiver receiver() { return new Receiver(); } @Bean public MessageListenerAdapter messageListenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } }
[ "yuanjiaxin@fmsh.com.cn" ]
yuanjiaxin@fmsh.com.cn
7eaaf35f9dafb385b7c7aea9a23a65d07b6a4f45
a4a51084cfb715c7076c810520542af38a854868
/src/main/java/com/shopee/app/ui/image/k.java
81ba2a8094c279b24268bc8f5b54a8f2806d169d
[]
no_license
BharathPalanivelu/repotest
ddaf56a94eb52867408e0e769f35bef2d815da72
f78ae38738d2ba6c9b9b4049f3092188fabb5b59
refs/heads/master
2020-09-30T18:55:04.802341
2019-12-02T10:52:08
2019-12-02T10:52:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,045
java
package com.shopee.app.ui.image; import android.content.Context; import android.content.res.Resources; import android.view.View; import android.widget.ImageButton; import com.garena.android.uikit.image.browser.GImageBrowserView; import com.shopee.app.ui.image.indicator.PageIndicatorView; import com.shopee.id.R; import java.util.List; import org.a.a.b.a; import org.a.a.b.b; import org.a.a.b.c; public final class k extends j implements a, b { private boolean k = false; private final c l = new c(); public k(Context context, List<MediaData> list, boolean z, int i, boolean z2) { super(context, list, z, i, z2); g(); } public static j a(Context context, List<MediaData> list, boolean z, int i, boolean z2) { k kVar = new k(context, list, z, i, z2); kVar.onFinishInflate(); return kVar; } public void onFinishInflate() { if (!this.k) { this.k = true; inflate(getContext(), R.layout.image_browser_layout, this); this.l.a((a) this); } super.onFinishInflate(); } private void g() { c a2 = c.a(this.l); Resources resources = getContext().getResources(); c.a((b) this); this.f23025e = resources.getDimensionPixelSize(R.dimen.dp16); this.f23026f = resources.getDimensionPixelSize(R.dimen.dp8); c.a(a2); } public <T extends View> T internalFindViewById(int i) { return findViewById(i); } public void onViewChanged(a aVar) { this.f23022b = (GImageBrowserView) aVar.internalFindViewById(R.id.browser); this.f23023c = (ImageButton) aVar.internalFindViewById(R.id.back_button); this.f23024d = (PageIndicatorView) aVar.internalFindViewById(R.id.page_indicator); if (this.f23023c != null) { this.f23023c.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { k.this.b(); } }); } a(); } }
[ "noiz354@gmail.com" ]
noiz354@gmail.com
243a1d2ab2922f1e5b94e77d15aa54bce0930cef
81523c9d7512447413c9e7dd4bf79f0894789eac
/app/src/test/java/mtz/fernando/edu/mx/ipn/com/login/ExampleUnitTest.java
4a0c9afadce8d29abf100c64bd3c4bef19ca19af
[]
no_license
FernandoMtz54744/Login
55f5058979aebeeb668f91ec26d64a608ad002f5
b9a3d4ef3b022bf3c1538edc16b477c7d39cbedb
refs/heads/master
2020-04-22T08:26:24.006882
2019-02-12T03:02:43
2019-02-12T03:02:43
170,241,998
0
0
null
null
null
null
UTF-8
Java
false
false
394
java
package mtz.fernando.edu.mx.ipn.com.login; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "fer_f@outlook.com" ]
fer_f@outlook.com
c6e5f899969b107f7893ee47e2c798cf29408a17
ba3b25d6cf9be46007833ce662d0584dc1246279
/droidsafe_modified/modeling/api/java/io/NotSerializableException.java
8f23db584bf177cf493e60812e48f9fde174bad0
[]
no_license
suncongxd/muDep
46552d4156191b9dec669e246188080b47183a01
b891c09f2c96ff37dcfc00468632bda569fc8b6d
refs/heads/main
2023-03-20T20:04:41.737805
2021-03-01T19:52:08
2021-03-01T19:52:08
326,209,904
8
0
null
null
null
null
UTF-8
Java
false
false
3,423
java
/* * Copyright (C) 2015, Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Please email droidsafe@lists.csail.mit.edu if you need additional * information or have any questions. * * * This file incorporates work covered by the following copyright and * permission notice: * * 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. */ /***** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. *****/ package java.io; // Droidsafe Imports import droidsafe.runtime.*; import droidsafe.helpers.*; import droidsafe.annotations.*; public class NotSerializableException extends ObjectStreamException { @DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:56:47.590 -0500", hash_original_field = "60837B5C1B966117A8FB2ADDBC15466F", hash_generated_field = "48F39D42996338B3D3EADC139002C622") private static final long serialVersionUID = 2906642554793891381L; /** * Constructs a new {@code NotSerializableException} with its stack trace * filled in. */ @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:56:47.592 -0500", hash_original_method = "F05776C79D2C056D2A5E9037EDB03920", hash_generated_method = "8CFF896851B0FED7312E9CAEDF084484") public NotSerializableException() { } /** * Constructs a new {@link NotSerializableException} with its stack trace * and detail message filled in. * * @param detailMessage * the detail message for this exception. */ @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:56:47.595 -0500", hash_original_method = "AC41FE5CB653485B7C55102BD4EBFA1E", hash_generated_method = "F054EB24726814C2CD166590686070CF") public NotSerializableException(String detailMessage) { super(detailMessage); } }
[ "suncong@xidian.edu.cn" ]
suncong@xidian.edu.cn
ee2e34cc6d2551ae52fdaad049d2b6ea4238c48b
5f47e66d4eba3da0348c6f3e41765750f5f97496
/CestUnMac_Android/src/com/cestunmac/android/ui/CategoriesTabFragment.java
947810d2b65f851e0d0c93d64401f8d41f4f413b
[]
no_license
obonal/cestunmac
7f363f3e77ff9cc0ffdf9038c7b39e6a0c249f78
ae02d216d8811980cde884e1fded00298388e422
refs/heads/master
2020-09-22T02:14:51.446572
2014-12-18T16:23:05
2014-12-18T16:23:05
32,143,519
0
1
null
null
null
null
UTF-8
Java
false
false
4,047
java
package com.cestunmac.android.ui; import java.util.Iterator; import org.codehaus.jackson.JsonNode; import android.content.Context; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cestunmac.android.Constants; import com.cestunmac.android.IDataRefreshListener; import com.cestunmac.android.ISAMAbstractDataContainerFragment; import com.cestunmac.android.R; import com.cestunmac.android.data.Category; import com.cestunmac.android.utils.ServerExchangeUtils; public class CategoriesTabFragment extends ISAMAbstractDataContainerFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); addDataRefreshListener((IDataRefreshListener) getActivity()); refreshData(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { int layout_id = R.layout.categories_main; View v = inflater.inflate(layout_id, container, false); CategoryListFragment titles = new CategoryListFragment(); // Execute a transaction, replacing any existing fragment // with this one inside the frame. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.category_list, titles); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); return v; } public void refreshData(final Context _context) { Runnable r = new Runnable() { public void run() { Looper.prepare(); fireDataRefreshBegin(Constants.CATEGORIES_REFRESH_KEYWORD); try { String request_url_string = Constants.REQUEST_URL_CATEGORIES; JsonNode json_result = ServerExchangeUtils.getRequestForJSonResponse(request_url_string, _context); if (json_result != null) { handleJSonResponse(json_result, _context); } else { handleJSonRequestFailure(); } } catch (Throwable e) { handleJSonRequestFailure(); e.printStackTrace(); } // setWorkingStatus(false); Looper.loop(); } }; Thread t = new Thread(r, "Server Exchange Thread"); t.start(); } protected void handleJSonRequestFailure() { Log.e(Constants.LOG_TAG, "Request to server failed :-("); fireDataRefreshEnd(Constants.CATEGORIES_REFRESH_KEYWORD); } protected void handleJSonResponse(JsonNode json_response, Context _context) { Log.i(Constants.LOG_TAG, "Categories Request Response: " + json_response); JsonNode status_node = ServerExchangeUtils.safeJSonGet(json_response, Constants.JSON_STATUSCODE_KEYWORD); String status = status_node == null ? null : status_node.getTextValue(); if (Constants.OK_STATUS.equals(status)) { JsonNode categories_array = ServerExchangeUtils.safeJSonGet(json_response, Constants.JSON_CATEGORIES_KEYWORD); if (categories_array != null) { Iterator<JsonNode> it = categories_array.getElements(); while (it.hasNext()) { JsonNode category_node = (JsonNode) it.next(); Category category = new Category(category_node, _context); if ((category.getStoredDBId() == Constants.DB_STORAGE_ID_NOT_STORED)) { category.persist(_context); } } } } fireDataRefreshEnd(Constants.CATEGORIES_REFRESH_KEYWORD); } }
[ "olivier.bonal@gmail.com" ]
olivier.bonal@gmail.com
704b41e3bd9f7d55ef899635a49a24ec85a24218
c879e095def598160ba46a08a9b58e6356fab2bf
/src/main/java/com/zjh/graduationproject/service/admin/impl/AdminServiceImpl.java
795e6244ad82182d5e9774146fb6dd0a84bd17cb
[]
no_license
JiaHanZhuang/graduation
9483be9ead44eba8f5e26a620ed79534f8c8e61d
fdec012b72df0cd763c6518aac9890113cc4fe6e
refs/heads/master
2021-07-02T21:28:33.475569
2019-12-21T06:34:00
2019-12-21T06:34:00
229,386,750
0
0
null
2021-04-26T19:48:37
2019-12-21T06:24:11
JavaScript
UTF-8
Java
false
false
2,878
java
package com.zjh.graduationproject.service.admin.impl; import com.zjh.graduationproject.dao.AdminDao; import com.zjh.graduationproject.dao.TypeDao; import com.zjh.graduationproject.pojo.Admin; import com.zjh.graduationproject.pojo.Movie; import com.zjh.graduationproject.pojo.MovieType; import com.zjh.graduationproject.service.admin.AdminService; import com.zjh.graduationproject.utils.MD5Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author zjh * @date 2019/10/17 */ @Service public class AdminServiceImpl implements AdminService { private Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class); private final String USERNAME = "admin"; private final String PASSWORD = "123456"; @Autowired private AdminDao adminDao; @Autowired private TypeDao typeDao; @Override public Map<String, Object> login(Admin admin) { Map<String,Object> map = new HashMap<>(2); if(USERNAME.equals(admin.getUsername()) && PASSWORD.equals(admin.getPassword())) { map.put("HttpCode",200); map.put("admin",new Admin(0,"admin","123456")); } else { String password = MD5Util.getMd5(admin.getPassword()); admin = adminDao.findAdminByUsernameAndPassword(admin.getUsername(),password); logger.info(admin.toString()); if(admin != null && admin.getId() != null) { map.put("HttpCode",200); map.put("admin",admin); } else { map.put("HttpCode",404); map.put("message","账户密码错误"); } } return map; } @Override public Map<String, Object> install() { Map<String,Object> map = new HashMap<>(2); String[] str = {"动作","传记","犯罪","亲情","恐怖","浪漫","体育", "战争","冒险","喜剧","记录","玄幻","惊悚","卡通","古装","戏剧","历史", "音乐","心理"}; //查询是否已经录入 List<MovieType> movieTypeList = typeDao.findAll(); if(movieTypeList.size() == 0) { for(int i = 0;i < str.length; i++) { typeDao.save(new MovieType(str[i])); } } else if(movieTypeList.size() < str.length) { typeDao.deleteAll(); for(int i = 0;i < str.length; i++) { typeDao.save(new MovieType(str[i])); } } else { map.put("HttpCode",202); map.put("message","已经安装,不需要重复安装"); return map; } map.put("HttpCode",200); map.put("message","安装完成"); return map; } }
[ "1290660512@qq.com" ]
1290660512@qq.com
1b2a3eea954aace8eecbcb57c0a9cd1b5889b53e
79a9f0240a98269939e8e87374289e5b7ef58dc0
/src/test/java/com/user/dao/mysqlConnect.java
f4ba19e86db6ce2b594069bc861091e745bd1737
[]
no_license
chosung-dev/spring_board
0583a13db83029b87324b99374bf0b3d90674da6
4feb4aab74797572556e8053c8239550c9e6dc1f
refs/heads/master
2023-04-09T02:10:26.470952
2021-04-10T12:49:43
2021-04-10T12:49:43
355,490,185
0
0
null
null
null
null
UTF-8
Java
false
false
608
java
package com.user.dao; import static org.junit.jupiter.api.Assertions.*; import java.sql.Connection; import java.sql.DriverManager; import org.junit.jupiter.api.Test; class mysqlConnect { static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch(Exception e) { e.printStackTrace(); } } @Test public void testConnection() { try(Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/spring_board?serverTimezone=Asia/Seoul", "root", "pw1234")){ System.out.println(con); } catch (Exception e) { fail(e.getMessage()); } } }
[ "chosung.dev@gmail.com" ]
chosung.dev@gmail.com
c607e46fa9e4ae4e06ec6736ff1398b0ed904a63
288151cf821acf7fe9430c2b6aeb19e074a791d4
/mfoyou-agent-server/mfoyou-agent-taobao/src/main/java/com/alipay/api/domain/ZhimaAuthInfoAuthqueryModel.java
86a6af5ba63d12ebdfb5a9a4d9b8451ee670437d
[]
no_license
jiningeast/distribution
60022e45d3a401252a9c970de14a599a548a1a99
c35bfc5923eaecf2256ce142955ecedcb3c64ae5
refs/heads/master
2020-06-24T11:27:51.899760
2019-06-06T12:52:59
2019-06-06T12:52:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
708
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 查询是否授权的接口 * * @author auto create * @since 1.0, 2016-09-21 19:49:58 */ public class ZhimaAuthInfoAuthqueryModel extends AlipayObject { private static final long serialVersionUID = 5416969632331155112L; /** * json格式的内容,包含userId,userId为支付宝用户id,用户授权后商户可以拿到这个支付宝userId */ @ApiField("identity_param") private String identityParam; public String getIdentityParam() { return this.identityParam; } public void setIdentityParam(String identityParam) { this.identityParam = identityParam; } }
[ "15732677882@163.com" ]
15732677882@163.com
d75184762f452d7d6018da52136161035cef9315
816232db2f21e193612eaa60eda0d5897d31caaf
/Programmers/LEVEL1/java/solution23.java
5242e3474994b5555ded24a7084cac9f3ffc32ae
[]
no_license
Juyoung4/StudyAlgorithm
a60bfa7657eac57f59200bfa204aff1ad27c79f8
4b190e0bfeb268bef4be00ae9bedd9ca8946fbd6
refs/heads/master
2023-08-31T04:37:07.422641
2021-09-27T08:38:09
2021-09-27T08:38:09
282,757,306
0
0
null
null
null
null
UTF-8
Java
false
false
350
java
package Programmers.LEVEL1.java; import java.util.*; public class solution23 { public boolean solution(int x) { int sum = 0; int temp = x; while (temp > 0){ sum += (temp % 10); temp /= 10; } if (x % sum == 0) return true; else return false; } }
[ "47167335+Juyoung4@users.noreply.github.com" ]
47167335+Juyoung4@users.noreply.github.com
384b01bcec496b3f47d8be231db204cb0e86170b
ea1a74759081f381aba69750c6f1daa71425ee79
/RFID/src/com/zj/net/ServerSoap.java
3ae6cd50cc5c5c7c81ece15c3910b888e57cc0a8
[]
no_license
LukaszRichterUI/RFID-1
f5d4f711ed244a0da146f318e6dff710179bbd9c
2b2a6086dd8f2246c40ae6bdabeebd057898e644
refs/heads/master
2018-12-28T12:51:49.304385
2014-08-26T03:16:37
2014-08-26T03:16:37
null
0
0
null
null
null
null
GB18030
Java
false
false
18,540
java
package com.zj.net; import java.util.ArrayList; import java.util.List; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.AndroidHttpTransport; import org.ksoap2.transport.HttpTransportSE; import com.zj.rfid.ConstDefine; import android.content.Context; import android.content.Intent; import android.util.Log; public class ServerSoap { // 定义Web Service的命名空间 static final String SERVICE_NS = "http://WebXml.com.cn/"; static final String NS = "http://tempuri.org/"; // 定义Web Service提供服务的URL static final String SERVICE_URL = "http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx"; static final String URL = "http://59.37.161.150/DGMService.asmx"; String mUser,mPassword; String mID; String mStyle; Context mContext; public ServerSoap(Context context,String User,String Password){ mContext = context; mUser = User; mPassword = Password; } public ServerSoap(Context context,String ID){ mContext = context; mID = ID; } public void getUser(){ String User = null; try { String METHOD_NAME = "Get_User_Grant"; //1.实例化SoapObject对象 SoapObject request = new SoapObject(NS, METHOD_NAME); Log.d("Uer:"+mUser, "PSW:"+mPassword); //2.如果方法需要参数,设置参数 request.addProperty("uid", mUser); request.addProperty("psw", mPassword); //3.设置Soap的请求信息,参数部分为Soap协议的版本号 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); //4.构建传输对象 try { AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); // MyAndroidHttpTransport httpTranstation = new MyAndroidHttpTransport(URL, 10000); httpTranstation.debug = true; //5.访问WebService,第一个参数为命名空间 + 方法名,第二个参数为Envelope对象 httpTranstation.call(NS+METHOD_NAME, envelope); //6.解析返回的数据 String tempString = envelope.getResponse().toString(); Log.d("unlock",tempString); User = tempString.substring(tempString.indexOf("=")+1, tempString.indexOf(",")); Log.d("unlock",User); Intent mIntent = new Intent(ConstDefine.Action_login); mIntent.putExtra(ConstDefine.Action_login, User); mContext.sendBroadcast(mIntent); }catch (Exception e) { // TODO: handle exception Log.d("", "Exception连接超时"); Intent mIntent = new Intent(ConstDefine.Action_login); mIntent.putExtra(ConstDefine.Action_login, ConstDefine.login_faild); mContext.sendBroadcast(mIntent); } } catch (Exception e) { Log.e("no response", "读取信息,返回信息错误"); e.printStackTrace(); } } public static List<String> GetTaskMaster(String muid,String mstyle) { String[] s = null; ArrayList<String> result = new ArrayList<String>(); try { String METHOD_NAME = "Get_Task_Master"; //1.实例化SoapObject对象 SoapObject request = new SoapObject(NS, METHOD_NAME); //Log.d("Uer:"+mUser, "PSW:"+mPassword); //2.如果方法需要参数,设置参数 request.addProperty("uid", muid); request.addProperty("style", mstyle); //Log.d("222",muid+mPassword); //3.设置Soap的请求信息,参数部分为Soap协议的版本号 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); //4.构建传输对象 AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); // MyAndroidHttpTransport httpTranstation = new MyAndroidHttpTransport(URL, 10000); httpTranstation.debug = true; //5.访问WebService,第一个参数为命名空间 + 方法名,第二个参数为Envelope对象 httpTranstation.call(NS+METHOD_NAME, envelope); //6.解析返回的数据 String tempString = envelope.getResponse().toString(); Log.d("xxx",tempString); Log.d("unlock","ServerSoap.GetTaskMaster------>"+tempString); s = tempString.split(";"); for(int i = 0;i<s.length-1;i++){ if(!s[i].split("=")[1].equals("null")){ s[i] = s[i].split("=")[1]; // s[i] = s[i].split(",")[arg0]; result.add(s[i]); }} } catch (Exception e) { Log.e("no response", "读取信息,返回信息错误"); e.printStackTrace(); } return result; } public static String GetTaskList(String muid , String mstyle){ String str = null; try{ String METHOD_NAME = "Get_Task_List"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("uid", muid); request.addProperty("style", mstyle); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); str = envelope.getResponse().toString(); /* String[] s = str.split("string="); for(int i=1;i<s.length;i++){ if(!s[i].equals("null; ")&&!s[i].equals("null; }")){ s0 = s0+s[i]; } } result = s0.split("null")[1];//str.substring(str.indexOf("=")+1, str.indexOf(";"));//*/ }catch(Exception e){ e.printStackTrace(); } return str; } public static String GetSetupDetail(String mtaskid){ String result = null; String s0 = null; try{ String METHOD_NAME = "Get_Setup_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); Log.d("ser",mtaskid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); str = str.substring(str.indexOf("{")+1, str.indexOf("}")); Log.d("str",str); if(str!=null){ String[] s = str.split("string="); Log.d("s",s[1]); for(int i=1;i<s.length;i++){ s0 = s0+s[i]; } result = s0.split("null")[1]; Log.d("unlock","ServerSoap.GetSetupDetail--->"+result); //ServerSoap.GetSetupDetail--->201310061001,00000001,A小区,,,,,,江门市A小区,,,,; }else{result = "nomeg";} }catch(Exception e){ e.printStackTrace(); } return result; } public static void SetSetupDetail(String mtaskid,String mcustid,String mcustname, String mlockserial,String mlocknumber,String mcolor,String msetpos, String msettime,String maddr,String msetuserid,String mmeterserial, String mmeternumber,String mnote,String mtype,String moldlocknumber){ //String result = null; try{ String METHOD_NAME = "Set_Setup_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); request.addProperty("custid",mcustid); request.addProperty("custname",mcustname); request.addProperty("lockserial",mlockserial); request.addProperty("locknumber",mlocknumber); request.addProperty("color",mcolor); request.addProperty("setpos",msetpos); request.addProperty("settime",msettime); request.addProperty("addr",maddr); request.addProperty("setuserid",msetuserid); request.addProperty("meterserial",mmeterserial); request.addProperty("meternumber",mmeternumber); request.addProperty("note",mnote); request.addProperty("type",mtype); request.addProperty("oldlocknumber",moldlocknumber); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); Log.d("str",str); //result = str.substring(str.indexOf("=")+1, str.indexOf(";")); //Log.d("result",result); }catch(Exception e){ e.printStackTrace(); } } public static void UPSetupDetail(String mtaskid,String muid){ //String result = null; try{ String METHOD_NAME = "UP_Setup_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); request.addProperty("uid",muid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); Log.d("str",str); //result = str.substring(str.indexOf("=")+1, str.indexOf(";")); //Log.d("result",result); }catch(Exception e){ e.printStackTrace(); } } public static String GetCheckDetail(String mtaskid){ String result = null; String s0 = null; try{ String METHOD_NAME = "Get_Check_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); Log.d("Soap_taskid",mtaskid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); Log.d("str",str); String[] s = str.split("string="); Log.d("s",s[1]); // if() for(int i=1;i<s.length;i++){ if(!s[i].equals("null; ")&&!s[i].equals("null; }")){ s0 = s0+s[i]; //Log.d("s0",s0); } } result = s0.split("null")[1];//str.substring(str.indexOf("=")+1, str.indexOf(";")); Log.d("result",result); }catch(Exception e){ e.printStackTrace(); } return result; } public static void SetCheckDetail(String mtaskid, String mlockserial, String msetresult,String muid){ //String result = null; try{ String METHOD_NAME = "Set_Check_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); request.addProperty("lockserial", mlockserial); request.addProperty("setresult", msetresult); request.addProperty("uid", muid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); //result = str.substring(str.indexOf("=")+1, str.indexOf(";")); Log.d("omg",str); }catch(Exception e){ e.printStackTrace(); } } public static void InsertCheckDetail(String mtaskid, String mlockserial, String mStatus){ //String result = null; try{ String METHOD_NAME = "Insert_Check_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); request.addProperty("lockserial", mlockserial); request.addProperty("status", mStatus); // request.addProperty("uid", muid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); //result = str.substring(str.indexOf("=")+1, str.indexOf(";")); Log.d("omg",str); }catch(Exception e){ e.printStackTrace(); } } public static void UPCheckDetail1(String mtaskid){ //String result = null; try{ String METHOD_NAME = "UP_Check_Detail1"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); // request.addProperty("uid",muid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); Log.d("UPCheckDetai",str); //result = str.substring(str.indexOf("=")+1, str.indexOf(";")); //Log.d("result",result); }catch(Exception e){ e.printStackTrace(); } } public static void UPCheckDetail(String mtaskid,String muid){ //String result = null; try{ String METHOD_NAME = "UP_Check_Detail"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("taskid", mtaskid); request.addProperty("uid",muid); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); Log.d("UPCheckDetai",str); //result = str.substring(str.indexOf("=")+1, str.indexOf(";")); //Log.d("result",result); }catch(Exception e){ e.printStackTrace(); } } public static String GetLockInfo(String mlocknumber){ String result = null; String s0 = null; try{ String METHOD_NAME = "Get_Lock_Info"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("LockNumber", mlocknumber); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); String str = envelope.getResponse().toString(); String[] s = str.split("string="); for(int i=1;i<s.length;i++){ if(!s[i].equals("null; ")&&!s[i].equals("null; }")){ s0 = s0+s[i]; } } result = s0.split("null")[1];//str.substring(str.indexOf("=")+1, str.indexOf(";")); Log.d("result",result); }catch(Exception e){ e.printStackTrace(); } return result; } public void GetLockInfo(){ String temp = null; String result = null; String[] s = null; try { // String NAMESPACE = "GetService"; // String URL = "http://59.37.161.150/service.asmx"; String METHOD_NAME = "Get_Lock_Info"; // String SOAP_ACTION = "GetService/get_RFID"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("LockNumber", mID); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); // HttpTransportSE httpTransportSE = new HttpTransportSE(URL, 10000); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); temp = envelope.getResponse().toString(); Log.d("sc",temp); } catch (Exception e) { e.printStackTrace(); } temp = temp.substring(temp.indexOf("=")+1, temp.indexOf(";")); if(!temp.equals("anyType{}")){ result = temp; }else{ result = "没有相关数据"; } Intent mIntent = new Intent(ConstDefine.Action_getRFID); mIntent.putExtra(ConstDefine.Action_getRFID, result); mContext.sendBroadcast(mIntent); } public void getRFID(){ String temp = null; String result = null; String[] s = null; try { // String NAMESPACE = "GetService"; // String URL = "http://59.37.161.150/service.asmx"; String METHOD_NAME = "Get_Lock_List"; // String SOAP_ACTION = "GetService/get_RFID"; SoapObject request = new SoapObject(NS, METHOD_NAME); request.addProperty("LockNumber", mID); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport httpTranstation = new AndroidHttpTransport(URL); // HttpTransportSE httpTransportSE = new HttpTransportSE(URL, 10000); httpTranstation.debug = true; httpTranstation.call(NS+METHOD_NAME, envelope); temp = envelope.getResponse().toString(); Log.d("sc",temp); } catch (Exception e) { e.printStackTrace(); } // if(!temp.equals("anyType{}")){ temp = temp.substring(temp.indexOf("=")+1, temp.indexOf(";")); s = temp.split(","); result = "封印编号:"+s[0]+"\n封印颜色:"+s[1]+"\n加封位置:"+s[2]+"\n电表号:"+s[3]+"\n电表识别码:" +s[4]+"\n客户编号:"+s[5]+"\n客户名称:"+s[6]+"\n加封人员:"+s[7]+"\n加封时间:"+s[8]+"\n状态:"+s[9]; }else{ result = "没有相关数据"; } Intent mIntent = new Intent(ConstDefine.Action_getRFID); mIntent.putExtra(ConstDefine.Action_getRFID, result); mContext.sendBroadcast(mIntent); } }
[ "21422826@qq.com" ]
21422826@qq.com
ef7bc932562ca89eba871c4a7574fcbf2baeeb39
c51cde45051e4a29044e2df34b23fb2a0bef98ff
/INFONOTETST/18_ConexaoBD/src/model/DAO/ContatoDAO.java
057ccac349e5def5abc1c93998c380443e43b826
[]
no_license
rhborges7/Testes
5062c511b7d10f95c619c8ca2df8dfd0f8867d12
14e89d9d02346bb6b010452882d532b97e749951
refs/heads/master
2020-04-08T01:04:26.109419
2018-12-19T23:49:25
2018-12-19T23:49:25
158,880,038
0
0
null
null
null
null
ISO-8859-1
Java
false
false
4,137
java
package model.DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import model.Contato; import util.Conexao; public class ContatoDAO { public static Contato inserir(String nome, String email, String mensagem) { Contato contato = null; try { // CRIAÇÃO DO INSERT String sql = "insert into contato (nome,email,mensagem) values (?,?,?)"; // OBTER A CONEXÃO COM O BANCO DE DADOS Conexao conex = new Conexao("jdbc:mysql://localhost:3306/18_conexaobd?useTimezone=true&serverTimezone=UTC", "com.mysql.cj.jdbc.Driver", "rhuan", "1234"); // ABRIR A CONEXÃO Connection con = conex.obterConexao(); // PREPARAR O COMANDO PARA SER EXECUTADO PreparedStatement comando = con.prepareStatement(sql); comando.setString(1, nome); comando.setString(2, email); comando.setString(3, mensagem); // COMANDO EXECUTADO comando.executeUpdate(); } catch (Exception e) { System.out.println(e.getMessage()); } contato = new Contato(nome, email, mensagem); return contato; } public static Contato excluir(int id) { Contato contato = null; try { // CRIAÇÃO DO DELETE String sql = "delete from contato where id = ? "; // OBTER A CONEXÃO COM O BANCO DE DADOS Conexao conex = new Conexao("jdbc:mysql://localhost:3306/18_conexaobd?useTimezone=true&serverTimezone=UTC", "com.mysql.cj.jdbc.Driver", "rhuan", "1234"); // ABRIR A CONEXÃO Connection con = conex.obterConexao(); // PREPARAR O COMANDO PARA SER EXECUTADO PreparedStatement comando = con.prepareStatement(sql); comando.setInt(1, id); comando.executeUpdate(); // COMANDO EXECUTADO comando.executeUpdate(); } catch (Exception e) { System.out.println(e.getMessage()); } return contato; } public static Contato atualizar(String mensagem, int id) { Contato contato = null; try { // CRIAÇÃO DO UPDATE String sql = "update contato set mensagem = ? where id = ?"; // OBTER A CONEXÃO COM O BANCO DE DADOS Conexao conex = new Conexao("jdbc:mysql://localhost:3306/18_conexaobd?useTimezone=true&serverTimezone=UTC", "com.mysql.cj.jdbc.Driver", "rhuan", "1234"); // ABRIR A CONEXÃO Connection con = conex.obterConexao(); // PREPARAR O COMANDO PARA SER EXECUTADO PreparedStatement comando = con.prepareStatement(sql); comando.setString(1, mensagem); comando.setInt(2, id); // COMANDO EXECUTADO comando.executeUpdate(); } catch (Exception e) { System.out.println(e.getMessage()); } return contato; } public static Contato[] buscarTodos() { Contato[] contatos = null; try { // CRIAÇÃO DO SELECT String sql = "Select * from contato"; // OBTER A CONEXAO COM O BANCO DE DADOS Conexao conex = new Conexao("jdbc:mysql://localhost:3306/18_conexaobd?useTimezone=true&serverTimezone=UTC", "com.mysql.cj.jdbc.Driver", "rhuan", "1234"); Connection con = conex.obterConexao(); /* * EXECUTA A CONFIRMAÇÃO DIRETA DE ACESSO AO BANCO POIS NAO SAO NECESSARIAS * INFORMAÇÕES PARA A QUERY (CARACTER CURINGA) */ Statement comando = con.createStatement(); /* * ResutSet - CLASSE JAVA QUE MONTA EM MEMORIA UMA MATRIZ COM A RESPOSTA DAS * LINHAS DO BANCO DE DADOS */ ResultSet rs = comando.executeQuery(sql); // VETOR DE OBJETOS contatos = new Contato[10]; /* * PASSAGEM DE LINHA DE DADOS DO ResultSet PARA O VETOR DE OBJETOS (UMA LINHA DE * DADOS DA MATRIZ DO ResultSet É COPIADA PARA UM OBJETO NO VETOR CONTATOS) * */ int i = 0; while (rs.next()) { contatos[i++] = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("email"), rs.getString("mensagem")); } // É NECESSARIO ENCERRAR O ACESSO AO BANCO PARA LIBERAR A CONEXAO rs.close(); comando.close(); con.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return contatos; } }
[ "noreply@github.com" ]
noreply@github.com
6ce2b9c28551458145b7bcc41396e65a2e09f7ae
2fcd688e4ab0732e6510524827334f82e9ae0471
/src/main/java/com/worldpay/offer/service/CancelOfferService.java
ff15d10d670f32eda6cb871b73fce83f13fd6c9d
[]
no_license
stugrul/offer-service
096f811d6f50cb8db031b7da729e93ecc7c5837b
597ccee7433677c912b86e11e60b57826ca181d4
refs/heads/master
2020-03-28T19:29:39.009668
2019-01-22T10:04:28
2019-01-22T10:04:28
148,982,159
0
0
null
null
null
null
UTF-8
Java
false
false
765
java
package com.worldpay.offer.service; import com.worldpay.offer.persistence.model.Offer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; @Service public class CancelOfferService { private JpaRepository<Offer, Long> offerJpaRepository; private RetrieveOffersService retrieveOffersService; private CancelOfferService(final JpaRepository<Offer, Long> offerJpaRepository, final RetrieveOffersService retrieveOffersService) { this.offerJpaRepository = offerJpaRepository; this.retrieveOffersService = retrieveOffersService; } public void cancel(final long id) { Offer offer = retrieveOffersService.findById(id); offerJpaRepository.delete(offer); } }
[ "stugrul@travix.com" ]
stugrul@travix.com
d27f201961c7c4821328c3f2513fcd77caee7ac7
c7a97925e531e443a648b61209c031c4b2832d85
/mfsdk/src/main/java/com/morfeus/android/mfsdk/ui/config/exception/ConfigLoadException.java
55d0b64f7832dcc5d40c711738df8ffa28167bf8
[]
no_license
Siddharthyadav123/bSdk
b33433167fc497e7ecf8b5cca65ba3888a38e19c
62ee33919df7d5b837fb5461f185e4cebc0a7252
refs/heads/master
2020-12-30T11:27:49.853357
2017-05-17T09:23:16
2017-05-17T09:23:16
91,557,848
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package com.morfeus.android.mfsdk.ui.config.exception; /** * Thrown when fails to load config properly */ public class ConfigLoadException extends Exception { public ConfigLoadException(String message) { super(message); } public ConfigLoadException(String message, Throwable cause) { super(message, cause); } }
[ "siddharthdv80@gmail.com" ]
siddharthdv80@gmail.com
eab9f89db3f895afe136753455d7e334333c71e3
a5fb8913a497d58839a6943b203c0b44647b651e
/Client/src/main/java/org/xdi/oxauth/client/JwkRequest.java
6721b3659896aafb6171013f895133c60ded5fbf
[ "MIT" ]
permissive
naveenkumargopi/oxAuth
7b85f63791ad05998eced2b35b62b51b192836c0
d94c769707428b851ef7be9b9fb8c047401b8bc2
refs/heads/master
2020-04-08T08:46:50.337735
2018-11-26T11:23:06
2018-11-26T11:47:28
142,112,443
0
0
MIT
2018-07-24T06:08:33
2018-07-24T06:08:33
null
UTF-8
Java
false
false
442
java
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.client; /** * Represents a JSON Web Key (JWK) request to send to the authorization server. * * @author Javier Rojas Blum Date: 11.15.2011 */ public class JwkRequest extends BaseRequest { @Override public String getQueryString() { return null; } }
[ "Yuriy.Movchan@gmail.com" ]
Yuriy.Movchan@gmail.com
ea13d4cc13540a80beb4da328e2a5a9430bd804d
b16521cd7e5d2584e5e6f4ffd93181710fd90f57
/app/src/main/java/com/wezebra/zebraking/ui/installment/ReFillActivity.java
e7db0754fa047310f8cd00097ffb24112a806c3d
[]
no_license
ch1025540473/Android
70047fba3feae3847f7f2771c30e76a31d19df20
399d051ec86d368eb6968b5793be10d3ed8e5110
refs/heads/master
2021-01-21T06:55:23.353174
2015-08-21T10:17:17
2015-08-21T10:17:17
40,282,898
1
0
null
null
null
null
UTF-8
Java
false
false
3,004
java
package com.wezebra.zebraking.ui.installment; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.wezebra.zebraking.R; import com.wezebra.zebraking.ui.BaseActivity; public class ReFillActivity extends BaseActivity implements View.OnClickListener{ private String title; private int redirect; private TextView submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_re_fill); title = getIntent().getExtras().getString("title"); redirect = getIntent().getExtras().getInt("redirect"); submit = (TextView)findViewById(R.id.submit); submit.setOnClickListener(this); } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.menu_re_fill, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // int id = item.getItemId(); // // //noinspection SimplifiableIfStatement // if (id == R.id.action_settings) { // return true; // } // // return super.onOptionsItemSelected(item); // } //根据传过来的标识符来判断应该修改那个类型 @Override public void onClick(View v) { Intent intent = new Intent(); switch (redirect) { case 1: intent.setClass(this,BaseInfoStepInitialActivity.class); break; case 2: intent.setClass(this,IdentificationActivity.class); break; case 3: intent.setClass(this,JobInfoActivity.class); // intent.setClass(this,JobInfoChoiceActivity.class); break; case 4: intent.setClass(this,EducationAuthActivity.class); break; case 5: intent.setClass(this,ContactsAuthActivity.class); break; case 6: intent.setClass(this,IncomeAuthActivity.class); break; case 7: intent.setClass(this,SocialSecurityAuthActivity.class); break; case 8: intent.setClass(this,PublicAccFundsAuthActivity.class); break; case 9: intent.setClass(this,PhoneAuthStepOneActivity.class); break; case 10: intent.setClass(this,CompanyEmailAuth.class); break; } startActivity(intent); this.finish(); } }
[ "andy.chen@wezebra.com" ]
andy.chen@wezebra.com
d8b7057308260cfd4080db9b2da56e297c62497b
a3ebd03f2458f14b1acdb3746c826793b3036dc5
/src/main/java/com/company/socket/Catcher.java
15b68d3eabd15bffa098e592bed6220c926cfb93
[]
no_license
Bellatrix95/java-tcp-ping
b5067051db8a42deb09ad799573ba7e327f47ede
1b29fbacddbd9d4a7c99cc77938c7100fc4b62f7
refs/heads/master
2022-11-21T04:31:06.831247
2020-07-08T17:49:34
2020-07-08T17:49:34
274,092,546
0
0
null
null
null
null
UTF-8
Java
false
false
2,720
java
package main.java.com.company.socket; import main.java.com.company.messages.Message; import main.java.com.company.messages.MessageParser; import main.java.com.company.utils.LoggerClass; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Socket server class for handling incoming messages. * * @author Ivana Salmanić */ public class Catcher implements ICatcher { private ServerSocket serverSocket; private int numOfThreadsUsed; /** * @param bind socket server IP * @param port socket server port number */ public Catcher(String bind, int port) throws IOException { serverSocket = new ServerSocket(port, 10, InetAddress.getByName(bind)); } /** * @param numOfThreadsUsed number of threads for handling incoming messages */ public void setNumOfThreadsUsed(int numOfThreadsUsed) { this.numOfThreadsUsed = numOfThreadsUsed; } public void start() { ExecutorService executor = Executors.newFixedThreadPool(numOfThreadsUsed); while (true) { try { executor.execute((new MessageHandler(serverSocket.accept()))); } catch (IOException e) { e.printStackTrace(); } } } private static class MessageHandler extends SocketDataStream implements Runnable { MessageHandler(Socket socket) { super.clientSocket = socket; } public void run() { try { this.startConnection(); if(in.readChar() != 'b') throw new RuntimeException("The Catcher can only read byte type messages!"); int length = in.readInt(); byte[] messageBytes = new byte[length]; in.readFully(messageBytes); long receivedOnB = ZonedDateTime.now(ZoneId.of("UTC")).toInstant().toEpochMilli(); Message message = MessageParser.createMessageFromByteArray(messageBytes); message.setReceivedOnB(receivedOnB); message.setSendToA(ZonedDateTime.now(ZoneId.of("UTC")).toInstant().toEpochMilli()); out.writeChar('b'); out.writeInt(length); out.write(MessageParser.createByteArrayFromMessage(message, length)); this.stopConnection(); } catch (Exception e) { e.printStackTrace(); LoggerClass.log.warning("Exception occurred while handling incoming message!"); } } } }
[ "tipuric.ivana@nsoft.com" ]
tipuric.ivana@nsoft.com
c4c9a6a11dcad3e12f7d61b4521c99e2a50126ed
09d0ddd512472a10bab82c912b66cbb13113fcbf
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/Fernflower/src/main/java/org/telegram/ui/_$$Lambda$PassportActivity$5Sry1zhVbDTBEYl5VpIUjvovUNY.java
8517c8b5d6909d072d3f75d2fb2193a3d95c4d04
[]
no_license
sgros/activity_flow_plugin
bde2de3745d95e8097c053795c9e990c829a88f4
9e59f8b3adacf078946990db9c58f4965a5ccb48
refs/heads/master
2020-06-19T02:39:13.865609
2019-07-08T20:17:28
2019-07-08T20:17:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
960
java
package org.telegram.ui; import android.view.View; import android.view.View.OnClickListener; import java.util.ArrayList; import org.telegram.tgnet.TLRPC; // $FF: synthetic class public final class _$$Lambda$PassportActivity$5Sry1zhVbDTBEYl5VpIUjvovUNY implements OnClickListener { // $FF: synthetic field private final PassportActivity f$0; // $FF: synthetic field private final ArrayList f$1; // $FF: synthetic field private final TLRPC.TL_secureRequiredType f$2; // $FF: synthetic field private final boolean f$3; // $FF: synthetic method public _$$Lambda$PassportActivity$5Sry1zhVbDTBEYl5VpIUjvovUNY(PassportActivity var1, ArrayList var2, TLRPC.TL_secureRequiredType var3, boolean var4) { this.f$0 = var1; this.f$1 = var2; this.f$2 = var3; this.f$3 = var4; } public final void onClick(View var1) { this.f$0.lambda$addField$65$PassportActivity(this.f$1, this.f$2, this.f$3, var1); } }
[ "crash@home.home.hr" ]
crash@home.home.hr
6a84528ff094bf3c6bb581e4fe0de6bd471ecdf8
ade9d0f65898338f1e99a33d2630f3db74c32cf9
/src/main/java/io/osdf/actions/info/api/InfoApiImpl.java
fc1a7c830e9e5bbafe5635830a6064d10fe8940e
[]
no_license
microconfig/osdf
12c3f5064328832355f117f2447ebfe6277c7986
d2355e7245562db875724f598febe5fa71f8643b
refs/heads/master
2022-05-13T17:13:22.519756
2021-06-02T13:04:24
2021-06-02T13:04:24
249,974,202
7
4
null
2022-04-16T16:20:55
2020-03-25T12:36:25
Java
UTF-8
Java
false
false
2,059
java
package io.osdf.actions.info.api; import io.osdf.actions.info.api.logs.LogsCommand; import io.osdf.actions.info.api.status.StatusCommand; import io.osdf.common.exceptions.StatusCodeException; import io.osdf.core.application.core.Application; import io.osdf.core.connection.cli.ClusterCli; import io.osdf.settings.paths.OsdfPaths; import lombok.RequiredArgsConstructor; import java.util.List; import static io.osdf.actions.info.api.healthcheck.AppsStatusChecker.deployStatusChecker; import static io.osdf.actions.info.printer.ColumnPrinter.printer; import static io.osdf.core.application.core.AllApplications.all; import static io.osdf.core.application.core.files.loaders.ApplicationFilesLoaderImpl.appLoader; import static io.osdf.core.application.core.files.loaders.filters.GroupComponentsFilter.groupComponentsFilter; import static io.osdf.core.application.core.files.loaders.filters.HiddenComponentsFilter.hiddenComponentsFilter; import static io.osdf.core.connection.cli.LoginCliProxy.loginCliProxy; @RequiredArgsConstructor public class InfoApiImpl implements InfoApi { private final OsdfPaths paths; private final ClusterCli cli; public static InfoApi infoApi(OsdfPaths paths, ClusterCli cli) { return loginCliProxy(new InfoApiImpl(paths, cli), cli); } @Override public void logs(String component, String pod) { new LogsCommand(paths, cli).show(component, pod); } @Override public void status(List<String> components, Boolean withHealthCheck) { new StatusCommand(paths, cli, printer(), withHealthCheck).run(components); } @Override public void healthcheck(String group, Integer timeout) { List<Application> apps = appLoader(paths) .withDirFilter(groupComponentsFilter(paths, group)) .withAppFilter(hiddenComponentsFilter()) .load(all(cli)); List<Application> failedApps = deployStatusChecker(cli) .findFailed(apps); if (!failedApps.isEmpty()) throw new StatusCodeException(1); } }
[ "noreply@github.com" ]
noreply@github.com
70a3d6a6d76aaa81a7c6fea7aec58704ae5ac00b
0ee3697d1ab6b7a35945ec27795b3f67959e37ae
/src/main/java/com/vsu/by/app/education/task/TaskController.java
c38ca5eaecb97e9ee9e72b3f26325ea26027b46d
[]
no_license
NikitaKuzmichou/testing-programm-back
48750acf9cfefdd198dbee98049888aa7923b54a
a419ff009165e273bfc5446e7b22fc127a5afa64
refs/heads/master
2022-09-26T14:46:10.856168
2020-04-26T16:19:16
2020-04-26T16:19:16
230,741,888
0
0
null
null
null
null
UTF-8
Java
false
false
3,343
java
package com.vsu.by.app.education.task; import com.vsu.by.app.education.task.dto.*; import com.vsu.by.app.people.teacher.Teacher; import com.vsu.by.app.people.teacher.TeacherService; import com.vsu.by.app.service.text.TextProcessing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; @RestController @RequestMapping("tasks") @Transactional public class TaskController { @Autowired private TaskService taskService; @Autowired private TaskMapper taskMapper; @Autowired private TeacherService teacherService; @Autowired private TextProcessing textProcessing; @GetMapping public ResponseEntity<List<TaskMinInfoDto>> getTasks() { return new ResponseEntity<>( this.taskMapper.toTaskMinInfoDto(this.taskService.findAll()), HttpStatus.OK); } @GetMapping("/{id}") public ResponseEntity<TaskDetailDto> getTask(@PathVariable("id") Long id) { Optional<Task> task = this.taskService.getTask(id); if (task.isPresent()) { return new ResponseEntity<>( this.taskMapper.toTaskDetailDto(task.get()), HttpStatus.OK); } else { /**TODO EXCEPTION*/ throw new NoSuchElementException("Такого задания не существует"); } } @GetMapping("/{subjectId}/{taskTypeId}") public ResponseEntity<List<TaskInfoDto>> getTaskBySubjectAndType(@PathVariable("subjectId") Long subjectId, @PathVariable("taskTypeId") Long taskTypeId) { List<Task> tasks = this.taskService.findAllBySubjectAndTaskType(subjectId, taskTypeId); return new ResponseEntity<>(this.taskMapper.toTaskInfoDto(tasks), HttpStatus.OK); } @PostMapping public ResponseEntity<TaskDetailDto> addTask(@RequestBody TaskDetailDto taskDetailDto) { Task task = this.taskMapper.fromTaskDetailDto(taskDetailDto); task.setTaskText(this.textProcessing.processText(task.getTaskText())); task = this.taskService.saveTask(this.taskMapper.fromTaskDetailDto(taskDetailDto)); return new ResponseEntity<>( this.taskMapper.toTaskDetailDto(task), HttpStatus.ACCEPTED); } @PutMapping public ResponseEntity<TaskDetailDto> updateTask(@RequestBody TaskDetailDto taskDetailDto) { Task fromClient = this.taskMapper.fromTaskDetailDto(taskDetailDto); Teacher teacher = this.teacherService.getTeacher(fromClient.getInfo().getTeacher().getId()).get(); fromClient.getInfo().setTeacher(teacher); return new ResponseEntity<>( this.taskMapper.toTaskDetailDto(this.taskService.updateTask(fromClient)), HttpStatus.ACCEPTED); } @DeleteMapping("/{id}") public ResponseEntity<String> deleteTask(@PathVariable("id") Long id) { this.taskService.deleteTask(id); return new ResponseEntity<>("redirect:/tasks/", HttpStatus.ACCEPTED); } }
[ "nekit338@gmail.com" ]
nekit338@gmail.com
0c9a126ac842d4e5f20d9af85da9579609a05394
deb6c92422f047cc5d2ed41ae837d24e0a935bfb
/src/main/java/br/ufpa/facomp/veiculos/domain/enumeration/Identificador.java
2246f61978b1b3fb0323bb079fd5cf142502c852
[]
no_license
ufpa-engenharia-software/reserva-veiculos-web
79f366f0dddd49a1151e55f134871abbb322a3bd
c76b894185132a420689bb51172ebbb69a2bc259
refs/heads/main
2023-04-28T01:24:41.550415
2021-05-12T12:58:35
2021-05-12T12:58:35
366,713,918
2
0
null
2021-05-12T12:58:36
2021-05-12T12:50:39
Java
UTF-8
Java
false
false
166
java
package br.ufpa.facomp.veiculos.domain.enumeration; /** * The Identificador enumeration. */ public enum Identificador { SIAPE, MATRICULA_SIGAA, CNH, }
[ "jhipster-bot@jhipster.tech" ]
jhipster-bot@jhipster.tech
a86504e0c9bd0a0aaca28bcb1f7c565e832155a6
dc8bc7e3825a5abfec34e4656fb5f7a346093afe
/MyChat/app/src/main/java/com/example/aliasghar/mychat/Profile.java
1fb0ad5811751fb418066921840f5eef6f229c78
[]
no_license
aliasghar7552/Android
894fbb66abe5280923dc56d09761a91884c81fde
c07c75fdcd69985f7b01d13008bcbbd58364c26b
refs/heads/master
2021-05-11T21:04:59.610135
2018-11-18T14:56:50
2018-11-18T14:56:50
117,459,491
1
1
null
null
null
null
UTF-8
Java
false
false
15,678
java
package com.example.aliasghar.mychat; import android.icu.text.SimpleDateFormat; import android.icu.util.Calendar; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.HashMap; public class Profile extends AppCompatActivity { Button sendFriendRequest, declineFriendRequest; TextView profileUsername, profileStatus; ImageView profileImage; private DatabaseReference userDataRef; private DatabaseReference friendRequestRef; private DatabaseReference friendsRef; private DatabaseReference notificationsRef; private FirebaseAuth auth; private String currentState; String senderUserId, receiverUserId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); userDataRef = FirebaseDatabase.getInstance().getReference().child("Users"); receiverUserId = getIntent().getExtras().get("VISITUSERID").toString(); friendRequestRef = FirebaseDatabase.getInstance().getReference().child("Friend_Requests"); friendRequestRef.keepSynced(true); auth = FirebaseAuth.getInstance(); senderUserId = auth.getCurrentUser().getUid(); friendsRef = FirebaseDatabase.getInstance().getReference().child("Friends"); friendsRef.keepSynced(true); notificationsRef = FirebaseDatabase.getInstance().getReference().child("Notifications"); notificationsRef.keepSynced(true); sendFriendRequest = (Button) findViewById(R.id.btn_sendFriendRequest); declineFriendRequest = (Button) findViewById(R.id.btn_declineFriendRequest); profileUsername = (TextView) findViewById(R.id.tv_profileUsername); profileStatus = (TextView) findViewById(R.id.tv_profileStatus); profileImage = (ImageView) findViewById(R.id.userProfileImage); currentState = "NOT_FRIENDS"; //getting data from database to profile userDataRef.child(receiverUserId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String name = dataSnapshot.child("username").getValue().toString(); String status = dataSnapshot.child("status").getValue().toString(); String image = dataSnapshot.child("image").getValue().toString(); profileUsername.setText(name); profileStatus.setText(status); Picasso.with(getBaseContext()).load(image).placeholder(R.drawable.default_profile).into(profileImage); //sending friend request button changing friendRequestRef.child(senderUserId) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(receiverUserId)) { String req_type = dataSnapshot.child(receiverUserId).child("request_type").getValue().toString(); if (req_type.equals("sent")) { currentState = "REQUEST_SENT"; sendFriendRequest.setText("Cancel Friend Request"); } else if (req_type.equals("received")) { currentState = "REQUEST_RECEIVED"; sendFriendRequest.setText("Acccept Friend Request"); } } else { friendsRef.child(senderUserId) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(receiverUserId)) { currentState = "FRIENDS"; sendFriendRequest.setText("UnFriend"); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); if( ! senderUserId.equals(receiverUserId)) { //sending friend request to other users sendFriendRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendFriendRequest.setEnabled(false); if (currentState.equals("NOT_FRIENDS")) { sendFriendRequestMethod(); } if (currentState.equals("REQUEST_SENT")) { cancelFriendRequest(); } if (currentState.equals("REQUEST_RECEIVED")) { acceptFriendRequest(); } if (currentState.equals("FRIENDS")) { unFriend(); } } }); } else { declineFriendRequest.setVisibility(View.INVISIBLE); sendFriendRequest.setVisibility(View.INVISIBLE); } } private void unFriend() { friendsRef.child(senderUserId).child(receiverUserId).removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { friendsRef.child(receiverUserId).child(senderUserId).removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { sendFriendRequest.setEnabled(true); currentState = "NOT_FRIENDS"; sendFriendRequest.setText("Send Friend Request"); } } }); } } }); } private void acceptFriendRequest() { Calendar calender = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy"); final String date = currentDate.format(calender.getTime()); friendsRef.child(senderUserId).child(receiverUserId).child("date").setValue(date) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { friendsRef.child(receiverUserId).child(senderUserId).child("date").setValue(date) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { friendRequestRef.child(senderUserId).child(receiverUserId).removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { friendRequestRef.child(receiverUserId).child(senderUserId).removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { sendFriendRequest.setEnabled(true); currentState = "FRIENDS"; sendFriendRequest.setText("UnFriend"); } } }); } } }); } }); } }); } private void cancelFriendRequest() { friendRequestRef.child(senderUserId).child(receiverUserId).removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { friendRequestRef.child(receiverUserId).child(senderUserId).removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { sendFriendRequest.setEnabled(true); currentState = "NOT_FRIENDS"; sendFriendRequest.setText("Send Friend Request"); declineFriendRequest.setVisibility(View.INVISIBLE); declineFriendRequest.setEnabled(false); } } }); } } }); } private void sendFriendRequestMethod() { friendRequestRef.child(senderUserId).child(receiverUserId).child("request_type").setValue("sent") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { friendRequestRef.child(receiverUserId).child(senderUserId).child("request_type").setValue("received") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { //notification on sending friend request HashMap<String, String> notificationData = new HashMap<String, String>(); notificationData.put("from", senderUserId); notificationData.put("type", "request"); notificationsRef.child(receiverUserId).push().setValue(notificationData) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { sendFriendRequest.setEnabled(true); currentState = "REQUEST_SENT"; sendFriendRequest.setText("Cancel Friend Request"); declineFriendRequest.setVisibility(View.INVISIBLE); declineFriendRequest.setEnabled(false); } } }); } } }); } } }); } }
[ "aliasghar.7552@gmail.com" ]
aliasghar.7552@gmail.com
577c1bcfdfc3d6361e70b13a9ce98679201792fc
539979e3bc4ef82cc6e4323c8f778900b91fed77
/InstructionParser/src/edu/umich/eecs/soar/delta/LispishObject.java
fe5f160bf71561193c941e1c2b03a55e68cf2676
[ "BSD-2-Clause" ]
permissive
Bryan-Stearns/Delta
beeb2ae1f2e67352f26c4964d103a73da96079aa
795023ced703d45e88a2318ffc64524a92e8feac
refs/heads/main
2023-03-02T11:11:41.218483
2021-02-04T23:07:00
2021-02-04T23:07:00
335,648,101
0
0
null
null
null
null
UTF-8
Java
false
false
7,301
java
package edu.umich.eecs.soar.delta; import java.util.ArrayList; import java.util.List; /** * This class is for representing parsed text from a lisp-style file. * Each object can be either a single String, or a list of strings, corresponding to the tokens within a parenthesis block. * @author Bryan Stearns * @since Oct 2020 */ public class LispishObject { private String data; private LispishObject parentObject = null; private ArrayList<LispishObject> dataList; public LispishObject(String str) { data = str; parentObject = null; dataList = null; } public LispishObject() { data = null; parentObject = null; dataList = null; } public String getData() { return data; } public LispishObject getParent() { return parentObject; } public ArrayList<LispishObject> getDataList() { return dataList; } public boolean isList() { return (dataList != null); } public boolean isEmpty() { return (data == null && dataList == null); } public int size() { if (dataList != null) return dataList.size(); else if (data != null) return 1; return 0; } /** * Clears all contained data references */ public void clear() { data = null; if (dataList != null) dataList.clear(); else dataList = null; } public String getString(int index) throws ArrayIndexOutOfBoundsException { if (index == 0 && dataList == null) { return data; } else if (dataList == null || dataList.size() < index || index < 0) { int sz = 0; if (dataList != null) { sz = dataList.size(); } throw new ArrayIndexOutOfBoundsException("Invalid index " + index + " for LispishObject. Size is " + sz + "."); } return dataList.get(index).toString(); } /** * Get the LispishObject at the given index within this object. * If there is no object at the given index, throws OutOfBoundsException. * @param index The index of the requested object, where 0 is the first index * @return A LispishObject referenced at the given index within this object * @throws ArrayIndexOutOfBoundsException */ public LispishObject get(int index) throws ArrayIndexOutOfBoundsException { if (dataList == null) { throw new ArrayIndexOutOfBoundsException("Cannot get LispishObject at index " + index + ". The object is either empty or has only a single string."); } else if (dataList.size() < index || index < 0) { int sz = dataList.size(); throw new ArrayIndexOutOfBoundsException("Invalid index " + index + " in LispishObject data list. Size is " + sz + "."); } return dataList.get(index); } /** * Add an empty object to the data list and return its reference. * This action also converts any existing non-list String data into list form, and the new object is then appended to the list. * @return the new LispishObject instance */ public LispishObject addObject() { if (dataList == null) dataList = new ArrayList<LispishObject>(3); // If there is a single String data so far only, convert that to the first list element if (data != null) { dataList.add(new LispishObject(data)); data = null; } LispishObject retVal = new LispishObject(); dataList.add(retVal); retVal.parentObject = this; return retVal; } /** * Add an object to the data list with the given string as its first item, and return the reference to the new object. * This action also converts any existing non-list String data into list form, and the new object is then appended to the list. * @param str The String to add as the first item of the new object * @return The new LispishObject instance */ public LispishObject addObject(String str) { LispishObject retval = addObject(); retval.addString(str); return retval; } /** * Set the contents of this object to a single string. * This overwrites any existing data in this object. * @param str */ public void setSingleData(String str) { data = str; if (dataList != null) dataList.clear(); else dataList = null; } /** * Set the contents of this object to be a list of strings corresponding to the given ArrayList of Strings. * This overwrites any existing data in this object. * @param strs */ public void setListData(ArrayList<String> strs) { // Configure if (dataList != null) { dataList.clear(); data = null; // Should already be null if dataList isn't, but clear it to be safe } else { dataList = new ArrayList<LispishObject>(3); data = null; } // Make a list of objects corresponding to each item in the String list for (String str : strs) { LispishObject obj = new LispishObject(str); dataList.add(obj); obj.parentObject = this; } } /** * Add a String to the object in list form. * If there is already single non-list String data here, it will become the first list item, and the new string will be the second item. * @param str */ public void addString(String str) { // Create the list if currently empty if (dataList == null) { dataList = new ArrayList<LispishObject>(3); } // If there is a single String data so far only, convert that to the first list element if (data != null) { LispishObject obj = new LispishObject(data); obj.parentObject = this; dataList.add(obj); data = null; } // Add the new String LispishObject obj = new LispishObject(str); obj.parentObject = this; dataList.add(obj); } public String getSmemVarName() { return "<wm-" + String.valueOf(this.hashCode()) + ">"; } /** * Get an ascending list of the indices in this object's data list whose first string matches the given string. * For example, if this object was "(foo bar berry (bar ...) cherry)" and the pattern was "bar", return [1,3] * @param pattern The string to match * @return The list of indices in which the pattern was found */ public List<Integer> getNamedSublistIndices(String pattern) { List<Integer> retval = new ArrayList<Integer>(); // Check if there is a list to search if (!isList()) { // If not, just check the single string data if (data == null) { return retval; } if (data.equals(pattern)) { retval.add(0); } return retval; } // Iterate and search for (int i=0; i<dataList.size(); ++i) { if (dataList.get(i).getString(0).equals(pattern)) { retval.add(i); } } return retval; } /** * Returns a string suitable to include inside an "smem --add" command. * This method is recursive. The returned string represents both the given object and its descendants. * @return */ public String toSmemString() { // Terminating string: if (!isList()) { return data; } // Is a list: print as its own object String varName = getSmemVarName(); String retval = "(" + varName; for (LispishObject obj : dataList) { if (obj.isList()) // TODO retval += "\t^child " + obj.getSmemVarName(); } return retval; } @Override public String toString() { if (data != null) { return data; } else if (dataList == null) { return "NULL"; } else if (dataList.size() == 0) { return ""; } String retval = " ("; for (LispishObject obj : dataList) { if (obj.isList()) retval += " (...)"; else retval += " " + obj.toString(); } retval += " )"; return retval; } }
[ "bws3263827@gmail.com" ]
bws3263827@gmail.com
9f2368fcbeef3fd64f5ef8038da0d745498e2ddc
b02a75ad17eb2b88287807575ceaabeeef4c0995
/src/test/java/com/huobi/examples/IsolatedMarginClientExample.java
7351b1743e5aed55e8c231577245647dde57ecd4
[ "Apache-2.0" ]
permissive
hengxuZ/huobi_Java
4fa3c061af5b20af28af553ebb74dda65ef80b02
18af788eefc53c022e62ec9c683b84585e23e0aa
refs/heads/master
2022-12-10T09:16:19.780588
2020-09-03T07:48:38
2020-09-03T07:48:38
293,540,470
1
0
Apache-2.0
2020-09-07T13:47:18
2020-09-07T13:47:17
null
UTF-8
Java
false
false
4,274
java
package com.huobi.examples; import java.math.BigDecimal; import java.util.List; import com.huobi.Constants; import com.huobi.client.IsolatedMarginClient; import com.huobi.client.req.margin.IsolatedMarginAccountRequest; import com.huobi.client.req.margin.IsolatedMarginApplyLoanRequest; import com.huobi.client.req.margin.IsolatedMarginLoanInfoRequest; import com.huobi.client.req.margin.IsolatedMarginLoanOrdersRequest; import com.huobi.client.req.margin.IsolatedMarginRepayLoanRequest; import com.huobi.client.req.margin.IsolatedMarginTransferRequest; import com.huobi.constant.HuobiOptions; import com.huobi.constant.enums.MarginTransferDirectionEnum; import com.huobi.model.isolatedmargin.IsolatedMarginAccount; import com.huobi.model.isolatedmargin.IsolatedMarginLoadOrder; import com.huobi.model.isolatedmargin.IsolatedMarginSymbolInfo; import com.huobi.service.huobi.utils.DataUtils; public class IsolatedMarginClientExample { public static void main(String[] args) { IsolatedMarginClient marginService = IsolatedMarginClient.create(HuobiOptions.builder() .apiKey(Constants.API_KEY) .secretKey(Constants.SECRET_KEY) .build()); String symbol = "xrpusdt"; String currency = "usdt"; // 划转至margin Long transferInId = marginService.transfer(IsolatedMarginTransferRequest.builder() .direction(MarginTransferDirectionEnum.SPOT_TO_MARGIN) .symbol(symbol) .currency(currency) .amount(new BigDecimal(50)) .build()); System.out.println(" transfer to margin :" + transferInId); // 查询余额 List<IsolatedMarginAccount> accountList = marginService.getLoanBalance(IsolatedMarginAccountRequest.builder().build()); accountList.forEach(isolatedMarginAccount -> { System.out.println("account:" + isolatedMarginAccount.toString()); isolatedMarginAccount.getBalanceList().forEach(balance -> { System.out.println("===>Balance:" + balance.toString()); }); }); // 停100ms DataUtils.timeWait(100L); BigDecimal loanAmount = new BigDecimal("100"); // 申请贷款 Long applyId = marginService.applyLoan(IsolatedMarginApplyLoanRequest.builder() .symbol(symbol) .currency(currency) .amount(loanAmount) .build()); System.out.println(" margin apply loan :" + applyId); // 查询余额 List<IsolatedMarginAccount> accountList1 = marginService.getLoanBalance(IsolatedMarginAccountRequest.builder().build()); accountList1.forEach(isolatedMarginAccount -> { System.out.println("account:" + isolatedMarginAccount.toString()); isolatedMarginAccount.getBalanceList().forEach(balance -> { System.out.println("===>Balance:" + balance.toString()); }); }); // 停1000ms DataUtils.timeWait(5000L); // 还款 Long repayId = marginService.repayLoan(IsolatedMarginRepayLoanRequest.builder() .orderId(applyId) .amount(loanAmount) .build()); System.out.println(" margin repay loan :" + repayId); //转出 Long transferOutId = marginService.transfer(IsolatedMarginTransferRequest.builder() .direction(MarginTransferDirectionEnum.MARGIN_TO_SPOT) .symbol(symbol) .currency(currency) .amount(new BigDecimal(50)) .build()); System.out.println(" transfer to spot :" + transferOutId); List<IsolatedMarginAccount> accountList2 = marginService.getLoanBalance(IsolatedMarginAccountRequest.builder().build()); accountList2.forEach(isolatedMarginAccount -> { System.out.println("account:" + isolatedMarginAccount.toString()); isolatedMarginAccount.getBalanceList().forEach(balance -> { System.out.println("===>Balance:" + balance.toString()); }); }); List<IsolatedMarginLoadOrder> loanOrderList = marginService.getLoanOrders(IsolatedMarginLoanOrdersRequest.builder() .symbol(symbol) .size(1) .build()); loanOrderList.forEach(order -> { System.out.println(order.toString()); }); List<IsolatedMarginSymbolInfo> list = marginService.getLoanInfo(IsolatedMarginLoanInfoRequest.builder().symbols("xrpusdt").build()); list.forEach(info -> { System.out.println(info); }); } }
[ "duqingxiang@huobi.com" ]
duqingxiang@huobi.com
976e38e3e961ca3feba1726251fe8ecb9b3af575
7d4131c1fae05d684acd0fe98fdb09d54c26decd
/Collection01/src/cn/itheima/collectionTest/TestCollection02.java
1685dbe7bb5eb8143d864c0b07c1ee0e8e553e21
[]
no_license
zhangzhuang521/iterableProject
3902302cf89b7b685482cfe73daa007e1a74016d
6b0cc4db4b00cf89b8dc55790292b3436c973ba2
refs/heads/master
2023-07-06T06:23:09.562267
2021-08-09T15:00:53
2021-08-09T15:00:54
394,332,733
0
0
null
null
null
null
UTF-8
Java
false
false
465
java
package cn.itheima.collectionTest; import java.util.ArrayList; import java.util.Collection; public class TestCollection02 { public static void main(String[] args) { Collection<String> collection = new ArrayList<>(); System.out.println(collection); String s = new String(); System.out.println(s); int[] ints = new int[10]; System.out.println(ints); String A="123"; System.out.println(A); } }
[ "1158654165@qq.com" ]
1158654165@qq.com
2a9cde79f8b0e0ad16d0817824b9e27249ff548b
4b2a844e3319cc322b27a746cee381e90c0ab580
/src/main/java/com/fusion/pageobjects/claims/MassAdjustment.java
300ac8883123385735bdc3aef01bca4734839e87
[]
no_license
TT23990/SeleniumAutomationFramework
236bb079f9f380644c6cbcb4c2f638c58c40571a
d737d3d6c057eb2cb902643f4c7d8d236d4aafa7
refs/heads/master
2023-06-30T10:15:18.276143
2021-08-02T01:07:05
2021-08-02T01:07:05
391,778,809
0
0
null
null
null
null
UTF-8
Java
false
false
80
java
package com.fusion.pageobjects.classic.claims; public class MassAdjustment { }
[ "touseef.tamboli@anthem.com" ]
touseef.tamboli@anthem.com
e4e09cc99988a9511086eaa135818b573bc67f70
da38cf37c18f25a50fbbf040794dd134ebf38d66
/HibernateDAOLayer/src/main/java/com/zygotecorp/app/HibernateDaoLayerApplication.java
2121dd8b1760529d40bc8026be7d51402b7ae833
[]
no_license
radhakrishnan0404/microservices
8350502798bb269026f17c449b76042cd58b2435
4923c8a6bb12d6098d5a8facbee3e2b95ac0052b
refs/heads/zotrix
2022-09-05T09:38:06.358677
2020-07-08T11:34:09
2020-07-08T11:34:09
201,642,600
0
0
null
2022-09-01T23:13:48
2019-08-10T14:42:07
Java
UTF-8
Java
false
false
333
java
package com.zygotecorp.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HibernateDaoLayerApplication { public static void main(String[] args) { SpringApplication.run(HibernateDaoLayerApplication.class, args); } }
[ "radha.ta2008@gmail.com" ]
radha.ta2008@gmail.com
0f5fe4fb849c28408646c105320bf80abff9e359
31d2d473a225418a71d317a75bbd433308a71dd2
/src/TeenNumberChecker.java
17673b480a454dd79f9c4c20f2b6dde30b1d530a
[]
no_license
Ted404/UdemyChallange
bd71f7c4de6b709658a349bd6093fdf401fbc176
64025ba0658d2b3181bb390b5d98707c7617d6ea
refs/heads/master
2022-12-19T03:45:36.362073
2020-09-29T23:42:16
2020-09-29T23:42:16
298,397,891
1
1
null
null
null
null
UTF-8
Java
false
false
271
java
public class TeenNumberChecker { public static boolean hasTeen(int a, int b, int c){ return ((a >= 13 && a <= 19) || (b >= 13 && b <= 19) || (c >= 13 && c <= 19)); } public static boolean isTeen(int a){ return (a >= 13 && a <= 19); } }
[ "tyahyayev@gmail.com" ]
tyahyayev@gmail.com
c6e491b96c6c2546fd7838e5468ec62e21d38ee2
57bccc9613f4d78acd0a6ede314509692f2d1361
/pbk-vis-lib/src/main/java/ru/armd/pbk/services/viss/VisExchangeService.java
3d9cf57495d18591061647bac917e9fa173f858f
[]
no_license
mannyrobin/Omnecrome
70f27fd80a9150b89fe3284d5789e4348cba6a11
424d484a9858b30c11badae6951bccf15c2af9cb
refs/heads/master
2023-01-06T16:20:50.181849
2020-11-06T14:37:14
2020-11-06T14:37:14
310,620,098
0
0
null
null
null
null
UTF-8
Java
false
false
3,081
java
package ru.armd.pbk.services.viss; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.armd.pbk.core.services.BaseDomainService; import ru.armd.pbk.domain.viss.VisExchange; import ru.armd.pbk.dto.viss.VisExchangeDTO; import ru.armd.pbk.matcher.VisExchangeMatcher; import ru.armd.pbk.repositories.viss.VisExchangeConfigRepository; import ru.armd.pbk.repositories.viss.VisExchangeObjectRepository; import ru.armd.pbk.repositories.viss.VisExchangeOperationRepository; import ru.armd.pbk.repositories.viss.VisExchangeRepository; import ru.armd.pbk.repositories.viss.VisExchangeStateRepository; import ru.armd.pbk.repositories.viss.VisRepository; import ru.armd.pbk.repositories.viss.VisTransportTypeRepository; import ru.armd.pbk.services.nsi.DriverService; /** * Сервис журнала взаимодействия с ВИС. */ @Service public class VisExchangeService extends BaseDomainService<VisExchange, VisExchangeDTO> { private static final Logger LOGGER = Logger.getLogger(DriverService.class); private VisExchangeConfigRepository visExchangeConfigRepository; private VisExchangeStateRepository visExchangeStateRepository; private VisTransportTypeRepository visTransportTypeRepository; private VisExchangeObjectRepository visExchangeObjectRepository; private VisExchangeOperationRepository visExchangeOperationRepository; private VisRepository visRepository; @Autowired private VisExchangeConfigService visExchangeConfigService; @Autowired VisExchangeService(VisExchangeRepository repository, VisExchangeConfigRepository visExchangeConfig, VisExchangeStateRepository visExchangeState, VisTransportTypeRepository visTransportType, VisExchangeObjectRepository visExchangeObject, VisExchangeOperationRepository visExchangeOperation, VisRepository vis) { super(repository); visExchangeConfigRepository = visExchangeConfig; visExchangeStateRepository = visExchangeState; visTransportTypeRepository = visTransportType; visExchangeObjectRepository = visExchangeObject; visExchangeOperationRepository = visExchangeOperation; visRepository = vis; } @Override public Logger getLogger() { return LOGGER; } @Override public VisExchangeDTO toDTO(VisExchange domain) { return VisExchangeMatcher.INSTANCE.toDTOForView(domain, visExchangeConfigRepository, visExchangeStateRepository, visTransportTypeRepository, visExchangeObjectRepository, visExchangeOperationRepository, visRepository); } @Override public VisExchange toDomain(VisExchangeDTO dto) { return VisExchangeMatcher.INSTANCE.toDomain(dto); } /** * Повторить обмен с ВИС. * * @param exchangeId - ИД обмена с ВИС. */ public void repeat(Long exchangeId) { VisExchange exchange = domainRepository.getById(exchangeId); visExchangeConfigService.start(exchange.getConfigId(), exchange.getParameter(), exchange.getWorkDate(), exchange.getWorkDate()); } }
[ "malike@hipcreativeinc.com" ]
malike@hipcreativeinc.com
ef9422a8357247943371575cb0fb8e1f346d0f54
46301c7752ed33a35ab9b72feb9463ce66f9c416
/CommonLibrary/src/main/java/com/zjclugger/lib/base/BaseListFragment.java
203bbab5301fd3c9d645e5aa2f0b935ae2dc4edf
[ "Apache-2.0" ]
permissive
zjclugger/JLibrary
81b22613f530a7b7977114641baab17312070711
d004c5673e36ce90dc6e934c7bb5c647283ad857
refs/heads/master
2022-11-19T06:30:25.043053
2020-07-24T07:37:38
2020-07-24T07:37:38
275,754,517
0
0
null
null
null
null
UTF-8
Java
false
false
5,168
java
package com.zjclugger.lib.base; import android.content.Context; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import com.zjclugger.component.Log; import com.zjclugger.lib.R; import com.zjclugger.lib.ui.adapter.JBaseQuickAdapter; import com.zjclugger.lib.utils.Constants; import com.zjclugger.lib.utils.WidgetUtils; import com.zjclugger.lib.view.ExtendRecyclerView; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import java.util.Map; /** * 列表基类<br> * Created by King.Zi on 2020/4/9.<br> * Copyright (c) 2020 zjclugger.com */ public abstract class BaseListFragment extends BaseFragment { private final static String TAG = "BaseList"; protected Bundle mSearchCondition; protected Map<String, Object> mQueryCondition; //分页参数 protected int mCurrentPageIndex = 1; protected int mPageCount; protected int mPageSize = 10; protected JBaseQuickAdapter mAdapter; protected boolean mIsPagingQuery; public abstract ExtendRecyclerView getRecyclerView(); public abstract void getDataFromServer(boolean isPagingQuery); public abstract void initTabLayout(); public abstract void bindData(); public abstract boolean isShowLastLine(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSearchCondition = new Bundle(); } @Override public void onResume() { super.onResume(); if (!isHidden()) { if (mSearchCondition != null && !mSearchCondition.isEmpty()) { /* //获取查询条件并发起查询请求,然后清空condition mCompanyName = mSearchCondition.getString(SellerConstants.Keywords.KEY_SEARCH_TEXT, ""); mStartDate = mSearchCondition.getString(SellerConstants.Keywords.KEY_SEARCH_START_DATE , ""); mEntryDate = mSearchCondition.getString(SellerConstants.Keywords.KEY_SEARCH_ENTRY_DATE , ""); mSearchCondition = null;*/ } //查询条件非空,自动获取数据(TODO: 把查询条件也加到参数中) getDataFromServer(mIsPagingQuery); } } @Override public void onStop() { super.onStop(); getRecyclerView().setForceTop(false); } @Override public void onShown() { super.onShown(); } @Override public void initViews() { //1. init tab list initTabLayout(); //2. bind data bindData(); //先要初始化Adapter getRecyclerView().setRefreshLayoutListener(new OnRefreshListener() { @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { //下拉顶部刷新 if (mCurrentPageIndex != 1) { mQueryCondition.put(Constants.QueryParameter.PAGE_INDEX, mCurrentPageIndex - 1); getRecyclerView().setForceTop(true); getDataFromServer(true); } else { toastMessage(mContext, getString(R.string.info_first_page)); refreshLayout.finishRefresh(); } } }, new OnLoadMoreListener() { @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) { Log.d("page count=" + mPageCount + ",page index=" + mCurrentPageIndex); //上滑底部加载更多 //load more mQueryCondition.put(Constants.QueryParameter.PAGE_INDEX, mCurrentPageIndex + 1); getRecyclerView().setForceTop(true); getDataFromServer(true); } }).create(true, 3, isShowLastLine(), mAdapter, new View.OnClickListener() { @Override public void onClick(View v) { getDataFromServer(mIsPagingQuery); } }); } protected void resetQueryCondition() { mQueryCondition.put(Constants.QueryParameter.PAGE_INDEX, 1); mQueryCondition.put(Constants.QueryParameter.PAGE_SIZE, mPageSize); } @Override public void closeFloatView() { } @Override public boolean doBackPress() { return true; } protected void toastMessage(Context context, String message) { WidgetUtils.toast(mContext, message, false); } /* @Override public void onSearchViewClick() { *//* ARouterUtils.openFragment(getActivity(), SearchKeywordFragment.class.getName(), null, R.color.white, false);*//* } @Override public boolean isSearchViewTitle() { return true; } @Override public void onFilterViewClick() { *//* ARouterUtils.openFragment(getActivity(), SearchFilterFragment.class.getName(), null , R.color.white, false);*//* }*/ }
[ "zjclugger@126.com" ]
zjclugger@126.com
16e81c311fe59bc091356804de0b82c6209f643f
455c91418eccae2693c1014e0ebede4b2e1e99a2
/diamond-client/src/main/java/com/taobao/diamond/client/DiamondConfigure.java
04b5f112a29a4839c4ec869ec5aa3f5de00db409
[]
no_license
topno3rpg/diamond
2e0ae32e35f45d917e1e37239bc0ae3233c2d951
5b785e6d2bb94884d734cad8f1335798708060d3
refs/heads/master
2020-04-18T13:24:22.600247
2017-01-05T02:36:35
2017-01-05T02:36:35
66,806,851
0
0
null
null
null
null
UTF-8
Java
false
false
10,163
java
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * 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. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.client; import java.io.File; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.taobao.diamond.common.Constants; /** * Diamond客户端的配置信息 * * @author aoqiong * */ public class DiamondConfigure { private volatile int pollingIntervalTime = Constants.POLLING_INTERVAL_TIME;// 异步查询的间隔时间 private volatile int onceTimeout = Constants.ONCE_TIMEOUT;// 获取对于一个DiamondServer所对应的查询一个DataID对应的配置信息的Timeout时间 private volatile int receiveWaitTime = Constants.RECV_WAIT_TIMEOUT;// 同步查询一个DataID所花费的时间 private volatile List<String> domainNameList = new LinkedList<String>(); private volatile boolean useFlowControl = true; private boolean localFirst = false; // 以下参数不支持运行后动态更新 private int maxHostConnections = 1; private boolean connectionStaleCheckingEnabled = true; private int maxTotalConnections = 20; private int connectionTimeout = Constants.CONN_TIMEOUT; private int port = Constants.DEFAULT_PORT; private int scheduledThreadPoolSize = 1; // 获取数据时的重试次数 private int retrieveDataRetryTimes = Integer.MAX_VALUE / 10; private String configServerAddress = Constants.DEFAULT_DOMAINNAME; private int configServerPort = Constants.DEFAULT_PORT; // 本地数据保存路径 private String filePath; public DiamondConfigure() { filePath = System.getProperty("user.home") + "/diamond"; File dir = new File(filePath); dir.mkdirs(); final String configServerAddress = System.getProperty("diamond.configServerAddress"); if (StringUtils.isNotBlank(configServerAddress)) { this.configServerAddress = configServerAddress; } domainNameList.add(this.configServerAddress); if (!dir.exists()) { throw new RuntimeException("创建diamond目录失败:" + filePath); } } /** * 获取和同一个DiamondServer的最大连接数 * * @return */ public int getMaxHostConnections() { return maxHostConnections; } /** * 设置和同一个DiamondServer的最大连接数<br> * 不支持运行时动态更新 * * @param maxHostConnections */ public void setMaxHostConnections(int maxHostConnections) { this.maxHostConnections = maxHostConnections; } /** * 是否允许对陈旧的连接情况进行检测。<br> * 如果不检测,性能上会有所提升,但是,会有使用不可用连接的风险导致的IO Exception * * @return */ @Deprecated public boolean isConnectionStaleCheckingEnabled() { return connectionStaleCheckingEnabled; } /** * 设置是否允许对陈旧的连接情况进行检测。<br> * 不支持运行时动态更新 * * @param connectionStaleCheckingEnabled */ public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) { this.connectionStaleCheckingEnabled = connectionStaleCheckingEnabled; } /** * 获取允许的最大的连接数量。 * * @return */ public int getMaxTotalConnections() { return maxTotalConnections; } /** * 设置允许的最大的连接数量。<br> * 不支持运行时动态更新 * * @param maxTotalConnections */ public void setMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; } /** * 获取轮询的间隔时间。单位:秒<br> * 此间隔时间代表轮询查找一次配置信息的间隔时间,对于容灾相关,请设置短一些;<br> * 对于其他不可变的配置信息,请设置长一些 * * @return */ public int getPollingIntervalTime() { return pollingIntervalTime; } /** * 设置轮询的间隔时间。单位:秒 * * @param pollingIntervalTime */ public void setPollingIntervalTime(int pollingIntervalTime) { if (pollingIntervalTime < Constants.POLLING_INTERVAL_TIME) { return; } this.pollingIntervalTime = pollingIntervalTime; } /** * 获取当前支持的所有的DiamondServer域名列表 * * @return */ public List<String> getDomainNameList() { return domainNameList; } /** * 设置当前支持的所有的DiamondServer域名列表,当设置了域名列表后,缺省的域名列表将失效 * * @param domainNameList */ public void setDomainNameList(List<String> domainNameList) { if (null == domainNameList) { throw new NullPointerException(); } this.domainNameList = new LinkedList<String>(domainNameList); } /** * 添加一个DiamondServer域名,当设置了域名列表后,缺省的域名列表将失效 * * @param domainName */ public void addDomainName(String domainName) { if (null == domainName) { throw new NullPointerException(); } this.domainNameList.add(domainName); } /** * 添加多个DiamondServer域名,当设置了域名列表后,缺省的域名列表将失效 * * @param domainNameList */ public void addDomainNames(Collection<String> domainNameList) { if (null == domainNameList) { throw new NullPointerException(); } this.domainNameList.addAll(domainNameList); } /** * 获取DiamondServer的端口号 * * @return */ public int getPort() { return port; } /** * 设置DiamondServer的端口号<br> * 不支持运行时动态更新 * * @param port */ public void setPort(int port) { this.port = port; } /** * 获取探测本地文件的路径 * * @return */ public String getFilePath() { return filePath; } /** * 设置探测本地文件的路径<br> * 不支持运行时动态更新 * * @param filePath */ public void setFilePath(String filePath) { this.filePath = filePath; } /** * 获取对于一个DiamondServer所对应的查询一个DataID对应的配置信息的Timeout时间<br> * 即一次HTTP请求的超时时间<br> * 单位:毫秒<br> * * @return */ public int getOnceTimeout() { return onceTimeout; } /** * 设置对于一个DiamondServer所对应的查询一个DataID对应的配置信息的Timeout时间<br> * 单位:毫秒<br> * 配置信息越大,请将此值设置得越大 * * @return */ public void setOnceTimeout(int onceTimeout) { this.onceTimeout = onceTimeout; } /** * 获取和DiamondServer的连接建立超时时间。单位:毫秒 * * @return */ public int getConnectionTimeout() { return connectionTimeout; } /** * 设置和DiamondServer的连接建立超时时间。单位:毫秒<br> * 不支持运行时动态更新 * * @param connectionTimeout */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } /** * 同步查询一个DataID的最长等待时间<br> * 实际最长等待时间小于receiveWaitTime + min(connectionTimeout, onceTimeout) * * @return */ public int getReceiveWaitTime() { return receiveWaitTime; } /** * 设置一个DataID的最长等待时间<br> * 实际最长等待时间小于receiveWaitTime + min(connectionTimeout, onceTimeout) * 建议此值设置为OnceTimeout * (DomainName个数 + 1) * * @param receiveWaitTime */ public void setReceiveWaitTime(int receiveWaitTime) { this.receiveWaitTime = receiveWaitTime; } /** * 获取线程池的线程数量 * * @return */ public int getScheduledThreadPoolSize() { return scheduledThreadPoolSize; } /** * 设置线程池的线程数量,缺省为1 * * @param scheduledThreadPoolSize */ public void setScheduledThreadPoolSize(int scheduledThreadPoolSize) { this.scheduledThreadPoolSize = scheduledThreadPoolSize; } /** * 是否使用同步接口流控 * * @return */ public boolean isUseFlowControl() { return useFlowControl; } /** * 设置是否使用同步接口流控 * * @param useFlowControl */ public void setUseFlowControl(boolean useFlowControl) { this.useFlowControl = useFlowControl; } public String getConfigServerAddress() { return configServerAddress; } public void setConfigServerAddress(String configServerAddress) { this.configServerAddress = configServerAddress; } public int getConfigServerPort() { return configServerPort; } public void setConfigServerPort(int configServerPort) { this.configServerPort = configServerPort; } public int getRetrieveDataRetryTimes() { return retrieveDataRetryTimes; } public void setRetrieveDataRetryTimes(int retrieveDataRetryTimes) { this.retrieveDataRetryTimes = retrieveDataRetryTimes; } public boolean isLocalFirst() { return localFirst; } public void setLocalFirst(boolean localFirst) { this.localFirst = localFirst; } }
[ "guozhongping@aixuedai.com" ]
guozhongping@aixuedai.com
4b50d04b5a2651d48d1c595c7b7090272a3fe0aa
9260e329cb9520de217abc88197c7e867fa3b772
/app/src/main/java/cn/redcdn/hvs/udtroom/view/fragment/UDTChatFragment.java
f39e90e9eca7fc6873b5be55cf47cf9489af7216
[]
no_license
cdc0002829/YiLianTiButelMedical
2c27672ee01bb5fbb4563bb6be3dc18bb42c805e
46901c4c7427f51f7505d3649a04c6b4b9cd5008
refs/heads/master
2021-09-04T12:30:52.341094
2018-01-18T16:18:52
2018-01-18T16:18:52
117,952,582
1
0
null
null
null
null
UTF-8
Java
false
false
94,770
java
package cn.redcdn.hvs.udtroom.view.fragment; import android.annotation.TargetApi; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import cn.redcdn.datacenter.hpucenter.data.CSLRoomDetailInfo; import cn.redcdn.datacenter.hpucenter.data.HPUCommonCode; import cn.redcdn.datacenter.medicalcenter.MDSAppSearchUsers; import cn.redcdn.datacenter.medicalcenter.data.MDSAccountInfo; import cn.redcdn.datacenter.meetingmanage.GetMeetingInfomation; import cn.redcdn.datacenter.meetingmanage.data.MeetingInfomation; import cn.redcdn.hvs.AccountManager; import cn.redcdn.hvs.MedicalApplication; import cn.redcdn.hvs.R; import cn.redcdn.hvs.base.BaseFragment; import cn.redcdn.hvs.config.SettingData; import cn.redcdn.hvs.contacts.VerificationReplyDialog; import cn.redcdn.hvs.contacts.contact.ContactTransmitConfig; import cn.redcdn.hvs.contacts.contact.interfaces.Contact; import cn.redcdn.hvs.contacts.contact.manager.ContactManager; import cn.redcdn.hvs.im.IMConstant; import cn.redcdn.hvs.im.activity.ChatActivity; import cn.redcdn.hvs.im.activity.MultiImageChooserActivity; import cn.redcdn.hvs.im.activity.SelectGroupMemeberActivity; import cn.redcdn.hvs.im.activity.SelectLinkManActivity; import cn.redcdn.hvs.im.activity.UDTChatInputFragment; import cn.redcdn.hvs.im.bean.BookMeetingExInfo; import cn.redcdn.hvs.im.bean.ButelPAVExInfo; import cn.redcdn.hvs.im.bean.ButelVcardBean; import cn.redcdn.hvs.im.bean.ContactFriendBean; import cn.redcdn.hvs.im.bean.FriendInfo; import cn.redcdn.hvs.im.bean.GroupMemberBean; import cn.redcdn.hvs.im.bean.NoticesBean; import cn.redcdn.hvs.im.bean.ShowNameUtil; import cn.redcdn.hvs.im.bean.StrangerMessage; import cn.redcdn.hvs.im.bean.ThreadsBean; import cn.redcdn.hvs.im.column.GroupMemberTable; import cn.redcdn.hvs.im.column.NoticesTable; import cn.redcdn.hvs.im.common.CommonWaitDialog; import cn.redcdn.hvs.im.common.ThreadPoolManger; import cn.redcdn.hvs.im.dao.DtNoticesDao; import cn.redcdn.hvs.im.dao.GroupDao; import cn.redcdn.hvs.im.dao.NetPhoneDaoImpl; import cn.redcdn.hvs.im.dao.ThreadsDao; import cn.redcdn.hvs.im.fileTask.FileTaskManager; import cn.redcdn.hvs.im.manager.CollectionManager; import cn.redcdn.hvs.im.manager.FriendsManager; import cn.redcdn.hvs.im.preference.DaoPreference; import cn.redcdn.hvs.im.provider.ProviderConstant; import cn.redcdn.hvs.im.receiver.NetWorkChangeReceiver; import cn.redcdn.hvs.im.task.QueryDTNoticeAsyncTask; import cn.redcdn.hvs.im.util.IMCommonUtil; import cn.redcdn.hvs.im.util.ListSort; import cn.redcdn.hvs.im.util.PinyinUtil; import cn.redcdn.hvs.im.util.PlayerManager; import cn.redcdn.hvs.im.util.SendCIVMDTUtil; import cn.redcdn.hvs.im.util.SendCIVMUtil; import cn.redcdn.hvs.im.util.WakeLockHelper; import cn.redcdn.hvs.im.view.BottomMenuWindow; import cn.redcdn.hvs.im.view.CommonDialog; import cn.redcdn.hvs.im.view.MedicalAlertDialog; import cn.redcdn.hvs.im.view.SharePressableImageView; import cn.redcdn.hvs.im.view.VoiceTipView; import cn.redcdn.hvs.meeting.activity.ReserveSuccessActivity; import cn.redcdn.hvs.meeting.meetingManage.MedicalMeetingManage; import cn.redcdn.hvs.profiles.activity.CollectionActivity; import cn.redcdn.hvs.udtroom.adapter.UDTChatListAdapter; import cn.redcdn.hvs.udtroom.configs.UDTGlobleData; import cn.redcdn.hvs.udtroom.repository.RemoteDataSource; import cn.redcdn.hvs.udtroom.util.DateUtils; import cn.redcdn.hvs.util.CommonUtil; import cn.redcdn.hvs.util.CustomToast; import cn.redcdn.hvs.util.NotificationUtil; import cn.redcdn.jmeetingsdk.JMeetingAgent; import cn.redcdn.log.CustomLog; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static android.content.Context.MODE_PRIVATE; import static android.view.View.OVER_SCROLL_NEVER; import static cn.redcdn.hvs.MedicalApplication.getFileTaskManager; import static cn.redcdn.hvs.udtroom.view.activity.UDTChatRoomActivity.END_DT_BROADCAST; import static cn.redcdn.hvs.udtroom.view.activity.UDTChatRoomActivity.RECEIVER_END_DT_BROADCAST; /** * 联合会诊室图文聊天 Fragment */ public class UDTChatFragment extends BaseFragment implements UDTChatListAdapter.CallbackInterface, UDTChatListAdapter.MeetingLinkClickListener , UDTGlobleData.DateChangeListener { private static final String TAG = UDTChatFragment.class.getSimpleName(); // // 上一次查询的时间 // 添加好友task // 群聊ID public static final String KEY_GROUP_ID = "KEY_GROUP_ID"; // 消息转发,改走 本地照片分享逻辑 public static final int ACTION_FORWARD_NOTICE = 1105; /** * 消息界面类型 */ public static final String KEY_NOTICE_FRAME_TYPE = "key_notice_frame_type"; /** * 新消息界面 */ public static final int VALUE_NOTICE_FRAME_TYPE_NEW = 1; /** * 聊天列表界面 */ public static final int VALUE_NOTICE_FRAME_TYPE_LIST = 2; /** * 通过nube好友发送消息 */ public static final int VALUE_NOTICE_FRAME_TYPE_NUBE = 3; /** * 聊天类型 */ public static final String KEY_CONVERSATION_TYPE = "key_conversation_type"; /** * 单人聊天 */ public static final int VALUE_CONVERSATION_TYPE_SINGLE = 1; /** * 群发 */ public static final int VALUE_CONVERSATION_TYPE_MULTI = 2; /** * 会话ID */ public static final String KEY_CONVERSATION_ID = "key_conversation_id"; /** * 会话扩展信息 */ public static final String KEY_CONVERSATION_EXT = "key_conversation_ext"; /** * 会话对象视讯号 */ public static final String KEY_CONVERSATION_NUBES = "key_conversation_nubes"; /** * 聊天对象名称 */ public static final String KEY_CONVERSATION_SHORTNAME = "key_conversation_shortname"; /** * 聊天页面返回标记 */ public static final String KEY_SERVICE_NUBE_INFO = "ServiceNubeInfo"; //语音消息扬声器播放模式 private static final boolean SPEAKER = true; //语音消息听筒播放模式 private static final boolean HEADSET = false; /** * 添加为好友 */ // 界面类型(单聊,群聊) private int frameType = 2; // 当前会话ID(单聊,群聊) private String convstId = ""; // 聊天类型(单聊,群聊) private int conversationType = VALUE_CONVERSATION_TYPE_MULTI; //系统 Nube private static final String SYS_NUBE = "10000"; // 聊天对象视讯号 private String targetNubeNumber = ""; // 聊天对象名称(单聊) private String targetShortName = ""; // 会话扩展信息(单聊,群聊) private String convstExtInfo = ""; // 列表listview private ListView noticeListView = null; // 列表适配器 private UDTChatListAdapter chatAdapter = null; // Load ImageData private View headerLoadingView = null; private View headerRoot = null; private Handler mHandler = new Handler(); // 自身视讯号 private String selfNubeNumber = ""; // 数据变更监听 private UDTChatFragment.MyContentObserver observer = null; // 系统camera拍照或拍视频文件路径 private String cameraFilePath = ""; // 待转发的消息ID private String forwardNoticeId = null; // 官方帐号 // 添加好友的nube号码 private String addFriendNube = ""; // 输入区域 private UDTChatInputFragment inputFragment; // 收件人视频号码 public ArrayList<String> receiverNumberLst = new ArrayList<String>(); // 收件人名称 public Map<String, String> receiverNameMap = new HashMap<String, String>(); // 是否选择联系人 private boolean isSelectReceiver = false; // 创建群界面是否要保留界面 private boolean isSaveDraft = true; // 全部消息的起始时间 private long recvTimeBegin = 0l; private Object recvTimeLock = new Object(); // 群组id private String groupId = ""; // 群组表监听器 private UDTChatFragment.GroupMemberObserver observeGroupMember; // 群成员表监听器 private UDTChatFragment.GroupObserver groupObserve; private UDTChatFragment.FriendRelationObserver observeFriendRelation; // 存放群成员人数 private int groupMemberSize = 0; // 是否是群成员 private boolean isGroupMember = false; private ArrayList<String> selectNubeList = new ArrayList<String>(); // 收件人名称 public ArrayList<String> selectNameList = new ArrayList<String>(); private LinkedHashMap<String, GroupMemberBean> dateList = new LinkedHashMap<String, GroupMemberBean>();// 显示数据 protected CommonWaitDialog waitDialog; // 页面返回标记 private boolean back_flag = true; // 软件盘是否弹起的判断标记 private boolean SoftInput = false; // 第一次进入页面标记 private boolean firstFlag = true; private DtNoticesDao dtNoticeDao = null; private ThreadsDao threadDao = null; private GroupDao groupDao = null; //多选操作模式下的相关widget和数据对象 private RelativeLayout moreOpLayout = null; private ImageButton forwardBtn = null; private ImageButton collectBtn = null; private ImageButton delBtn = null; private TextView newNoticeNum; private boolean titlebackbtn = false; private Button backbtn; private TextView backtext; private LinearLayout chatlayout; private LinearLayout addMeetinglayout; private TextView addMeetingThemeTxt; //修改后的群名称 // private String nameForModify = ""; private Boolean newNoticeNumflag = false; private boolean isPlaying = false; //初始化屏幕亮暗帮助类 private WakeLockHelper helper; //初始化 private String audioPath; SharedPreferences voiceMsgSettings; private PlayerManager playerManager = PlayerManager.getManager(); private VoiceTipView voiceTipView; MDSAppSearchUsers searchUsers = null; private String getGroupClsFail = ""; private String meetingNub = ""; private String meetingTheme = ""; private String meetingPaw = ""; private JMeetingAgent agent; private BroadcastReceiver netReceiver; private UDTChatFragment fragmentContext; private BroadcastReceiver dtEndBroadcastReceiver; private LinearLayout chatEmptyView; private UDTGlobleData mUDTGlobleData; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); CustomLog.i(TAG, "onCreate()"); fragmentContext = this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { CustomLog.i(TAG, "onCreateView()"); View contentView = inflater.inflate(R.layout.fragment_udtchat_layout, container, false); convstId = mUDTGlobleData.getDTGroupID(); groupId = convstId; targetNubeNumber = convstId; initEnvironment(contentView); initMoreOpWidget(contentView); initCommonWidget(contentView); initView(contentView); return contentView; } private void initEnvironment(View v) { CustomLog.i(TAG, "initEnvironment()"); dtNoticeDao = new DtNoticesDao(getActivity()); threadDao = new ThreadsDao(getActivity()); groupDao = new GroupDao(getActivity()); inputFragment = new UDTChatInputFragment(); headerLoadingView = getActivity().getLayoutInflater().inflate( R.layout.page_load_header, null); headerRoot = headerLoadingView.findViewById(R.id.header_root); selfNubeNumber = AccountManager.getInstance(getActivity()).getAccountInfo().nube; helper = new WakeLockHelper(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); CustomLog.i(TAG, "onActivityCreated"); if (savedInstanceState == null) { frameType = 2; back_flag = true; if (frameType == VALUE_NOTICE_FRAME_TYPE_LIST) { // 群聊类型,配置初始化参数 conversationType = VALUE_NOTICE_FRAME_TYPE_LIST; targetShortName = null; convstExtInfo = "{\"draftText\":\"\"}"; } } else { Bundle paramsBundle = savedInstanceState.getBundle("params"); if (paramsBundle != null) { cameraFilePath = paramsBundle.getString("cameraFilePath"); forwardNoticeId = paramsBundle.getString("forwardNoticeId"); addFriendNube = paramsBundle.getString("addFriendNube"); receiverNumberLst = paramsBundle .getStringArrayList("receiverNumberLst"); receiverNameMap = (Map<String, String>) paramsBundle .getSerializable("receiverNameMap"); selectNameList = paramsBundle .getStringArrayList("selectNameList"); selectNubeList = paramsBundle .getStringArrayList("selectNubeList"); groupId = paramsBundle.getString(KEY_GROUP_ID); frameType = paramsBundle.getInt(KEY_NOTICE_FRAME_TYPE, VALUE_NOTICE_FRAME_TYPE_NEW); if (frameType == VALUE_NOTICE_FRAME_TYPE_LIST) { convstId = paramsBundle.getString(KEY_CONVERSATION_ID); conversationType = paramsBundle.getInt( KEY_CONVERSATION_TYPE, VALUE_CONVERSATION_TYPE_SINGLE); groupId = paramsBundle.getString(KEY_GROUP_ID); targetNubeNumber = paramsBundle .getString(KEY_CONVERSATION_NUBES); targetShortName = paramsBundle .getString(KEY_CONVERSATION_SHORTNAME); convstExtInfo = paramsBundle .getString(KEY_CONVERSATION_EXT); } else if (frameType == VALUE_NOTICE_FRAME_TYPE_NUBE) { targetNubeNumber = paramsBundle .getString(KEY_CONVERSATION_NUBES); targetShortName = paramsBundle .getString(KEY_CONVERSATION_SHORTNAME); } } } } @Override protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return null; } @Override protected void setListener() { } @Override protected void initData() { } @Override public void onSaveInstanceState(Bundle outState) { CustomLog.d(TAG, "onSaveInstanceState begin"); Bundle bundle = new Bundle(); bundle.putString("cameraFilePath", cameraFilePath); bundle.putString("forwardNoticeId", forwardNoticeId); bundle.putString("addFriendNube", addFriendNube); bundle.putStringArrayList("receiverNumberLst", receiverNumberLst); bundle.putStringArrayList("selectNubeList", selectNubeList); bundle.putStringArrayList("selectNameList", selectNameList); bundle.putSerializable("receiverNameMap", (Serializable) receiverNameMap); bundle.putInt(KEY_NOTICE_FRAME_TYPE, frameType); if (frameType == VALUE_NOTICE_FRAME_TYPE_LIST) { bundle.putString(KEY_CONVERSATION_ID, convstId); bundle.putInt(KEY_CONVERSATION_TYPE, conversationType); bundle.putString(KEY_CONVERSATION_NUBES, targetNubeNumber); bundle.putString(KEY_GROUP_ID, groupId); bundle.putString(KEY_CONVERSATION_SHORTNAME, targetShortName); bundle.putString(KEY_CONVERSATION_EXT, convstExtInfo); } else if (frameType == VALUE_NOTICE_FRAME_TYPE_NUBE) { bundle.putString(KEY_CONVERSATION_NUBES, targetNubeNumber); bundle.putString(KEY_CONVERSATION_SHORTNAME, targetShortName); } outState.putBundle("params", bundle); super.onSaveInstanceState(outState); } @Override public void onStart() { super.onStart(); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { initReceiver(); } } @Override public void onResume() { super.onResume(); CustomLog.i(TAG, "onResume()"); CommonUtil.hideSoftInputFromWindow(getActivity()); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { dateList.clear(); if (!TextUtils.isEmpty(groupId)) { dateList.putAll(groupDao.queryGroupMembers(groupId)); String value = MedicalApplication.getPreference() .getKeyValue(DaoPreference.PrefType.KEY_CHAT_REMIND_LIST, ""); if (value != null && value.contains(groupId)) { value = value.replace(groupId + ";", ""); MedicalApplication.getPreference().setKeyValue( DaoPreference.PrefType.KEY_CHAT_REMIND_LIST, value); } } } isSelectReceiver = false; cancelNotifacation(); } @Override public void onStop() { super.onStop(); cleanCheckData(); removeLoadingView(); if (chatAdapter != null) { chatAdapter.onStop(); } if (isSelectReceiver) { // 选择收件人的场合,不需要保存草稿 isSelectReceiver = false; } else { saveDraftTxt(); } } @Override public void onDestroy() { CustomLog.d(TAG, "onDestory()"); super.onDestroy(); cleanCheckData(); if (observer != null) { getActivity().getContentResolver().unregisterContentObserver(observer); observer = null; } if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { String value = MedicalApplication.getPreference().getKeyValue( DaoPreference.PrefType.KEY_CHAT_REMIND_LIST, ""); if (value != null && value.contains(groupId)) { value = value.replace(groupId + ";", ""); MedicalApplication.getPreference().setKeyValue( DaoPreference.PrefType.KEY_CHAT_REMIND_LIST, value); } } if (observeGroupMember != null) { getActivity().getContentResolver().unregisterContentObserver(observeGroupMember); observeGroupMember = null; } if (groupObserve != null) { getActivity().getContentResolver().unregisterContentObserver(groupObserve); groupObserve = null; } if (chatAdapter != null) { chatAdapter.onDestroy(); chatAdapter = null; } if (observeFriendRelation != null) { getActivity().getContentResolver().unregisterContentObserver(observeFriendRelation); observeFriendRelation = null; } if (searchUsers != null) { searchUsers.cancel(); } if (netReceiver != null) { getActivity().unregisterReceiver(netReceiver); } if (dtEndBroadcastReceiver != null) { getActivity().unregisterReceiver(dtEndBroadcastReceiver); } mUDTGlobleData.removeListener(this); } private void saveDraftTxt() { if (!isSaveDraft) { return; } // 保存草稿 String draftTxt = inputFragment.obtainInputTxt(); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { ArrayList<String> resList = new ArrayList<String>(); resList = IMCommonUtil.getList(draftTxt); for (int i = 0; i < resList.size(); i++) { for (int j = 0; j < selectNameList.size(); j++) { if (resList.get(i).equals(selectNameList.get(j))) { draftTxt = draftTxt.replace(resList.get(i), selectNubeList.get(j)); break; } } } } if (TextUtils.isEmpty(convstId)) { if (TextUtils.isEmpty(draftTxt)) { // 还没有会话的场合,没有草稿信息,无需保存 return; } else { threadDao.saveDraft(getReceivers(), draftTxt); } } else { // 有会话的场合,退出时,需更新草稿信息 threadDao.saveDraftById(convstId, draftTxt); } } /** * 分页查询,必须一次查询完成后才能开始下次查询,所以队列中只能保存一个类型 * 而范围查询,只要起始时间改变了,就需要重新查询 */ private void queryNoticeData(int queryType) { // 接诊后第一次进入图文会诊界面,由于 dt_notice 数据库为空,处理为不查询数据 if (TextUtils.isEmpty(groupId)) { return; } String queryKey = queryType + "_" + getRecvTimeBegin(); if (queryList.contains(queryKey)) { // 查询队列里有相同的查询请求,则放弃查询 return; } // 队列为空,加入队列并启动线程;队列不为空,则加入队列,等待线程执行完成后启动下一个线程 synchronized (queryList) { if (queryList.isEmpty()) { queryList.add(queryKey); queryRunnable = new QueryRunnable(); queryRunnable.queryType = queryType; queryRunnable.recvTimeBg = getRecvTimeBegin(); mHandler.postDelayed(queryRunnable, 100); } else { queryList.add(queryKey); } } } private long getRecvTimeBegin() { synchronized (recvTimeLock) { return recvTimeBegin; } } private void setRecvTimeBegin(long rTb) { synchronized (recvTimeLock) { recvTimeBegin = rTb; } } // 线程安全的并发查询队列 private List<String> queryList = new CopyOnWriteArrayList<String>(); // 查询数据Runnable private UDTChatFragment.QueryRunnable queryRunnable = null; @Override public void meetingLinkClick(final String meetingId) { GetMeetingInfomation meetingInfomation = new GetMeetingInfomation() { @Override protected void onSuccess(MeetingInfomation responseContent) { removeLoadingView(); if (responseContent.meetingType == 2) { final BookMeetingExInfo exInfo = new BookMeetingExInfo(); exInfo.setBookNube(responseContent.terminalAccount); exInfo.setBookName(responseContent.terminalAccountName); exInfo.setMeetingRoom(responseContent.meetingId + ""); exInfo.setMeetingTheme(responseContent.topic); exInfo.setMeetingTime(Long.parseLong(responseContent.yyBeginTime) * 1000); exInfo.setMeetingUrl(MedicalMeetingManage.JMEETING_INVITE_URL); exInfo.setHasMeetingPassWord(responseContent.hasMeetingPwd); Intent i = new Intent(getActivity(), ReserveSuccessActivity.class); i.putExtra(ReserveSuccessActivity.KEY_BOOK_MEETING_EXINFO, exInfo); getActivity().startActivity(i); } else { int isSuccess = MedicalMeetingManage.getInstance().joinMeeting(meetingId, new MedicalMeetingManage.OnJoinMeetingListener() { @Override public void onJoinMeeting(String valueDes, int valueCode) { if (valueCode < 0) { CustomToast.show(getActivity(), getString(R.string.join_consultation_fail), 1); } } }); if (isSuccess == 0) { } else if (isSuccess == -9992) { CustomToast.show(getActivity(), getString(R.string.login_checkNetworkError), 1); } else { CustomToast.show(getActivity(), getString(R.string.join_consultation_fail), 1); } } } @Override protected void onFail(int statusCode, String statusInfo) { removeLoadingView(); CustomToast.show(getActivity(), getString(R.string.get_meeting_info_fail), CustomToast.LENGTH_SHORT); } }; int result = meetingInfomation.getMeetingInfomation(Integer.valueOf(meetingId)); if (result == 0) { showLoadingView(getString(R.string.querying_consultation_info), new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO 可以下此处进行撤销加入会议 removeLoadingView(); } }); } else { CustomToast.show(getActivity(), getString(R.string.get_meeting_info_fail), CustomToast.LENGTH_SHORT); } } /** * 监听外部会诊状态变化 */ @Override public void onDateChanged() { CustomLog.i(TAG, "onDateChanged()"); int DTState = mUDTGlobleData.getState(); if (DTState == HPUCommonCode.SEEK_STATE_NOW) { setRemoteGroupID(mUDTGlobleData.getDTId()); CustomLog.i(TAG, "groupID from dataChanged = " + groupId); } } private void setRemoteGroupID(final String dtId) { CustomLog.i(TAG, "getRemoteGroupID()"); new RemoteDataSource().getRemoteCSLRoomDetailData( AccountManager.getInstance(getActivity()).getMdsToken(), dtId, new RemoteDataSource.DataCallback() { @Override public void onSuccess(CSLRoomDetailInfo data) { CustomLog.i(TAG, "RemoteDataSource getGroupID success"); groupId = data.groupId; CustomLog.i(TAG, "current group ID : " + groupId); if (!groupId.equals("")) { // 显示输入框 getChildFragmentManager().beginTransaction() .replace(R.id.udt_input_line, inputFragment).commit(); } } @Override public void onFailed(int statusCode, String statusInfo) { CustomLog.e(TAG, "groupID 未获取到" + statusInfo + " | " + statusCode); CustomToast.show(getActivity(), "图文会诊初始化失败,请稍后重试", CustomToast.LENGTH_LONG); } }); } /** * 设置 UDT 全局数据 */ public void setUDTGlobleData(UDTGlobleData data) { CustomLog.i(TAG, "setUDTGlobleData()"); CustomLog.i(TAG, "groupID from OutSide = " + data.getDTGroupID()); if (data.getDTGroupID().equals("")) { CustomToast.show(getActivity(), "会诊室初始化失败,请稍后重试", CustomToast.LENGTH_LONG); } this.mUDTGlobleData = data; mUDTGlobleData.addListener(this); } class QueryRunnable implements Runnable { public int queryType = 0; public long recvTimeBg = 0l; public void run() { CustomLog.i(TAG, "QueryRunnable :: run()"); CustomLog.d(TAG, "查询会话消息:" + convstId); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { convstId = groupId; } // 查询动态数据 QueryDTNoticeAsyncTask task = new QueryDTNoticeAsyncTask( getActivity(), convstId, queryType, getRecvTimeBegin(), IMConstant.NOTICE_PAGE_CNT); task.setQueryTaskListener(new QueryDTNoticeAsyncTask.QueryTaskPostListener() { @Override public void onQuerySuccess(Cursor cursor) { CustomLog.d(TAG, "QueryDTNoticeAsyncTask onQuerySuccess"); inputFragment.setVoiceInfo(voiceTipView, cursor); if (chatAdapter != null) { if (cursor.getCount() == 0) { CustomLog.i(TAG, "NoticeList no data"); // 没有查询到数据 headerRoot.setPadding(0, 0, 0, 0); headerRoot.setVisibility(View.INVISIBLE); chatEmptyView.setVisibility(View.VISIBLE); // 显示数据为空界面 } else { // 查询到了数据 CustomLog.i(TAG, "NoticeList data Found"); if (queryType == QueryDTNoticeAsyncTask.QUERY_TYPE_PAGE) { CustomLog.i(TAG, "QueryDTNoticeAsyncTask.QUERY_TYPE_PAGE"); chatEmptyView.setVisibility(View.GONE); // 分页查询的场合 int pageCursorCnt = cursor.getCount(); CustomLog.d(TAG, "QueryDTNoticeAsyncTask:" + pageCursorCnt); if (pageCursorCnt < IMConstant.NOTICE_PAGE_CNT) { // 数据量小于一页数据的场合,没有上一页数据了 headerRoot.setPadding(0, 0, 0, 0); headerRoot.setVisibility(View.INVISIBLE); } else { headerRoot.setPadding(0, 0, 0, 0); headerRoot.setVisibility(View.VISIBLE); } if (cursor.moveToFirst()) { setRecvTimeBegin(cursor.getLong(cursor .getColumnIndex(NoticesTable.NOTICE_COLUMN_SENDTIME))); } chatAdapter.mergeLastPageCursor(cursor); if (pageCursorCnt > 0) { // 定位到最下面一条 noticeListView.setSelection(pageCursorCnt); } } else if (queryType == QueryDTNoticeAsyncTask.QUERY_TYPE_COND) { CustomLog.i(TAG, "QueryDTNoticeAsyncTask.QUERY_TYPE_COND"); headerRoot.setPadding(0, 0, 0, 0); headerRoot.setVisibility(View.INVISIBLE); // 范围查询的场合 chatEmptyView.setVisibility(View.GONE); if (cursor != null && cursor.moveToFirst()) { setRecvTimeBegin(cursor.getLong(cursor .getColumnIndex(NoticesTable.NOTICE_COLUMN_SENDTIME))); } int oldCnt = chatAdapter.getCount(); chatAdapter.changeCursor(cursor); int newCnt = chatAdapter.getCount(); if (newCnt > oldCnt) { CustomLog.d(TAG, "消息查询结果:oldCnt=" + oldCnt + " | newCnt=" + newCnt); // 有新消息的场合,定位到最下面一条 noticeListView.setSelection(newCnt - 1); } } } } // 初始化im面板 if (firstFlag) { firstFlag = false; if ((cursor == null || cursor.getCount() == 0)) { SoftInput = true; } else { SoftInput = false; } } else { if (cursor.getCount() > 0) { SoftInput = false; } } afterQuery(queryType, recvTimeBg); noticeListView.removeFooterView(voiceTipView); } @Override public void onQueryFailure() { CustomLog.d(TAG, "QueryDTNoticeAsyncTask onQueryFailure"); CustomToast.show(MedicalApplication.shareInstance(), R.string.load_msg_fail, Toast.LENGTH_SHORT); afterQuery(queryType, recvTimeBg); } }); task.executeOnExecutor(ThreadPoolManger.THREAD_POOL_EXECUTOR, ""); } } ; private void afterQuery(int queryType, long recvTb) { String queryKey = queryType + "_" + recvTb; queryList.remove(queryKey); synchronized (queryList) { if (!queryList.isEmpty()) { // 查询队列 String key = queryList.get(0); String[] keys = key.split("_"); // 继续下一个查询 queryRunnable = new QueryRunnable(); queryRunnable.queryType = Integer.parseInt(keys[0]); queryRunnable.recvTimeBg = Long.parseLong(keys[1]); mHandler.postDelayed(queryRunnable, 100); } } } private void initCommonWidget(View v) { noticeListView = (ListView) v.findViewById(R.id.notice_listview); chatlayout = (LinearLayout) v.findViewById(R.id.chat_linearlayout); backbtn = (Button) chatlayout.findViewById(R.id.back_btn); backtext = (TextView) chatlayout.findViewById(R.id.back_str); chatAdapter = new UDTChatListAdapter(getActivity(), null, dtNoticeDao, targetNubeNumber, targetShortName); chatAdapter.setDTGlobleData(mUDTGlobleData); //kevin add chatAdapter.setSelfNubeNumber(selfNubeNumber); chatAdapter.setCallbackInterface((UDTChatListAdapter.CallbackInterface) this); chatAdapter.setMeetingLinkClickListener(this); chatAdapter.setConversationType(conversationType); noticeListView.addHeaderView(headerLoadingView); noticeListView.setAdapter(chatAdapter); noticeListView.setOverScrollMode(OVER_SCROLL_NEVER); String nube = ""; if (conversationType == VALUE_CONVERSATION_TYPE_SINGLE) { nube = targetNubeNumber; } else { nube = groupId; } CustomLog.d(TAG, nube + ""); voiceTipView = new VoiceTipView(getActivity()); inputFragment.mContext = getActivity(); inputFragment.setNubeNum(nube); inputFragment.setListview(noticeListView); inputFragment.callback = new UDTChatInputFragment.SendCallbackInterface() { @Override public boolean onSendTxtMsg(final String txtMsg) { CustomLog.i(TAG, "onSendTxtMsg()"); // 发送文字 new Thread(new Runnable() { @Override public void run() { String uuid = ""; if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { CustomLog.i(TAG, "VALUE_CONVERSATION_TYPE_MULTI"); // 插入发送记录 ArrayList<String> resList = new ArrayList<String>(); ArrayList<String> lastList = new ArrayList<String>(); resList = IMCommonUtil.getList(txtMsg); //确认发送消息的类型 int txtMsgType = FileTaskManager.NOTICE_TYPE_TXT_SEND; if (resList.size() > 0) { txtMsgType = FileTaskManager.NOTICE_TYPE_REMIND_ONE_SEND; } if (resList.size() == 0) { txtMsgType = FileTaskManager.NOTICE_TYPE_TXT_SEND; } lastList.addAll(resList); String str = ""; str = new String(txtMsg); boolean repalceflg = true; for (int i = 0; i < resList.size(); i++) { for (int j = 0; j < selectNameList .size(); j++) { if (resList.get(i).equals( selectNameList.get(j))) { str = str.replace( resList.get(i), selectNubeList.get(j)); repalceflg = false; lastList.remove(0); break; } } } if (lastList != null && lastList.size() != 0) { for (int i = 0; i < lastList.size(); i++) { ArrayList<GroupMemberBean> beanList = groupDao .queryAllGroupMembers( groupId, selfNubeNumber); for (int j = 0; j < beanList.size(); j++) { ShowNameUtil.NameElement element = ShowNameUtil .getNameElement( beanList.get(j) .getName(), beanList.get(j) .getNickName(), beanList.get(j) .getPhoneNum(), beanList.get(j) .getNubeNum()); String MName = ShowNameUtil .getShowName(element); if (lastList .get(i) .equals("@" + MName + IMConstant.SPECIAL_CHAR)) { str = str.replace( lastList.get(i), "@" + beanList .get(j) .getNubeNum() + IMConstant.SPECIAL_CHAR); repalceflg = false; break; } } } } if (resList.size() == 0 && repalceflg) { str = txtMsg; } uuid = sendDTGroupIMMessage(txtMsgType, str); selectNameList.clear(); selectNubeList.clear(); } else { CustomLog.i(TAG, "VALUE_CONVERSATION_SINGLE"); // 插入发送记录 uuid = dtNoticeDao .createSendFileNotice( selfNubeNumber, getReceivers(), null, "", FileTaskManager.NOTICE_TYPE_TXT_SEND, txtMsg, convstId, null); } getFileTaskManager() .addDTTask(uuid, null); } }).start(); return true; } @Override public void onSendPic() { SendCIVMDTUtil.sendPic(fragmentContext); } @Override public void onSendPicFromCamera() { if (!isFriend()) { CustomLog.d(TAG, targetShortName + "onSendPicFromCamera 不是好友"); return; } SendCIVMUtil.sendPicFromCamera(getActivity()); } @Override public void onSendVideo() { if (!isFriend()) { CustomLog.d(TAG, targetShortName + "onSendVideo 不是好友"); return; } SendCIVMUtil.sendVideo(getActivity()); } @Override public void onSendVcard() { if (!isFriend()) { CustomLog.d(TAG, targetShortName + "onSendVcard 不是好友"); return; } SendCIVMUtil.sendVcard(getActivity()); } @Override public boolean doPreSendCheck() { return true; } @Override public void onSendAudio(final String rcdFilePah, final int rcdLenth) { if (!isFriend()) { CustomLog.d(TAG, targetShortName + "onSendAudio 不是好友"); return; } // 发送音频 new Thread(new Runnable() { @Override public void run() { ButelPAVExInfo extInfo = new ButelPAVExInfo(); extInfo.setDuration(rcdLenth); List<String> localFiles = new ArrayList<String>(); localFiles.add(rcdFilePah); String uuid = ""; if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { // 插入发送记录 uuid = dtNoticeDao .createSendFileNotice( selfNubeNumber, groupId, localFiles, "", FileTaskManager.NOTICE_TYPE_AUDIO_SEND, "", groupId, extInfo); } else { // 插入发送记录 uuid = dtNoticeDao .createSendFileNotice( selfNubeNumber, getReceivers(), localFiles, "", FileTaskManager.NOTICE_TYPE_AUDIO_SEND, "", convstId, extInfo); } getFileTaskManager() .addDTTask(uuid, null); } }).start(); } @Override public void onSelectGroupMemeber() { CustomLog.d(TAG, "onSelectGroupMemeber 选择回复的人"); // 选择回复的人 if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { Intent intent = new Intent(getActivity(), SelectLinkManActivity.class); intent.putExtra( SelectLinkManActivity.OPT_FLAG, SelectLinkManActivity.OPT_HAND_OVER_START_FOR_RESULT); intent.putExtra( SelectLinkManActivity.AVITVITY_TITLE, getString(R.string.select_revert_person)); intent.putExtra( SelectLinkManActivity.ACTIVITY_FLAG, SelectLinkManActivity.AVITVITY_START_FOR_RESULT); intent.putExtra( SelectLinkManActivity.KEY_IS_SIGNAL_SELECT, false); intent.putExtra( SelectLinkManActivity.KEY_SINGLE_CLICK_BACK, true); intent.putExtra( SelectLinkManActivity.HAND_OVER_MASTER_LIST, GroupMemberToContactsBean()); intent.putExtra( SelectGroupMemeberActivity.SELECT_GROUPID, groupId); startActivityForResult(intent, ACTION_FORWARD_NOTICE); } } @Override public void onAudioCall() { } @Override public void onVedioCall() { } @Override public void onMeetingCall() { } @Override public void onAudioRecStart() { // 重新播放 if (chatAdapter != null) { chatAdapter.stopCurAuPlaying(); } } @Override public void onShareCollection() { if (!isFriend()) { CustomLog.d(TAG, targetShortName + "onShareCollection 不是好友"); return; } String receiver = ""; if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { receiver = groupId; } else { receiver = getReceivers(); } if (receiver.length() == 0) { CustomLog.d(TAG, "收藏的received 为空字符串"); return; } Intent intent = new Intent(getActivity(), CollectionActivity.class); intent.putExtra(CollectionActivity.KEY_RECEIVER, receiver); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { // 群成员人数 groupMemberSize = groupDao.queryGroupMemberCnt(targetNubeNumber); intent.putExtra("headUrl", groupDao.getGroupHeadUrl(targetNubeNumber)); intent.putExtra("chatNames", groupDao.getGroupNameByGid(targetNubeNumber)); intent.putExtra("chatNumber", groupMemberSize); intent.putExtra("chatType", "group"); } else { Contact contact = ContactManager.getInstance(getActivity()) .getContactInfoByNubeNumber(targetNubeNumber); intent.putExtra("headUrl", contact.getHeadUrl()); intent.putExtra("chatNames", targetShortName); intent.putExtra("chatType", "single"); } getActivity().startActivity(intent); } }; noticeListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { CustomLog.d(TAG, "列表正在滚动..."); // list列表滚动过程中,暂停图片上传下载 } else { } if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { // 滚动停止的场合,加载更多数据 int firstVP = noticeListView.getFirstVisiblePosition(); CustomLog.d(TAG, "列表停止滚动...FirstVisiblePosition:" + firstVP); if (firstVP == 0 && headerRoot.getVisibility() == View.VISIBLE) { queryNoticeData(QueryDTNoticeAsyncTask.QUERY_TYPE_ALL); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); noticeListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // 隐藏输入法及素材面板 CommonUtil.hideSoftInputFromWindow(getActivity()); inputFragment.setHide(); return false; } }); } /** * 发送群组会诊消息 */ private String sendDTGroupIMMessage(int txtMsgType, String groupMsg) { CustomLog.i(TAG, "sendDTGroupIMMessage()"); String uuid; String dtExtendContent = ""; JSONObject dtExtendInfo = new JSONObject(); try { dtExtendInfo.put("medicalComboMsg", 1); dtExtendContent = dtExtendInfo.toString(); } catch (JSONException e) { e.printStackTrace(); } uuid = dtNoticeDao .createSendFileNotice( selfNubeNumber, groupId, null, "", txtMsgType, groupMsg, groupId, dtExtendContent); return uuid; } public void initView(View v) { addMeetinglayout = (LinearLayout) v.findViewById(R.id.add_meeting_line); addMeetinglayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CommonUtil.hideSoftInputFromWindow(getActivity()); } }); addMeetingThemeTxt = (TextView) v.findViewById(R.id.add_meeting_theme); chatEmptyView = (LinearLayout) v.findViewById(R.id.chat_empty_layout); switch (frameType) { case VALUE_NOTICE_FRAME_TYPE_NUBE: { // 单聊 conversationType = VALUE_CONVERSATION_TYPE_SINGLE; // 根据nube号查询会话信息 // 已产生会话,则并入已有会话 // 未产生会话,则继续监听数据库后,直到产生会话 if (mergeThreads() == 0) { convstId = ""; convstExtInfo = ""; // 清空列表数据 if (chatAdapter != null) { chatAdapter.changeCursor(null); } } //第一次进入会话页面 inputFragment.setVoiceInfo(voiceTipView, null); } case VALUE_NOTICE_FRAME_TYPE_LIST: { // 聊天列表的场合,隐藏收件人区域 if (SYS_NUBE.equals(targetNubeNumber)) { // 官方帐号,隐藏输入框,禁止回复 inputFragment.isShowing = false; getChildFragmentManager().beginTransaction() .remove(inputFragment).commit(); targetShortName = getString(R.string.str_butel_name); convstExtInfo = ""; } else if (SettingData.getInstance().adminNubeNum.equals(targetNubeNumber)) { inputFragment.isShowing = false; getChildFragmentManager().beginTransaction() .remove(inputFragment).commit(); targetShortName = getAdminNickName(); convstExtInfo = ""; } else if (conversationType == VALUE_CONVERSATION_TYPE_SINGLE) { // 单人聊天 inputFragment.isShowing = true; getChildFragmentManager().beginTransaction() .replace(R.id.udt_input_line, inputFragment).commit(); //如果是系统 Nube 不显示个人详情页按钮 if (!targetNubeNumber.equals(SYS_NUBE) || !targetNubeNumber.equals(SettingData.getInstance().adminNubeNum)) { } //单人聊天时,监听好友关系表 if (observeFriendRelation == null) { observeFriendRelation = new FriendRelationObserver(); getActivity().getContentResolver().registerContentObserver( ProviderConstant.Friend_Relation_URI, true, observeFriendRelation); } } else if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { // 群发 inputFragment.isShowing = true; int DTState = mUDTGlobleData.getState(); if (DTState != HPUCommonCode.SEEK_STATE_END && !groupId.equals("")) { getChildFragmentManager().beginTransaction() .replace(R.id.udt_input_line, inputFragment).commit(); } // 群发名称 chatAdapter.setNoticeType(conversationType, groupId); targetShortName = getGroupNameTitle(); if (observeGroupMember == null) { observeGroupMember = new GroupMemberObserver(); getActivity().getContentResolver().registerContentObserver( ProviderConstant.NETPHONE_GROUP_URI, true, observeGroupMember); } if (groupObserve == null) { groupObserve = new GroupObserver(); getActivity().getContentResolver().registerContentObserver( ProviderConstant.NETPHONE_GROUP_MEMBER_URI, true, groupObserve); } if (!isGroupMember) { } else { } } // 草稿文字填充 initDraftText(); if (observer == null) { observer = new MyContentObserver(); getActivity().getContentResolver().registerContentObserver( ProviderConstant.NETPHONE_HPU_NOTICE_URI, true, observer); } if (frameType == VALUE_NOTICE_FRAME_TYPE_LIST) { // 初始化 SoftInput = false; firstFlag = true; setRecvTimeBegin(0); if (chatAdapter != null) { chatAdapter.clearData(); } // 查询聊天数据 queryNoticeData(QueryDTNoticeAsyncTask.QUERY_TYPE_ALL); } else { // 隐藏分页加载等待view headerRoot.setPadding(0, -headerRoot.getHeight(), 0, 0); headerRoot.setVisibility(View.INVISIBLE); SoftInput = true; firstFlag = false; } // 去除状态栏通知 cancelNotifacation(); } break; } chatEmptyView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { // 隐藏输入法及素材面板 CommonUtil.hideSoftInputFromWindow(getActivity()); inputFragment.setHide(); return false; } }); } private void cancelNotifacation() { CustomLog.i(TAG, "cancelNotifacation()"); if (conversationType == VALUE_CONVERSATION_TYPE_SINGLE) { NotificationUtil.cancelNewMsgNotifacation(targetNubeNumber); // 清除未接来电通知 NotificationUtil.cancelNotifacationById(targetNubeNumber); } else if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { int notifyId = NotificationUtil.getGroupNotifyID(groupId); NotificationUtil.cancelNewMsgNotifacation(notifyId + ""); } } private void initDraftText() { CustomLog.i(TAG, "initDraftText()"); // 草稿文字填充 String draftTxt = ""; try { if (!TextUtils.isEmpty(convstExtInfo)) { JSONObject extObj = new JSONObject(convstExtInfo); draftTxt = extObj.optString("draftText"); } } catch (Exception e) { CustomLog.d(TAG, "草稿信息解析失败" + e.toString()); } if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { ArrayList<String> dispNubeList = new ArrayList<String>(); dispNubeList = CommonUtil.getDispList(draftTxt); for (int i = 0; i < dispNubeList.size(); i++) { GroupMemberBean gbean = groupDao.queryGroupMember(groupId, dispNubeList.get(i)); ShowNameUtil.NameElement element = ShowNameUtil.getNameElement( gbean.getName(), gbean.getNickName(), gbean.getPhoneNum(), gbean.getNubeNum()); String MName = ShowNameUtil.getShowName(element); selectNameList.add("@" + MName + IMConstant.SPECIAL_CHAR); selectNubeList.add("@" + dispNubeList.get(i) + IMConstant.SPECIAL_CHAR); draftTxt = draftTxt.replace("@" + dispNubeList.get(i) + IMConstant.SPECIAL_CHAR, "@" + MName + IMConstant.SPECIAL_CHAR); } } if (!inputFragment.obtainInputTxt().equals(draftTxt)) { inputFragment.setDraftTxt(draftTxt); } } private class MyContentObserver extends ContentObserver { public MyContentObserver() { super(new Handler()); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onChange(boolean selfChange, Uri uri) { super.onChange(selfChange, uri); CustomLog.d(TAG, "消息数据库数据发生变更1:" + selfChange + "|" + uri.toString()); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); CustomLog.d(TAG, "消息数据库数据发生变更2:" + selfChange); int mergeInt = mergeThreads(); // 刷新界面显示 if (mergeInt == 1) { queryNoticeData(QueryDTNoticeAsyncTask.QUERY_TYPE_COND); } else if (mergeInt == 2) { queryNoticeData(QueryDTNoticeAsyncTask.QUERY_TYPE_ALL); } } } private synchronized int mergeThreads() { CustomLog.i(TAG, "mergeThreads()"); if (frameType == VALUE_NOTICE_FRAME_TYPE_NUBE) { ThreadsBean th = threadDao.getThreadByRecipentIds(targetNubeNumber); if (th != null) { CustomLog.d("TAG", "已产生会话,则并入已有会话"); // 已产生会话,则并入已有会话 convstId = th.getId(); convstExtInfo = th.getExtendInfo(); frameType = VALUE_NOTICE_FRAME_TYPE_LIST; return 2; } else { return 0; } } else { return 1; } } @Override public void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); CustomLog.i(TAG, "onActivityResult()"); if (Activity.RESULT_CANCELED == resultCode) { return; } switch (requestCode) { case SendCIVMUtil.ACTION_SHARE_PIC_FROM_CAMERA: case SendCIVMUtil.ACTION_SHARE_VIDEO_FROM_CAMERA: CustomLog.d(TAG, "拍摄视频 返回"); if (!isFriend()) { CustomLog.d(TAG, "ACTION_SHARE_VIDEO_FROM_CAMERA 不是好友"); return; } if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { if (data.getExtras().getInt("OK_TYPE", 0) == 1) { SendCIVMUtil.onSendVideoFromCameraBack(getActivity(), data, selfNubeNumber, groupId, groupId); } else if (data.getExtras().getInt("OK_TYPE", 0) == 0) { SendCIVMUtil.onSendPicFromCameraBack(getActivity(), selfNubeNumber, groupId, groupId); } else { } } else { if (data.getExtras().getInt("OK_TYPE", 0) == 1) { SendCIVMUtil.onSendVideoFromCameraBack(getActivity(), data, selfNubeNumber, getReceivers(), convstId); } else if (data.getExtras().getInt("OK_TYPE", 0) == 0) { SendCIVMUtil.onSendPicFromCameraBack(getActivity(), selfNubeNumber, getReceivers(), convstId); } else { } } break; case SendCIVMUtil.ACTION_SHARE_PIC_FROM_NATIVE: CustomLog.d(TAG, "选择图片 返回"); int anInt = data.getExtras().getInt(MultiImageChooserActivity.KEY_CHOOSER_TYPE); if (anInt == (MultiImageChooserActivity.CHOOSER_TYPE_VIDEO)) { if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { SendCIVMUtil.onSendVideoFromNativeBack(getActivity(), data, selfNubeNumber, groupId, groupId); } else { SendCIVMUtil.onSendVideoFromNativeBack(getActivity(), data, selfNubeNumber, getReceivers(), convstId); } } else if (anInt == (MultiImageChooserActivity.CHOOSER_TYPE_VIDEO_IMAGE)) { ArrayList<String> selectedVideoList = data.getExtras() .getStringArrayList(Intent.EXTRA_STREAM); ArrayList<String> mList = new ArrayList<>(); ArrayList<String> tList = new ArrayList<>(); for (int i = 0; i < selectedVideoList.size(); i++) { if (selectedVideoList.get(i).contains(".rm") || selectedVideoList.get(i).contains(".flv") || selectedVideoList.get(i).contains(".mp4") || selectedVideoList.get(i).contains(".mkv") || selectedVideoList.get(i).contains(".avi") || selectedVideoList.get(i).contains(".3gp") || selectedVideoList.get(i).contains(".ts") || selectedVideoList.get(i).contains(".wmv") || selectedVideoList.get(i).contains(".mov") || selectedVideoList.get(i).contains(".asf")) { mList.add(selectedVideoList.get(i)); } else { tList.add(selectedVideoList.get(i)); } } Intent intent1 = new Intent(); intent1.putStringArrayListExtra(Intent.EXTRA_STREAM, tList); Intent intent2 = new Intent(); intent2.putStringArrayListExtra(Intent.EXTRA_STREAM, mList); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { SendCIVMDTUtil.onSendPicFromNativeBack(getActivity(), intent1, selfNubeNumber, groupId, groupId); SendCIVMUtil.onSendVideoFromNativeBack(getActivity(), intent2, selfNubeNumber, groupId, groupId); } else { SendCIVMUtil.onSendPicFromNativeBack(getActivity(), intent1, selfNubeNumber, getReceivers(), convstId); SendCIVMUtil.onSendVideoFromNativeBack(getActivity(), intent2, selfNubeNumber, getReceivers(), convstId); } } else { if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { SendCIVMUtil.onSendPicFromNativeBack(getActivity(), data, selfNubeNumber, groupId, groupId); } else { SendCIVMUtil.onSendPicFromNativeBack(getActivity(), data, selfNubeNumber, getReceivers(), convstId); } } break; case SendCIVMUtil.ACTION_SHARE_VIDEO_FROM_NATIVE: CustomLog.d(TAG, "选择视频 返回"); if (!isFriend()) { CustomLog.d(TAG, "ACTION_SHARE_VIDEO_FROM_NATIVE 不是好友"); return; } if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { SendCIVMUtil.onSendVideoFromNativeBack(getActivity(), data, selfNubeNumber, groupId, groupId); } else { SendCIVMUtil.onSendVideoFromNativeBack(getActivity(), data, selfNubeNumber, getReceivers(), convstId); } break; case SendCIVMUtil.ACTION_SHARE_VCARD: if (!isFriend()) { CustomLog.d(TAG, "ACTION_SHARE_VCARD 不是好友"); return; } sendVcardBack(data); break; case SendCIVMUtil.ACTION_FOR_RESERVE_MEETING: CustomLog.d(TAG, "预约会议结束后,返回到chat页面"); break; case ACTION_FORWARD_NOTICE: if (data == null) { return; } Bundle bundle = data.getExtras(); String nubeNumb = bundle.getStringArrayList( SelectLinkManActivity.START_RESULT_NUBE).get(0); String name = bundle.getStringArrayList( SelectLinkManActivity.START_RESULT_NAME).get(0); String niName = bundle.getStringArrayList( SelectLinkManActivity.START_RESULT_NICKNAME).get(0); String nuber = bundle.getStringArrayList( SelectLinkManActivity.START_RESULT_NUMBER).get(0); ShowNameUtil.NameElement element = ShowNameUtil.getNameElement(name, niName, nuber, nubeNumb); String nicName = ShowNameUtil.getShowName(element); selectNubeList.add("@" + nubeNumb + IMConstant.SPECIAL_CHAR); selectNameList.add("@" + nicName + IMConstant.SPECIAL_CHAR); inputFragment.setSpecialtxt(nicName); break; case ContactTransmitConfig.REQUEST_REPLY_CODE: String msgContent = data.getStringExtra("reply"); CustomLog.d(TAG, "发送好友验证消息返回"); sendAddNewFriendMsg(msgContent); break; } } /** * 选择完名片,返回到本页的操作 */ private void sendVcardBack(Intent data) { CustomLog.i(TAG, "sendVcardBack()"); if (data == null) { CustomLog.d(TAG, "data == null"); return; } ArrayList<String> nubeNumebrs = data.getExtras().getStringArrayList( SelectLinkManActivity.START_RESULT_NUBE); String nubeNumber = ""; if (nubeNumebrs != null && nubeNumebrs.size() > 0) { nubeNumber = nubeNumebrs.get(0); } if (TextUtils.isEmpty(nubeNumber)) { tipToast(getString(R.string.date_illegal)); return; } ContactFriendBean Info = new NetPhoneDaoImpl(getActivity()) .queryFriendInfoByNube(nubeNumber); ButelVcardBean extInfo = new ButelVcardBean(); extInfo.setUserId(Info.getContactId()); extInfo.setNubeNumber(Info.getNubeNumber()); extInfo.setHeadUrl(Info.getHeadUrl()); extInfo.setNickname(Info.getNickname()); extInfo.setPhoneNumber(Info.getNumber()); extInfo.setSex(Info.getSex()); showSendVcardDialog(extInfo); } /** * 显示二次 确认对话框 */ private void showSendVcardDialog(final ButelVcardBean bean) { CustomLog.d(TAG, "showSendVcardDialog()"); LayoutInflater inflater = LayoutInflater .from(getActivity()); View selfView = inflater.inflate( R.layout.share_confirm_dialog_view, null);//分享确认弹框布局文 TextView nameView = (TextView) selfView.findViewById(R.id.name_txt); TextView numView = (TextView) selfView .findViewById(R.id.recv_num_field); SharePressableImageView icon = (SharePressableImageView) selfView .findViewById(R.id.contact_icon); String headUrl = ""; if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { // 群成员人数 groupMemberSize = groupDao.queryGroupMemberCnt(targetNubeNumber); numView.setVisibility(View.VISIBLE); numView.setText(groupMemberSize + getString(R.string.person)); headUrl = groupDao.getGroupHeadUrl(targetNubeNumber); Glide.with(this).load(headUrl).placeholder(R.drawable.group_icon) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .crossFade().into(icon.shareImageview); nameView.setText(groupDao.getGroupNameByGid(targetNubeNumber)); } else { Contact contact = ContactManager.getInstance(getActivity()) .getContactInfoByNubeNumber(targetNubeNumber); headUrl = contact.getHeadUrl(); Glide.with(this).load(headUrl).placeholder(R.drawable.default_head_image) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .crossFade().into(icon.shareImageview); nameView.setText(targetShortName); numView.setVisibility(View.GONE); } CommonDialog conDlg = new CommonDialog(getActivity(), getActivity().getLocalClassName(), 300); conDlg.addView(selfView); conDlg.setTitleVisible(getString(R.string.send_to)); conDlg.setTransmitCardInfo(bean.getNickname(), Integer.parseInt(bean.getNubeNumber())); conDlg.setCancleButton(null, R.string.btn_cancle); conDlg.setPositiveButton(new CommonDialog.BtnClickedListener() { @Override public void onBtnClicked() { CustomLog.d(TAG, "点击确定"); if (conversationType == VALUE_CONVERSATION_TYPE_MULTI) { SendCIVMUtil.onSendVcardBack(getActivity(), bean, selfNubeNumber, groupId, groupId); } else { SendCIVMUtil.onSendVcardBack(getActivity(), bean, selfNubeNumber, getReceivers(), convstId); } CustomToast.show(getActivity(), getString(R.string.toast_sent), 1); } }, R.string.btn_send); if (!getActivity().isFinishing()) { conDlg.showDialog(); } } private String getReceivers() { CustomLog.i(TAG, "getReceivers()"); if (frameType == VALUE_NOTICE_FRAME_TYPE_LIST || frameType == VALUE_NOTICE_FRAME_TYPE_NUBE) { return targetNubeNumber; } else { // 新建消息的场合,接收者为收件人输入框数据 if (receiverNumberLst != null && receiverNumberLst.size() > 0) { String nubes = ""; for (String nubeNum : receiverNumberLst) { nubes = nubes + nubeNum + ";"; } return nubes.substring(0, nubes.length() - 1); } else { return ""; } } } @Override public void onMsgDelete(String uuid, long receivedTime, int dataCnt) { CustomLog.i(TAG, "onMsgDelete"); CustomLog.d(TAG, "删除消息:" + uuid); getFileTaskManager().cancelTask(uuid); if (dataCnt == 1) { // 最后一条消息删除时,需要更新会话表lastTime dtNoticeDao.deleteLastNotice(uuid, convstId, receivedTime); } else { dtNoticeDao.deleteNotice(uuid); } } @Override public void onMsgForward(String uuid, String sender, int msgType, int msgStatus, String localPath) {} @Override public void onMsgForward(String uuid, String sender, int msgType, int msgStatus, String localPath, String txt, String vcardName, String vcardNumber, String creator, String meetingRoomId, String meetingTopic, String date, String hms) {} @Override public void onMoreClick(String uuid, int msgType, int msgStatus, boolean checked) {} private void preCheckDataforCollection() { Map<String, NoticesBean> uidMap = null; if (chatAdapter != null) { uidMap = chatAdapter.getCheckedDataMap(); } if (uidMap != null) { boolean hasInvalidData = false; List<NoticesBean> validList = new ArrayList<NoticesBean>(); Iterator<Map.Entry<String, NoticesBean>> entries = uidMap.entrySet() .iterator(); while (entries.hasNext()) { Map.Entry<String, NoticesBean> entry = entries.next(); String uid = entry.getKey(); NoticesBean bean = entry.getValue(); CustomLog.d(TAG, "uid = " + uid); boolean valid = true; if (bean != null) { int type = bean.getType(); int status = bean.getStatus(); CustomLog.d(TAG, "type = " + type + " status=" + status); if (type == FileTaskManager.NOTICE_TYPE_VCARD_SEND || type == FileTaskManager.NOTICE_TYPE_RECORD || type == FileTaskManager.NOTICE_TYPE_MEETING_INVITE || type == FileTaskManager.NOTICE_TYPE_MEETING_BOOK) { hasInvalidData = true; valid = false; } if (valid) { validList.add(bean); } } else { continue; } } if (hasInvalidData) { //弹提醒对话框 invalidCollectDialog(validList); } else { //直接收藏 doCollectWork(validList); } } } private void preCheckDataforDel() { CustomLog.i(TAG, "preCheckDataforDel()"); Map<String, NoticesBean> uidMap = null; if (chatAdapter != null) { uidMap = chatAdapter.getCheckedDataMap(); } if (uidMap != null) { List<String> validList = new ArrayList<String>(); for (String key : uidMap.keySet()) { validList.add(key); CustomLog.d(TAG, "uid = " + key); } delDialog(validList, chatAdapter.getCount()); } } private void invalidCollectDialog(final List<NoticesBean> dataList) { CommonDialog confDlg = new CommonDialog(getActivity(), getActivity().getLocalClassName(), 12351); confDlg.setCancelable(false); confDlg.setTitle(R.string.send_Vcard_dialog_title); confDlg.setMessage(getString(R.string.not_collect)); confDlg.setCancleButton(null, R.string.btn_cancle); confDlg.setPositiveButton(new CommonDialog.BtnClickedListener() { @Override public void onBtnClicked() { CustomLog.d(TAG, "点击收藏"); doCollectWork(dataList); } }, R.string.collect_str); if (!getActivity().isFinishing()) { confDlg.showDialog(); } } private void delDialog(final List<String> uidList, int listCount) { final MedicalAlertDialog menuDlg = new MedicalAlertDialog(getActivity()); menuDlg.addButtonFirst(new BottomMenuWindow.MenuClickedListener() { @Override public void onMenuClicked() { CustomLog.d(TAG, "批量删除所选消息"); dtNoticeDao.deleteNotices(uidList); cleanCheckData(); } }, getActivity().getString(R.string.chat_delete)); menuDlg.addButtonSecond(new BottomMenuWindow.MenuClickedListener() { @Override public void onMenuClicked() { menuDlg.dismiss(); } }, getActivity().getString(R.string.btn_cancle)); menuDlg.show(); } private void doCollectWork(List<NoticesBean> dataList) { if (dataList != null && dataList.size() > 0) { for (int i = 0; i < dataList.size(); i++) { NoticesBean bean = dataList.get(i); if (bean.getType() == FileTaskManager.NOTICE_TYPE_ARTICAL_SEND) { JSONArray newBodyArray = new JSONArray(); try { JSONObject newBodyObj = new JSONObject(); JSONArray bodyArray = new JSONArray(bean.getBody()); if (bodyArray != null && bodyArray.length() > 0) { JSONObject bodyObj = bodyArray.optJSONObject(0); JSONObject tmpObj = bodyObj.optJSONObject("articleInfo"); newBodyObj.put("ArticleId", tmpObj.optString("articleId")); newBodyObj.put("title", tmpObj.optString("title")); newBodyObj.put("previewUrl", tmpObj.optString("previewUrl")); newBodyObj.put("introduction", tmpObj.optString("introduction")); newBodyObj.put("articleType", tmpObj.optInt("articleType")); newBodyObj.put("name", tmpObj.optString("officeName")); newBodyObj.put("isforwarded", 1); newBodyArray.put(0, newBodyObj); } } catch (Exception e) { CustomLog.e(TAG, "批量收藏文章被选择" + e.toString()); } bean.setBody(newBodyArray.toString()); } else if (bean.getType() == FileTaskManager.NOTICE_TYPE_CHATRECORD_SEND) { try { JSONArray bodyArray = new JSONArray(bean.getBody()); if (bodyArray != null && bodyArray.length() > 0) { JSONObject bodyObj = bodyArray.optJSONObject(0); JSONArray detailArray = bodyObj.optJSONArray("chatrecordInfo"); for (int j = 0; j < detailArray.length(); j++) { JSONObject tmpObj = detailArray.optJSONObject(j); if (tmpObj.optInt("type") == FileTaskManager.NOTICE_TYPE_TXT_SEND) { tmpObj.put("txt", tmpObj.optString("text")); } else if (tmpObj.optInt("type") == FileTaskManager.NOTICE_TYPE_ARTICAL_SEND) { tmpObj.put("offAccLogoUrl", tmpObj.optString("previewUrl")); } } } bean.setBody(bodyArray.toString()); } catch (Exception e) { CustomLog.e(TAG, "收藏聊天记录,解析json出错"); } } } CollectionManager.getInstance().addCollectionByNoticesBeans(dataList); Toast.makeText(getActivity(), R.string.have_collected, Toast.LENGTH_SHORT).show(); } cleanCheckData(); } private void cleanCheckData() { if (chatAdapter != null) { chatAdapter.cleanCheckedData(); } } private void initMoreOpWidget(View v) { moreOpLayout = (RelativeLayout) v.findViewById(R.id.more_op_layout); forwardBtn = (ImageButton) v.findViewById(R.id.chat_more_forward_btn); forwardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {} }); collectBtn = (ImageButton) v.findViewById(R.id.chat_more_collect_btn); collectBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { preCheckDataforCollection(); } }); delBtn = (ImageButton) v.findViewById(R.id.chat_more_del_btn); delBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub preCheckDataforDel(); } }); } /* * 监听群信息和群成员表 */ private class GroupMemberObserver extends ContentObserver { public GroupMemberObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); CustomLog.i(TAG, "GroupMemberObserver::onChange()"); } } private class GroupObserver extends ContentObserver { public GroupObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); CustomLog.i(TAG, "GroupObserver :: onChange()"); CustomLog.d(TAG, "t_multi_chat_users 群成员表数据库数据发生变更"); } } private String getGroupNameTitle() { String gruopName = groupDao.getGroupNameByGidTitle(groupId); //如果群名称超过15字,截取,以便显示免打扰铃铛 gruopName = checkGroupNameLength(gruopName); isGroupMember = groupDao.isGroupMember(groupId, selfNubeNumber); return gruopName; } private String checkGroupNameLength(String groupName) { if (groupName.length() > 8) { groupName = groupName.substring(0, 8) + "..."; return groupName; } return groupName; } @Override public void onSetSelectMemeber(String name, String nube) { // 选择@回復的成員 selectNubeList.add("@" + nube + IMConstant.SPECIAL_CHAR); selectNameList.add("@" + name + IMConstant.SPECIAL_CHAR); inputFragment.setSpecialtxt("@" + name); } private ArrayList<ContactFriendBean> GroupMemberToContactsBean() { ArrayList<ContactFriendBean> List = new ArrayList<ContactFriendBean>(); ContactFriendBean data; Iterator<Map.Entry<String, GroupMemberBean>> iter = dateList.entrySet() .iterator(); while (iter.hasNext()) { GroupMemberBean bean = iter.next().getValue(); if (!bean.getNubeNum().equals(selfNubeNumber)) { data = new ContactFriendBean(); data.setHeadUrl(bean.getHeadUrl()); data.setName(bean.getDispName()); data.setNickname(bean.getNickName()); data.setNumber(bean.getPhoneNum()); data.setNubeNumber(bean.getNubeNum()); data.setSex( (bean.getGender() == GroupMemberTable.GENDER_MALE ? GroupMemberTable.GENDER_MALE : GroupMemberTable.GENDER_FEMALE) + ""); data.setPym(PinyinUtil.getPinYin(bean.getDispName()) .toUpperCase()); List.add(data); } } ListSort<ContactFriendBean> listSort = new ListSort<ContactFriendBean>(); listSort.Sort(List, "getPym", null); return List; } private static void tipToast(String txt) { CommonUtil.showToast(txt); CustomLog.d(TAG, txt); } @Override public void reBookMeeting() {} @Override public void reCreatMeeting() {} @Override public void addNewFriend() { int relationCode = FriendsManager.getInstance() .getFriendRelationByNubeNumber(targetNubeNumber); if (relationCode == FriendsManager.RELATION_TYPE_BOTH) { // CustomToast.show(getActivity(),targetShortName + "已经是您的好友",CustomToast.LENGTH_LONG); CustomToast.show(getActivity(), getString(R.string.have_been_friend), CustomToast.LENGTH_LONG); return; } Intent intent = new Intent(getActivity(), VerificationReplyDialog.class); intent.putExtra(VerificationReplyDialog.KEY_DIALOG_TYPE, 1); // 0从名片页进入 1:从IM页面进入 intent.putExtra("nubeNumber", targetNubeNumber); startActivityForResult(intent, ContactTransmitConfig.REQUEST_REPLY_CODE); } private boolean isFriend() { if (conversationType != VALUE_CONVERSATION_TYPE_MULTI) { if (ContactManager.getInstance(getActivity()) .checkNubeIsCustomService(targetNubeNumber)) { CustomLog.d(TAG, targetNubeNumber + "是客服账号,可以直接发送消息"); return true; } int relationCode = FriendsManager.getInstance() .getFriendRelationByNubeNumber(targetNubeNumber); if (relationCode != FriendsManager.RELATION_TYPE_BOTH) { String tmpStr = targetShortName + getString(R.string.start_friend_approve_send_approve_request) + getString(R.string.pass_request_chat_send_request); dtNoticeDao.createAddFriendTxt("", targetNubeNumber, "", null, "", FileTaskManager.NOTICE_TYPE_DESCRIPTION, tmpStr, convstId, null , System.currentTimeMillis() + ""); return false; } return true; } return true; } private void sendAddNewFriendMsg(String msgContent) { MDSAccountInfo loginUserInfo = AccountManager.getInstance(getActivity()).getAccountInfo(); MedicalApplication.getFileTaskManager().sendStrangerMsg(loginUserInfo.getNube(), targetNubeNumber, loginUserInfo.getNickName(), loginUserInfo.getHeadThumUrl(), msgContent, false); Contact contact = ContactManager.getInstance(getActivity()) .getContactInfoByNubeNumber(targetNubeNumber); StrangerMessage strangerMessage = new StrangerMessage( targetNubeNumber, contact.getHeadUrl(), targetShortName, 0, msgContent, String.valueOf(System.currentTimeMillis()), 1); int addResutl = FriendsManager.getInstance().addStrangerMsg(strangerMessage); if (addResutl == 0) { CustomLog.d(TAG, "addStrangerMsg 成功"); } else { CustomLog.d(TAG, "addStrangerMsg 失败, addStrangerMessageResult:" + addResutl); } FriendInfo friendInfo = new FriendInfo(); friendInfo.setNubeNumber(contact.getNubeNumber()); friendInfo.setName(contact.getName()); friendInfo.setHeadUrl(contact.getHeadUrl()); friendInfo.setEmail(contact.getEmail()); friendInfo.setWorkUnitType(String.valueOf(contact.getWorkUnitType())); friendInfo.setWorkUnit(contact.getWorkUnit()); friendInfo.setDepartment(contact.getDepartment()); friendInfo.setProfessional(contact.getProfessional()); friendInfo.setOfficeTel(contact.getOfficeTel()); friendInfo.setUserFrom(Integer.valueOf(contact.getUserFrom())); friendInfo.setIsDeleted(FriendInfo.NOT_DELETE); friendInfo.setRelationType(FriendInfo.RELATION_TYPE_POSITIVE); int addFriendResult = FriendsManager.getInstance().addFriend(friendInfo); if (addFriendResult == 0) { CustomLog.d(TAG, "addFriend 成功"); } else { CustomLog.d(TAG, "addFriend 失败, addFriendResult:" + addFriendResult); } } /** * 监听好友关系表 */ private class FriendRelationObserver extends ContentObserver { public FriendRelationObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); CustomLog.i(TAG, "FriendRelationObserver :: onChange()"); CustomLog.d(TAG, "好友关系数据库数据发生变更"); } } private String getAdminNickName() { SharedPreferences preferences = getActivity(). getSharedPreferences(ChatActivity.KEY_SERVICE_NUBE_INFO, MODE_PRIVATE); return preferences.getString("USERNAME", "10000"); } /** * 初始化广播接收器 */ private void initReceiver() { netReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 判断当前网络状态 if (intent.getIntExtra(NetWorkChangeReceiver.NET_TYPE, 0) == 0) { CustomLog.d(TAG, "网络断开"); } else { CustomLog.d(TAG, "网络连接"); } } }; IntentFilter filter = new IntentFilter(NetWorkChangeReceiver.NET_CHANGE); getActivity().registerReceiver(netReceiver, filter); dtEndBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(RECEIVER_END_DT_BROADCAST)) { CustomLog.i(TAG, "receive end dt broadcast"); inputFragment.hideChatInputLayout(); } else if (action.equals(END_DT_BROADCAST)) { CustomLog.i(TAG, "receive end dt broadcast"); inputFragment.hideChatInputLayout(); } } }; IntentFilter filter2 = new IntentFilter(RECEIVER_END_DT_BROADCAST); IntentFilter filter3 = new IntentFilter(END_DT_BROADCAST); getActivity().registerReceiver(dtEndBroadcastReceiver, filter2); getActivity().registerReceiver(dtEndBroadcastReceiver, filter3); } /** * 到达了正确的接诊时间 * 用例:预约时间早于等于服务器时间才认为可以接诊 */ private boolean arriveScheduleTime() { CustomLog.i(TAG, "arriveScheduleTime()"); int scheduleTime = Integer.valueOf(mUDTGlobleData.getSchedulDate()); String serverTimeStamp = mUDTGlobleData.getServerDate(); int serverTime = Integer.valueOf(DateUtils.timeStamp2Date(serverTimeStamp)); if (scheduleTime == serverTime) { return true; } else { return false; } } public boolean isInputPanelVisible() { if (inputFragment != null) { return inputFragment.isPanelVisible(); } else { return false; } } public void setInputPanelHide() { CustomLog.i(TAG, "setInputPanelHide()"); if (inputFragment != null) { inputFragment.setHide(); } } }
[ "cdc0002829@126.com" ]
cdc0002829@126.com
b775fe4e92360074564a6481153cd3c5102837d4
eb1517897d7e9e372538b0982223b7ecaaff46b0
/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java
9b0a82c178c811b70c8d9620f656d783c7ab80cd
[ "BSD-3-Clause" ]
permissive
jiachengii/chromium
c93e9cfa8fb79d6a0b5e66848dc204e87236252c
ead0d3601849269629ff31de4daed20fce453ba7
refs/heads/master
2022-11-16T02:35:53.671352
2020-06-13T06:43:44
2020-06-13T06:43:44
271,964,385
0
0
BSD-3-Clause
2020-06-13T07:47:21
2020-06-13T07:47:21
null
UTF-8
Java
false
false
46,114
java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.fullscreen; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.app.Activity; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.FrameLayout; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; import org.chromium.base.ApplicationStatus.ActivityStateListener; import org.chromium.base.ApplicationStatus.WindowFocusChangedListener; import org.chromium.base.ObserverList; import org.chromium.base.TraceEvent; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.supplier.ObservableSupplierImpl; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.ActivityTabProvider.ActivityTabTabObserver; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.SadTab; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabAttributeKeys; import org.chromium.chrome.browser.tab.TabAttributes; import org.chromium.chrome.browser.tab.TabBrowserControlsConstraintsHelper; import org.chromium.chrome.browser.tab.TabBrowserControlsOffsetHelper; import org.chromium.chrome.browser.tab.TabHidingType; import org.chromium.chrome.browser.tabmodel.TabModelImpl; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabObserver; import org.chromium.chrome.browser.toolbar.ControlContainer; import org.chromium.chrome.browser.vr.VrModuleProvider; import org.chromium.components.browser_ui.util.BrowserControlsVisibilityDelegate; import org.chromium.components.embedder_support.view.ContentView; import org.chromium.content_public.browser.GestureListenerManager; import org.chromium.content_public.browser.NavigationHandle; import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.common.BrowserControlsState; import org.chromium.ui.util.TokenHolder; import org.chromium.ui.vr.VrModeObserver; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; /** * A class that manages control and content views to create the fullscreen mode. */ public class ChromeFullscreenManager implements ActivityStateListener, WindowFocusChangedListener, ViewGroup.OnHierarchyChangeListener, View.OnSystemUiVisibilityChangeListener, VrModeObserver, BrowserControlsSizer { // The amount of time to delay the control show request after returning to a once visible // activity. This delay is meant to allow Android to run its Activity focusing animation and // have the controls scroll back in smoothly once that has finished. private static final long ACTIVITY_RETURN_SHOW_REQUEST_DELAY_MS = 100; /** * Maximum duration for the control container slide-in animation. Note that this value matches * the one in browser_controls_offset_manager.cc. */ private static final int MAX_CONTROLS_ANIMATION_DURATION_MS = 200; private final Activity mActivity; private final BrowserStateBrowserControlsVisibilityDelegate mBrowserVisibilityDelegate; @ControlsPosition private final int mControlsPosition; private final boolean mExitFullscreenOnStop; private final TokenHolder mHidingTokenHolder = new TokenHolder(this::scheduleVisibilityUpdate); /** * An observable for browser controls being at its minimum height or not. * This is as good as the controls being hidden when both min heights are 0. */ private final ObservableSupplierImpl<Boolean> mControlsAtMinHeight = new ObservableSupplierImpl<>(); private TabModelSelectorTabObserver mTabFullscreenObserver; @Nullable private ControlContainer mControlContainer; private int mTopControlContainerHeight; private int mTopControlsMinHeight; private int mBottomControlContainerHeight; private int mBottomControlsMinHeight; private boolean mAnimateBrowserControlsHeightChanges; private boolean mControlsResizeView; private int mRendererTopControlOffset; private int mRendererBottomControlOffset; private int mRendererTopContentOffset; private int mRendererTopControlsMinHeightOffset; private int mRendererBottomControlsMinHeightOffset; private int mPreviousContentOffset; private float mControlOffsetRatio; private boolean mOffsetsChanged; private ActivityTabTabObserver mActiveTabObserver; private boolean mInGesture; private boolean mContentViewScrolling; // Current ContentView. Updates when active tab is switched or WebContents is swapped // in the current Tab. private ContentView mContentView; private final ArrayList<FullscreenListener> mListeners = new ArrayList<>(); private final ObserverList<BrowserControlsStateProvider.Observer> mControlsObservers = new ObserverList<>(); private Runnable mViewportSizeDelegate; private FullscreenHtmlApiHandler mHtmlApiHandler; @Nullable private Tab mTab; /** The animator for slide-in animation on the Android controls. */ private ValueAnimator mControlsAnimator; /** * Indicates if control offset is in the overridden state by animation. Stays {@code true} * from animation start till the next offset update from compositor arrives. */ private boolean mOffsetOverridden; @IntDef({ControlsPosition.TOP, ControlsPosition.NONE}) @Retention(RetentionPolicy.SOURCE) public @interface ControlsPosition { /** Controls are at the top, eg normal ChromeTabbedActivity. */ int TOP = 0; /** Controls are not present, eg NoTouchActivity. */ int NONE = 1; } /** * A listener that gets notified of changes to the fullscreen state. */ public interface FullscreenListener { /** * Called when entering fullscreen mode. * @param tab The tab whose content is entering fullscreen mode. * @param options Options to adjust fullscreen mode. */ default void onEnterFullscreen(Tab tab, FullscreenOptions options) {} /** * Called when exiting fullscreen mode. * @param tab The tab whose content is exiting fullscreen mode. */ default void onExitFullscreen(Tab tab) {} } private final Runnable mUpdateVisibilityRunnable = new Runnable() { @Override public void run() { int visibility = shouldShowAndroidControls() ? View.VISIBLE : View.INVISIBLE; if (mControlContainer == null || mControlContainer.getView().getVisibility() == visibility) { return; } // requestLayout is required to trigger a new gatherTransparentRegion(), which // only occurs together with a layout and let's SurfaceFlinger trim overlays. // This may be almost equivalent to using View.GONE, but we still use View.INVISIBLE // since drawing caches etc. won't be destroyed, and the layout may be less expensive. mControlContainer.getView().setVisibility(visibility); mControlContainer.getView().requestLayout(); } }; /** * Creates an instance of the fullscreen mode manager. * @param activity The activity that supports fullscreen. * @param controlsPosition Where the browser controls are. */ public ChromeFullscreenManager(Activity activity, @ControlsPosition int controlsPosition) { this(activity, controlsPosition, true); } /** * Creates an instance of the fullscreen mode manager. * @param activity The activity that supports fullscreen. * @param controlsPosition Where the browser controls are. * @param exitFullscreenOnStop Whether fullscreen mode should exit on stop - should be * true for Activities that are not always fullscreen. */ public ChromeFullscreenManager(Activity activity, @ControlsPosition int controlsPosition, boolean exitFullscreenOnStop) { mActivity = activity; mControlsPosition = controlsPosition; mExitFullscreenOnStop = exitFullscreenOnStop; mControlsAtMinHeight.set(false); mHtmlApiHandler = new FullscreenHtmlApiHandler(activity.getWindow(), this::getTab, mControlsAtMinHeight, () -> !(isInVr() || bootsToVr())); mBrowserVisibilityDelegate = new BrowserStateBrowserControlsVisibilityDelegate( mHtmlApiHandler.getPersistentFullscreenModeSupplier()); mBrowserVisibilityDelegate.addObserver((constraints) -> { if (constraints == BrowserControlsState.SHOWN) setPositionsForTabToNonFullscreen(); }); VrModuleProvider.registerVrModeObserver(this); if (isInVr()) onEnterVr(); } /** * Initializes the fullscreen manager with the required dependencies. * * @param controlContainer Container holding the controls (Toolbar). * @param activityTabProvider Provider of the current activity tab. * @param modelSelector The tab model selector that will be monitored for tab changes. * @param resControlContainerHeight The dimension resource ID for the control container height. */ public void initialize(ControlContainer controlContainer, ActivityTabProvider activityTabProvider, final TabModelSelector modelSelector, int resControlContainerHeight) { ApplicationStatus.registerStateListenerForActivity(this, mActivity); ApplicationStatus.registerWindowFocusChangedListener(this); mActiveTabObserver = new ActivityTabTabObserver(activityTabProvider) { @Override protected void onObservingDifferentTab(Tab tab) { setTab(tab); } @Override public void onContentViewScrollingStateChanged(boolean scrolling) { mContentViewScrolling = scrolling; if (!scrolling) updateContentOffsetAndNotify(); } }; mTabFullscreenObserver = new TabModelSelectorTabObserver(modelSelector) { @Override public void onHidden(Tab tab, @TabHidingType int reason) { // Clean up any fullscreen state that might impact other tabs. exitPersistentFullscreenMode(); } @Override public void onContentChanged(Tab tab) { if (tab == getTab()) updateViewStateListener(); } @Override public void onDidFinishNavigation(Tab tab, NavigationHandle navigation) { if (navigation.isInMainFrame() && !navigation.isSameDocument()) { if (tab == getTab()) exitPersistentFullscreenMode(); } } @Override public void onInteractabilityChanged(Tab tab, boolean interactable) { Tab currentTab = getTab(); if (!interactable || tab != currentTab) return; Runnable enterFullscreen = getEnterFullscreenRunnable(currentTab); if (enterFullscreen != null) enterFullscreen.run(); TabBrowserControlsOffsetHelper offsetHelper = TabBrowserControlsOffsetHelper.get(currentTab); if (!offsetHelper.offsetInitialized()) return; onOffsetsChanged(offsetHelper.topControlsOffset(), offsetHelper.bottomControlsOffset(), offsetHelper.contentOffset(), offsetHelper.topControlsMinHeightOffset(), offsetHelper.bottomControlsMinHeightOffset()); } @Override public void onCrash(Tab tab) { if (tab == getTab() && SadTab.isShowing(tab)) showAndroidControls(false); } @Override public void onRendererResponsiveStateChanged(Tab tab, boolean isResponsive) { if (tab == getTab() && !isResponsive) showAndroidControls(false); } @Override public void onBrowserControlsOffsetChanged(Tab tab, int topControlsOffset, int bottomControlsOffset, int contentOffset, int topControlsMinHeightOffset, int bottomControlsMinHeightOffset) { if (tab == getTab() && tab.isUserInteractable()) { onOffsetsChanged(topControlsOffset, bottomControlsOffset, contentOffset, topControlsMinHeightOffset, bottomControlsMinHeightOffset); } } }; assert controlContainer != null || mControlsPosition == ControlsPosition.NONE; mControlContainer = controlContainer; switch (mControlsPosition) { case ControlsPosition.TOP: assert resControlContainerHeight != ChromeActivity.NO_CONTROL_CONTAINER; mTopControlContainerHeight = mActivity.getResources().getDimensionPixelSize(resControlContainerHeight); break; case ControlsPosition.NONE: // Treat the case of no controls as controls always being totally offscreen. mControlOffsetRatio = 1.0f; break; } mRendererTopContentOffset = mTopControlContainerHeight; updateControlOffset(); scheduleVisibilityUpdate(); } @Override public BrowserStateBrowserControlsVisibilityDelegate getBrowserVisibilityDelegate() { return mBrowserVisibilityDelegate; } /** * @return The currently selected tab for fullscreen. */ @Nullable @VisibleForTesting Tab getTab() { return mTab; } private void setTab(@Nullable Tab tab) { Tab previousTab = getTab(); mTab = tab; if (previousTab != tab) { updateViewStateListener(); if (tab != null) { mBrowserVisibilityDelegate.showControlsTransient(); updateMultiTouchZoomSupport(!getPersistentFullscreenMode()); if (tab.isUserInteractable()) restoreControlsPositions(); } } if (tab == null && mBrowserVisibilityDelegate.get() != BrowserControlsState.HIDDEN) { setPositionsForTabToNonFullscreen(); } } /** * Enter fullscreen. * @param tab {@link Tab} that goes into fullscreen. * @param options Fullscreen options. */ public void onEnterFullscreen(Tab tab, FullscreenOptions options) { // If enabling fullscreen while the tab is not interactable, fullscreen // will be delayed until the tab is interactable. Runnable r = () -> { enterPersistentFullscreenMode(options); destroySelectActionMode(tab); setEnterFullscreenRunnable(tab, null); }; if (tab.isUserInteractable()) { r.run(); } else { setEnterFullscreenRunnable(tab, r); } for (FullscreenListener listener : mListeners) listener.onEnterFullscreen(tab, options); } /** * Exit fullscreen. * @param tab {@link Tab} that goes out of fullscreen. */ public void onExitFullscreen(Tab tab) { setEnterFullscreenRunnable(tab, null); if (tab == getTab()) exitPersistentFullscreenMode(); for (FullscreenListener listener : mListeners) listener.onExitFullscreen(tab); } /** * Enters persistent fullscreen mode. In this mode, the browser controls will be * permanently hidden until this mode is exited. */ private void enterPersistentFullscreenMode(FullscreenOptions options) { mHtmlApiHandler.enterPersistentFullscreenMode(options); updateMultiTouchZoomSupport(false); } /** * Exits persistent fullscreen mode. In this mode, the browser controls will be * permanently hidden until this mode is exited. */ public void exitPersistentFullscreenMode() { mHtmlApiHandler.exitPersistentFullscreenMode(); updateMultiTouchZoomSupport(true); } /** * @see GestureListenerManager#updateMultiTouchZoomSupport(boolean). */ private void updateMultiTouchZoomSupport(boolean enable) { Tab tab = getTab(); if (tab == null || tab.isHidden()) return; WebContents webContents = tab.getWebContents(); if (webContents != null) { GestureListenerManager manager = GestureListenerManager.fromWebContents(webContents); if (manager != null) manager.updateMultiTouchZoomSupport(enable); } } /** * @return Whether the application is in persistent fullscreen mode. * @see #setPersistentFullscreenMode(boolean) */ public boolean getPersistentFullscreenMode() { return mHtmlApiHandler.getPersistentFullscreenMode(); } /** * Notified when the system UI visibility for the current ContentView has changed. * @param visibility The updated UI visibility. * @see View#getSystemUiVisibility() */ public void onContentViewSystemUiVisibilityChange(int visibility) { mHtmlApiHandler.onContentViewSystemUiVisibilityChange(visibility); } private void destroySelectActionMode(Tab tab) { WebContents webContents = tab.getWebContents(); if (webContents != null) { SelectionPopupController.fromWebContents(webContents).destroySelectActionMode(); } } private void setEnterFullscreenRunnable(Tab tab, Runnable runnable) { TabAttributes attrs = TabAttributes.from(tab); if (runnable == null) { attrs.clear(TabAttributeKeys.ENTER_FULLSCREEN); } else { attrs.set(TabAttributeKeys.ENTER_FULLSCREEN, runnable); } } private Runnable getEnterFullscreenRunnable(Tab tab) { return tab != null ? TabAttributes.from(tab).get(TabAttributeKeys.ENTER_FULLSCREEN) : null; } private void updateViewStateListener() { if (mContentView != null) { mContentView.removeOnHierarchyChangeListener(this); mContentView.removeOnSystemUiVisibilityChangeListener(this); } mContentView = getContentView(); if (mContentView != null) { mContentView.addOnHierarchyChangeListener(this); mContentView.addOnSystemUiVisibilityChangeListener(this); } } @Override public void onActivityStateChange(Activity activity, int newState) { if (newState == ActivityState.STOPPED && mExitFullscreenOnStop) { // Exit fullscreen in onStop to ensure the system UI flags are set correctly when // showing again (on JB MR2+ builds, the omnibox would be covered by the // notification bar when this was done in onStart()). exitPersistentFullscreenMode(); } else if (newState == ActivityState.STARTED) { PostTask.postDelayedTask(UiThreadTaskTraits.DEFAULT, () -> mBrowserVisibilityDelegate.showControlsTransient(), ACTIVITY_RETURN_SHOW_REQUEST_DELAY_MS); } else if (newState == ActivityState.DESTROYED) { ApplicationStatus.unregisterActivityStateListener(this); ApplicationStatus.unregisterWindowFocusChangedListener(this); } } @Override public void onWindowFocusChanged(Activity activity, boolean hasFocus) { if (mActivity != activity) return; mHtmlApiHandler.onWindowFocusChanged(hasFocus); // {@link ContentVideoView#getContentVideoView} requires native to have been initialized. if (!LibraryLoader.getInstance().isInitialized()) return; } @Override public float getBrowserControlHiddenRatio() { return mControlOffsetRatio; } /** * @return True if the browser controls are showing as much as the min height. Note that this is * the same as * {@link BrowserControlsUtils#areBrowserControlsOffScreen(BrowserControlsStateProvider)} when * both min-heights are 0. */ @VisibleForTesting boolean areBrowserControlsAtMinHeight() { return mControlsAtMinHeight.get(); } @Override public void setBottomControlsHeight(int bottomControlsHeight, int bottomControlsMinHeight) { if (mBottomControlContainerHeight == bottomControlsHeight && mBottomControlsMinHeight == bottomControlsMinHeight) { return; } mBottomControlContainerHeight = bottomControlsHeight; mBottomControlsMinHeight = bottomControlsMinHeight; for (BrowserControlsStateProvider.Observer obs : mControlsObservers) { obs.onBottomControlsHeightChanged( mBottomControlContainerHeight, mBottomControlsMinHeight); } } @Override public void setTopControlsHeight(int topControlsHeight, int topControlsMinHeight) { if (mTopControlContainerHeight == topControlsHeight && mTopControlsMinHeight == topControlsMinHeight) { return; } mTopControlContainerHeight = topControlsHeight; mTopControlsMinHeight = topControlsMinHeight; for (BrowserControlsStateProvider.Observer obs : mControlsObservers) { obs.onTopControlsHeightChanged(mTopControlContainerHeight, mTopControlsMinHeight); } } @Override public void setAnimateBrowserControlsHeightChanges( boolean animateBrowserControlsHeightChanges) { mAnimateBrowserControlsHeightChanges = animateBrowserControlsHeightChanges; } @Override public int getTopControlsHeight() { return mTopControlContainerHeight; } @Override public int getTopControlsMinHeight() { return mTopControlsMinHeight; } @Override public int getBottomControlsHeight() { return mBottomControlContainerHeight; } @Override public int getBottomControlsMinHeight() { return mBottomControlsMinHeight; } @Override public boolean shouldAnimateBrowserControlsHeightChanges() { return mAnimateBrowserControlsHeightChanges; } public boolean controlsResizeView() { return mControlsResizeView; } @Override public int getContentOffset() { return mRendererTopContentOffset; } @Override public int getTopControlOffset() { return mRendererTopControlOffset; } @Override public int getTopControlsMinHeightOffset() { return mRendererTopControlsMinHeightOffset; } /** * @return The content offset from the bottom of the screen, or the visible height of the bottom * controls, in px. */ public int getBottomContentOffset() { return getBottomControlsHeight() - getBottomControlOffset(); } @Override public int getBottomControlOffset() { // If the height is currently 0, the offset generated by the bottom controls should be too. // TODO(crbug.com/103602): Send a offset update from the fullscreen manager when the height // changes to ensure correct offsets (removing the need for min()). return Math.min(mRendererBottomControlOffset, mBottomControlContainerHeight); } @Override public int getBottomControlsMinHeightOffset() { return mRendererBottomControlsMinHeightOffset; } private void updateControlOffset() { if (mControlsPosition == ControlsPosition.NONE) return; if (getTopControlsHeight() == 0) { // Treat the case of 0 height as controls being totally offscreen. mControlOffsetRatio = 1.0f; } else { mControlOffsetRatio = Math.abs((float) mRendererTopControlOffset / getTopControlsHeight()); } } @Override public float getTopVisibleContentOffset() { return getTopControlsHeight() + getTopControlOffset(); } @Override public void addObserver(Observer obs) { mControlsObservers.addObserver(obs); } @Override public void removeObserver(Observer obs) { mControlsObservers.removeObserver(obs); } /** * @param listener The {@link FullscreenListener} to be notified of fullscreen changes. */ public void addListener(FullscreenListener listener) { if (!mListeners.contains(listener)) mListeners.add(listener); } /** * @param listener The {@link FullscreenListener} to no longer be notified of fullscreen * changes. */ public void removeListener(FullscreenListener listener) { mListeners.remove(listener); } /** * @param delegate A Runnable to be executed when the WebContents viewport should be updated. */ public void setViewportSizeDelegate(Runnable delegate) { mViewportSizeDelegate = delegate; } /** * Updates viewport size to have it render the content correctly. */ public void updateViewportSize() { if (mInGesture || mContentViewScrolling) return; // Update content viewport size only if the browser controls are not moving, i.e. not // scrolling or animating. if (!areBrowserControlsIdle()) return; mControlsResizeView = getContentOffset() > getTopControlsMinHeight() || getBottomContentOffset() > getBottomControlsMinHeight(); if (mViewportSizeDelegate != null) mViewportSizeDelegate.run(); } /** * @return Whether browser controls are currently idle, i.e. not scrolling or animating. */ private boolean areBrowserControlsIdle() { return (getContentOffset() == getTopControlsMinHeight() || getContentOffset() == getTopControlsHeight()) && (getBottomContentOffset() == getBottomControlsMinHeight() || getBottomContentOffset() == getBottomControlsHeight()); } // View.OnHierarchyChangeListener implementation @Override public void onChildViewRemoved(View parent, View child) { updateContentViewChildrenState(); } @Override public void onChildViewAdded(View parent, View child) { updateContentViewChildrenState(); } /** * Updates the current ContentView's children and any popups with the correct offsets based on * the current fullscreen state. */ private void updateContentViewChildrenState() { ViewGroup view = getContentView(); if (view == null) return; float topViewsTranslation = getTopVisibleContentOffset(); float bottomMargin = getBottomContentOffset(); applyTranslationToTopChildViews(view, topViewsTranslation); applyMarginToFullChildViews(view, topViewsTranslation, bottomMargin); updateViewportSize(); } @Override public void onSystemUiVisibilityChange(int visibility) { onContentViewSystemUiVisibilityChange(visibility); } /** * Utility routine for ensuring visibility updates are synchronized with * animation, preventing message loop stalls due to untimely invalidation. */ private void scheduleVisibilityUpdate() { if (mControlContainer == null) { return; } final int desiredVisibility = shouldShowAndroidControls() ? View.VISIBLE : View.INVISIBLE; if (mControlContainer.getView().getVisibility() == desiredVisibility) return; mControlContainer.getView().removeCallbacks(mUpdateVisibilityRunnable); mControlContainer.getView().postOnAnimation(mUpdateVisibilityRunnable); } private void updateContentOffsetAndNotify() { TraceEvent.begin("FullscreenManager:updateContentOffsetAndNotify"); updateContentViewChildrenState(); int contentOffset = getContentOffset(); if (mPreviousContentOffset != contentOffset) { for (BrowserControlsStateProvider.Observer obs : mControlsObservers) { obs.onContentOffsetChanged(contentOffset); } mPreviousContentOffset = contentOffset; } TraceEvent.end("FullscreenManager:updateContentOffsetAndNotify"); } /** * Forces the Android controls to hide. While there are acquired tokens the browser controls * Android view will always be hidden, otherwise they will show/hide based on position. * * NB: this only affects the Android controls. For controlling composited toolbar visibility, * implement {@link BrowserControlsVisibilityDelegate#canShowBrowserControls()}. */ private int hideAndroidControls() { return mHidingTokenHolder.acquireToken(); } @Override public int hideAndroidControlsAndClearOldToken(int oldToken) { int newToken = hideAndroidControls(); mHidingTokenHolder.releaseToken(oldToken); return newToken; } @Override public void releaseAndroidControlsHidingToken(int token) { mHidingTokenHolder.releaseToken(token); } private boolean shouldShowAndroidControls() { if (mControlContainer == null) return false; if (mHidingTokenHolder.hasTokens()) { return false; } Tab tab = getTab(); if (tab != null) { if (tab.isInitialized()) { if (offsetOverridden()) return true; } else { assert false : "Accessing a destroyed tab, setTab should have been called"; } } boolean showControls = !BrowserControlsUtils.drawControlsAsTexture(this); ViewGroup contentView = getContentView(); if (contentView == null) return showControls; for (int i = 0; i < contentView.getChildCount(); i++) { View child = contentView.getChildAt(i); if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue; FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) child.getLayoutParams(); if (Gravity.TOP == (layoutParams.gravity & Gravity.FILL_VERTICAL)) { showControls = true; break; } } return showControls; } private void applyMarginToFullChildViews( ViewGroup contentView, float topMargin, float bottomMargin) { for (int i = 0; i < contentView.getChildCount(); i++) { View child = contentView.getChildAt(i); if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue; FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) child.getLayoutParams(); if (layoutParams.height == LayoutParams.MATCH_PARENT && (layoutParams.topMargin != (int) topMargin || layoutParams.bottomMargin != (int) bottomMargin)) { layoutParams.topMargin = (int) topMargin; layoutParams.bottomMargin = (int) bottomMargin; child.requestLayout(); TraceEvent.instant("FullscreenManager:child.requestLayout()"); } } } private void applyTranslationToTopChildViews(ViewGroup contentView, float translation) { for (int i = 0; i < contentView.getChildCount(); i++) { View child = contentView.getChildAt(i); if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue; FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) child.getLayoutParams(); if (Gravity.TOP == (layoutParams.gravity & Gravity.FILL_VERTICAL)) { child.setTranslationY(translation); TraceEvent.instant("FullscreenManager:child.setTranslationY()"); } } } private ContentView getContentView() { Tab tab = getTab(); return tab != null ? (ContentView) tab.getContentView() : null; } /** * Updates the positions of the browser controls and content to the default non fullscreen * values. */ private void setPositionsForTabToNonFullscreen() { Tab tab = getTab(); if (tab == null || TabBrowserControlsConstraintsHelper.getConstraints(tab) != BrowserControlsState.HIDDEN) { setPositionsForTab(0, 0, getTopControlsHeight(), getTopControlsMinHeight(), getBottomControlsMinHeight()); } else { // Tab isn't null and the BrowserControlsState is HIDDEN. In this case, set the offsets // to values that will position the browser controls at the min-height. setPositionsForTab(getTopControlsMinHeight() - getTopControlsHeight(), getBottomControlsHeight() - getBottomControlsMinHeight(), getTopControlsMinHeight(), getTopControlsMinHeight(), getBottomControlsMinHeight()); } } /** * Updates the positions of the browser controls and content based on the desired position of * the current tab. * @param topControlsOffset The Y offset of the top controls in px. * @param bottomControlsOffset The Y offset of the bottom controls in px. * @param topContentOffset The Y offset for the content in px. * @param topControlsMinHeightOffset The Y offset for the top controls min-height in px. * @param bottomControlsMinHeightOffset The Y offset for the bottom controls min-height in px. */ private void setPositionsForTab(int topControlsOffset, int bottomControlsOffset, int topContentOffset, int topControlsMinHeightOffset, int bottomControlsMinHeightOffset) { // This min/max logic is here to handle changes in the browser controls height. For example, // if we change either height to 0, the offsets of the controls should also be 0. This works // assuming we get an event from the renderer after the browser control heights change. int rendererTopControlOffset = Math.max(topControlsOffset, -getTopControlsHeight()); int rendererBottomControlOffset = Math.min(bottomControlsOffset, getBottomControlsHeight()); int rendererTopContentOffset = Math.min(topContentOffset, rendererTopControlOffset + getTopControlsHeight()); if (rendererTopControlOffset == mRendererTopControlOffset && rendererBottomControlOffset == mRendererBottomControlOffset && rendererTopContentOffset == mRendererTopContentOffset && topControlsMinHeightOffset == mRendererTopControlsMinHeightOffset && bottomControlsMinHeightOffset == mRendererBottomControlsMinHeightOffset) { return; } mRendererTopControlOffset = rendererTopControlOffset; mRendererBottomControlOffset = rendererBottomControlOffset; mRendererTopControlsMinHeightOffset = topControlsMinHeightOffset; mRendererBottomControlsMinHeightOffset = bottomControlsMinHeightOffset; mRendererTopContentOffset = rendererTopContentOffset; mControlsAtMinHeight.set(getContentOffset() == getTopControlsMinHeight() && getBottomContentOffset() == getBottomControlsMinHeight()); updateControlOffset(); notifyControlOffsetChanged(); updateContentOffsetAndNotify(); } private void notifyControlOffsetChanged() { scheduleVisibilityUpdate(); if (shouldShowAndroidControls()) { mControlContainer.getView().setTranslationY(getTopControlOffset()); } // Whether we need the compositor to draw again to update our animation. // Should be |false| when the browser controls are only moved through the page // scrolling. boolean needsAnimate = shouldShowAndroidControls(); for (BrowserControlsStateProvider.Observer obs : mControlsObservers) { obs.onControlsOffsetChanged(getTopControlOffset(), getTopControlsMinHeightOffset(), getBottomControlOffset(), getBottomControlsMinHeightOffset(), needsAnimate); } } /** * Notifies the fullscreen manager that a motion event has occurred. * @param e The dispatched motion event. */ public void onMotionEvent(MotionEvent e) { int eventAction = e.getActionMasked(); if (eventAction == MotionEvent.ACTION_DOWN || eventAction == MotionEvent.ACTION_POINTER_DOWN) { mInGesture = true; // TODO(qinmin): Probably there is no need to hide the toast as it will go away // by itself. mHtmlApiHandler.hideNotificationToast(); } else if (eventAction == MotionEvent.ACTION_CANCEL || eventAction == MotionEvent.ACTION_UP) { mInGesture = false; updateContentOffsetAndNotify(); } } /** * Called when offset values related with fullscreen functionality has been changed by the * compositor. * @param topControlsOffsetY The Y offset of the top controls in physical pixels. * @param bottomControlsOffsetY The Y offset of the bottom controls in physical pixels. * @param contentOffsetY The Y offset of the content in physical pixels. * @param topControlsMinHeightOffsetY The current offset of the top controls min-height. * @param bottomControlsMinHeightOffsetY The current offset of the bottom controls min-height. */ private void onOffsetsChanged(int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY, int topControlsMinHeightOffsetY, int bottomControlsMinHeightOffsetY) { // Cancel any animation on the Android controls and let compositor drive the offset updates. resetControlsOffsetOverridden(); Tab tab = getTab(); if (SadTab.isShowing(tab) || tab.isNativePage()) { showAndroidControls(false); } else { updateFullscreenManagerOffsets(false, topControlsOffsetY, bottomControlsOffsetY, contentOffsetY, topControlsMinHeightOffsetY, bottomControlsMinHeightOffsetY); } TabModelImpl.setActualTabSwitchLatencyMetricRequired(); } @Override public void showAndroidControls(boolean animate) { if (animate) { runBrowserDrivenShowAnimation(); } else { updateFullscreenManagerOffsets(true, 0, 0, getTopControlsHeight(), getTopControlsMinHeight(), getBottomControlsMinHeight()); } } /** * Restores the controls positions to the cached positions of the active Tab. */ private void restoreControlsPositions() { resetControlsOffsetOverridden(); // Make sure the dominant control offsets have been set. Tab tab = getTab(); TabBrowserControlsOffsetHelper offsetHelper = null; if (tab != null) offsetHelper = TabBrowserControlsOffsetHelper.get(tab); if (offsetHelper != null && offsetHelper.offsetInitialized()) { updateFullscreenManagerOffsets(false, offsetHelper.topControlsOffset(), offsetHelper.bottomControlsOffset(), offsetHelper.contentOffset(), offsetHelper.topControlsMinHeightOffset(), offsetHelper.bottomControlsMinHeightOffset()); } else { showAndroidControls(false); } TabBrowserControlsConstraintsHelper.updateEnabledState(tab); } /** * Helper method to update offsets and notify offset changes to observers if necessary. */ private void updateFullscreenManagerOffsets(boolean toNonFullscreen, int topControlsOffset, int bottomControlsOffset, int topContentOffset, int topControlsMinHeightOffset, int bottomControlsMinHeightOffset) { if (isInVr()) { rawTopContentOffsetChangedForVr(); // The dip scale of java UI and WebContents are different while in VR, leading to a // mismatch in size in pixels when converting from dips. Since we hide the controls in // VR anyways, just set the offsets to what they're supposed to be with the controls // hidden. // TODO(mthiesse): Should we instead just set the top controls height to be 0 while in // VR? topControlsOffset = -getTopControlsHeight(); bottomControlsOffset = getBottomControlsHeight(); topContentOffset = 0; topControlsMinHeightOffset = 0; bottomControlsMinHeightOffset = 0; setPositionsForTab(topControlsOffset, bottomControlsOffset, topContentOffset, topControlsMinHeightOffset, bottomControlsMinHeightOffset); } else if (toNonFullscreen) { setPositionsForTabToNonFullscreen(); } else { setPositionsForTab(topControlsOffset, bottomControlsOffset, topContentOffset, topControlsMinHeightOffset, bottomControlsMinHeightOffset); } } @Override public boolean offsetOverridden() { return mOffsetOverridden; } /** * Sets the flat indicating if browser control offset is overridden by animation. * @param flag Boolean flag of the new offset overridden state. */ private void setOffsetOverridden(boolean flag) { mOffsetOverridden = flag; } /** * Helper method to cancel overridden offset on Android browser controls. */ private void resetControlsOffsetOverridden() { if (!offsetOverridden()) return; if (mControlsAnimator != null) mControlsAnimator.cancel(); setOffsetOverridden(false); } /** * Helper method to run slide-in animations on the Android browser controls views. */ private void runBrowserDrivenShowAnimation() { if (mControlsAnimator != null) return; setOffsetOverridden(true); final float hiddenRatio = getBrowserControlHiddenRatio(); final int topControlHeight = getTopControlsHeight(); final int topControlOffset = getTopControlOffset(); // Set animation start value to current renderer controls offset. mControlsAnimator = ValueAnimator.ofInt(topControlOffset, 0); mControlsAnimator.setDuration( (long) Math.abs(hiddenRatio * MAX_CONTROLS_ANIMATION_DURATION_MS)); mControlsAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mControlsAnimator = null; } @Override public void onAnimationCancel(Animator animation) { updateFullscreenManagerOffsets(false, 0, 0, topControlHeight, getTopControlsMinHeight(), getBottomControlsMinHeight()); } }); mControlsAnimator.addUpdateListener((animator) -> { updateFullscreenManagerOffsets(false, (int) animator.getAnimatedValue(), 0, topControlHeight, getTopControlsMinHeight(), getBottomControlsMinHeight()); }); mControlsAnimator.start(); } // VR-related methods to make this class test-friendly. These are overridden in unit tests. protected boolean isInVr() { return VrModuleProvider.getDelegate().isInVr(); } protected boolean bootsToVr() { return VrModuleProvider.getDelegate().bootsToVr(); } protected void rawTopContentOffsetChangedForVr() { // TODO(https://crbug.com/1055619): VR wants to wait until the controls are fully hidden, as // otherwise there may be a brief race where the omnibox is rendered over the webcontents. // However, something seems to be happening in the case where the browser is launched on the // NTP, such that the top content offset is never set to 0. If we can figure out what that // is, we should be passing the TopContentOffset into this method again. VrModuleProvider.getDelegate().rawTopContentOffsetChanged(0); } @Override public void onEnterVr() { restoreControlsPositions(); } @Override public void onExitVr() { // Clear the VR-specific overrides for controls height. restoreControlsPositions(); // Show the Controls explicitly because under some situations, like when we're showing a // Native Page, the renderer won't send any new offsets. showAndroidControls(false); } /** * Destroys the FullscreenManager */ public void destroy() { mTab = null; if (mActiveTabObserver != null) mActiveTabObserver.destroy(); mBrowserVisibilityDelegate.destroy(); if (mTabFullscreenObserver != null) mTabFullscreenObserver.destroy(); if (mContentView != null) { mContentView.removeOnHierarchyChangeListener(this); mContentView.removeOnSystemUiVisibilityChangeListener(this); } VrModuleProvider.unregisterVrModeObserver(this); } @VisibleForTesting TabModelSelectorTabObserver getTabFullscreenObserverForTesting() { return mTabFullscreenObserver; } }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
cc574301a657b2057705657743ae3b21f6689763
918fd6904bfb768053e4c7d0f7f0b371ab225efa
/pl.plgrid.unicore.common/src/main/java/pl/plgrid/unicore/common/resources/StandardResources.java
002d6c7ceb0cde957fb9c5f926eb6ca2068e0c91
[]
no_license
rkluszczynski/unicore-portal-plugins
03e87da0403bb28812b357597988688ca14de59f
1836c3eef0e0702f3844fe500aea3f3255359651
refs/heads/master
2020-05-18T15:42:39.154908
2016-11-20T13:20:43
2016-11-20T13:20:43
18,237,750
0
0
null
2016-11-20T13:20:50
2014-03-29T08:53:36
Java
UTF-8
Java
false
false
1,013
java
package pl.plgrid.unicore.common.resources; import eu.unicore.portal.core.GlobalState; import pl.plgrid.unicore.portal.core.i18n.SiteResourcesI18N; /** * Enumeration of well known names of Grid resources, defined in standards (JSDL). * * @author K. Benedyczak */ public enum StandardResources { individualCPUSpeed("JSDLUtils.CPU_speed"), cpuArchitecture("JSDLUtils.CPU_architecture"), individualCPUTime("JSDLUtils.CPU_time"), individualNumberOfCPUs("JSDLUtils.CPU_per_node"), individualPhysicalMemory("JSDLUtils.RAM"), osType("JSDLUtils.OS"), totalNumberOfCPUs("JSDLUtils.total_CPUs"), totalNumberOfNodes("JSDLUtils.total_nodes"); private String msgKey; StandardResources(String msgKey) { this.msgKey = msgKey; } public String readableName() { return GlobalState.getMessage(SiteResourcesI18N.ID, msgKey); } public String description() { return GlobalState.getMessage(SiteResourcesI18N.ID, msgKey + ".description"); } }
[ "rkluszczynski@gmail.com" ]
rkluszczynski@gmail.com
0740dfac75ec614f555ae7f810db38c1ca5b55a3
4ff01e9aac5fc5b6e199ff13738e44104871c786
/General/JavaFIles/Servidor.java
749a7fceb046adfd0c4b5247403e6e7d68c0dc38
[ "MIT" ]
permissive
zazilibarra/Comunicacion
5e11cc7b8f6e63c41702feef4f15f154a935f2cb
25f935000187180339e274ff286b286da6bf6747
refs/heads/master
2021-01-13T18:36:56.638872
2020-06-06T22:18:31
2020-06-06T22:18:31
242,456,866
0
0
null
null
null
null
UTF-8
Java
false
false
1,501
java
/** * @author Alvarez Esaú * @author Ibarra Zazil * @author Torres Daniel */ package comunicacion; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.List; import java.util.logging.*; public class Servidor { //Lista para guardar los clientes conectados al servidor static List<ServidorHilo> clientes; public static void main(String[] args) { //Se inicializa lista clientes = new ArrayList<ServidorHilo>(); ServerSocket ss; System.out.print("Inicializando servidor... "); try { //Se crea una nueva instancia de ServerSocket para recibir comunicaciones //en el puerto 10578 ss = new ServerSocket(10578); System.out.println("\t[OK]"); int idCliente = 0; /*Siempre espera nuevas conexiones, cuando identifica una nueva, crea una instancia de Socket y lo agrega a la lista de clientes*/ while (true) { Socket socket; socket = ss.accept(); System.out.println("Nueva conexión entrante: "+socket); ServidorHilo nCliente = new ServidorHilo(socket, idCliente); clientes.add(nCliente); nCliente.start(); idCliente++; } } catch (IOException ex) { Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex); } } }
[ "=" ]
=
5efa0d99cd9f9ff83d97a3216d825b6c86a53c52
31e53c77d56df2f096ded87a8f0c3fd060bb68d5
/src/main/java/org/bian/dto/CRPaymentInitiationTransactionUpdateInputModel.java
7f1e56d2bd67a8baa8a55481b6df02ef562d49cc
[ "Apache-2.0" ]
permissive
bianapis/sd-payment-initiation-v2.0
c0bc406be8b3f2e38120a378476ba05563b16585
d7c2761b5b8999a0e4dc31fc0b5ad780067dcff5
refs/heads/master
2020-07-18T13:25:02.212945
2019-09-04T13:02:53
2019-09-04T13:02:53
206,253,706
0
0
null
null
null
null
UTF-8
Java
false
false
3,823
java
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRPaymentInitiationTransactionUpdateInputModelPaymentInitiationTransactionInstanceRecord; import javax.validation.Valid; /** * CRPaymentInitiationTransactionUpdateInputModel */ public class CRPaymentInitiationTransactionUpdateInputModel { private String paymentInitiationServicingSessionReference = null; private String paymentInitiationTransactionInstanceReference = null; private CRPaymentInitiationTransactionUpdateInputModelPaymentInitiationTransactionInstanceRecord paymentInitiationTransactionInstanceRecord = null; private Object paymentInitiationTransactionUpdateActionTaskRecord = null; private String updateActionRequest = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the active servicing session * @return paymentInitiationServicingSessionReference **/ public String getPaymentInitiationServicingSessionReference() { return paymentInitiationServicingSessionReference; } public void setPaymentInitiationServicingSessionReference(String paymentInitiationServicingSessionReference) { this.paymentInitiationServicingSessionReference = paymentInitiationServicingSessionReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the Payment Initiation Transaction instance * @return paymentInitiationTransactionInstanceReference **/ public String getPaymentInitiationTransactionInstanceReference() { return paymentInitiationTransactionInstanceReference; } public void setPaymentInitiationTransactionInstanceReference(String paymentInitiationTransactionInstanceReference) { this.paymentInitiationTransactionInstanceReference = paymentInitiationTransactionInstanceReference; } /** * Get paymentInitiationTransactionInstanceRecord * @return paymentInitiationTransactionInstanceRecord **/ public CRPaymentInitiationTransactionUpdateInputModelPaymentInitiationTransactionInstanceRecord getPaymentInitiationTransactionInstanceRecord() { return paymentInitiationTransactionInstanceRecord; } public void setPaymentInitiationTransactionInstanceRecord(CRPaymentInitiationTransactionUpdateInputModelPaymentInitiationTransactionInstanceRecord paymentInitiationTransactionInstanceRecord) { this.paymentInitiationTransactionInstanceRecord = paymentInitiationTransactionInstanceRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The update service call consolidated processing record * @return paymentInitiationTransactionUpdateActionTaskRecord **/ public Object getPaymentInitiationTransactionUpdateActionTaskRecord() { return paymentInitiationTransactionUpdateActionTaskRecord; } public void setPaymentInitiationTransactionUpdateActionTaskRecord(Object paymentInitiationTransactionUpdateActionTaskRecord) { this.paymentInitiationTransactionUpdateActionTaskRecord = paymentInitiationTransactionUpdateActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the update action service request * @return updateActionRequest **/ public String getUpdateActionRequest() { return updateActionRequest; } public void setUpdateActionRequest(String updateActionRequest) { this.updateActionRequest = updateActionRequest; } }
[ "team1@bian.org" ]
team1@bian.org
2384b0bf896b1b7db73fdafff933cfabd82adb59
40c4ba6396c527797795d9978b3a1673f43ea118
/src/jav/io/ReadWriteFileTest1.java
cb6dfdea6410651dbfe436db0c9f67cebe80966a
[]
no_license
RakibHasanRiyad/Object-Oriented-Programming
2c73a20dd527cfa5e11616f25eb6e85e5009e198
9c91758e6b85aa2988b1b4ddd3e6ca1842c33c92
refs/heads/master
2023-04-09T04:53:33.143686
2021-03-19T18:01:20
2021-03-19T18:01:20
335,740,409
0
0
null
null
null
null
UTF-8
Java
false
false
1,028
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 jav.io; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** * * @author HP */ public class ReadWriteFileTest1 { public static void main(String[] args) throws FileNotFoundException { // Specify a filename directly File inFile = new File("C:\\zzz\\myfile.txt"); PrintWriter out; try (Scanner in = new Scanner(inFile)) { out = new PrintWriter("text1.out.txt"); int lineNumber = 1; // Read the input and write the output while (in.hasNextLine()) { String line = in.nextLine(); out.println("/* " + lineNumber + " */ " + line); lineNumber++; } } out.close(); System.out.println("Program terminated."); } }
[ "riyadrakib@gmail.com" ]
riyadrakib@gmail.com
d4b914c1b2375b53004b728e3b7dea5e94886792
c288c58acd283e3ddb757aa931c2edb00e3afac2
/src/automatas/Monomio.java
ecea70c3b960ddeb6f9c4b522c49f945f9a1287b
[]
no_license
raullucero/InterpreteFuncionesPolinomicas
9cf9275da0d4603d450c4ac2d57c5d1f95ae0abe
651cef21f740105b60dbd10affa1bb56af992fbf
refs/heads/master
2021-01-25T08:28:39.482478
2014-12-11T01:31:16
2014-12-11T01:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
838
java
package automatas; public class Monomio { private double coeficiente; private int exponente; public Monomio() { } public Monomio(double coeficiente, int exponente) { this.coeficiente = coeficiente; this.exponente = exponente; } /** * @return the coeficiente */ public double getCoeficiente() { return coeficiente; } /** * @param coeficiente the coeficiente to set */ public void setCoeficiente(double coeficiente) { this.coeficiente = coeficiente; } /** * @return the exponente */ public int getExponente() { return exponente; } /** * @param exponente the exponente to set */ public void setExponente(int exponente) { this.exponente = exponente; } }
[ "raul.lucero27@gmail.com" ]
raul.lucero27@gmail.com
0ec13be1b9f82fac3c7f1387e2ca6eaac88afe67
b79e2b505f61a908019d31305dc5fbc87ebf4b4a
/src/main/java/com/trabalhoweb/trabalhoweb/DataConfiguration.java
2f08ae9e878d5bb91b343022474848980b66743f
[]
no_license
Ramonlobo633/TrabalhoWeb-Ramon
cb0a8180633413b0ed6a2fc80996305dcb065a5a
ff121e5b3976c5edd642816281b38b4cc3dcd6a5
refs/heads/master
2021-06-09T12:02:53.556155
2018-06-29T00:25:49
2018-06-29T00:25:49
139,081,726
0
0
null
2021-04-01T05:15:21
2018-06-29T00:25:02
HTML
UTF-8
Java
false
false
1,152
java
package com.trabalhoweb.trabalhoweb; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; @Configuration public class DataConfiguration { @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/TrabalhoF"); dataSource.setUsername("root"); dataSource.setPassword(""); return dataSource; } @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setShowSql(true); adapter.setGenerateDdl(true); adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect"); adapter.setPrepareConnection(true); return adapter; } }
[ "ramonlobo633@gmail.com" ]
ramonlobo633@gmail.com