blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
10218c8104c70c36b82ba29d2c4f069c1155a789
2649e529cd8744017852738df07f90454533def6
/offer/src/chapter2/Main9.java
7bffdccad1189889914253493dac77bf6a08ca79
[]
no_license
Parallelline1996/-Algorithm
ba67db46a8dc86149153422d3368e6d36c7f328f
a3ac715d2824b2de6f4a8e981b04557239287c3f
refs/heads/master
2020-03-28T18:36:30.473978
2019-03-28T08:01:52
2019-03-28T08:01:52
148,894,985
0
0
null
null
null
null
UTF-8
Java
false
false
844
java
package chapter2; import java.util.Stack; /* * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 * */ public class Main9 { public static void main(String[] args) { } // 这个用于进栈 private static Stack<Integer> stack1 = new Stack<Integer>(); // 这个用于出栈 private static Stack<Integer> stack2 = new Stack<Integer>(); // 实现入队列操作 public static void push(int node) { stack1.push(node); } // 出队列 public static int pop() { // 查看用于出栈的栈是否空 if (!stack2.isEmpty()) { return stack2.pop(); } else { // 当用于出栈的栈为空时,将所有用于入栈的栈里的元素全部移动到出栈的 while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } }
2a9d7c6eebe435818d6082898576ff888cb9ca9d
c7f57adb518d033ec342279c148f2647bc3ec855
/java_test_api_client/src/main/java/io/swagger/client/Configuration.java
685a94cf66f1e79c88e49b99c98efb1cb61ea7f7
[ "Apache-2.0" ]
permissive
shanjingheng/test-swagger
a299d2ceb27b7dc7d2ab0e8b45e61a7e2ac7009b
267efb8d891fcbe29b2cbf151d31ff4bc2ed062f
refs/heads/master
2021-01-21T06:53:34.408155
2018-11-16T10:11:50
2018-11-16T10:11:50
83,293,749
2
0
null
null
null
null
UTF-8
Java
false
false
1,664
java
/** * swagger 测试 * spring-boot restful接口 * * OpenAPI spec version: v1.0 * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.swagger.client; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2017-02-27T17:13:22.296+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); /** * Get the default API client, which would be used when creating API * instances without providing an API client. * * @return Default API client */ public static ApiClient getDefaultApiClient() { return defaultApiClient; } /** * Set the default API client, which would be used when creating API * instances without providing an API client. * * @param apiClient API client */ public static void setDefaultApiClient(ApiClient apiClient) { defaultApiClient = apiClient; } }
414884a7da9a2689be437faaad4ff67fe65b76e8
cbd3bd1db55ba5efeafec885efde434b58cb843d
/Algo/src/Z18_DFS.java
9fb0818f63567e18779e67a29e334940192ebfbc
[]
no_license
solomoni1/Algo
d86d80e890cea87b182e4ddb81149ce7ee151bbb
a0aee2290fa3bf054159409d502e3d2e2a3dc980
refs/heads/master
2020-12-01T04:22:29.847702
2020-02-04T10:08:16
2020-02-04T10:08:16
230,556,354
0
0
null
null
null
null
UTF-8
Java
false
false
1,411
java
import java.util.Stack; public class Z18_DFS { public static void dfs(int a) { } public static void main(String[] args) { int[][] G = { //그래프에서 연결된 정점들의 간선 정보를 저장 {}, {2,3}, {1,4,5}, {1,7}, {2,6}, {2,6}, {4,5,7}, {3,6}, }; int[] stack = new int[10]; int top = -1;// 스택의 인덱스를 관리할 변수 boolean[] visit = new boolean[8];//0은 안씀 //시작정점 하나를 결정 후 방문, 스택에 넣고, 반복을 시작 int v = 1;//시작 정점 A를 의미 System.out.print(v+" ");//방문해서 할 일 //방문 여부 체크 visit[v]=true; stack[++top] = v;//마지막 갈림길을 확인하기 위해 지나가는 정점들을 저장 //반복, 스택에서 값을 꺼내서 인접한 정점 중 방문 안한 정점을 찾아서 방문 while(top>-1) {//반복 종료: 스택이 비워지면 종료 v = stack[top];//마지막 정점을 읽어옴(삭제는 안함) int w= -1;//다음 정점, 플래그 변수 역할 for (int i = 0; i < G[v].length; i++) {//인접한 정점만큼 반복 if(!visit[G[v][i]]) { w = G[v][i];//다음 정점을 저장 System.out.print(w+" "); visit[w]=true; stack[++top]=w; break; } } if(w==-1) {//인접한 정점중 방문 안한 정점이 없음 top--; } } }// end of main }// end of class
7bbd7b856d43005acf57979819cc37e471e098dc
5c14b3ce18298145a17c7a7bbef989c6eb316724
/anr_ui_activity22/gen/com/maranr/anr_ui_activity22/R.java
52a3a4d85bbca6136271cfcec92697d401189093
[]
no_license
anr-private/workspace_old_eclipse_projects
6b07520101a7427680051a0b1070a0ef95b60281
8aa1c11e8f0538b73cfd731841852d705a54a55b
refs/heads/master
2016-09-09T17:34:02.358189
2014-10-25T20:47:48
2014-10-25T20:47:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
880
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.maranr.anr_ui_activity22; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int button1=0x7f050002; public static final int button2=0x7f050003; public static final int editText1=0x7f050001; public static final int textView1=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } }
[ "art@phantom" ]
art@phantom
45d9509064d8f1b7b8f1e0abf8cea83d9feaef71
dbe33e261ff6ab2b647f59bfa8d4e1a6f1a749fd
/src/cn/yjpt/dao/ResumeDao.java
7f0bec2000b3d872b47c7622284f67eb191b349e
[]
no_license
Zane56Git/-javaee-
19c7881c6b840b11099e3099836e569d4eee3dc3
912ee57283b1d59e9d8a88ae21459e71bf2c5cd3
refs/heads/master
2020-04-11T21:32:43.767308
2018-12-17T09:37:49
2018-12-17T09:37:49
162,109,208
2
0
null
2018-12-17T09:52:32
2018-12-17T09:52:31
null
UTF-8
Java
false
false
172
java
package cn.yjpt.dao; import cn.yjpt.bean.Resume; public interface ResumeDao { public boolean addResume(Resume resume); public Resume lookResume(int sid); }
ea6a0f1ed4ab98e71ea71d9c0bb8beb35267402c
0b68b5410cc45cbec71bc8a07a34826ae8eaef4b
/Quizmi/src/fileControllers/QuizExporter.java
c25657e1813dc21b887a0bdcb3e277954eb2bb2c
[]
no_license
BaccarellaD/Quizmi
5ade6c0d81e5510c9f8bc89d4ca447c4778d4c6f
a6357aff307ae8d844d19e5cdeca8aa9d6acab32
refs/heads/master
2021-01-22T04:10:47.855132
2017-05-28T02:17:56
2017-05-28T02:17:56
92,438,978
0
0
null
null
null
null
UTF-8
Java
false
false
200
java
package fileControllers; import java.util.ArrayList; import java.util.List; import models.Quiz; public class QuizExporter { public void exportQuizzes(List<Quiz> quizzes) { } }
73dbb2912d044091f7d89611d084b9d5c4e866e6
9af487055bb6b1e4d481c78b5a3a210e25e5d974
/src/recursiveProblemSolving/Main.java
60a7c4e09a07572bec8fef6558369d00337c09c3
[]
no_license
tfprado/Demo-Java-Programs
87138f6b046716259eb05f47b0f23c1e849b7442
768547a5c3d29fc9623b683eb424f0b176404326
refs/heads/master
2020-03-31T23:49:53.320452
2018-10-13T00:25:09
2018-10-13T00:25:09
152,671,308
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
1,933
java
package recursiveProblemSolving; import java.util.ArrayList; /**A recursive program that outputs all possibilities to put + or - or nothing * between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. * For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100. * @author Thiago Prado * */ public class Main { //this is where you can change function values private static int TARGET_SUM = 100; private static int[] VALUES = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; static ArrayList add(int digit, String sign, ArrayList branches) { for (int i = 0; i < branches.size(); i++) { branches.set(i, digit + sign + branches.get(i)); } return branches; } static ArrayList f(int sum, int number, int index) { int digit = Math.abs(number % 10); if (index >= VALUES.length) { if (sum == number) { ArrayList result = new ArrayList(); result.add(Integer.toString(digit)); return result; } else { return new ArrayList(); } } ArrayList branch1 = f(sum - number, VALUES[index], index + 1); ArrayList branch2 = f(sum - number, -VALUES[index], index + 1); int concatenatedNumber = number >= 0 ? 10 * number + VALUES[index] : 10 * number - VALUES[index]; ArrayList branch3 = f(sum, concatenatedNumber, index + 1); ArrayList results = new ArrayList(); results.addAll(add(digit, "+", branch1)); results.addAll(add(digit, "-", branch2)); results.addAll(add(digit, "", branch3)); return results; } /** * @param args */ public static void main(String[] args) { ArrayList demo = f(TARGET_SUM, VALUES[0], 1); System.out.println(demo); } }
a5c54ec666a67800d1f7f700cb4d79f75c933403
555d6b6b63dc7a1dac12ed5629307796f1bcf537
/net/minecraft/world/biome/BiomeGenDesert.java
767e8e849a6ed1bf3189650ffa336928ce8550e4
[]
no_license
CrxsCode/Minecraft-Hack-Client-1.8
179d992cc41d8564b4ed6aaccdd99e1710f7cccf
ea2901180d51806c432d7acd85ecf430f9a6167c
refs/heads/master
2020-03-19T10:12:05.310557
2018-06-06T16:01:24
2018-06-06T16:01:24
136,345,526
1
0
null
null
null
null
UTF-8
Java
false
false
1,126
java
package net.minecraft.world.biome; import java.util.Random; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenDesertWells; public class BiomeGenDesert extends BiomeGenBase { public BiomeGenDesert(int p_i1977_1_) { super(p_i1977_1_); this.spawnableCreatureList.clear(); this.topBlock = Blocks.sand.getDefaultState(); this.fillerBlock = Blocks.sand.getDefaultState(); this.theBiomeDecorator.treesPerChunk = -999; this.theBiomeDecorator.deadBushPerChunk = 2; this.theBiomeDecorator.reedsPerChunk = 50; this.theBiomeDecorator.cactiPerChunk = 10; this.spawnableCreatureList.clear(); } public void decorate(World worldIn, Random rand, BlockPos pos) { super.decorate(worldIn, rand, pos); if(rand.nextInt(1000) == 0) { int i = rand.nextInt(16) + 8; int j = rand.nextInt(16) + 8; BlockPos blockpos = worldIn.getHeight(pos.add(i, 0, j)).up(); (new WorldGenDesertWells()).generate(worldIn, rand, blockpos); } } }
80337c3f5a4d4339ff8ece3d3af7007fe66201b4
49e93f23a4f46fd3407756314bd3d674273500b4
/app/src/main/java/com/example/linearprogressbar/MainActivity.java
1bbb0ec03b90e0fe834bd019e28ff04699a1af91
[]
no_license
fsctke/linearProgress
c5fcf76c5fdd62bbf8f37730f645b86f9cb41134
449c26dab719c9e169f6c876d22d6faab96c2faf
refs/heads/master
2020-05-16T13:34:16.066097
2019-04-23T19:01:18
2019-04-23T19:01:18
183,078,761
0
0
null
null
null
null
UTF-8
Java
false
false
1,918
java
package com.example.linearprogressbar; import android.app.ProgressDialog; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { ProgressDialog dialog; Handler myHandler; Runnable myRunnable; Timer myTimer; int i = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dialog = new ProgressDialog(MainActivity.this,R.style.linearProgress); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setIndeterminate(false); //change to true for indeterminate, false for determinate dialog.setTitle("Progress Dialog"); dialog.setMessage("Please wait..."); dialog.show(); dialog.setProgress(0); dialog.setMax(100); myHandler = new Handler(); myRunnable = new Runnable() { @Override public void run() { i = i + 5; //declare i=0; outside the method and inside the class if (i <= 100) { dialog.setProgress(i); } else { myTimer.cancel(); dialog.cancel(); i = 0; } } }; myTimer = new Timer(); myTimer.schedule(new TimerTask() { @Override public void run() { myHandler.post(myRunnable); } }, 8000, 500); //dialog.cancel(); } }
de4b114b8cc354d96021caf70a6151d2b62dc048
1764b571370c8e9f7533bb657d5d0c015946da23
/springworkspace_shangguigu00/spring00/src/com/tjj/property/ReadProperties.java
8bfd371f1c2c66b39eb14eb5b232007b60c5104f
[]
no_license
tangnew/history-project
bbdea7933409ceedef9fcd997f83731fa19c115e
7cbe1374491bcf2aa672aade0f12f0d1540d1899
refs/heads/master
2020-03-19T04:12:22.370139
2018-06-02T10:42:13
2018-06-02T10:42:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
package com.tjj.property; public class ReadProperties { private String user; public void setUser(String user) { this.user = user; } public String getUser() { return user; } }
ea6af06cd2750660038429f80473cba083756121
baa2b30b7003eec034f4d1ada005b40c2e8b61a5
/RbacAuth/src/main/java/com/feagle/service/RoleService.java
b06617c0008f54297b4845af49908cb8382c3473
[]
no_license
adanac/ssm-project
d96270d560bc179ddf0a1ef536bcddc7facff837
b99788f6c4c6925776436a932abfa286edcc90eb
refs/heads/master
2021-05-12T01:13:35.662614
2018-01-15T15:25:08
2018-01-15T15:25:08
117,554,698
0
0
null
null
null
null
UTF-8
Java
false
false
2,982
java
package com.feagle.service; import com.feagle.dao.RoleDao; import com.feagle.dao.RoleFunctionDao; import com.feagle.entity.Role; import com.feagle.entity.RoleFunction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.List; /** * Created by Feagle on 2017/6/5. */ @Service public class RoleService { @Autowired private RoleDao roleDAO; @Autowired private RoleFunctionDao roleFunctionDAO; /** * 保存角色信息,同时保存角色对应的功能 * @param role 角色 * @param roleFunctions 角色对应的功能(即角色功能的关联关系) */ public List<Long> addRole(Role role, Collection<RoleFunction> roleFunctions) { roleDAO.saveRole(role); roleFunctions.forEach((rf) -> rf.setRoleId(role.getId())); List<Long> longList = roleFunctionDAO.saveRoleFunctionsReturnKey(roleFunctions); return longList; } /** * 修改角色信息,同时修改角色对应的功能 * @param role 角色 * @param roleFunctions 角色对应的功能(即角色功能的关联关系) */ public void editRole(Role role, Collection<RoleFunction> roleFunctions) { roleDAO.updateRole(role); roleFunctionDAO.deleteByRoleId(role.getId()); roleFunctions.forEach((rf) -> rf.setRoleId(role.getId())); roleFunctionDAO.saveRoleFunctions(roleFunctions); } /** * 根据 ID 删除角色 * @param roleId 角色 ID */ public void deleteRole(Long roleId) { roleDAO.deleteRole(roleId); roleFunctionDAO.deleteByRoleId(roleId); } /** * 分页查询角色信息 * @param page 当前页码 * @param size 每页记录数 * @return 角色集合 */ public List<Role> getRoles(int page, int size) { List<Role> roles = roleDAO.findRoles(page, size); roles.forEach((role) -> { List<RoleFunction> roleFunctions = roleFunctionDAO.findRoleFunctionsByRoleId(role.getId()); StringBuilder functionIds = new StringBuilder(); roleFunctions.forEach((rf) -> { functionIds.append(rf.getFunctionId()).append(","); }); if(functionIds.length() > 1) { role.setFunctionIds(functionIds.deleteCharAt(functionIds.length() - 1).toString()); } }); return roles; } /** * 根据 ID 集合查询角色集合 * @param ids 角色 ID 集合 * @return 角色集合 */ public List<Role> getRoles(Collection<Long> ids) { return roleDAO.findRoles(ids); } /** * 根据角色 ID 查询角色功能对应关系 * @param roleId 角色 ID * @return 角色功能对应关系 */ public List<RoleFunction> getRoleFunctions(Long roleId) { return roleFunctionDAO.findRoleFunctionsByRoleId(roleId); } }
8e1af4c1c1d35d0b9be1c77714129b1ce2119173
9900ad9b87a38388a4fc480b9cd9ebeb20ae620e
/BE/src/main/java/com/codesquad/team10/todo/service/AuthService.java
1f93b792c64ebd81db8f1a90c12d688603225172
[]
no_license
codesquad-member-2020/todo-10
a81b8b9c6db7df0dc23d7480f48e2e1acde13699
65392bb0a90204c1de8e3484f65b04c080e05aad
refs/heads/dev
2021-05-23T15:55:16.399731
2020-07-22T06:10:05
2020-07-22T06:10:05
253,369,582
4
1
null
2020-07-22T06:10:06
2020-04-06T01:40:22
Swift
UTF-8
Java
false
false
1,742
java
package com.codesquad.team10.todo.service; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.codesquad.team10.todo.entity.User; import com.codesquad.team10.todo.exception.custom.UserNotFoundException; import com.codesquad.team10.todo.repository.UserRepository; import com.codesquad.team10.todo.util.JWTUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Service public class AuthService { private static final Logger logger = LoggerFactory.getLogger(AuthService.class); private UserRepository userRepository; public AuthService(UserRepository userRepository) { this.userRepository = userRepository; } public boolean verifyUser(User loginUser, HttpServletResponse response) { User dbUser = userRepository.findByName(loginUser.getName()).orElseThrow(UserNotFoundException::new); if (!dbUser.confirmPassword(loginUser)) return false; logger.debug("board id: {}", dbUser.getBoard()); response.setHeader(HttpHeaders.AUTHORIZATION, JWTUtils.createTokenByUser(dbUser)); return true; } public boolean checkAuthorization(HttpServletRequest request) { try { User userData = JWTUtils.getUserFromJWT(request.getHeader(HttpHeaders.AUTHORIZATION)); request.setAttribute("user", userData); } catch (SignatureVerificationException | JWTDecodeException | NullPointerException e) { return false; } return true; } }
8c66ff97cab4f84f0ad2219f5b44b666b598f8fd
4e1b2e68357ba88cdffb81a2f47153288724062a
/src/main/java/com/learning/jhipster/web/rest/errors/FieldErrorVM.java
e21967c6bfc75f0e180141412d17975cab06b480
[]
no_license
rishisha19/jhipster-app
0df7c847b8a8295d2598408bda0761194559692f
53d4157f96be0ef17914e643097ca3696881800e
refs/heads/master
2022-12-11T12:15:18.819501
2019-11-15T07:23:26
2019-11-15T07:23:26
221,865,647
0
0
null
2022-12-10T09:02:01
2019-11-15T07:11:28
Java
UTF-8
Java
false
false
653
java
package com.learning.jhipster.web.rest.errors; import java.io.Serializable; public class FieldErrorVM implements Serializable { private static final long serialVersionUID = 1L; private final String objectName; private final String field; private final String message; public FieldErrorVM(String dto, String field, String message) { this.objectName = dto; this.field = field; this.message = message; } public String getObjectName() { return objectName; } public String getField() { return field; } public String getMessage() { return message; } }
0b6e42ce12f280c7f5170aaf72096e8f31e102ce
1818870fa6a216c585b1bfe4c2f6fd80853c61ed
/src/main/java/com/chang/happyshopping/controller/LoginController.java
574b23eb77f24178ee1e7b2b89064f0a51945b5d
[]
no_license
evenstars/HighConcurrencyShopping
4fa980470d7ba7cebd645da6ba7616a9d2fed594
f89789f63dd2bb17ee84e5b9660bb947553b35c2
refs/heads/master
2022-07-16T07:03:10.358612
2019-12-22T22:25:38
2019-12-22T22:25:38
227,732,877
6
0
null
2022-06-21T02:26:08
2019-12-13T01:51:19
Java
UTF-8
Java
false
false
2,743
java
package com.chang.happyshopping.controller; import com.chang.happyshopping.domain.User; import com.chang.happyshopping.redis.RedisService; import com.chang.happyshopping.redis.UserKey; import com.chang.happyshopping.result.CodeMsg; import com.chang.happyshopping.result.Result; import com.chang.happyshopping.service.HappyShoppingUserService; import com.chang.happyshopping.service.UserService; import com.chang.happyshopping.utils.ValidatorUtil; import com.chang.happyshopping.vo.LoginVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; @Controller @RequestMapping("/login") public class LoginController { private static Logger log = LoggerFactory.getLogger(LoginController.class); @Autowired UserService userService; @Autowired RedisService redisService; @Autowired HappyShoppingUserService happyShoppingUserService; @RequestMapping("/to_login") public String toLogin(){ return "login"; } @RequestMapping("/do_login") @ResponseBody public Result<Boolean> doLogin(HttpServletResponse response, @Valid LoginVo loginVo){ log.info(loginVo.toString()); //login happyShoppingUserService.login(response,loginVo); return Result.success(true); } @RequestMapping("/hello") @ResponseBody public Result<String> hello(){ return Result.success("hello chang"); } @RequestMapping("/error") @ResponseBody public Result<String> error(){ return Result.error(CodeMsg.SERVER_ERROR); } @RequestMapping("/thymeleaf") public String thymeleaf(Model model){ model.addAttribute("name","chang"); return "hello"; } @RequestMapping("/db/get") @ResponseBody public Result<User> dbGet(){ User user = userService.getById(1); return Result.success(user); } @RequestMapping("/db/tx") @ResponseBody public Result<Boolean> dbTx(){ boolean res=userService.tx(); return Result.success(res); } @RequestMapping("/redis/get") @ResponseBody public Result<User> redisGet(){ User user = redisService.get(UserKey.getById,"1",User.class); return Result.success(user); } @RequestMapping("/redis/set") @ResponseBody public Result<Boolean> redisSet(){ User user = new User(); user.setId(1); user.setName("1111"); redisService.set(UserKey.getById,""+1,user); return Result.success(true); } }
cbc75cd2899ce884ac402891e52e091cb8b72278
43ddacea6d1722a8371337c3664e210f4d51dbce
/src/DBPLResponse.java
74fb529609104ecda15e9136de5dc7bda9abf020
[]
no_license
saurabhgoyal12/Sample-JAXB
11f2581d3677fa9912aba235bbc3872f104bb0aa
6f7014e2bdde1ea17aba80b5bd369e6c3b6a5ee3
refs/heads/master
2021-05-12T14:45:05.828187
2018-01-10T14:04:00
2018-01-10T14:04:00
116,964,762
0
0
null
null
null
null
UTF-8
Java
false
false
489
java
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "response") public class DBPLResponse { DBPLResponseHeader header; private DBPLResponseDetail detail; public DBPLResponseHeader getHeader() { return header; } public void setHeader(DBPLResponseHeader header) { this.header = header; } public DBPLResponseDetail getDetail() { return detail; } public void setDetail(DBPLResponseDetail detail) { this.detail = detail; } }
c9e2714a27e54f8f28d54812bdbd03d7cd66fa7a
d704cfce52af46e11489fd2324634d8f4cf3089b
/src/main/java/com/example/alexthbot/fab/actions/ActionAny.java
e1ecce250c32454973b59fff3fc34d6955cbbb4d
[]
no_license
Vincerenko/TG
397609d31c4cdd18a77e6bf005c74a95b9967538
34fa3996185e665bd988cfff3443b1237f44b829
refs/heads/main
2023-07-17T09:23:38.249746
2021-08-31T09:54:14
2021-08-31T09:54:14
398,987,842
0
0
null
null
null
null
UTF-8
Java
false
false
1,059
java
package com.example.alexthbot.fab.actions; import com.example.alexthbot.fab.actions.parent.Action; import com.example.alexthbot.fab.actions.router.ActionEnum; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.bots.AbsSender; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; @Component public class ActionAny extends Action { @Override public void action(Update update, AbsSender absSender) { String chatId = update.getMessage().getChatId().toString(); SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(chatId); sendMessage.setText("Неизвестная операция"); try { absSender.execute(sendMessage); } catch (TelegramApiException e) { e.printStackTrace(); } } @Override public ActionEnum getKey() { return ActionEnum.ANY; } }
a26226eb17c4834742107ea93d21f843a0a09c99
6bfee90cc5225a225043bd1b59b5334495c70b11
/src/main/java/com/test/campaingapi/repository/CampaignRepository.java
2d47935ddf6b52389c02ef8b9fe5296ee01fde29
[]
no_license
renanpallin/spring-campaign-teams
ddd78f7fa145c2a508bd72aa3d2e68d429916141
d96ec2ba8ce191fb923b3d03f323004b09a976bf
refs/heads/master
2021-01-22T18:38:24.597492
2017-08-21T05:58:45
2017-08-21T05:58:45
100,760,141
2
0
null
null
null
null
UTF-8
Java
false
false
1,205
java
package com.test.campaingapi.repository; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashSet; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.test.campaingapi.model.Campaign; public interface CampaignRepository extends CrudRepository<Campaign, Long> { @Query("FROM Campaign c WHERE c.name=:campaingName") public Iterable<Campaign> findByName(@Param("campaingName") String campaingName); @Query("FROM Campaign c WHERE c.start > CURRENT_DATE AND c.end < CURRENT_DATE") public Iterable<Campaign> findActives(); @Query("FROM Campaign c WHERE c.start > CURRENT_DATE") public Iterable<Campaign> findOnGoingCampaigns(); @Query("FROM Campaign c WHERE :start BETWEEN c.start AND c.end OR :end BETWEEN c.start AND c.end ORDER BY c.createdAt DESC") public ArrayList<Campaign> findOnGoingCampaignsByDate(@Param("start") LocalDate start, @Param("end") LocalDate end); @Query("SELECT c FROM Campaign c JOIN c.team t WHERE t.id = :id AND c.start > CURRENT_DATE") public HashSet<Campaign> findOnGoingByTeamId(@Param("id") long id); }
0c78079dba133311ea24eace49d62cd78336b376
d9ecd163cf58571da7ca653d3f924b89e5a625b7
/app/src/main/java/br/usjt/ftce/progmulti/meuprimeiroappsi/MainActivity.java
123ff1a7c1d36e38e99d27ce32b179ad0023c87f
[]
no_license
AccelEight/MeuPrimeiroAppSI
16e5a0420598d029fe532d46f450dce0c10c0ef7
a5372965f98fe74c2a345523a69d6debb64af045
refs/heads/master
2021-01-24T16:33:55.762367
2018-03-06T20:30:11
2018-03-06T20:30:11
123,203,063
0
0
null
null
null
null
UTF-8
Java
false
false
589
java
package br.usjt.ftce.progmulti.meuprimeiroappsi; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void sendMessage(View view) { EditText text = (EditText)findViewById(R.id.edit_message); String menssagem = text.getText().toString(); System.out.println(menssagem); } }
85cb5afaea6d81c78c82027d87e4195f44a2d0ac
1664956b521388037e72f07b487aad9cc0b49b59
/src/main/java/de/userlarsb/pactDemo/someConsumer/ConsumerResponseData.java
35db1800f87dc3dc12ea0a956f9e551a7a3c38be
[]
no_license
userlarsb/pact-demo
9e0cb468a40acf7a1b5e7e3f6e02f5d69e0a3a02
c418633527fce6966592394f8077bab2feb7dd34
refs/heads/main
2023-02-02T21:42:20.237473
2020-12-23T14:20:19
2020-12-23T14:20:19
323,721,567
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package de.userlarsb.pactDemo.someConsumer; public class ConsumerResponseData { private String response; public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public ConsumerResponseData() {} public ConsumerResponseData(String response) { this.response = response; } }
556c9b297edb6c1b1939530522e68efb1d408992
e37792e3770390718c824d6da927a47092ae26f3
/src/test/java/com/github/kilianB/MathUtilTest.java
09ea83d33a657e738797d129897ff99cd1a34e25
[ "MIT" ]
permissive
codacy-badger/UtilityCode
7414c933675bc15ac19e4c551640798be67066e8
9ae40b15c0fb2c3f352d1402c333c4c6fd0c8d69
refs/heads/master
2020-04-13T16:42:08.905898
2018-12-25T02:11:06
2018-12-25T02:11:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,911
java
package com.github.kilianB; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; /** * @author Kilian * */ class MathUtilTest { @Nested class ClosestDivisibleInteger{ @Test void findClosestDivisibleIntegerTest() { // Error assertThrows(java.lang.ArithmeticException.class, () -> { MathUtil.findClosestDivisibleInteger(0, 0); }); } @Test void findClosestDivisibleIntegerIdentityTest() { assertEquals(1, MathUtil.findClosestDivisibleInteger(1, 1)); } @Test void findClosestDivisibleIntegerPossibleDivisionTest() { assertEquals(4, MathUtil.findClosestDivisibleInteger(4, 2)); } @Test void findClosestDivisibleIntegerUpperBoundTest() { assertEquals(9, MathUtil.findClosestDivisibleInteger(8, 3)); } @Test void findClosestDivisibleIntegerLowerBoundTest() { assertEquals(8, MathUtil.findClosestDivisibleInteger(9, 4)); } @Test void findClosestDivisibleIntegerEquidistantTest() { // 3 to each side 12 - 15 - 18 assertEquals(18, MathUtil.findClosestDivisibleInteger(15, 6)); } @Test void findClosestDivisibleIntegerIdentityNegativeDivisorTest() { assertEquals(1, MathUtil.findClosestDivisibleInteger(1, -1)); } @Test void findClosestDivisibleIntegerIdentityNegativeDivisorTest2() { assertEquals(2, MathUtil.findClosestDivisibleInteger(2, -2)); } @Test void findClosestDivisibleIntegerPossibleDivisionNegativeDivisorTest() { assertEquals(4, MathUtil.findClosestDivisibleInteger(4, -2)); } @Test void findClosestDivisibleIntegerUpperBoundNegativeDivisorTest() { assertEquals(12, MathUtil.findClosestDivisibleInteger(11, -3)); } @Test void findClosestDivisibleIntegerLowerBoundNegativeDivisorTest() { assertEquals(6, MathUtil.findClosestDivisibleInteger(7, -3)); } @Test void findClosestDivisibleIntegerIdentityNegativeDividendTest() { assertEquals(-1, MathUtil.findClosestDivisibleInteger(-1, 1)); } @Test void findClosestDivisibleIntegerIdentityNegativeDividendTest2() { assertEquals(-2, MathUtil.findClosestDivisibleInteger(-2, 2)); } @Test void findClosestDivisibleIntegerPossibleDivisionNegativeDividendTest() { assertEquals(-4, MathUtil.findClosestDivisibleInteger(-4, 2)); } @Test void findClosestDivisibleIntegerLowerBoundNegativeDividendTest() { assertEquals(-12, MathUtil.findClosestDivisibleInteger(-11, 3)); } @Test void findClosestDivisibleIntegerUpperBoundNegativeDividendTest() { assertEquals(-6, MathUtil.findClosestDivisibleInteger(-7, 3)); } @Test void findClosestDivisibleIntegerEquidistantNegativeDividendTest() { // 3 to each side 12 - 15 - 18 assertEquals(18, MathUtil.findClosestDivisibleInteger(15, 6)); } } @Nested class ClampNumber{ @Test void clampNumberIdentity() { assertEquals(0,(int)MathUtil.clampNumber(0,0,0)); } @Test void clampNumberExactUpper() { assertEquals(1,(int)MathUtil.clampNumber(1,0,1)); } @Test void clampNumberExactLower() { assertEquals(0,(int)MathUtil.clampNumber(0,0,1)); } @Test void clampNumberUpper() { assertEquals(1,(int)MathUtil.clampNumber(2,0,1)); } @Test void clampNumberLower() { assertEquals(0,(int)MathUtil.clampNumber(-1,0,1)); } @Test void clampNumberInBetween() { assertEquals(2,(int) MathUtil.clampNumber(0,2,4)); } } @Nested class FractionalPart{ @Test void fractionalNothing() { assertEquals(0,MathUtil.getFractionalPart(4d)); } @Test void fractionalDefined() { assertEquals(0.123,MathUtil.getFractionalPart(4.123d),1e-6); } @Test void fractionalDefinedNegative() { assertEquals(-0.123,MathUtil.getFractionalPart(-4.123d),1e-6); } } @Nested class DoubleEquals{ @Test void isDoubleEqualsValid() { assertTrue(MathUtil.isDoubleEquals(1d,1d,0)); } @Test void isDoubleEqualsInvalid() { assertFalse(MathUtil.isDoubleEquals(2d,1d,0)); } @Test void isDoubleEqualsNegativeValid() { assertTrue(MathUtil.isDoubleEquals(-1d,-1d,0)); } @Test void isDoubleEqualsNegativeInValid() { assertFalse(MathUtil.isDoubleEquals(-2d,1d,0)); } @Test void isDoubleEqualsValidEpisolon() { assertTrue(MathUtil.isDoubleEquals(1.2d,1d,1)); } @Test void isDoubleEqualsNegativeValidEpisolon() { assertTrue(MathUtil.isDoubleEquals(-1.2d,-1d,1)); } @Test void isDoubleEqualsInvalidEpsilon() { assertFalse(MathUtil.isDoubleEquals(2.2d,2d,0.1d)); } } @Nested class IsNumeric{ @Test void intPrimitive() { assertTrue(MathUtil.isNumeric(1)); } @Test void bytePrimitive() { assertTrue(MathUtil.isNumeric((byte)1)); } @Test void booleanPrimitive() { assertFalse(MathUtil.isNumeric(false)); } @Test void longPrimitive() { assertTrue(MathUtil.isNumeric(1l)); } @Test void floatPrimitive() { assertTrue(MathUtil.isNumeric(1f)); } @Test void doublePrimitive() { assertTrue(MathUtil.isNumeric(1d)); } @Test void charPrimitive() { assertFalse(MathUtil.isNumeric('c')); } @Test void string() { assertFalse(MathUtil.isNumeric("HelloWorld")); } @Test void object() { assertFalse(MathUtil.isNumeric(new Object())); } //Numeric Objects @Test void Byte() { assertTrue(MathUtil.isNumeric(Byte.valueOf((byte)1))); } @Test void Boolean() { assertFalse(MathUtil.isNumeric(Boolean.TRUE)); } @Test void Long() { assertTrue(MathUtil.isNumeric(Long.valueOf(0))); } @Test void Float() { assertTrue(MathUtil.isNumeric(Float.valueOf(0.2f))); } @Test void Double() { assertTrue(MathUtil.isNumeric(Double.valueOf(0.1d))); } @Test void Character() { assertFalse(MathUtil.isNumeric(Character.valueOf('c'))); } } @Nested class Log{ @Test void valid() { assertEquals(2,MathUtil.log(4,2)); } @Test void validFractional() { assertEquals(2.321928094887362347870319429489390175864831393024580612054,MathUtil.log(5,2),1e-15); } @Test void logBase10() { assertEquals(1.176091259055681242081289008530622282431938982728587323519,MathUtil.log(15,10),1e-15); } @Test void validBase3() { assertEquals(1.630929753571457437099527114342760854299585640131880427870,MathUtil.log(6,3),1e-15); } @Test void zeroValue() { assertEquals(Double.NEGATIVE_INFINITY,MathUtil.log(0,1)); } @Test void negativeValue() { assertEquals(Double.NaN,MathUtil.log(-1,1)); } @Test void zeroBase() { assertEquals(Double.NaN,MathUtil.log(10,0)); } @Test void nanValue() { assertEquals(Double.NaN,MathUtil.log(Double.NaN,2)); } @Test void nanBase() { assertEquals(Double.NaN,MathUtil.log(3,Double.NaN)); } } @Nested class TriangularNumber{ @Test void one() { assertEquals(1,MathUtil.triangularNumber(1)); } @Test void two() { assertEquals(3,MathUtil.triangularNumber(2)); } @Test void three() { assertEquals(6,MathUtil.triangularNumber(3)); } @Test void four() { assertEquals(10,MathUtil.triangularNumber(4)); } @Test void five() { assertEquals(15,MathUtil.triangularNumber(5)); } @Test void six() { assertEquals(21,MathUtil.triangularNumber(6)); } } @Nested class FitGaussian { //TODO more test cases void zero() { assertEquals(0,MathUtil.fitGaussian(0,1,0)); } void meanMove() { assertEquals(0,MathUtil.fitGaussian(1,1,1)); } } @Nested class NormalizeValue{ @Test void testLowerZeroIncrease() { assertEquals(0,MathUtil.normalizeValue(0,0,1,0,10)); } @Test void testLowerZeroDecrease() { assertEquals(0,MathUtil.normalizeValue(0,0,10,0,1)); } @Test void testLowerIncrease() { assertEquals(1,MathUtil.normalizeValue(1,1,2,1,10)); } @Test void testLowerDecrease() { assertEquals(1,MathUtil.normalizeValue(1,1,10,1,2)); } @Test void testHigherIncrease() { assertEquals(10,MathUtil.normalizeValue(1,0,1,0,10)); } @Test void testHigherDecrease() { assertEquals(1,MathUtil.normalizeValue(5,0,5,0,1)); } @Test void increase() { assertEquals(5,MathUtil.normalizeValue(1,0,2,0,10)); } @Test void decrease() { assertEquals(1,MathUtil.normalizeValue(5,0,10,0,2)); } } @Nested class LowerShiftBitMask{ @Test void zeroMask(){ assertEquals(-1,MathUtil.getLowerShiftBitMask(0x0)); } @Test void zeroOffset(){ assertEquals(0,MathUtil.getLowerShiftBitMask(0x1)); } @Test void zeroOffsetNegative(){ assertEquals(0,MathUtil.getLowerShiftBitMask(-1)); } @Test void oneBitOffset(){ assertEquals(1,MathUtil.getLowerShiftBitMask(0x2)); } @Test void oneBitOffsetNegative(){ assertEquals(1,MathUtil.getLowerShiftBitMask(-2)); } @Test void twoBitOffset(){ assertEquals(2,MathUtil.getLowerShiftBitMask(0x4)); } //RGB @Test void eightBitOffset(){ assertEquals(8,MathUtil.getLowerShiftBitMask(0x0000ff00)); } @Test void sixteenBitOffset(){ assertEquals(16,MathUtil.getLowerShiftBitMask(0x00ff0000)); } @Test void twentyFourBitOffset(){ assertEquals(24,MathUtil.getLowerShiftBitMask(0xff000000)); } @Test void mixedBitOffset(){ assertEquals(0,MathUtil.getLowerShiftBitMask(0xff0000ff)); } } }
83a7637063f189d930904e4f6c64dddfd8b8274b
c55e44881109ae91c50f8a91b22f93ebe7dc1b03
/src/model/Map/Terrain/Ground.java
d713504afcee098fdc105cfc8342d5a0ab3f1ae1
[]
no_license
TylerBarkley/OOP2ElectricBoogaloo
a01f808963b7ddebde79e2d5307dca8ab886d598
7a304e44d2588b66eeff8debc78c32a3b510b7e3
refs/heads/master
2021-01-22T08:19:57.041208
2017-03-15T17:33:28
2017-03-15T17:33:28
81,892,860
0
0
null
2017-03-15T16:14:33
2017-02-14T01:59:21
Java
UTF-8
Java
false
false
362
java
package model.Map.Terrain; import model.TerrainVisitor; public class Ground extends Terrain { private static Ground terrain; private Ground(){} public static Ground getGroundTerrain(){ if(terrain==null) { terrain=new Ground(); } return terrain; } @Override public void visitTerrain(TerrainVisitor tv) { tv.visitGroundTerrain(); } }
2291409005966729f1f54356265c07acc0549f80
6b5c7eb307c27742a6082b653c3934b7e7800910
/src java/ArrayLists.java
9595903ac44f5f1637adc0897839ebf375a42be5
[]
no_license
andreamalin/HT-4
576179a8d8ebe7e2bab86aaea60a88e88e0b5e4e
f796fca5f7c3f0c9c12ddd6ee5d778787e8602aa
refs/heads/master
2021-01-15T02:04:23.184108
2020-02-27T02:56:53
2020-02-27T02:56:53
242,843,098
0
0
null
null
null
null
UTF-8
Java
false
false
1,038
java
/********************************************************** *ArrayList.java Fecha de creacion: 24/02/2020 * Ultima fecha de modificación: 24/02/2020 * *Interfaz que contiene los metodos que puede usar un ArrayList * *@author Andrea Amaya #19357 *@author Carlos Raxtum #19721 **********************************************************/ import java.util.*; public class ArrayLists<E> extends Stack<E>{ /* CODIGO ADAPTADO DE: ADT Stack en Java Extraido de: https://uvg.instructure.com/courses/13715/pages/adt-stack-en-java?module_item_id=195245 */ protected ArrayList<E> expresion = new ArrayList<E>(); //Post: Agrega un dato al comienzo del arraylist public void push(E dato){ expresion.add(dato); } //Post: Remueve el ultimo dato del arraylist public E pop(){ return expresion.remove(size()-1); } //Post: Retorna el ultimo dato del arraylist public E peek(){ return expresion.get(size()-1); } //Post: Retorna el entero del tamano del arraylist public int size(){ return expresion.size(); } }
6b1f39139316d777a85a247688722b7f1c229ab8
3df14ed4c6b32e3671910632d1606695fec149f3
/M1905AndroidV3.0/src/com/m1905/mobile/service/ConnectionChangeReceiver.java
79ee97dbb9c5effcdaff0e02ccc1fd667e932634
[]
no_license
junges521/TYMobil
e06f0e971f08cd3b243af0a5be27d296d4655f34
daea88d3eaad5724d52e1f39f2f1176f87b45588
refs/heads/master
2020-06-17T21:20:55.600747
2015-07-12T08:32:40
2015-07-12T08:32:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,097
java
package com.m1905.mobile.service; import com.m1905.mobile.common.TianyiContent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) { System.out.println("网络不可用"); //改变背景或者 处理网络的全局变量 }else { //改变背景或者 处理网络的全局变量 if(TianyiContent.token.equals("")){ TianyiContent.tokenInit(context); } } } }
9c9eaf2c48db949adb940b37193934e869cc41cc
a915d83d3088d355d90ba03e5b4df4987bf20a2a
/src/Applications/jetty/websocket/api/annotations/OnWebSocketClose.java
f43d33c8954060de5fab164263afce9e14aec659
[]
no_license
worldeditor/Aegean
164c74d961185231d8b40dbbb6f8b88dcd978d79
33a2c651e826561e685fb84c1e3848c44d2ac79f
refs/heads/master
2022-02-15T15:34:02.074428
2019-08-21T03:52:48
2019-08-21T15:37:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,471
java
// // ======================================================================== // Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package Applications.jetty.websocket.api.annotations; import Applications.jetty.websocket.api.Session; import java.lang.annotation.*; /** * Annotation for tagging methods to receive connection close events. * <p> * Acceptable method patterns.<br> * Note: <code>methodName</code> can be any name you want to use. * <ol> * <li><code>public void methodName(int statusCode, String reason)</code></li> * <li><code>public void methodName({@link Session} session, int statusCode, String reason)</code></li> * </ol> */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(value = {ElementType.METHOD}) public @interface OnWebSocketClose { /* no config */ }
bab52ebca1949ed32929dd6aeea95f080b048812
cd0f8d4a01a404dccb52a79ab17d26925612d620
/vehicle/src/main/java/com/vehicle/controller/HomeController.java
73e86c6398d00fe7001923fd4324fba186063fbe
[]
no_license
qquangz066/eureka-microservice
1bc778f0c97a97ba8c42c3702418910cc55aacc4
5a951912901c7188d2674a00adb46bde8ba00059
refs/heads/master
2020-05-05T03:00:06.122605
2019-04-05T09:56:35
2019-04-05T09:56:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
778
java
package com.vehicle.controller; import com.vehicle.feign.UaaClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; @RestController public class HomeController { @Autowired UaaClient uaaClient; @GetMapping("/health") String get(HttpServletRequest request) { return "vehicle: " + request.getServerPort(); } @GetMapping("/test") String test(HttpServletRequest request) { return "vehicle test : " + request.getServerPort(); } @GetMapping("/call-uaa") String test2(HttpServletRequest request) { return uaaClient.test(); } }
47dc1ccf8a54d17fc55a9f89743a6dcfa5f6a1f8
95e8abd9fe2e5a9706bc3f16cc4671955eeaad87
/src/main/java/ua/com/owu/dao/UserDao.java
1373b4c608e23e7272f4bb816cf1b0e9aee52dac
[]
no_license
TBones123/springStart
733dc5e3a8c3aa3cf19baff61b1d758624a3f0b4
4909b8e64795156c90cdf3965e3d81ff460fad1a
refs/heads/master
2020-03-16T02:53:53.611640
2018-05-07T14:50:03
2018-05-07T14:50:03
132,475,345
0
0
null
null
null
null
UTF-8
Java
false
false
1,246
java
package ua.com.owu.dao; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import ua.com.owu.models.User; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContext; @Repository public class UserDao { // private EntityManagerFactory entityManagerFactory; @PersistenceContext private EntityManager entityManager; public UserDao() { } public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } // public EntityManagerFactory getEntityManagerFactory() { // return entityManagerFactory; // } // // public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { // this.entityManagerFactory = entityManagerFactory; // } @Transactional public void save(User user){ // EntityManager entityManager = entityManagerFactory.createEntityManager(); // entityManager.getTransaction().begin(); entityManager.persist(user); // entityManager.getTransaction().commit(); // entityManager.close(); } }
448debbb1e6288dd6ee0433658d0a234d84d61bd
ca30af78d74bce6c601fd97d2bbb51d03fe4281b
/src/main/java/com/ganesh/learn/more/java/Main1.java
0ea312ed5e8339bce8411155251ef50f14bf8496
[]
no_license
ganesh-sg/morejava
198affeb11dcac6d059db3f357bcbbab155276c9
799fef8a1678a4d3d6562f822027e35f3bcfeffd
refs/heads/master
2020-06-11T03:36:35.624222
2019-06-26T06:11:25
2019-06-26T06:11:25
193,840,370
0
0
null
null
null
null
UTF-8
Java
false
false
1,178
java
package com.ganesh.learn.more.java; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; public class Main1 { public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { Coffee coffee = new Coffee("Coffee taste", "Lot of sugar"); //Tea tea = new Tea(); //BeanUtils.copyProperties(tea, coffee); PropertyUtils.setProperty(coffee, "sugar", "Added Sugar"); System.out.println(coffee); // List<?> someList = new ArrayList<String>(); // someList.add(new Object()); // // List<Object> someObjectList = new ArrayList<>(); // someObjectList.add("One"); List<String> listOfStrings = new ArrayList<>(); listOfStrings.add("One"); listOfStrings.add("Two"); listOfStrings.add("Three"); Iterator<String> iterator = listOfStrings.iterator(); boolean removed = false; } }
9290eae3d1ff01664d8774f3f534607afe5a8b9b
4bb96a86442ba1eb8567f6099d3ae05c5428add2
/demo/src/DP/P122.java
cca27b109470d517a5b8fffd5e573bc623839265
[]
no_license
yimfeng/LeetCode
7550f9b6a50493d369799d157f1a94e1e8b6e3f4
1cbf807d1d2c763ca8d6a8d079c9bbe383aa30d1
refs/heads/master
2023-03-14T14:17:41.293270
2021-03-05T07:11:42
2021-03-05T07:11:42
271,497,949
1
0
null
null
null
null
UTF-8
Java
false
false
1,137
java
package DP; /** * @author: yimfeng * @date: 2020-12-26 1:00 下午 * @desc: 买卖股票的最佳时机 II */ public class P122 { public static void main(String[] args) { } public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) return 0; int len = prices.length; int[][] dp = new int[len][2]; dp[0][0] = 0; dp[0][1] = -prices[0]; for (int i = 1; i < len; i++) { dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]); dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]); } return dp[len-1][0]; } // 优化算法 public int max_Profit(int[] prices){ if(prices == null || prices.length == 0) return 0; int price0 = 0, price1 = -prices[0]; int len = prices.length; for (int i = 1; i < len; i++) { int newProfit0 = Math.max(price0, price1 + prices[i]); int newProfit1 = Math.max(price1, price0 - prices[i]); price0 = newProfit0; price1 = newProfit1; } return price0; } }
6f2a43456181fdb0a9d5e8da320a9f7290c6ff9c
16a40b0e36c86d59c2481937d030a2468f38f543
/src/main/java/com/fiap/facade/CarroFacade.java
4e6a783a44731a5902a6b0d49791a7ea574ecc81
[]
no_license
rafarcm/simcar
a50d80b544333029a0c0267f457b5844a7649869
a8b47dd14690ca1d255203564d675323de637483
refs/heads/master
2021-01-24T03:38:10.767823
2020-05-27T14:27:12
2020-05-27T14:27:12
86,176,473
0
0
null
null
null
null
UTF-8
Java
false
false
1,093
java
package com.fiap.facade; import com.fiap.entity.CarroEntity; import com.fiap.entity.UsuarioEntity; import com.fiap.repository.CarroRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by logonrm on 25/03/2017. */ @RestController @RequestMapping("/carro") public class CarroFacade { @Autowired CarroRepository repository; @RequestMapping(value = "/criar", method = RequestMethod.POST) public String criar(@RequestBody CarroEntity carro){ repository.save(carro); return "Carro criado!"; } @RequestMapping("/listar") public List<CarroEntity> listar(){ return repository.findAll(); } @RequestMapping("/buscar") public CarroEntity buscar(Integer placa){ return repository.findOne(Long.valueOf(placa)); } }
d215d7eb6026c6490832b885f5f518042ff07523
e2e32e5f30250bbac0932b02609567d06b3f3e6c
/src/c04_collision/Missile.java
578b144a7682ab5cc9d09f1fea51e8c5389d7f51
[]
no_license
codingbird1234/zetcode
95e73d4219fc24bb823c47beca10f38cac3539ec
aa8659cc855208ae710adcac87809e61c154e847
refs/heads/master
2023-06-02T18:05:55.889840
2019-05-16T12:01:21
2019-05-16T12:01:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package c04_collision; import java.awt.Image; import java.awt.Rectangle; import javax.swing.ImageIcon; public class Missile extends Entity { // protected final String IMAGE_FILE = "missile.png"; private final int BOARD_WIDTH = 390; private final int MISSILE_SPEED = 2; public Missile(int x, int y) { IMAGE_FILE = "resources/missile.png"; this.init(x,y); } public void move() { mX += MISSILE_SPEED; if (mX > BOARD_WIDTH) { mVisible = false; } } }
b2828e29f24e8288917fba67b37df4bf86c34493
c978a18649599e4c48bc0677e3efd3f1bd862bbd
/src/MianJing/ixl/onsite/TopStudentScores.java
42600379d62ef39b945fa557cf15d188893ad763
[]
no_license
TianboZ/LeetCode
d6de42ca8e1ad067fa9fc133880c851601e845bc
e1065321b9aa0f9f9b453fa3d5d588f2cb80291f
refs/heads/master
2022-06-11T12:34:54.232728
2022-04-21T04:10:33
2022-04-21T04:10:33
120,261,610
2
2
null
null
null
null
UTF-8
Java
false
false
2,231
java
package MianJing.ixl.onsite; import java.util.*; /* * * assumption: * k << # of students * *clarification: * given unsorted input, find top k largest student score * * solution: * use a min heap, add each element into heap one by one, while keeping min heap size <= k * * e.g. * 1, 3, -1, 10, 100 * k = 2 * * min heap: * [ 10, 100] * * * Student { * name, * score, * } * * * complexity: * time O(logk * n) k is min heap size, n is # of students * space O(k) * * */ class Student { public String name; public int score; public Student(String name, int score) { this.name = name; this.score = score; } } public class TopStudentScores { // public void topK(List<Student> students, int k) { // Queue<Student> pq = new PriorityQueue<>((s1, s2) -> s1.score - s2.score); // min heap // // for (Student s: students) { // pq.offer(s); // if (pq.size() > k) { // pq.poll(); // } // } // // while (!pq.isEmpty()) { // System.out.println(pq.poll().score); // } // } public List<Student> topK(List<Student> students, int k) { // sanity check // todo if (students == null || k <= 0) return null; Queue<Student> pq = new PriorityQueue<>((s1, s2) -> s1.score - s2.score); // min heap, sort Student by score for (Student s : students) { pq.offer(s); if (pq.size() > k) pq.poll(); } List<Student> topk = new ArrayList<>(); while (!pq.isEmpty()) { topk.add(pq.poll()); } return topk; } public static void main(String[] args) { Student s1 = new Student("a", 1); Student s2 = new Student("b", 10); Student s3 = new Student("c", 5); Student s4 = new Student("d", 1000); Student s5 = new Student("e", 1001); Student s6 = new Student("f", -10); List<Student> list = Arrays.asList(s1, s2, s3, s4, s5, s6); TopStudentScores sol = new TopStudentScores(); List<Student> res = sol.topK(list, 3); for (Student s : res) { System.out.println(s.name + ": " + s.score); } } }
09ceac1f16d9c15dddd1594b6a90e710092503b4
d410c28e37e91c26ad48e1b142f7420058502063
/src/com/gms/demo/SaveData.java
3d751b798ae6e81278cd6cff088ca2db3ebe6037
[]
no_license
katul/OrderMgmt
85c224e84542ce80936bdc3ddae8b52918e8b7a7
a69afd65af5e956970616924ae4585749681674e
refs/heads/master
2022-11-15T07:02:25.497195
2020-06-28T17:58:19
2020-06-28T17:58:19
275,437,877
0
0
null
null
null
null
UTF-8
Java
false
false
1,825
java
package com.gms.demo; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/SaveData") public class SaveData extends HttpServlet { private static final long serialVersionUID = 1L; public SaveData() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String username=request.getParameter("username"); String password=request.getParameter("password"); String firstName=request.getParameter("fname"); String lastName=request.getParameter("lname"); String adderess=request.getParameter("address"); String ph=request.getParameter("phone"); Long phone = Long.parseLong(ph); int status=RegisterUser.updateUser(username, firstName, lastName, adderess, password, phone); HttpSession session = request.getSession(); session.setAttribute("username",username); if(status>0){ request.setAttribute("successmessage", "Profile updated successfully"); session.setAttribute("username", username); RequestDispatcher rd=request.getRequestDispatcher("userview.jsp"); rd.include(request, response); }else{ request.setAttribute("errormessage","Sorry,Update failed. please try later"); RequestDispatcher rd=request.getRequestDispatcher("EditFormData.jsp"); rd.include(request, response); } } }
f59568f3d3c65d01fd38fc2292a7967f1f4d436c
ec7685150e0210b4d1b64b8fd3e04b24634d7347
/exec/backend/roufarm/src/main/java/com/c105/roufarm/model/RoutineLog.java
aa12f5c384ec494bdb3d414f78462023221ab2ab
[]
no_license
wealways/RouFarm
3bd0c1530eb8d3d7090dcc764c96e160d46df5b5
bbeb7fae8847ae1626cca7fc64d7718ecedfc345
refs/heads/master
2023-06-01T22:43:14.020999
2021-06-20T03:42:02
2021-06-20T03:42:02
369,978,803
1
0
null
null
null
null
UTF-8
Java
false
false
255
java
package com.c105.roufarm.model; import lombok.Data; @Data public class RoutineLog { private String id; // 고유 id private String routineId; // 루틴의 id private String time; // 시각 private String isSuccess; // 성공여부 }
fbad1a38fbe42bc1e0a4020b11166ec3f28ea24b
67987e4e5ff91339d045f07a68ff6f7d2beb0d39
/src/main/java/com/zvos/app/api/sdk/utils/ByteUtils.java
3c060095d7eeebd37ae4897de53921309280a860
[]
no_license
zhangjunchao09/httpsdk
a13df223fe7056f21b3e2dd6a2490a3606e9c25c
66f67cf5300aca2415520e1e18757a5a72991449
refs/heads/master
2022-06-02T14:51:02.957969
2020-03-28T03:59:08
2020-03-28T03:59:08
250,705,202
0
0
null
2022-05-20T21:29:50
2020-03-28T03:23:33
Java
UTF-8
Java
false
false
1,415
java
package com.zvos.app.api.sdk.utils; import java.util.HashMap; import java.util.Map; public class ByteUtils { private static final char[] HEX_CHAR_TABLE = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static final Map<Character, Byte> HEX_CHAR_MAP = new HashMap<>(); static { for (int i = 0; i < HEX_CHAR_TABLE.length; i++) { char c = HEX_CHAR_TABLE[i]; HEX_CHAR_MAP.put(c, (byte) i); } } public static String byte2Hex(byte value) { return String.format("%02X", new Object[]{Byte.valueOf(value)}); } public static String bytes2Hex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(HEX_CHAR_TABLE[(b & 0xf0) >> 4]); sb.append(HEX_CHAR_TABLE[b & 0x0f]); } return sb.toString(); } public static byte[] hex2Bytes(String hexString) { //单数长度补全 if ((hexString.length() & 1) == 1) { hexString = "0" + hexString; } byte[] result = new byte[hexString.length() / 2]; for (int i = 0; i < result.length; i++) { char hi = hexString.charAt(i * 2); char lo = hexString.charAt(i * 2 + 1); result[i] = (byte) ((HEX_CHAR_MAP.get(hi) << 4) + HEX_CHAR_MAP.get(lo)); } return result; } }
[ "zjc" ]
zjc
f97fa4917799cebcfdbda3ce4957e4008c9fed56
c4bae91d1910961c067a7222194768b76b241f27
/src/main/java/ru/sberbank/smartoffice/at/visitors/tracker/Tracker.java
d0b6fa8cce84b193cccb5056f90870511a6864da
[]
no_license
civildeath0/at-framework
db288ec5d2519ff520ead21460c3cd124d283802
81591e6323c0958fc21387e78fd8be46677a9d2e
refs/heads/master
2023-03-23T18:08:40.292361
2021-03-16T10:04:34
2021-03-16T10:04:34
348,295,099
0
0
null
null
null
null
UTF-8
Java
false
false
406
java
package ru.sberbank.smartoffice.at.visitors.tracker; import ru.sberbank.smartoffice.at.pageobjects.classes.detailed.*; public interface Tracker { void track(AirportPage airportPage); void track(CompanyPage companyPage); void track(FlightPage flightPage); void track(MeetingPage meetingPage); void track(AssignmentPage assignmentPage); void track(ContactPage contactPage); }
149992959edaafcb465f1fe2cb5a86c8ae831e5c
85d2321e40c146846e89e3217eea36383d8247ad
/NeuralNetworks/src/ml/Run.java
f8b139ddc8658d1aeb648a80892001eba1e3d87c
[]
no_license
darshandpatel/MachineLearningAlgorithms
22c0eecfea86f4deec8ba48e4d3c50999010b7b0
229ea79aab1a1df6294ee4ed51b365bd1ed3d3d7
refs/heads/master
2020-04-15T11:26:08.858481
2016-12-02T20:14:07
2016-12-02T20:14:07
42,361,790
0
0
null
null
null
null
UTF-8
Java
false
false
259
java
package ml; public class Run { public static void main(String args[]) { //Perceptron perceptron = new Perceptron(); //perceptron.formPerceptron(); NeuralNetworks neuralNetworks = new NeuralNetworks(); neuralNetworks.formNeuralNetwork(); } }
c7b637353730f7354f23a8d3a34dd96397103bf1
9b4c4aa0df2692b69a61aff9ab80e866bb000628
/src/test/java/spring/finEdu/FinEduApplicationTests.java
cb7cd7d562db50f1732e43bf01eb2e980db5700c
[]
no_license
yuseogi0218/Fintech_SpringBoot
6d03b2759c49a04eb581bf045baec9e2a880a7ed
8607f4f16214b26ac7c1c9ca936acaf29fc5d410
refs/heads/main
2023-07-23T09:52:32.630284
2021-09-04T06:45:10
2021-09-04T06:45:10
391,221,577
0
0
null
null
null
null
UTF-8
Java
false
false
205
java
package spring.finEdu; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class FinEduApplicationTests { @Test void contextLoads() { } }
dcf4b329dc4045bc7bdae256fe1d69aa7ea84af1
6c107846bde93e656ef4a2e9c6b6cb32ac1ce091
/app/src/main/java/com/apsakare/opengl/Triangle.java
fd8416c047030989eeb5222671fe52622866af21
[]
no_license
AkshaySakare/OpenGLStudyTest
102019e8237b93bda27be417a573191cd30e5389
229d44f691253632e00ab4ffadabf5f9c77d965e
refs/heads/master
2021-04-09T11:06:35.239223
2020-11-27T12:09:48
2020-11-27T12:09:48
124,729,031
0
0
null
2020-05-03T15:33:30
2018-03-11T06:15:31
Java
UTF-8
Java
false
false
1,229
java
package com.apsakare.opengl; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; /** * Created by AKshay on 8/26/2017. */ class Triangle { private FloatBuffer mFVertexBuffer; private ByteBuffer mIndexBuffer; public Triangle() { float vertices[] = { -1f, -0.29f, -10f, 1f, -0.29f, -10f, 0f, 1f, -10f }; byte indices[] = { 0, 1, 2 }; mFVertexBuffer = makeFloatBuffer(vertices); mIndexBuffer = ByteBuffer.allocateDirect(indices.length); mIndexBuffer.put(indices); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glVertexPointer(3, GL11.GL_FLOAT, 0, mFVertexBuffer); gl.glDrawElements(GL11.GL_TRIANGLES, 3, GL11.GL_UNSIGNED_BYTE, mIndexBuffer); } private static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } }
233ef3bd67cc7b10786b3db1173450c11b19ae5f
df38d9c11139eaa9301a46d7f549483336036647
/labo4_opgave_src/src/main/java/org/ibcn/gso/labo4/MainApp.java
d5fd2c4f9488da9227f308281a92d7fe0ca40073
[]
no_license
BenjaminFraeyman/ASD_Lab4
14079dc6e5a04f5a4e01ff6e028e0bc122abdfa1
77d6a39ae4f06799229280b8960fdb1bdea94431
refs/heads/master
2020-04-30T08:35:37.218884
2019-03-27T10:57:07
2019-03-27T10:57:07
176,721,277
0
0
null
null
null
null
UTF-8
Java
false
false
1,099
java
package org.ibcn.gso.labo4; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class MainApp extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml")); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage.setTitle("GSO Labo 4: A Simple Image Editor"); stage.setScene(scene); stage.show(); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
99e26c95a47bf108d793c26afeefc25ea592e3a0
e92c68552b062874268fa2655d9c8ecd2de5d00a
/src/main/java/de/hhu/cs/dbs/internship/project/table/account/GekaufteTB.java
636ba777dc92eb079b3a090049f3c5d3e0265271
[]
no_license
baris8/DatabaseProject
ba512ef74591eead6508b0755fe0e93a23afda6f
b892b19616fd0d7145f42a37031d12dc2ae22a5b
refs/heads/master
2020-10-01T01:02:49.291846
2019-12-11T17:01:24
2019-12-11T17:01:24
227,416,091
0
0
null
null
null
null
UTF-8
Java
false
false
1,604
java
package de.hhu.cs.dbs.internship.project.table.account; import com.alexanderthelen.applicationkit.database.Data; import com.alexanderthelen.applicationkit.database.Table; import de.hhu.cs.dbs.internship.project.Project; import java.sql.PreparedStatement; import java.sql.SQLException; public class GekaufteTB extends Table { private String verkaueferEMail; public GekaufteTB(String s){ verkaueferEMail = s; } @Override public String getSelectQueryForTableWithFilter(String s) throws SQLException { String sql = "SELECT sid as ID, EMail, Datum, Nummer, Typ FROM Seite " + "WHERE EMail = '" + verkaueferEMail + "' "; if (s != null && !s.isEmpty()) { sql += "AND Datum LIKE '%" + s + "%'"; } return sql; } @Override public String getSelectQueryForRowWithData(Data data) throws SQLException { String sql = "SELECT sid, Datum, Nummer, Typ FROM Seite " + "WHERE EMail = '" + verkaueferEMail + "' " + "AND sid = '" + data.get("Seite.ID") + "'"; return sql; } @Override public void insertRowWithData(Data data) throws SQLException { throw new SQLException("Sie koennen hier nichts einfuegen!!!"); } @Override public void updateRowWithData(Data data, Data data1) throws SQLException { throw new SQLException("Sie koennen hier nichts aendern!!!"); } @Override public void deleteRowWithData(Data data) throws SQLException { throw new SQLException("Sie koennen hier nichts loeschen!!!"); } }
e826e32429129bb65f1567227b56bb9f07ba5e25
74cf2bbc859beb54b74caf9f66855656c7b0e166
/app/src/main/java/com/example/nicholas/poundslasherfinal/forgotpass.java
f46ea458e0865506fd42d4e4be97d4a89a454752
[]
no_license
Health-2-Be/real_final_pls_no_more-ur-killing-me-
e3e96a01056ac877687f0b35930d44059b5d28aa
ed0d3eebc2985311602a115e60231fa9f1a3cb39
refs/heads/master
2020-03-11T00:23:15.981881
2018-03-26T22:52:53
2018-03-26T22:52:53
129,662,517
0
0
null
null
null
null
UTF-8
Java
false
false
355
java
package com.example.nicholas.poundslasherfinal; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class forgotpass extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgotpass); } }
e521c59517e66777dd45ef4c18edb24891e98a82
70126a9c4781b7fade61b98cc8789ce301a77213
/RestAssuredBDDAutomation/src/main/java/com/qa/restAssuredBDD/SerializationDesiJava.java
b5ea284ab03408d52217cd628d4478be6d174e47
[]
no_license
RamChennale/projects
59a42e2eb933a3431d3406b613e45aa46ed60481
242211a0ff12e06d7de74e1616cf4f8b37d763f1
refs/heads/master
2023-08-28T17:40:53.819500
2023-08-14T18:48:50
2023-08-14T18:48:50
203,310,306
0
0
null
2023-09-13T17:41:51
2019-08-20T06:06:05
Java
UTF-8
Java
false
false
1,489
java
package com.qa.restAssuredBDD; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.testng.annotations.Test; public class SerializationDesiJava implements Serializable{ static int a=100, b=1000; static String name="Ram chennale"; @Test(priority=1) public void serialization() throws FileNotFoundException,IOException{ SerializationDesiJava obj= new SerializationDesiJava(); FileOutputStream fileOutputStream= new FileOutputStream("text.ser"); ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(obj); objectOutputStream.flush(); objectOutputStream.close(); } @Test(priority=2, enabled=true) public void Deserialization() { try { FileInputStream fileInputStream= new FileInputStream("text.ser"); ObjectInputStream objectInputStream= new ObjectInputStream(fileInputStream); SerializationDesiJava obj=(SerializationDesiJava)objectInputStream.readObject(); System.out.println("a :"+obj.a+" b: "+obj.b); System.out.println("Name: "+obj.name); fileInputStream.close(); }catch(FileNotFoundException f) { f.printStackTrace(); }catch (IOException io) { io.printStackTrace(); }catch (ClassNotFoundException cls) { cls.printStackTrace(); } } }
ff644c82b1559a9bd01f7c0155b2301a4feb7f5d
cd984592acce4f10a836419e16aeab534e7fd62d
/src/org/usfirst/frc/team3539/robot/autongroups/GearRightGroup.java
6df36230455aae85ac6ceabc456e8b741d1f3f10
[]
no_license
BytingBulldogs3539/Steamworks-2017
332d55af7cb836fa6ba25f91cb49e37f3af9a01d
36da5ace70ef111e57df1810a9c7402ee0bd3e3f
refs/heads/master
2021-09-03T20:58:11.122182
2018-01-11T23:33:12
2018-01-11T23:33:12
82,123,505
2
0
null
null
null
null
UTF-8
Java
false
false
1,169
java
package org.usfirst.frc.team3539.robot.autongroups; import org.usfirst.frc.team3539.robot.Robot; import org.usfirst.frc.team3539.robot.RobotMap; import org.usfirst.frc.team3539.robot.autoncommands.AutoWait; import org.usfirst.frc.team3539.robot.autoncommands.AutonDrive; import org.usfirst.frc.team3539.robot.autoncommands.AutonGearClose; import org.usfirst.frc.team3539.robot.autoncommands.AutonGearOpen; import org.usfirst.frc.team3539.robot.autoncommands.AutonTurn; import org.usfirst.frc.team3539.robot.autoncommands.HoodReset; import org.usfirst.frc.team3539.robot.autoncommands.SetGearCamera; import org.usfirst.frc.team3539.robot.autoncommands.SetShootCamera; import org.usfirst.frc.team3539.robot.autonscurves.SuperDriveAuton; import edu.wpi.first.wpilibj.command.CommandGroup; /** * */ public class GearRightGroup extends CommandGroup { public GearRightGroup() { addParallel(new SetGearCamera()); addParallel(new HoodReset(3)); addSequential(new SuperDriveAuton(100, .6, 50, false, 4, 17)); addSequential(new AutoWait(.7)); addSequential(new AutonDrive(RobotMap.sidePegDistance + 8, true,2)); addSequential(new AutonGearOpen()); } }
850c48ca0631695e1499bb1da1abf064a68a5b84
ab98ea27384f849e9a52903da926357157c14365
/Offer/test9_.java
e762414e4a5f09e44450b9a6f0a9221a0ba47c30
[]
no_license
nda1992/Reading_Books_Notebook
51342ff066f6cb918eee1540b6fd4679c70e4dcd
4e6c7f00bcdfd620899e0ea16bfb5dc093a848b6
refs/heads/master
2020-05-23T20:20:23.785510
2020-03-10T07:41:28
2020-03-10T07:41:28
186,927,859
1
0
null
null
null
null
UTF-8
Java
false
false
608
java
import java.util.Arrays; //变态跳台阶 /* * 一次可以跳上1级台阶,也可以跳上2级台阶,也可以跳上n级台阶,求n级台阶有几种跳法 * f(n)=f(n-1)+f(n-2)+...+f(2)+f(1) * */ public class test9_ { public static void main(String[] args) { System.out.println(JumpFloor(6)); } public static int JumpFloor(int target){ int[] dp = new int[target]; Arrays.fill(dp,1); for (int i = 1; i < target; i++) { for (int j = 0; j < i; j++) { dp[i] += dp[j]; } } return dp[target-1]; } }
dd211837ac616fe2a32b784f45f0ec1c0cc28331
d13f101f429e912598f80f9b583b88967e8be039
/src/main/java/alessandraB/mar06/SimpleMethods.java
2ae0a489837eb044bd0b18bd9cf89d3addceaa5a
[]
no_license
egalli64/oved210
389751ae35f5a086a6eabcfc399c05e8cf4688b9
4a5d7078f46a3f4f6f4ad94d5975f000be14786d
refs/heads/master
2020-04-24T15:27:51.175208
2019-06-14T10:48:36
2019-06-14T10:48:36
172,068,768
2
2
null
null
null
null
UTF-8
Java
false
false
3,520
java
package alessandraB.mar06; public class SimpleMethods { /** * input : char c output : true if c is an upper character ('A') false otherwise * ('h'), anche '6' è un carattere se messo tra gli apici. */ public static boolean isUpper(char c) { if (c >= 'A' && c <= 'Z') { return true; } return false; } /** * * input: char c output: true if c is an alphabetic character ('A','c') false * otherwise ('6',')') */ public static boolean isAlpha(char c) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { return true; } return false; } /** * * input: char c outpur: char converted to uppercase 'x' --> 'X' */ public static char toUpper(char c) { if ((c >= 'a' && c <= 'z')) { int delta = c - 'a'; char result = (char) ('A' + delta); return (char) ('A' + delta); } return c; } /** * input: int[] data output : smaller element {1,2,5,-7} --> -7 * */ public static int smallest(int[] data) { if (data == null || data.length == 0) { return Integer.MAX_VALUE; } int currentMinumum = data[0]; for (int i = 1; i < data.length; i++) { if (currentMinumum > data[i]) { currentMinumum = data[i]; } } return currentMinumum; } public static int firstSmallestIndex(int[] data) { if (data == null || data.length == 0) { return -1; } int index = 0; for (int i = 1; i < data.length; i++) { if (data[index] > data[i]) { index = i; } } return index; } public static int lastSmallestIndex(int[] data) { if (data == null || data.length == 0) { return -1; } int index = 0; for (int i = 1; i < data.length; i++) { if (data[index] >= data[i]) { index = i; } } return index; } /** * {1,2,3}, 2 --> true; {1,2,3}, 7 ---> false; */ public static boolean find(int[] data, int target) { for (int i = 0; i < data.length; i++) { if (target == data[i]) return true; } return false; } public static int findPos(int[] data, int target) { int index = 0; for (int i = 0; i < data.length; i++) { if (target == data[i]) return data[index]; } return -1; } /** * checks if a string is palindrome. if the passed string is null, return false. * otherwise return true only if the string is a palindrome * * for example: "abba" --> true; "abac"--> false; * * @param s the string to be checked if palindrome * @return true only if the input is a palindrome */ public static boolean isPalindrome(String s) { if (s == null) { return false; } if (s.length() < 2) { return false; } int left = 0; int right = s.length() - 1; for (; left < right; left++, --right) { if (s.charAt(left) != s.charAt(right)) return false; } return true; } /** * {1,2,3} --> {3,2,1} * */ public static void reverse(int[] data) { if (data == null || data.length < 2) { return ; } int left = 0; int right = data.length - 1; for (; left < right; left++, right--) { int temp = data[left]; data[left] = data[right]; data[right] = temp; } } public static int[] reverseReturn(int[]data) { if(data ==null|| data.length <2) { return data; } int[] result = new int[data.length]; for(int i = 0; i < data.length;i++) { result[i] = data [data.length -1-i]; } return result; } }
4543695414b1bbabe42a24ee46ec26f4fc0b80eb
cd0db8908f7bde308403a286c42368589d8c86f8
/src/main/java/org/launchcode/resaleshopinventory/models/Category.java
7ccdaac3ce86bc640d973c830d6231f0e73731df
[ "MIT" ]
permissive
areichle1/resale-shop-inventory
ca9d54898526d8d939b94a78e4498f3ac7678e12
3515e7c44a88fe156bca6efa2abb9a264496eb49
refs/heads/master
2020-07-29T17:01:24.950381
2020-03-07T20:10:33
2020-03-07T20:10:33
209,892,548
1
0
null
2019-11-02T18:44:17
2019-09-20T22:42:35
Java
UTF-8
Java
false
false
1,055
java
package org.launchcode.resaleshopinventory.models; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.List; @Entity public class Category { @Id @GeneratedValue private int id; @NotNull @Size(min=3, max=30) private String name; @ManyToOne private User user; @OneToMany @JoinColumn(name = "category_id") private List<Item> items = new ArrayList<>(); public Category() {} public Category(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
c57e75302cf8e4eef22a064ff5cddd6d42cf438d
9a21bf74904ccc155f1007d8a53b416b61041082
/Day20190517/src/ex190517/RemoteControl.java
4fc8d0241b7d83e8babcf6a33c96563037425b2a
[]
no_license
jinminwook/20190517
f98fb41816f07910af74d4a718651e0bb6e2c88a
847942af6ab04b70905e40b7d2d76b433e12e0bb
refs/heads/master
2020-05-24T07:51:28.684611
2019-05-17T07:52:25
2019-05-17T07:52:25
187,171,096
0
0
null
null
null
null
UHC
Java
false
false
1,558
java
package ex190517; public interface RemoteControl { /*인터페이스(interface) * 1.인터페이스는 main 코드와 객체간의 접점 역할을 함. * 2.객체의 다형성을 구현하는데 용이함. * 3.인터페이스의 구성 요소 * 3.1 상수 필드만 선언이 가능함. * 일반적인 필드로 선언해도 컴파일 과정에서 * static final 이 자동으로 붙음. * 3.2 추상메소드를 가짐. * 3.3 디폴트 메소드 가짐. * 접근제한 default가 아니라 기본으로 가지고있는 메소드개념. * 3.4정적(static)메소드 가짐. * 인터페이스를 객체화 하지 않고도 직접 호출 가능. */ //필드선언 //인터페이스는 상수 필드만 가짐. //static final을 붙이지 않아도 자동으로 적용됨. public int MAX_VOLUME=10; public int MIN_VOLUME=0; //메소드 선언 //인터페이스에는 추상 메소드 선언만 가능 //abstract 를 붙이지 않아도 자동으로 적용됨. void turnOn(); void turnOff(); void setVolume(int volume); //디폴트메소드 선언 default void setMute(boolean mute) {//디폴트라고 써야함. 안쓰면 추상메소드로 인식함. if(mute) { System.out.println("무음 처리 합니다."); }else { System.out.println("무음 해제 합니다."); } //정적(static void)메소드 선언 =>되도록이면 쓰지않는게 좋다. } static void changeBattery() { System.out.println("건전지를 교환합니다."); } }
[ "user@user-PC" ]
user@user-PC
ca3230d6d340813a5a5e9ab299cacc00dd741df4
13e443a64c99bf0028db2eb27224eb6406f6c1c2
/src/main/java/net/minecraft/client/renderer/tileentity/ChestTileEntityRenderer.java
d236aa061ce9e27ff0c1eb4811abf8e272a13f14
[]
no_license
NicholasBlackburn1/Robo_Hacker
5a779679d643250676c1c075d6697b10e8a7a9c5
02506e742d30df6a255ba63b240773a08c40bd74
refs/heads/main
2023-06-19T14:37:19.499548
2021-05-10T15:08:28
2021-05-10T15:08:28
353,691,155
2
2
null
2021-04-02T14:16:50
2021-04-01T12:23:15
Java
UTF-8
Java
false
false
7,057
java
package net.minecraft.client.renderer.tileentity; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import it.unimi.dsi.fastutil.floats.Float2FloatFunction; import it.unimi.dsi.fastutil.ints.Int2IntFunction; import java.util.Calendar; import net.minecraft.block.AbstractChestBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.ChestBlock; import net.minecraft.client.renderer.Atlases; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.client.renderer.model.RenderMaterial; import net.minecraft.state.properties.ChestType; import net.minecraft.tileentity.ChestTileEntity; import net.minecraft.tileentity.IChestLid; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityMerger; import net.minecraft.util.Direction; import net.minecraft.util.math.vector.Vector3f; import net.minecraft.world.World; public class ChestTileEntityRenderer<T extends TileEntity & IChestLid> extends TileEntityRenderer<T> { private final ModelRenderer singleLid; private final ModelRenderer singleBottom; private final ModelRenderer singleLatch; private final ModelRenderer rightLid; private final ModelRenderer rightBottom; private final ModelRenderer rightLatch; private final ModelRenderer leftLid; private final ModelRenderer leftBottom; private final ModelRenderer leftLatch; private boolean isChristmas; public ChestTileEntityRenderer(TileEntityRendererDispatcher rendererDispatcherIn) { super(rendererDispatcherIn); Calendar calendar = Calendar.getInstance(); if (calendar.get(2) + 1 == 12 && calendar.get(5) >= 24 && calendar.get(5) <= 26) { this.isChristmas = true; } this.singleBottom = new ModelRenderer(64, 64, 0, 19); this.singleBottom.addBox(1.0F, 0.0F, 1.0F, 14.0F, 10.0F, 14.0F, 0.0F); this.singleLid = new ModelRenderer(64, 64, 0, 0); this.singleLid.addBox(1.0F, 0.0F, 0.0F, 14.0F, 5.0F, 14.0F, 0.0F); this.singleLid.rotationPointY = 9.0F; this.singleLid.rotationPointZ = 1.0F; this.singleLatch = new ModelRenderer(64, 64, 0, 0); this.singleLatch.addBox(7.0F, -1.0F, 15.0F, 2.0F, 4.0F, 1.0F, 0.0F); this.singleLatch.rotationPointY = 8.0F; this.rightBottom = new ModelRenderer(64, 64, 0, 19); this.rightBottom.addBox(1.0F, 0.0F, 1.0F, 15.0F, 10.0F, 14.0F, 0.0F); this.rightLid = new ModelRenderer(64, 64, 0, 0); this.rightLid.addBox(1.0F, 0.0F, 0.0F, 15.0F, 5.0F, 14.0F, 0.0F); this.rightLid.rotationPointY = 9.0F; this.rightLid.rotationPointZ = 1.0F; this.rightLatch = new ModelRenderer(64, 64, 0, 0); this.rightLatch.addBox(15.0F, -1.0F, 15.0F, 1.0F, 4.0F, 1.0F, 0.0F); this.rightLatch.rotationPointY = 8.0F; this.leftBottom = new ModelRenderer(64, 64, 0, 19); this.leftBottom.addBox(0.0F, 0.0F, 1.0F, 15.0F, 10.0F, 14.0F, 0.0F); this.leftLid = new ModelRenderer(64, 64, 0, 0); this.leftLid.addBox(0.0F, 0.0F, 0.0F, 15.0F, 5.0F, 14.0F, 0.0F); this.leftLid.rotationPointY = 9.0F; this.leftLid.rotationPointZ = 1.0F; this.leftLatch = new ModelRenderer(64, 64, 0, 0); this.leftLatch.addBox(0.0F, -1.0F, 15.0F, 1.0F, 4.0F, 1.0F, 0.0F); this.leftLatch.rotationPointY = 8.0F; } public void render(T tileEntityIn, float partialTicks, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn) { World world = tileEntityIn.getWorld(); boolean flag = world != null; BlockState blockstate = flag ? tileEntityIn.getBlockState() : Blocks.CHEST.getDefaultState().with(ChestBlock.FACING, Direction.SOUTH); ChestType chesttype = blockstate.hasProperty(ChestBlock.TYPE) ? blockstate.get(ChestBlock.TYPE) : ChestType.SINGLE; Block block = blockstate.getBlock(); if (block instanceof AbstractChestBlock) { AbstractChestBlock<?> abstractchestblock = (AbstractChestBlock)block; boolean flag1 = chesttype != ChestType.SINGLE; matrixStackIn.push(); float f = blockstate.get(ChestBlock.FACING).getHorizontalAngle(); matrixStackIn.translate(0.5D, 0.5D, 0.5D); matrixStackIn.rotate(Vector3f.YP.rotationDegrees(-f)); matrixStackIn.translate(-0.5D, -0.5D, -0.5D); TileEntityMerger.ICallbackWrapper <? extends ChestTileEntity > icallbackwrapper; if (flag) { icallbackwrapper = abstractchestblock.combine(blockstate, world, tileEntityIn.getPos(), true); } else { icallbackwrapper = TileEntityMerger.ICallback::func_225537_b_; } float f1 = icallbackwrapper.<Float2FloatFunction>apply(ChestBlock.getLidRotationCallback(tileEntityIn)).get(partialTicks); f1 = 1.0F - f1; f1 = 1.0F - f1 * f1 * f1; int i = icallbackwrapper.<Int2IntFunction>apply(new DualBrightnessCallback<>()).applyAsInt(combinedLightIn); RenderMaterial rendermaterial = Atlases.getChestMaterial(tileEntityIn, chesttype, this.isChristmas); IVertexBuilder ivertexbuilder = rendermaterial.getBuffer(bufferIn, RenderType::getEntityCutout); if (flag1) { if (chesttype == ChestType.LEFT) { this.renderModels(matrixStackIn, ivertexbuilder, this.leftLid, this.leftLatch, this.leftBottom, f1, i, combinedOverlayIn); } else { this.renderModels(matrixStackIn, ivertexbuilder, this.rightLid, this.rightLatch, this.rightBottom, f1, i, combinedOverlayIn); } } else { this.renderModels(matrixStackIn, ivertexbuilder, this.singleLid, this.singleLatch, this.singleBottom, f1, i, combinedOverlayIn); } matrixStackIn.pop(); } } private void renderModels(MatrixStack matrixStackIn, IVertexBuilder bufferIn, ModelRenderer chestLid, ModelRenderer chestLatch, ModelRenderer chestBottom, float lidAngle, int combinedLightIn, int combinedOverlayIn) { chestLid.rotateAngleX = -(lidAngle * ((float)Math.PI / 2F)); chestLatch.rotateAngleX = chestLid.rotateAngleX; chestLid.render(matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); chestLatch.render(matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); chestBottom.render(matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); } }
3262467db95a9c810164e34c1ec3261d553d0f78
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/14/14_45d47b4cefba0afb4d4da5fb1505f8515b2792f0/ComposeMessageActivity/14_45d47b4cefba0afb4d4da5fb1505f8515b2792f0_ComposeMessageActivity_s.java
c8c6a03a15b54ed41d81fee9a0495157732eb3ec
[]
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
159,054
java
/* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import static android.content.res.Configuration.KEYBOARDHIDDEN_NO; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_ABORT; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_COMPLETE; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_START; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_STATUS_ACTION; import static com.android.mms.ui.MessageListAdapter.COLUMN_ID; import static com.android.mms.ui.MessageListAdapter.COLUMN_MMS_LOCKED; import static com.android.mms.ui.MessageListAdapter.COLUMN_MSG_TYPE; import static com.android.mms.ui.MessageListAdapter.PROJECTION; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.AsyncQueryHandler; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnClickListener; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.database.sqlite.SqliteWrapper; import android.drm.mobile1.DrmException; import android.drm.mobile1.DrmRawContent; import android.graphics.drawable.Drawable; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.os.SystemProperties; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.provider.DrmStore; import android.provider.MediaStore; import android.provider.Settings; import android.provider.ContactsContract.Intents; import android.provider.MediaStore.Images; import android.provider.MediaStore.Video; import android.provider.Telephony.Mms; import android.provider.Telephony.Sms; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.telephony.PhoneNumberUtils; import android.telephony.SmsMessage; import android.text.ClipboardManager; import android.text.Editable; import android.text.InputFilter; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.TextKeyListener; import android.text.style.URLSpan; import android.text.util.Linkify; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewStub; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnKeyListener; import android.view.inputmethod.InputMethodManager; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.CursorAdapter; import android.widget.TextView; import android.widget.Toast; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.TelephonyProperties; import com.android.mms.LogTag; import com.android.mms.MmsApp; import com.android.mms.MmsConfig; import com.android.mms.R; import com.android.mms.TempFileProvider; import com.android.mms.data.Contact; import com.android.mms.data.ContactList; import com.android.mms.data.Conversation; import com.android.mms.data.WorkingMessage; import com.android.mms.data.WorkingMessage.MessageStatusListener; import com.google.android.mms.ContentType; import com.google.android.mms.pdu.EncodedStringValue; import com.google.android.mms.MmsException; import com.google.android.mms.pdu.PduBody; import com.google.android.mms.pdu.PduPart; import com.google.android.mms.pdu.PduPersister; import com.google.android.mms.pdu.SendReq; import com.google.android.mms.util.PduCache; import com.android.mms.model.SlideModel; import com.android.mms.model.SlideshowModel; import com.android.mms.transaction.MessagingNotification; import com.android.mms.ui.MessageUtils.ResizeImageResultCallback; import com.android.mms.ui.RecipientsEditor.RecipientContextMenuInfo; import com.android.mms.util.SendingProgressTokenManager; import com.android.mms.util.SmileyParser; import android.text.InputFilter.LengthFilter; /** * This is the main UI for: * 1. Composing a new message; * 2. Viewing/managing message history of a conversation. * * This activity can handle following parameters from the intent * by which it's launched. * thread_id long Identify the conversation to be viewed. When creating a * new message, this parameter shouldn't be present. * msg_uri Uri The message which should be opened for editing in the editor. * address String The addresses of the recipients in current conversation. * exit_on_sent boolean Exit this activity after the message is sent. */ public class ComposeMessageActivity extends Activity implements View.OnClickListener, TextView.OnEditorActionListener, MessageStatusListener, Contact.UpdateListener { public static final int REQUEST_CODE_ATTACH_IMAGE = 100; public static final int REQUEST_CODE_TAKE_PICTURE = 101; public static final int REQUEST_CODE_ATTACH_VIDEO = 102; public static final int REQUEST_CODE_TAKE_VIDEO = 103; public static final int REQUEST_CODE_ATTACH_SOUND = 104; public static final int REQUEST_CODE_RECORD_SOUND = 105; public static final int REQUEST_CODE_CREATE_SLIDESHOW = 106; public static final int REQUEST_CODE_ECM_EXIT_DIALOG = 107; public static final int REQUEST_CODE_ADD_CONTACT = 108; public static final int REQUEST_CODE_PICK = 109; private static final String TAG = "Mms/compose"; private static final boolean DEBUG = false; private static final boolean TRACE = false; private static final boolean LOCAL_LOGV = false; // Menu ID private static final int MENU_ADD_SUBJECT = 0; private static final int MENU_DELETE_THREAD = 1; private static final int MENU_ADD_ATTACHMENT = 2; private static final int MENU_DISCARD = 3; private static final int MENU_SEND = 4; private static final int MENU_CALL_RECIPIENT = 5; private static final int MENU_CONVERSATION_LIST = 6; private static final int MENU_DEBUG_DUMP = 7; // Context menu ID private static final int MENU_VIEW_CONTACT = 12; private static final int MENU_ADD_TO_CONTACTS = 13; private static final int MENU_EDIT_MESSAGE = 14; private static final int MENU_VIEW_SLIDESHOW = 16; private static final int MENU_VIEW_MESSAGE_DETAILS = 17; private static final int MENU_DELETE_MESSAGE = 18; private static final int MENU_SEARCH = 19; private static final int MENU_DELIVERY_REPORT = 20; private static final int MENU_FORWARD_MESSAGE = 21; private static final int MENU_CALL_BACK = 22; private static final int MENU_SEND_EMAIL = 23; private static final int MENU_COPY_MESSAGE_TEXT = 24; private static final int MENU_COPY_TO_SDCARD = 25; private static final int MENU_INSERT_SMILEY = 26; private static final int MENU_ADD_ADDRESS_TO_CONTACTS = 27; private static final int MENU_LOCK_MESSAGE = 28; private static final int MENU_UNLOCK_MESSAGE = 29; private static final int MENU_COPY_TO_DRM_PROVIDER = 30; private static final int MENU_PREFERENCES = 31; private static final int RECIPIENTS_MAX_LENGTH = 312; private static final int MESSAGE_LIST_QUERY_TOKEN = 9527; private static final int DELETE_MESSAGE_TOKEN = 9700; private static final int CHARS_REMAINING_BEFORE_COUNTER_SHOWN = 10; private static final long NO_DATE_FOR_DIALOG = -1L; private static final String EXIT_ECM_RESULT = "exit_ecm_result"; private ContentResolver mContentResolver; private BackgroundQueryHandler mBackgroundQueryHandler; private Conversation mConversation; // Conversation we are working in private boolean mExitOnSent; // Should we finish() after sending a message? // TODO: mExitOnSent is obsolete -- remove private View mTopPanel; // View containing the recipient and subject editors private View mBottomPanel; // View containing the text editor, send button, ec. private EditText mTextEditor; // Text editor to type your message into private TextView mTextCounter; // Shows the number of characters used in text editor private TextView mSendButtonMms; // Press to send mms private ImageButton mSendButtonSms; // Press to send sms private EditText mSubjectTextEditor; // Text editor for MMS subject private AttachmentEditor mAttachmentEditor; private View mAttachmentEditorScrollView; private MessageListView mMsgListView; // ListView for messages in this conversation public MessageListAdapter mMsgListAdapter; // and its corresponding ListAdapter private RecipientsEditor mRecipientsEditor; // UI control for editing recipients private ImageButton mRecipientsPicker; // UI control for recipients picker private boolean mIsKeyboardOpen; // Whether the hardware keyboard is visible private boolean mIsLandscape; // Whether we're in landscape mode private boolean mPossiblePendingNotification; // If the message list has changed, we may have // a pending notification to deal with. private boolean mToastForDraftSave; // Whether to notify the user that a draft is being saved private boolean mSentMessage; // true if the user has sent a message while in this // activity. On a new compose message case, when the first // message is sent is a MMS w/ attachment, the list blanks // for a second before showing the sent message. But we'd // think the message list is empty, thus show the recipients // editor thinking it's a draft message. This flag should // help clarify the situation. private WorkingMessage mWorkingMessage; // The message currently being composed. private AlertDialog mSmileyDialog; private ProgressDialog mProgressDialog; private boolean mWaitingForSubActivity; private int mLastRecipientCount; // Used for warning the user on too many recipients. private AttachmentTypeSelectorAdapter mAttachmentTypeSelectorAdapter; private boolean mSendingMessage; // Indicates the current message is sending, and shouldn't send again. private Intent mAddContactIntent; // Intent used to add a new contact private String mDebugRecipients; @SuppressWarnings("unused") public static void log(String logMsg) { Thread current = Thread.currentThread(); long tid = current.getId(); StackTraceElement[] stack = current.getStackTrace(); String methodName = stack[3].getMethodName(); // Prepend current thread ID and name of calling method to the message. logMsg = "[" + tid + "] [" + methodName + "] " + logMsg; Log.d(TAG, logMsg); } //========================================================== // Inner classes //========================================================== private void editSlideshow() { Uri dataUri = mWorkingMessage.saveAsMms(false); if (dataUri == null) { return; } Intent intent = new Intent(this, SlideshowEditActivity.class); intent.setData(dataUri); startActivityForResult(intent, REQUEST_CODE_CREATE_SLIDESHOW); } private final Handler mAttachmentEditorHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case AttachmentEditor.MSG_EDIT_SLIDESHOW: { editSlideshow(); break; } case AttachmentEditor.MSG_SEND_SLIDESHOW: { if (isPreparedForSending()) { ComposeMessageActivity.this.confirmSendMessageIfNeeded(); } break; } case AttachmentEditor.MSG_VIEW_IMAGE: case AttachmentEditor.MSG_PLAY_VIDEO: case AttachmentEditor.MSG_PLAY_AUDIO: case AttachmentEditor.MSG_PLAY_SLIDESHOW: MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this, mWorkingMessage, msg.what); break; case AttachmentEditor.MSG_REPLACE_IMAGE: case AttachmentEditor.MSG_REPLACE_VIDEO: case AttachmentEditor.MSG_REPLACE_AUDIO: showAddAttachmentDialog(true); break; case AttachmentEditor.MSG_REMOVE_ATTACHMENT: mWorkingMessage.removeAttachment(true); break; default: break; } } }; private final Handler mMessageListItemHandler = new Handler() { @Override public void handleMessage(Message msg) { String type; switch (msg.what) { case MessageListItem.MSG_LIST_EDIT_MMS: type = "mms"; break; case MessageListItem.MSG_LIST_EDIT_SMS: type = "sms"; break; default: Log.w(TAG, "Unknown message: " + msg.what); return; } MessageItem msgItem = getMessageItem(type, (Long) msg.obj, false); if (msgItem != null) { editMessageItem(msgItem); drawBottomPanel(); } } }; private final OnKeyListener mSubjectKeyListener = new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } // When the subject editor is empty, press "DEL" to hide the input field. if ((keyCode == KeyEvent.KEYCODE_DEL) && (mSubjectTextEditor.length() == 0)) { showSubjectEditor(false); mWorkingMessage.setSubject(null, true); return true; } return false; } }; // Shows the activity's progress spinner. Should be canceled if exiting the activity. private Runnable mShowProgressDialogRunnable = new Runnable() { public void run() { if (mProgressDialog != null) { mProgressDialog.show(); } } }; /** * Return the messageItem associated with the type ("mms" or "sms") and message id. * @param type Type of the message: "mms" or "sms" * @param msgId Message id of the message. This is the _id of the sms or pdu row and is * stored in the MessageItem * @param createFromCursorIfNotInCache true if the item is not found in the MessageListAdapter's * cache and the code can create a new MessageItem based on the position of the current cursor. * If false, the function returns null if the MessageItem isn't in the cache. * @return MessageItem or null if not found and createFromCursorIfNotInCache is false */ private MessageItem getMessageItem(String type, long msgId, boolean createFromCursorIfNotInCache) { return mMsgListAdapter.getCachedMessageItem(type, msgId, createFromCursorIfNotInCache ? mMsgListAdapter.getCursor() : null); } private boolean isCursorValid() { // Check whether the cursor is valid or not. Cursor cursor = mMsgListAdapter.getCursor(); if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) { Log.e(TAG, "Bad cursor.", new RuntimeException()); return false; } return true; } private void resetCounter() { mTextCounter.setText(""); mTextCounter.setVisibility(View.GONE); } private void updateCounter(CharSequence text, int start, int before, int count) { WorkingMessage workingMessage = mWorkingMessage; if (workingMessage.requiresMms()) { // If we're not removing text (i.e. no chance of converting back to SMS // because of this change) and we're in MMS mode, just bail out since we // then won't have to calculate the length unnecessarily. final boolean textRemoved = (before > count); if (!textRemoved) { showSmsOrMmsSendButton(workingMessage.requiresMms()); return; } } int[] params = SmsMessage.calculateLength(text, false); /* SmsMessage.calculateLength returns an int[4] with: * int[0] being the number of SMS's required, * int[1] the number of code units used, * int[2] is the number of code units remaining until the next message. * int[3] is the encoding type that should be used for the message. */ int msgCount = params[0]; int remainingInCurrentMessage = params[2]; if (!MmsConfig.getMultipartSmsEnabled()) { mWorkingMessage.setLengthRequiresMms( msgCount >= MmsConfig.getSmsToMmsTextThreshold(), true); } // Show the counter only if: // - We are not in MMS mode // - We are going to send more than one message OR we are getting close boolean showCounter = false; if (!workingMessage.requiresMms() && (msgCount > 1 || remainingInCurrentMessage <= CHARS_REMAINING_BEFORE_COUNTER_SHOWN)) { showCounter = true; } showSmsOrMmsSendButton(workingMessage.requiresMms()); if (showCounter) { // Update the remaining characters and number of messages required. String counterText = msgCount > 1 ? remainingInCurrentMessage + " / " + msgCount : String.valueOf(remainingInCurrentMessage); mTextCounter.setText(counterText); mTextCounter.setVisibility(View.VISIBLE); } else { mTextCounter.setVisibility(View.GONE); } } @Override public void startActivityForResult(Intent intent, int requestCode) { // requestCode >= 0 means the activity in question is a sub-activity. if (requestCode >= 0) { mWaitingForSubActivity = true; } super.startActivityForResult(intent, requestCode); } private void toastConvertInfo(boolean toMms) { final int resId = toMms ? R.string.converting_to_picture_message : R.string.converting_to_text_message; Toast.makeText(this, resId, Toast.LENGTH_SHORT).show(); } private class DeleteMessageListener implements OnClickListener { private final Uri mDeleteUri; private final boolean mDeleteLocked; public DeleteMessageListener(Uri uri, boolean deleteLocked) { mDeleteUri = uri; mDeleteLocked = deleteLocked; } public DeleteMessageListener(long msgId, String type, boolean deleteLocked) { if ("mms".equals(type)) { mDeleteUri = ContentUris.withAppendedId(Mms.CONTENT_URI, msgId); } else { mDeleteUri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgId); } mDeleteLocked = deleteLocked; } public void onClick(DialogInterface dialog, int whichButton) { PduCache.getInstance().purge(mDeleteUri); mBackgroundQueryHandler.startDelete(DELETE_MESSAGE_TOKEN, null, mDeleteUri, mDeleteLocked ? null : "locked=0", null); dialog.dismiss(); } } private class DiscardDraftListener implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { mWorkingMessage.discard(); dialog.dismiss(); finish(); } } private class SendIgnoreInvalidRecipientListener implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { sendMessage(true); dialog.dismiss(); } } private class CancelSendingListener implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { if (isRecipientsEditorVisible()) { mRecipientsEditor.requestFocus(); } dialog.dismiss(); } } private void confirmSendMessageIfNeeded() { if (!isRecipientsEditorVisible()) { sendMessage(true); return; } boolean isMms = mWorkingMessage.requiresMms(); if (mRecipientsEditor.hasInvalidRecipient(isMms)) { if (mRecipientsEditor.hasValidRecipient(isMms)) { String title = getResourcesString(R.string.has_invalid_recipient, mRecipientsEditor.formatInvalidNumbers(isMms)); new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(title) .setMessage(R.string.invalid_recipient_message) .setPositiveButton(R.string.try_to_send, new SendIgnoreInvalidRecipientListener()) .setNegativeButton(R.string.no, new CancelSendingListener()) .show(); } else { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.cannot_send_message) .setMessage(R.string.cannot_send_message_reason) .setPositiveButton(R.string.yes, new CancelSendingListener()) .show(); } } else { sendMessage(true); } } private final TextWatcher mRecipientsWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { // This is a workaround for bug 1609057. Since onUserInteraction() is // not called when the user touches the soft keyboard, we pretend it was // called when textfields changes. This should be removed when the bug // is fixed. onUserInteraction(); } public void afterTextChanged(Editable s) { // Bug 1474782 describes a situation in which we send to // the wrong recipient. We have been unable to reproduce this, // but the best theory we have so far is that the contents of // mRecipientList somehow become stale when entering // ComposeMessageActivity via onNewIntent(). This assertion is // meant to catch one possible path to that, of a non-visible // mRecipientsEditor having its TextWatcher fire and refreshing // mRecipientList with its stale contents. if (!isRecipientsEditorVisible()) { IllegalStateException e = new IllegalStateException( "afterTextChanged called with invisible mRecipientsEditor"); // Make sure the crash is uploaded to the service so we // can see if this is happening in the field. Log.w(TAG, "RecipientsWatcher: afterTextChanged called with invisible mRecipientsEditor"); return; } mWorkingMessage.setWorkingRecipients(mRecipientsEditor.getNumbers()); mWorkingMessage.setHasEmail(mRecipientsEditor.containsEmail(), true); checkForTooManyRecipients(); // Walk backwards in the text box, skipping spaces. If the last // character is a comma, update the title bar. for (int pos = s.length() - 1; pos >= 0; pos--) { char c = s.charAt(pos); if (c == ' ') continue; if (c == ',') { updateTitle(mConversation.getRecipients()); } break; } // If we have gone to zero recipients, disable send button. updateSendButtonState(); } }; private void checkForTooManyRecipients() { final int recipientLimit = MmsConfig.getRecipientLimit(); if (recipientLimit != Integer.MAX_VALUE) { final int recipientCount = recipientCount(); boolean tooMany = recipientCount > recipientLimit; if (recipientCount != mLastRecipientCount) { // Don't warn the user on every character they type when they're over the limit, // only when the actual # of recipients changes. mLastRecipientCount = recipientCount; if (tooMany) { String tooManyMsg = getString(R.string.too_many_recipients, recipientCount, recipientLimit); Toast.makeText(ComposeMessageActivity.this, tooManyMsg, Toast.LENGTH_LONG).show(); } } } } private final OnCreateContextMenuListener mRecipientsMenuCreateListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (menuInfo != null) { Contact c = ((RecipientContextMenuInfo) menuInfo).recipient; RecipientsMenuClickListener l = new RecipientsMenuClickListener(c); menu.setHeaderTitle(c.getName()); if (c.existsInDatabase()) { menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact) .setOnMenuItemClickListener(l); } else if (canAddToContacts(c)){ menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts) .setOnMenuItemClickListener(l); } } } }; private final class RecipientsMenuClickListener implements MenuItem.OnMenuItemClickListener { private final Contact mRecipient; RecipientsMenuClickListener(Contact recipient) { mRecipient = recipient; } public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { // Context menu handlers for the recipients editor. case MENU_VIEW_CONTACT: { Uri contactUri = mRecipient.getUri(); Intent intent = new Intent(Intent.ACTION_VIEW, contactUri); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); return true; } case MENU_ADD_TO_CONTACTS: { mAddContactIntent = ConversationList.createAddContactIntent( mRecipient.getNumber()); ComposeMessageActivity.this.startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT); return true; } } return false; } } private boolean canAddToContacts(Contact contact) { // There are some kind of automated messages, like STK messages, that we don't want // to add to contacts. These names begin with special characters, like, "*Info". final String name = contact.getName(); if (!TextUtils.isEmpty(contact.getNumber())) { char c = contact.getNumber().charAt(0); if (isSpecialChar(c)) { return false; } } if (!TextUtils.isEmpty(name)) { char c = name.charAt(0); if (isSpecialChar(c)) { return false; } } if (!(Mms.isEmailAddress(name) || Mms.isPhoneNumber(name) || contact.isMe())) { return false; } return true; } private boolean isSpecialChar(char c) { return c == '*' || c == '%' || c == '$'; } private void addPositionBasedMenuItems(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo"); return; } final int position = info.position; addUriSpecificMenuItems(menu, v, position); } private Uri getSelectedUriFromMessageList(ListView listView, int position) { // If the context menu was opened over a uri, get that uri. MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position); if (msglistItem == null) { // FIXME: Should get the correct view. No such interface in ListView currently // to get the view by position. The ListView.getChildAt(position) cannot // get correct view since the list doesn't create one child for each item. // And if setSelection(position) then getSelectedView(), // cannot get corrent view when in touch mode. return null; } TextView textView; CharSequence text = null; int selStart = -1; int selEnd = -1; //check if message sender is selected textView = (TextView) msglistItem.findViewById(R.id.text_view); if (textView != null) { text = textView.getText(); selStart = textView.getSelectionStart(); selEnd = textView.getSelectionEnd(); } // Check that some text is actually selected, rather than the cursor // just being placed within the TextView. if (selStart != selEnd) { int min = Math.min(selStart, selEnd); int max = Math.max(selStart, selEnd); URLSpan[] urls = ((Spanned) text).getSpans(min, max, URLSpan.class); if (urls.length == 1) { return Uri.parse(urls[0].getURL()); } } //no uri was selected return null; } private void addUriSpecificMenuItems(ContextMenu menu, View v, int position) { Uri uri = getSelectedUriFromMessageList((ListView) v, position); if (uri != null) { Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_SELECTED_ALTERNATIVE); menu.addIntentOptions(0, 0, 0, new android.content.ComponentName(this, ComposeMessageActivity.class), null, intent, 0, null); } } private final void addCallAndContactMenuItems( ContextMenu menu, MsgListMenuClickListener l, MessageItem msgItem) { if (TextUtils.isEmpty(msgItem.mBody)) { return; } SpannableString msg = new SpannableString(msgItem.mBody); Linkify.addLinks(msg, Linkify.ALL); ArrayList<String> uris = MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class)); // Remove any dupes so they don't get added to the menu multiple times HashSet<String> collapsedUris = new HashSet<String>(); for (String uri : uris) { collapsedUris.add(uri.toLowerCase()); } for (String uriString : collapsedUris) { String prefix = null; int sep = uriString.indexOf(":"); if (sep >= 0) { prefix = uriString.substring(0, sep); uriString = uriString.substring(sep + 1); } Uri contactUri = null; boolean knownPrefix = true; if ("mailto".equalsIgnoreCase(prefix)) { contactUri = getContactUriForEmail(uriString); } else if ("tel".equalsIgnoreCase(prefix)) { contactUri = getContactUriForPhoneNumber(uriString); } else { knownPrefix = false; } if (knownPrefix && contactUri == null) { Intent intent = ConversationList.createAddContactIntent(uriString); String addContactString = getString(R.string.menu_add_address_to_contacts, uriString); menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString) .setOnMenuItemClickListener(l) .setIntent(intent); } } } private Uri getContactUriForEmail(String emailAddress) { Cursor cursor = SqliteWrapper.query(this, getContentResolver(), Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(emailAddress)), new String[] { Email.CONTACT_ID, Contacts.DISPLAY_NAME }, null, null, null); if (cursor != null) { try { while (cursor.moveToNext()) { String name = cursor.getString(1); if (!TextUtils.isEmpty(name)) { return ContentUris.withAppendedId(Contacts.CONTENT_URI, cursor.getLong(0)); } } } finally { cursor.close(); } } return null; } private Uri getContactUriForPhoneNumber(String phoneNumber) { Contact contact = Contact.get(phoneNumber, false); if (contact.existsInDatabase()) { return contact.getUri(); } return null; } private final OnCreateContextMenuListener mMsgListMenuCreateListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (!isCursorValid()) { return; } Cursor cursor = mMsgListAdapter.getCursor(); String type = cursor.getString(COLUMN_MSG_TYPE); long msgId = cursor.getLong(COLUMN_ID); addPositionBasedMenuItems(menu, v, menuInfo); MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId, cursor); if (msgItem == null) { Log.e(TAG, "Cannot load message item for type = " + type + ", msgId = " + msgId); return; } menu.setHeaderTitle(R.string.message_options); MsgListMenuClickListener l = new MsgListMenuClickListener(); // It is unclear what would make most sense for copying an MMS message // to the clipboard, so we currently do SMS only. if (msgItem.isSms()) { // Message type is sms. Only allow "edit" if the message has a single recipient if (getRecipients().size() == 1 && (msgItem.mBoxId == Sms.MESSAGE_TYPE_OUTBOX || msgItem.mBoxId == Sms.MESSAGE_TYPE_FAILED)) { menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit) .setOnMenuItemClickListener(l); } menu.add(0, MENU_COPY_MESSAGE_TEXT, 0, R.string.copy_message_text) .setOnMenuItemClickListener(l); } addCallAndContactMenuItems(menu, l, msgItem); // Forward is not available for undownloaded messages. if (msgItem.isDownloaded()) { menu.add(0, MENU_FORWARD_MESSAGE, 0, R.string.menu_forward) .setOnMenuItemClickListener(l); } if (msgItem.isMms()) { switch (msgItem.mBoxId) { case Mms.MESSAGE_BOX_INBOX: break; case Mms.MESSAGE_BOX_OUTBOX: // Since we currently break outgoing messages to multiple // recipients into one message per recipient, only allow // editing a message for single-recipient conversations. if (getRecipients().size() == 1) { menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit) .setOnMenuItemClickListener(l); } break; } switch (msgItem.mAttachmentType) { case WorkingMessage.TEXT: break; case WorkingMessage.VIDEO: case WorkingMessage.IMAGE: if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) { menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard) .setOnMenuItemClickListener(l); } break; case WorkingMessage.SLIDESHOW: default: menu.add(0, MENU_VIEW_SLIDESHOW, 0, R.string.view_slideshow) .setOnMenuItemClickListener(l); if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) { menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard) .setOnMenuItemClickListener(l); } if (haveSomethingToCopyToDrmProvider(msgItem.mMsgId)) { menu.add(0, MENU_COPY_TO_DRM_PROVIDER, 0, getDrmMimeMenuStringRsrc(msgItem.mMsgId)) .setOnMenuItemClickListener(l); } break; } } if (msgItem.mLocked) { menu.add(0, MENU_UNLOCK_MESSAGE, 0, R.string.menu_unlock) .setOnMenuItemClickListener(l); } else { menu.add(0, MENU_LOCK_MESSAGE, 0, R.string.menu_lock) .setOnMenuItemClickListener(l); } menu.add(0, MENU_VIEW_MESSAGE_DETAILS, 0, R.string.view_message_details) .setOnMenuItemClickListener(l); if (msgItem.mDeliveryStatus != MessageItem.DeliveryStatus.NONE || msgItem.mReadReport) { menu.add(0, MENU_DELIVERY_REPORT, 0, R.string.view_delivery_report) .setOnMenuItemClickListener(l); } menu.add(0, MENU_DELETE_MESSAGE, 0, R.string.delete_message) .setOnMenuItemClickListener(l); } }; private void editMessageItem(MessageItem msgItem) { if ("sms".equals(msgItem.mType)) { editSmsMessageItem(msgItem); } else { editMmsMessageItem(msgItem); } if (msgItem.isFailedMessage() && mMsgListAdapter.getCount() <= 1) { // For messages with bad addresses, let the user re-edit the recipients. initRecipientsEditor(); } } private void editSmsMessageItem(MessageItem msgItem) { // When the message being edited is the only message in the conversation, the delete // below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a // thread contains no messages and silently deletes the thread. Meanwhile, the mConversation // object still holds onto the old thread_id and code thinks there's a backing thread in // the DB when it really has been deleted. Here we try and notice that situation and // clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll // create a new thread if necessary. synchronized(mConversation) { if (mConversation.getMessageCount() <= 1) { mConversation.clearThreadId(); } } // Delete the old undelivered SMS and load its content. Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId); SqliteWrapper.delete(ComposeMessageActivity.this, mContentResolver, uri, null, null); mWorkingMessage.setText(msgItem.mBody); } private void editMmsMessageItem(MessageItem msgItem) { // Load the selected message in as the working message. WorkingMessage newWorkingMessage = WorkingMessage.load(this, msgItem.mMessageUri); if (newWorkingMessage == null) { return; } // Discard the current message in progress. mWorkingMessage.discard(); mWorkingMessage = newWorkingMessage; mWorkingMessage.setConversation(mConversation); drawTopPanel(false); // WorkingMessage.load() above only loads the slideshow. Set the // subject here because we already know what it is and avoid doing // another DB lookup in load() just to get it. mWorkingMessage.setSubject(msgItem.mSubject, false); if (mWorkingMessage.hasSubject()) { showSubjectEditor(true); } } private void copyToClipboard(String str) { ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); clip.setText(str); } private void forwardMessage(MessageItem msgItem) { Intent intent = createIntent(this, 0); intent.putExtra("exit_on_sent", true); intent.putExtra("forwarded_message", true); if (msgItem.mType.equals("sms")) { intent.putExtra("sms_body", msgItem.mBody); } else { SendReq sendReq = new SendReq(); String subject = getString(R.string.forward_prefix); if (msgItem.mSubject != null) { subject += msgItem.mSubject; } sendReq.setSubject(new EncodedStringValue(subject)); sendReq.setBody(msgItem.mSlideshow.makeCopy( ComposeMessageActivity.this)); Uri uri = null; try { PduPersister persister = PduPersister.getPduPersister(this); // Copy the parts of the message here. uri = persister.persist(sendReq, Mms.Draft.CONTENT_URI); } catch (MmsException e) { Log.e(TAG, "Failed to copy message: " + msgItem.mMessageUri); Toast.makeText(ComposeMessageActivity.this, R.string.cannot_save_message, Toast.LENGTH_SHORT).show(); return; } intent.putExtra("msg_uri", uri); intent.putExtra("subject", subject); } // ForwardMessageActivity is simply an alias in the manifest for ComposeMessageActivity. // We have to make an alias because ComposeMessageActivity launch flags specify // singleTop. When we forward a message, we want to start a separate ComposeMessageActivity. // The only way to do that is to override the singleTop flag, which is impossible to do // in code. By creating an alias to the activity, without the singleTop flag, we can // launch a separate ComposeMessageActivity to edit the forward message. intent.setClassName(this, "com.android.mms.ui.ForwardMessageActivity"); startActivity(intent); } /** * Context menu handlers for the message list view. */ private final class MsgListMenuClickListener implements MenuItem.OnMenuItemClickListener { public boolean onMenuItemClick(MenuItem item) { if (!isCursorValid()) { return false; } Cursor cursor = mMsgListAdapter.getCursor(); String type = cursor.getString(COLUMN_MSG_TYPE); long msgId = cursor.getLong(COLUMN_ID); MessageItem msgItem = getMessageItem(type, msgId, true); if (msgItem == null) { return false; } switch (item.getItemId()) { case MENU_EDIT_MESSAGE: editMessageItem(msgItem); drawBottomPanel(); return true; case MENU_COPY_MESSAGE_TEXT: copyToClipboard(msgItem.mBody); return true; case MENU_FORWARD_MESSAGE: forwardMessage(msgItem); return true; case MENU_VIEW_SLIDESHOW: MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId), null); return true; case MENU_VIEW_MESSAGE_DETAILS: { String messageDetails = MessageUtils.getMessageDetails( ComposeMessageActivity.this, cursor, msgItem.mMessageSize); new AlertDialog.Builder(ComposeMessageActivity.this) .setTitle(R.string.message_details_title) .setMessage(messageDetails) .setCancelable(true) .show(); return true; } case MENU_DELETE_MESSAGE: { DeleteMessageListener l = new DeleteMessageListener( msgItem.mMessageUri, msgItem.mLocked); confirmDeleteDialog(l, msgItem.mLocked); return true; } case MENU_DELIVERY_REPORT: showDeliveryReport(msgId, type); return true; case MENU_COPY_TO_SDCARD: { int resId = copyMedia(msgId) ? R.string.copy_to_sdcard_success : R.string.copy_to_sdcard_fail; Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show(); return true; } case MENU_COPY_TO_DRM_PROVIDER: { int resId = getDrmMimeSavedStringRsrc(msgId, copyToDrmProvider(msgId)); Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show(); return true; } case MENU_LOCK_MESSAGE: { lockMessage(msgItem, true); return true; } case MENU_UNLOCK_MESSAGE: { lockMessage(msgItem, false); return true; } default: return false; } } } private void lockMessage(MessageItem msgItem, boolean locked) { Uri uri; if ("sms".equals(msgItem.mType)) { uri = Sms.CONTENT_URI; } else { uri = Mms.CONTENT_URI; } final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId); final ContentValues values = new ContentValues(1); values.put("locked", locked ? 1 : 0); new Thread(new Runnable() { public void run() { getContentResolver().update(lockUri, values, null, null); } }, "lockMessage").start(); } /** * Looks to see if there are any valid parts of the attachment that can be copied to a SD card. * @param msgId */ private boolean haveSomethingToCopyToSDCard(long msgId) { PduBody body = null; try { body = SlideshowModel.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); } catch (MmsException e) { Log.e(TAG, "haveSomethingToCopyToSDCard can't load pdu body: " + msgId); } if (body == null) { return false; } boolean result = false; int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("[CMA] haveSomethingToCopyToSDCard: part[" + i + "] contentType=" + type); } if (ContentType.isImageType(type) || ContentType.isVideoType(type) || ContentType.isAudioType(type)) { result = true; break; } } return result; } /** * Looks to see if there are any drm'd parts of the attachment that can be copied to the * DrmProvider. Right now we only support saving audio (e.g. ringtones). * @param msgId */ private boolean haveSomethingToCopyToDrmProvider(long msgId) { String mimeType = getDrmMimeType(msgId); return isAudioMimeType(mimeType); } /** * Copies media from an Mms to the DrmProvider * @param msgId */ private boolean copyToDrmProvider(long msgId) { boolean result = true; PduBody body = null; try { body = SlideshowModel.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); } catch (MmsException e) { Log.e(TAG, "copyToDrmProvider can't load pdu body: " + msgId); } if (body == null) { return false; } int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (ContentType.isDrmType(type)) { // All parts (but there's probably only a single one) have to be successful // for a valid result. result &= copyPartToDrmProvider(part); } } return result; } private String mimeTypeOfDrmPart(PduPart part) { Uri uri = part.getDataUri(); InputStream input = null; try { input = mContentResolver.openInputStream(uri); if (input instanceof FileInputStream) { FileInputStream fin = (FileInputStream) input; DrmRawContent content = new DrmRawContent(fin, fin.available(), DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING); String mimeType = content.getContentType(); return mimeType; } } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while opening or reading stream", e); } catch (DrmException e) { Log.e(TAG, "DrmException caught ", e); } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); } } } return null; } /** * Returns the type of the first drm'd pdu part. * @param msgId */ private String getDrmMimeType(long msgId) { PduBody body = null; try { body = SlideshowModel.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); } catch (MmsException e) { Log.e(TAG, "getDrmMimeType can't load pdu body: " + msgId); } if (body == null) { return null; } int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (ContentType.isDrmType(type)) { return mimeTypeOfDrmPart(part); } } return null; } private int getDrmMimeMenuStringRsrc(long msgId) { String mimeType = getDrmMimeType(msgId); if (isAudioMimeType(mimeType)) { return R.string.save_ringtone; } return 0; } private int getDrmMimeSavedStringRsrc(long msgId, boolean success) { String mimeType = getDrmMimeType(msgId); if (isAudioMimeType(mimeType)) { return success ? R.string.saved_ringtone : R.string.saved_ringtone_fail; } return 0; } private boolean isAudioMimeType(String mimeType) { return mimeType != null && mimeType.startsWith("audio/"); } private boolean isImageMimeType(String mimeType) { return mimeType != null && mimeType.startsWith("image/"); } private boolean copyPartToDrmProvider(PduPart part) { Uri uri = part.getDataUri(); InputStream input = null; try { input = mContentResolver.openInputStream(uri); if (input instanceof FileInputStream) { FileInputStream fin = (FileInputStream) input; // Build a nice title byte[] location = part.getName(); if (location == null) { location = part.getFilename(); } if (location == null) { location = part.getContentLocation(); } // Depending on the location, there may be an // extension already on the name or not String title = new String(location); int index; if ((index = title.indexOf(".")) == -1) { String type = new String(part.getContentType()); } else { title = title.substring(0, index); } // transfer the file to the DRM content provider Intent item = DrmStore.addDrmFile(mContentResolver, fin, title); if (item == null) { Log.w(TAG, "unable to add file " + uri + " to DrmProvider"); return false; } } } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while opening or reading stream", e); return false; } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); return false; } } } return true; } /** * Copies media from an Mms to the "download" directory on the SD card * @param msgId */ private boolean copyMedia(long msgId) { boolean result = true; PduBody body = null; try { body = SlideshowModel.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); } catch (MmsException e) { Log.e(TAG, "copyMedia can't load pdu body: " + msgId); } if (body == null) { return false; } int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (ContentType.isImageType(type) || ContentType.isVideoType(type) || ContentType.isAudioType(type)) { result &= copyPart(part, Long.toHexString(msgId)); // all parts have to be successful for a valid result. } } return result; } private boolean copyPart(PduPart part, String fallback) { Uri uri = part.getDataUri(); InputStream input = null; FileOutputStream fout = null; try { input = mContentResolver.openInputStream(uri); if (input instanceof FileInputStream) { FileInputStream fin = (FileInputStream) input; byte[] location = part.getName(); if (location == null) { location = part.getFilename(); } if (location == null) { location = part.getContentLocation(); } String fileName; if (location == null) { // Use fallback name. fileName = fallback; } else { // For locally captured videos, fileName can end up being something like this: // /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp fileName = new String(location); } File originalFile = new File(fileName); fileName = originalFile.getName(); // Strip the full path of where the "part" is // stored down to just the leaf filename. // Depending on the location, there may be an // extension already on the name or not String dir = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/"; String extension; int index; if ((index = fileName.lastIndexOf('.')) == -1) { String type = new String(part.getContentType()); extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type); } else { extension = fileName.substring(index + 1, fileName.length()); fileName = fileName.substring(0, index); } File file = getUniqueDestination(dir + fileName, extension); // make sure the path is valid and directories created for this file. File parentFile = file.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!"); return false; } fout = new FileOutputStream(file); byte[] buffer = new byte[8000]; int size = 0; while ((size=fin.read(buffer)) != -1) { fout.write(buffer, 0, size); } // Notify other applications listening to scanner events // that a media file has been added to the sd card sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); } } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while opening or reading stream", e); return false; } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); return false; } } if (null != fout) { try { fout.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); return false; } } } return true; } private File getUniqueDestination(String base, String extension) { File file = new File(base + "." + extension); for (int i = 2; file.exists(); i++) { file = new File(base + "_" + i + "." + extension); } return file; } private void showDeliveryReport(long messageId, String type) { Intent intent = new Intent(this, DeliveryReportActivity.class); intent.putExtra("message_id", messageId); intent.putExtra("message_type", type); startActivity(intent); } private final IntentFilter mHttpProgressFilter = new IntentFilter(PROGRESS_STATUS_ACTION); private final BroadcastReceiver mHttpProgressReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (PROGRESS_STATUS_ACTION.equals(intent.getAction())) { long token = intent.getLongExtra("token", SendingProgressTokenManager.NO_TOKEN); if (token != mConversation.getThreadId()) { return; } int progress = intent.getIntExtra("progress", 0); switch (progress) { case PROGRESS_START: setProgressBarVisibility(true); break; case PROGRESS_ABORT: case PROGRESS_COMPLETE: setProgressBarVisibility(false); break; default: setProgress(100 * progress); } } } }; private static ContactList sEmptyContactList; private ContactList getRecipients() { // If the recipients editor is visible, the conversation has // not really officially 'started' yet. Recipients will be set // on the conversation once it has been saved or sent. In the // meantime, let anyone who needs the recipient list think it // is empty rather than giving them a stale one. if (isRecipientsEditorVisible()) { if (sEmptyContactList == null) { sEmptyContactList = new ContactList(); } return sEmptyContactList; } return mConversation.getRecipients(); } private void updateTitle(ContactList list) { String title = null;; String subTitle = null; int cnt = list.size(); switch (cnt) { case 0: { String recipient = null; if (mRecipientsEditor != null) { recipient = mRecipientsEditor.getText().toString(); } title = TextUtils.isEmpty(recipient) ? getString(R.string.new_message) : recipient; break; } case 1: { title = list.get(0).getName(); // get name returns the number if there's no // name available. String number = list.get(0).getNumber(); if (!title.equals(number)) { subTitle = PhoneNumberUtils.formatNumber(number, number, MmsApp.getApplication().getCurrentCountryIso()); } break; } default: { // Handle multiple recipients title = list.formatNames(", "); subTitle = getResources().getQuantityString(R.plurals.recipient_count, cnt, cnt); break; } } mDebugRecipients = list.serialize(); ActionBar actionBar = getActionBar(); actionBar.setTitle(title); actionBar.setSubtitle(subTitle); } // Get the recipients editor ready to be displayed onscreen. private void initRecipientsEditor() { if (isRecipientsEditorVisible()) { return; } // Must grab the recipients before the view is made visible because getRecipients() // returns empty recipients when the editor is visible. ContactList recipients = getRecipients(); ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub); if (stub != null) { View stubView = stub.inflate(); mRecipientsEditor = (RecipientsEditor) stubView.findViewById(R.id.recipients_editor); mRecipientsPicker = (ImageButton) stubView.findViewById(R.id.recipients_picker); } else { mRecipientsEditor = (RecipientsEditor)findViewById(R.id.recipients_editor); mRecipientsEditor.setVisibility(View.VISIBLE); mRecipientsPicker = (ImageButton)findViewById(R.id.recipients_picker); } mRecipientsPicker.setOnClickListener(this); mRecipientsEditor.setAdapter(new RecipientsAdapter(this)); mRecipientsEditor.populate(recipients); mRecipientsEditor.setOnCreateContextMenuListener(mRecipientsMenuCreateListener); mRecipientsEditor.addTextChangedListener(mRecipientsWatcher); // TODO : Remove the max length limitation due to the multiple phone picker is added and the // user is able to select a large number of recipients from the Contacts. The coming // potential issue is that it is hard for user to edit a recipient from hundred of // recipients in the editor box. We may redesign the editor box UI for this use case. // mRecipientsEditor.setFilters(new InputFilter[] { // new InputFilter.LengthFilter(RECIPIENTS_MAX_LENGTH) }); mRecipientsEditor.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // After the user selects an item in the pop-up contacts list, move the // focus to the text editor if there is only one recipient. This helps // the common case of selecting one recipient and then typing a message, // but avoids annoying a user who is trying to add five recipients and // keeps having focus stolen away. if (mRecipientsEditor.getRecipientCount() == 1) { // if we're in extract mode then don't request focus final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager == null || !inputManager.isFullscreenMode()) { mTextEditor.requestFocus(); } } } }); mRecipientsEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { RecipientsEditor editor = (RecipientsEditor) v; ContactList contacts = editor.constructContactsFromInput(false); updateTitle(contacts); } } }); mTopPanel.setVisibility(View.VISIBLE); } //========================================================== // Activity methods //========================================================== public static boolean cancelFailedToDeliverNotification(Intent intent, Context context) { if (MessagingNotification.isFailedToDeliver(intent)) { // Cancel any failed message notifications MessagingNotification.cancelNotification(context, MessagingNotification.MESSAGE_FAILED_NOTIFICATION_ID); return true; } return false; } public static boolean cancelFailedDownloadNotification(Intent intent, Context context) { if (MessagingNotification.isFailedToDownload(intent)) { // Cancel any failed download notifications MessagingNotification.cancelNotification(context, MessagingNotification.DOWNLOAD_FAILED_NOTIFICATION_ID); return true; } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); resetConfiguration(getResources().getConfiguration()); setContentView(R.layout.compose_message_activity); setProgressBarVisibility(false); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); // Initialize members for UI elements. initResourceRefs(); mContentResolver = getContentResolver(); mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver); initialize(0); if (TRACE) { android.os.Debug.startMethodTracing("compose"); } } private void showSubjectEditor(boolean show) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("" + show); } if (mSubjectTextEditor == null) { // Don't bother to initialize the subject editor if // we're just going to hide it. if (show == false) { return; } mSubjectTextEditor = (EditText)findViewById(R.id.subject); mSubjectTextEditor.setFilters(new InputFilter[] { new LengthFilter(MmsConfig.getMaxSubjectLength())}); } mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null); if (show) { mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher); } else { mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher); } mSubjectTextEditor.setText(mWorkingMessage.getSubject()); mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE); hideOrShowTopPanel(); } private void hideOrShowTopPanel() { boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible()); mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE); } public void initialize(long originalThreadId) { Intent intent = getIntent(); // Create a new empty working message. mWorkingMessage = WorkingMessage.createEmpty(this); // Read parameters or previously saved state of this activity. This will load a new // mConversation initActivityState(intent); if (LogTag.SEVERE_WARNING && originalThreadId != 0 && originalThreadId == mConversation.getThreadId()) { LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " + " threadId didn't change from: " + originalThreadId, this); } log(" intent = " + intent + "originalThreadId = " + originalThreadId + " mConversation = " + mConversation); if (cancelFailedToDeliverNotification(getIntent(), this)) { // Show a pop-up dialog to inform user the message was // failed to deliver. undeliveredMessageDialog(getMessageDate(null)); } cancelFailedDownloadNotification(getIntent(), this); // Set up the message history ListAdapter initMessageList(); // Load the draft for this thread, if we aren't already handling // existing data, such as a shared picture or forwarded message. boolean isForwardedMessage = false; if (!handleSendIntent(intent)) { isForwardedMessage = handleForwardedMessage(); if (!isForwardedMessage) { loadDraft(); } } // Let the working message know what conversation it belongs to mWorkingMessage.setConversation(mConversation); // Show the recipients editor if we don't have a valid thread. Hide it otherwise. if (mConversation.getThreadId() <= 0) { // Hide the recipients editor so the call to initRecipientsEditor won't get // short-circuited. hideRecipientEditor(); initRecipientsEditor(); // Bring up the softkeyboard so the user can immediately enter recipients. This // call won't do anything on devices with a hard keyboard. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } else { hideRecipientEditor(); } updateSendButtonState(); drawTopPanel(false); drawBottomPanel(); onKeyboardStateChanged(mIsKeyboardOpen); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("update title, mConversation=" + mConversation.toString()); } updateTitle(mConversation.getRecipients()); if (isForwardedMessage && isRecipientsEditorVisible()) { // The user is forwarding the message to someone. Put the focus on the // recipient editor rather than in the message editor. mRecipientsEditor.requestFocus(); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); Conversation conversation = null; mSentMessage = false; // If we have been passed a thread_id, use that to find our // conversation. // Note that originalThreadId might be zero but if this is a draft and we save the // draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage // the thread will get a threadId behind the UI thread's back. long originalThreadId = mConversation.getThreadId(); long threadId = intent.getLongExtra("thread_id", 0); Uri intentUri = intent.getData(); boolean sameThread = false; if (threadId > 0) { conversation = Conversation.get(this, threadId, false); } else { if (mConversation.getThreadId() == 0) { // We've got a draft. Make sure the working recipients are synched // to the conversation so when we compare conversations later in this function, // the compare will work. mWorkingMessage.syncWorkingRecipients(); } // Get the "real" conversation based on the intentUri. The intentUri might specify // the conversation by a phone number or by a thread id. We'll typically get a threadId // based uri when the user pulls down a notification while in ComposeMessageActivity and // we end up here in onNewIntent. mConversation can have a threadId of zero when we're // working on a draft. When a new message comes in for that same recipient, a // conversation will get created behind CMA's back when the message is inserted into // the database and the corresponding entry made in the threads table. The code should // use the real conversation as soon as it can rather than finding out the threadId // when sending with "ensureThreadId". conversation = Conversation.get(this, intentUri, false); } if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("onNewIntent: data=" + intentUri + ", thread_id extra is " + threadId + ", new conversation=" + conversation + ", mConversation=" + mConversation); } // this is probably paranoid to compare both thread_ids and recipient lists, // but we want to make double sure because this is a last minute fix for Froyo // and the previous code checked thread ids only. // (we cannot just compare thread ids because there is a case where mConversation // has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1), // even though the recipient lists are different) sameThread = ((conversation.getThreadId() == mConversation.getThreadId() || mConversation.getThreadId() == 0) && conversation.equals(mConversation)); // Don't let any markAsRead DB updates occur before we've loaded the messages for // the thread. Unblocking occurs when we're done querying for the conversation // items. conversation.blockMarkAsRead(true); if (sameThread) { log("onNewIntent: same conversation"); if (mConversation.getThreadId() == 0) { mConversation = conversation; mWorkingMessage.setConversation(mConversation); } mConversation.markAsRead(); // dismiss any notifications for this convo } else { if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("onNewIntent: different conversation"); } saveDraft(false); // if we've got a draft, save it first initialize(originalThreadId); } loadMessageContent(); } private void sanityCheckConversation() { if (mWorkingMessage.getConversation() != mConversation) { LogTag.warnPossibleRecipientMismatch( "ComposeMessageActivity: mWorkingMessage.mConversation=" + mWorkingMessage.getConversation() + ", mConversation=" + mConversation + ", MISMATCH!", this); } } @Override protected void onRestart() { super.onRestart(); if (mWorkingMessage.isDiscarded()) { // If the message isn't worth saving, don't resurrect it. Doing so can lead to // a situation where a new incoming message gets the old thread id of the discarded // draft. This activity can end up displaying the recipients of the old message with // the contents of the new message. Recognize that dangerous situation and bail out // to the ConversationList where the user can enter this in a clean manner. if (mWorkingMessage.isWorthSaving()) { if (LogTag.VERBOSE) { log("onRestart: mWorkingMessage.unDiscard()"); } mWorkingMessage.unDiscard(); // it was discarded in onStop(). sanityCheckConversation(); } else if (isRecipientsEditorVisible()) { if (LogTag.VERBOSE) { log("onRestart: goToConversationList"); } goToConversationList(); } else { if (LogTag.VERBOSE) { log("onRestart: loadDraft"); } loadDraft(); mWorkingMessage.setConversation(mConversation); mAttachmentEditor.update(mWorkingMessage); } } } @Override protected void onStart() { super.onStart(); mConversation.blockMarkAsRead(true); initFocus(); // Register a BroadcastReceiver to listen on HTTP I/O process. registerReceiver(mHttpProgressReceiver, mHttpProgressFilter); loadMessageContent(); // Update the fasttrack info in case any of the recipients' contact info changed // while we were paused. This can happen, for example, if a user changes or adds // an avatar associated with a contact. mWorkingMessage.syncWorkingRecipients(); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("update title, mConversation=" + mConversation.toString()); } updateTitle(mConversation.getRecipients()); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } public void loadMessageContent() { startMsgListQuery(); updateSendFailedNotification(); drawBottomPanel(); } private void updateSendFailedNotification() { final long threadId = mConversation.getThreadId(); if (threadId <= 0) return; // updateSendFailedNotificationForThread makes a database call, so do the work off // of the ui thread. new Thread(new Runnable() { public void run() { MessagingNotification.updateSendFailedNotificationForThread( ComposeMessageActivity.this, threadId); } }, "updateSendFailedNotification").start(); } @Override protected void onResume() { super.onResume(); // OLD: get notified of presence updates to update the titlebar. // NEW: we are using ContactHeaderWidget which displays presence, but updating presence // there is out of our control. //Contact.startPresenceObserver(); addRecipientsListeners(); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("update title, mConversation=" + mConversation.toString()); } // There seems to be a bug in the framework such that setting the title // here gets overwritten to the original title. Do this delayed as a // workaround. mMessageListItemHandler.postDelayed(new Runnable() { public void run() { ContactList recipients = isRecipientsEditorVisible() ? mRecipientsEditor.constructContactsFromInput(false) : getRecipients(); updateTitle(recipients); } }, 100); } @Override protected void onPause() { super.onPause(); // OLD: stop getting notified of presence updates to update the titlebar. // NEW: we are using ContactHeaderWidget which displays presence, but updating presence // there is out of our control. //Contact.stopPresenceObserver(); removeRecipientsListeners(); clearPendingProgressDialog(); } @Override protected void onStop() { super.onStop(); // Allow any blocked calls to update the thread's read status. mConversation.blockMarkAsRead(false); if (mMsgListAdapter != null) { mMsgListAdapter.changeCursor(null); } if (mRecipientsEditor != null) { CursorAdapter recipientsAdapter = (CursorAdapter)mRecipientsEditor.getAdapter(); if (recipientsAdapter != null) { recipientsAdapter.changeCursor(null); } } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("save draft"); } saveDraft(true); // Cleanup the BroadcastReceiver. unregisterReceiver(mHttpProgressReceiver); } @Override protected void onDestroy() { if (TRACE) { android.os.Debug.stopMethodTracing(); } super.onDestroy(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (LOCAL_LOGV) { Log.v(TAG, "onConfigurationChanged: " + newConfig); } if (resetConfiguration(newConfig)) { // Have to re-layout the attachment editor because we have different layouts // depending on whether we're portrait or landscape. drawTopPanel(isSubjectEditorVisible()); } onKeyboardStateChanged(mIsKeyboardOpen); } // returns true if landscape/portrait configuration has changed private boolean resetConfiguration(Configuration config) { mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO; boolean isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE; if (mIsLandscape != isLandscape) { mIsLandscape = isLandscape; return true; } return false; } private void onKeyboardStateChanged(boolean isKeyboardOpen) { // If the keyboard is hidden, don't show focus highlights for // things that cannot receive input. if (isKeyboardOpen) { if (mRecipientsEditor != null) { mRecipientsEditor.setFocusableInTouchMode(true); } if (mSubjectTextEditor != null) { mSubjectTextEditor.setFocusableInTouchMode(true); } mTextEditor.setFocusableInTouchMode(true); mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send); } else { if (mRecipientsEditor != null) { mRecipientsEditor.setFocusable(false); } if (mSubjectTextEditor != null) { mSubjectTextEditor.setFocusable(false); } mTextEditor.setFocusable(false); mTextEditor.setHint(R.string.open_keyboard_to_compose_message); } } @Override public void onUserInteraction() { checkPendingNotification(); } @Override public void onWindowFocusChanged(boolean hasFocus) { if (hasFocus) { checkPendingNotification(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: if ((mMsgListAdapter != null) && mMsgListView.isFocused()) { Cursor cursor; try { cursor = (Cursor) mMsgListView.getSelectedItem(); } catch (ClassCastException e) { Log.e(TAG, "Unexpected ClassCastException.", e); return super.onKeyDown(keyCode, event); } if (cursor != null) { boolean locked = cursor.getInt(COLUMN_MMS_LOCKED) != 0; DeleteMessageListener l = new DeleteMessageListener( cursor.getLong(COLUMN_ID), cursor.getString(COLUMN_MSG_TYPE), locked); confirmDeleteDialog(l, locked); return true; } } break; case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: if (isPreparedForSending()) { confirmSendMessageIfNeeded(); return true; } break; case KeyEvent.KEYCODE_BACK: exitComposeMessageActivity(new Runnable() { public void run() { finish(); } }); return true; } return super.onKeyDown(keyCode, event); } private void exitComposeMessageActivity(final Runnable exit) { // If the message is empty, just quit -- finishing the // activity will cause an empty draft to be deleted. if (!mWorkingMessage.isWorthSaving()) { exit.run(); return; } if (isRecipientsEditorVisible() && !mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) { MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener()); return; } mToastForDraftSave = true; exit.run(); } private void goToConversationList() { finish(); startActivity(new Intent(this, ConversationList.class)); } private void hideRecipientEditor() { if (mRecipientsEditor != null) { mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher); mRecipientsEditor.setVisibility(View.GONE); hideOrShowTopPanel(); } } private boolean isRecipientsEditorVisible() { return (null != mRecipientsEditor) && (View.VISIBLE == mRecipientsEditor.getVisibility()); } private boolean isSubjectEditorVisible() { return (null != mSubjectTextEditor) && (View.VISIBLE == mSubjectTextEditor.getVisibility()); } public void onAttachmentChanged() { // Have to make sure we're on the UI thread. This function can be called off of the UI // thread when we're adding multi-attachments runOnUiThread(new Runnable() { public void run() { drawBottomPanel(); updateSendButtonState(); drawTopPanel(isSubjectEditorVisible()); } }); } public void onProtocolChanged(final boolean mms) { // Have to make sure we're on the UI thread. This function can be called off of the UI // thread when we're adding multi-attachments runOnUiThread(new Runnable() { public void run() { toastConvertInfo(mms); showSmsOrMmsSendButton(mms); if (mms) { // In the case we went from a long sms with a counter to an mms because // the user added an attachment or a subject, hide the counter -- // it doesn't apply to mms. mTextCounter.setVisibility(View.GONE); } } }); } // Show or hide the Sms or Mms button as appropriate. Return the view so that the caller // can adjust the enableness and focusability. private View showSmsOrMmsSendButton(boolean isMms) { View showButton; View hideButton; if (isMms) { showButton = mSendButtonMms; hideButton = mSendButtonSms; } else { showButton = mSendButtonSms; hideButton = mSendButtonMms; } showButton.setVisibility(View.VISIBLE); hideButton.setVisibility(View.GONE); return showButton; } Runnable mResetMessageRunnable = new Runnable() { public void run() { resetMessage(); } }; public void onPreMessageSent() { runOnUiThread(mResetMessageRunnable); } public void onMessageSent() { // If we already have messages in the list adapter, it // will be auto-requerying; don't thrash another query in. if (mMsgListAdapter.getCount() == 0) { if (LogTag.VERBOSE) { log("onMessageSent"); } startMsgListQuery(); } } public void onMaxPendingMessagesReached() { saveDraft(false); runOnUiThread(new Runnable() { public void run() { Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms, Toast.LENGTH_LONG).show(); } }); } public void onAttachmentError(final int error) { runOnUiThread(new Runnable() { public void run() { handleAddAttachmentError(error, R.string.type_picture); onMessageSent(); // now requery the list of messages } }); } // We don't want to show the "call" option unless there is only one // recipient and it's a phone number. private boolean isRecipientCallable() { ContactList recipients = getRecipients(); return (recipients.size() == 1 && !recipients.containsEmail()); } private void dialRecipient() { if (isRecipientCallable()) { String number = getRecipients().get(0).getNumber(); Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number)); startActivity(dialIntent); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (isRecipientCallable()) { MenuItem item = menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call) .setIcon(R.drawable.ic_menu_call) .setTitle(R.string.menu_call); if (!isRecipientsEditorVisible()) { // If we're not composing a new message, show the call icon in the actionbar item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } if (MmsConfig.getMmsEnabled()) { if (!isSubjectEditorVisible()) { menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon( R.drawable.ic_menu_edit); } menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment) .setIcon(R.drawable.ic_menu_attachment) .setTitle(R.string.add_attachment) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); // add to actionbar } if (isPreparedForSending()) { menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send); } if (!mWorkingMessage.hasSlideshow()) { menu.add(0, MENU_INSERT_SMILEY, 0, R.string.menu_insert_smiley).setIcon( R.drawable.ic_menu_emoticons); } if (mMsgListAdapter.getCount() > 0) { // Removed search as part of b/1205708 //menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon( // R.drawable.ic_menu_search); Cursor cursor = mMsgListAdapter.getCursor(); if ((null != cursor) && (cursor.getCount() > 0)) { menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon( android.R.drawable.ic_menu_delete); } } else { menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete); } buildAddAddressToContactMenuItem(menu); menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon( android.R.drawable.ic_menu_preferences); if (LogTag.DEBUG_DUMP) { menu.add(0, MENU_DEBUG_DUMP, 0, R.string.menu_debug_dump); } return true; } private void buildAddAddressToContactMenuItem(Menu menu) { // Look for the first recipient we don't have a contact for and create a menu item to // add the number to contacts. for (Contact c : getRecipients()) { if (!c.existsInDatabase() && canAddToContacts(c)) { Intent intent = ConversationList.createAddContactIntent(c.getNumber()); menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts) .setIcon(android.R.drawable.ic_menu_add) .setIntent(intent); break; } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ADD_SUBJECT: showSubjectEditor(true); mWorkingMessage.setSubject("", true); mSubjectTextEditor.requestFocus(); break; case MENU_ADD_ATTACHMENT: // Launch the add-attachment list dialog showAddAttachmentDialog(false); break; case MENU_DISCARD: mWorkingMessage.discard(); finish(); break; case MENU_SEND: if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } break; case MENU_SEARCH: onSearchRequested(); break; case MENU_DELETE_THREAD: confirmDeleteThread(mConversation.getThreadId()); break; case android.R.id.home: case MENU_CONVERSATION_LIST: exitComposeMessageActivity(new Runnable() { public void run() { goToConversationList(); } }); break; case MENU_CALL_RECIPIENT: dialRecipient(); break; case MENU_INSERT_SMILEY: showSmileyDialog(); break; case MENU_VIEW_CONTACT: { // View the contact for the first (and only) recipient. ContactList list = getRecipients(); if (list.size() == 1 && list.get(0).existsInDatabase()) { Uri contactUri = list.get(0).getUri(); Intent intent = new Intent(Intent.ACTION_VIEW, contactUri); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } break; } case MENU_ADD_ADDRESS_TO_CONTACTS: mAddContactIntent = item.getIntent(); startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT); break; case MENU_PREFERENCES: { Intent intent = new Intent(this, MessagingPreferenceActivity.class); startActivityIfNeeded(intent, -1); break; } case MENU_DEBUG_DUMP: mWorkingMessage.dump(); Conversation.dump(); LogTag.dumpInternalTables(this); break; } return true; } private void confirmDeleteThread(long threadId) { Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler, threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN); } // static class SystemProperties { // TODO, temp class to get unbundling working // static int getInt(String s, int value) { // return value; // just return the default value or now // } // } private void addAttachment(int type, boolean replace) { // Calculate the size of the current slide if we're doing a replace so the // slide size can optionally be used in computing how much room is left for an attachment. int currentSlideSize = 0; SlideshowModel slideShow = mWorkingMessage.getSlideshow(); if (replace && slideShow != null) { SlideModel slide = slideShow.get(0); currentSlideSize = slide.getSlideSize(); } switch (type) { case AttachmentTypeSelectorAdapter.ADD_IMAGE: MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE); break; case AttachmentTypeSelectorAdapter.TAKE_PICTURE: { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, TempFileProvider.SCRAP_CONTENT_URI); startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE); break; } case AttachmentTypeSelectorAdapter.ADD_VIDEO: MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO); break; case AttachmentTypeSelectorAdapter.RECORD_VIDEO: { long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize); if (sizeLimit > 0) { MessageUtils.recordVideo(this, REQUEST_CODE_TAKE_VIDEO, sizeLimit); } else { Toast.makeText(this, getString(R.string.message_too_big_for_video), Toast.LENGTH_SHORT).show(); } } break; case AttachmentTypeSelectorAdapter.ADD_SOUND: MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND); break; case AttachmentTypeSelectorAdapter.RECORD_SOUND: long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize); MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND, sizeLimit); break; case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW: editSlideshow(); break; default: break; } } public static long computeAttachmentSizeLimit(SlideshowModel slideShow, int currentSlideSize) { // Computer attachment size limit. Subtract 1K for some text. long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP; if (slideShow != null) { sizeLimit -= slideShow.getCurrentMessageSize(); // We're about to ask the camera to capture some video (or the sound recorder // to record some audio) which will eventually replace the content on the current // slide. Since the current slide already has some content (which was subtracted // out just above) and that content is going to get replaced, we can add the size of the // current slide into the available space used to capture a video (or audio). sizeLimit += currentSlideSize; } return sizeLimit; } private void showAddAttachmentDialog(final boolean replace) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_dialog_attach); builder.setTitle(R.string.add_attachment); if (mAttachmentTypeSelectorAdapter == null) { mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter( this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW); } builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace); dialog.dismiss(); } }); builder.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (LogTag.VERBOSE) { log("requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data); } mWaitingForSubActivity = false; // We're back! if (mWorkingMessage.isFakeMmsForDraft()) { // We no longer have to fake the fact we're an Mms. At this point we are or we aren't, // based on attachments and other Mms attrs. mWorkingMessage.removeFakeMmsForDraft(); } if (requestCode == REQUEST_CODE_PICK) { mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation); } if (requestCode == REQUEST_CODE_ADD_CONTACT) { // The user might have added a new contact. When we tell contacts to add a contact // and tap "Done", we're not returned to Messaging. If we back out to return to // messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore, // assume a contact was added and get the contact and force our cached contact to // get reloaded with the new info (such as contact name). After the // contact is reloaded, the function onUpdate() in this file will get called // and it will update the title bar, etc. if (mAddContactIntent != null) { String address = mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL); if (address == null) { address = mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE); } if (address != null) { Contact contact = Contact.get(address, false); if (contact != null) { contact.reload(); } } } } if (resultCode != RESULT_OK){ if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode); return; } switch (requestCode) { case REQUEST_CODE_CREATE_SLIDESHOW: if (data != null) { WorkingMessage newMessage = WorkingMessage.load(this, data.getData()); if (newMessage != null) { mWorkingMessage = newMessage; mWorkingMessage.setConversation(mConversation); drawTopPanel(false); updateSendButtonState(); } } break; case REQUEST_CODE_TAKE_PICTURE: { // create a file based uri and pass to addImage(). We want to read the JPEG // data directly from file (using UriImage) instead of decoding it into a Bitmap, // which takes up too much memory and could easily lead to OOM. File file = new File(TempFileProvider.getScrapPath()); Uri uri = Uri.fromFile(file); addImageAsync(uri, false); break; } case REQUEST_CODE_ATTACH_IMAGE: { if (data != null) { addImageAsync(data.getData(), false); } break; } case REQUEST_CODE_TAKE_VIDEO: Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null); addVideoAsync(videoUri, false); // can handle null videoUri break; case REQUEST_CODE_ATTACH_VIDEO: if (data != null) { addVideoAsync(data.getData(), false); } break; case REQUEST_CODE_ATTACH_SOUND: { Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) { break; } addAudio(uri); break; } case REQUEST_CODE_RECORD_SOUND: if (data != null) { addAudio(data.getData()); } break; case REQUEST_CODE_ECM_EXIT_DIALOG: boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false); if (outOfEmergencyMode) { sendMessage(false); } break; case REQUEST_CODE_PICK: if (data != null) { processPickResult(data); } break; default: if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode); break; } } private void processPickResult(final Intent data) { // The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the // multiple phone picker. final Parcelable[] uris = data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS); final int recipientCount = uris != null ? uris.length : 0; final int recipientLimit = MmsConfig.getRecipientLimit(); if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) { new AlertDialog.Builder(this) .setTitle(R.string.pick_too_many_recipients) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit)) .setPositiveButton(android.R.string.ok, null) .create().show(); return; } final Handler handler = new Handler(); final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle(getText(R.string.pick_too_many_recipients)); progressDialog.setMessage(getText(R.string.adding_recipients)); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); final Runnable showProgress = new Runnable() { public void run() { progressDialog.show(); } }; // Only show the progress dialog if we can not finish off parsing the return data in 1s, // otherwise the dialog could flicker. handler.postDelayed(showProgress, 1000); new Thread(new Runnable() { public void run() { final ContactList list; try { list = ContactList.blockingGetByUris(uris); } finally { handler.removeCallbacks(showProgress); progressDialog.dismiss(); } // TODO: there is already code to update the contact header widget and recipients // editor if the contacts change. we can re-use that code. final Runnable populateWorker = new Runnable() { public void run() { mRecipientsEditor.populate(list); updateTitle(list); } }; handler.post(populateWorker); } }).start(); } private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() { // TODO: make this produce a Uri, that's what we want anyway public void onResizeResult(PduPart part, boolean append) { if (part == null) { handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture); return; } Context context = ComposeMessageActivity.this; PduPersister persister = PduPersister.getPduPersister(context); int result; Uri messageUri = mWorkingMessage.saveAsMms(true); if (messageUri == null) { result = WorkingMessage.UNKNOWN_ERROR; } else { try { Uri dataUri = persister.persistPart(part, ContentUris.parseId(messageUri)); result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("ResizeImageResultCallback: dataUri=" + dataUri); } } catch (MmsException e) { result = WorkingMessage.UNKNOWN_ERROR; } } handleAddAttachmentError(result, R.string.type_picture); } }; private void handleAddAttachmentError(final int error, final int mediaTypeStringId) { if (error == WorkingMessage.OK) { return; } runOnUiThread(new Runnable() { public void run() { Resources res = getResources(); String mediaType = res.getString(mediaTypeStringId); String title, message; switch(error) { case WorkingMessage.UNKNOWN_ERROR: message = res.getString(R.string.failed_to_add_media, mediaType); Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show(); return; case WorkingMessage.UNSUPPORTED_TYPE: title = res.getString(R.string.unsupported_media_format, mediaType); message = res.getString(R.string.select_different_media, mediaType); break; case WorkingMessage.MESSAGE_SIZE_EXCEEDED: title = res.getString(R.string.exceed_message_size_limitation, mediaType); message = res.getString(R.string.failed_to_add_media, mediaType); break; case WorkingMessage.IMAGE_TOO_LARGE: title = res.getString(R.string.failed_to_resize_image); message = res.getString(R.string.resize_image_error_information); break; default: throw new IllegalArgumentException("unknown error " + error); } MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message); } }); } private void addImageAsync(final Uri uri, final boolean append) { runAsyncWithDialog(new Runnable() { public void run() { addImage(uri, append); } }, R.string.adding_attachments_title); } private void addImage(Uri uri, boolean append) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("append=" + append + ", uri=" + uri); } int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append); if (result == WorkingMessage.IMAGE_TOO_LARGE || result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("resize image " + uri); } MessageUtils.resizeImageAsync(ComposeMessageActivity.this, uri, mAttachmentEditorHandler, mResizeImageCallback, append); return; } handleAddAttachmentError(result, R.string.type_picture); } private void addVideoAsync(final Uri uri, final boolean append) { runAsyncWithDialog(new Runnable() { public void run() { addVideo(uri, append); } }, R.string.adding_attachments_title); } private void addVideo(Uri uri, boolean append) { if (uri != null) { int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append); handleAddAttachmentError(result, R.string.type_video); } } private void addAudio(Uri uri) { int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false); handleAddAttachmentError(result, R.string.type_audio); } /** * Asynchronously executes a task while blocking the UI with a progress spinner. * * Must be invoked by the UI thread. No exceptions! * * @param task the work to be done wrapped in a Runnable * @param dialogStringId the id of the string to be shown in the dialog */ private void runAsyncWithDialog(final Runnable task, final int dialogStringId) { new ModalDialogAsyncTask(dialogStringId).execute(new Runnable[] {task}); } /** * Asynchronously performs tasks specified by Runnables. * Displays a progress spinner while the tasks are running. The progress spinner * will only show if tasks have not finished after a certain amount of time. * * This AsyncTask must be instantiated and invoked on the UI thread. */ private class ModalDialogAsyncTask extends AsyncTask<Runnable, Void, Void> { final int mDialogStringId; /** * Creates the Task with the specified string id to be shown in the dialog */ public ModalDialogAsyncTask(int dialogStringId) { this.mDialogStringId = dialogStringId; // lazy initialization of progress dialog for loading attachments if (mProgressDialog == null) { mProgressDialog = createProgressDialog(); } } /** * Initializes the progress dialog with its intended settings. */ private ProgressDialog createProgressDialog() { ProgressDialog dialog = new ProgressDialog(ComposeMessageActivity.this); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.setMessage(ComposeMessageActivity.this. getText(mDialogStringId)); return dialog; } /** * Activates a progress spinner on the UI. This assumes the UI has invoked this Task. */ @Override protected void onPreExecute() { // activate spinner after half a second mAttachmentEditorHandler.postDelayed(mShowProgressDialogRunnable, 500); } /** * Perform the specified Runnable tasks on a background thread */ @Override protected Void doInBackground(Runnable... params) { if (params != null) { try { for (int i = 0; i < params.length; i++) { params[i].run(); } } finally { // Cancel pending display of the progress bar if the image has finished loading. mAttachmentEditorHandler.removeCallbacks(mShowProgressDialogRunnable); } } return null; } /** * Deactivates the progress spinner on the UI. This assumes the UI has invoked this Task. */ @Override protected void onPostExecute(Void result) { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } } private boolean handleForwardedMessage() { Intent intent = getIntent(); // If this is a forwarded message, it will have an Intent extra // indicating so. If not, bail out. if (intent.getBooleanExtra("forwarded_message", false) == false) { return false; } Uri uri = intent.getParcelableExtra("msg_uri"); if (Log.isLoggable(LogTag.APP, Log.DEBUG)) { log("" + uri); } if (uri != null) { mWorkingMessage = WorkingMessage.load(this, uri); mWorkingMessage.setSubject(intent.getStringExtra("subject"), false); } else { mWorkingMessage.setText(intent.getStringExtra("sms_body")); } // let's clear the message thread for forwarded messages mMsgListAdapter.changeCursor(null); return true; } private boolean handleSendIntent(Intent intent) { Bundle extras = intent.getExtras(); if (extras == null) { return false; } final String mimeType = intent.getType(); String action = intent.getAction(); if (Intent.ACTION_SEND.equals(action)) { if (extras.containsKey(Intent.EXTRA_STREAM)) { final Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM); runAsyncWithDialog(new Runnable() { public void run() { addAttachment(mimeType, uri, false); } }, R.string.adding_attachments_title); return true; } else if (extras.containsKey(Intent.EXTRA_TEXT)) { mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT)); return true; } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && extras.containsKey(Intent.EXTRA_STREAM)) { SlideshowModel slideShow = mWorkingMessage.getSlideshow(); final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM); int currentSlideCount = slideShow != null ? slideShow.size() : 0; int importCount = uris.size(); if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) { importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount, importCount); Toast.makeText(ComposeMessageActivity.this, getString(R.string.too_many_attachments, SlideshowEditor.MAX_SLIDE_NUM, importCount), Toast.LENGTH_LONG).show(); } // Attach all the pictures/videos asynchronously off of the UI thread. // Show a progress dialog if adding all the slides hasn't finished // within half a second. final int numberToImport = importCount; runAsyncWithDialog(new Runnable() { public void run() { for (int i = 0; i < numberToImport; i++) { Parcelable uri = uris.get(i); addAttachment(mimeType, (Uri) uri, true); } } }, R.string.adding_attachments_title); return true; } return false; } // mVideoUri will look like this: content://media/external/video/media private static final String mVideoUri = Video.Media.getContentUri("external").toString(); // mImageUri will look like this: content://media/external/images/media private static final String mImageUri = Images.Media.getContentUri("external").toString(); private void addAttachment(String type, Uri uri, boolean append) { if (uri != null) { // When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be // videos, and/or images, and/or some other unknown types we don't handle. When // a single attachment is "shared" the type will specify an image or video. When // there are multiple types, the type passed in is "*/*". In that case, we've got // to look at the uri to figure out if it is an image or video. boolean wildcard = "*/*".equals(type); if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) { addImage(uri, append); } else if (type.startsWith("video/") || (wildcard && uri.toString().startsWith(mVideoUri))) { addVideo(uri, append); } } } private String getResourcesString(int id, String mediaName) { Resources r = getResources(); return r.getString(id, mediaName); } private void drawBottomPanel() { // Reset the counter for text editor. resetCounter(); if (mWorkingMessage.hasSlideshow()) { mBottomPanel.setVisibility(View.GONE); mAttachmentEditor.requestFocus(); return; } mBottomPanel.setVisibility(View.VISIBLE); CharSequence text = mWorkingMessage.getText(); // TextView.setTextKeepState() doesn't like null input. if (text != null) { mTextEditor.setTextKeepState(text); } else { mTextEditor.setText(""); } } private void drawTopPanel(boolean showSubjectEditor) { boolean showingAttachment = mAttachmentEditor.update(mWorkingMessage); mAttachmentEditorScrollView.setVisibility(showingAttachment ? View.VISIBLE : View.GONE); showSubjectEditor(showSubjectEditor || mWorkingMessage.hasSubject()); } //========================================================== // Interface methods //========================================================== public void onClick(View v) { if ((v == mSendButtonSms || v == mSendButtonMms) && isPreparedForSending()) { confirmSendMessageIfNeeded(); } else if ((v == mRecipientsPicker)) { launchMultiplePhonePicker(); } } private void launchMultiplePhonePicker() { Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES); intent.addCategory("android.intent.category.DEFAULT"); intent.setType(Phone.CONTENT_TYPE); // We have to wait for the constructing complete. ContactList contacts = mRecipientsEditor.constructContactsFromInput(true); int recipientsCount = 0; int urisCount = 0; Uri[] uris = new Uri[contacts.size()]; urisCount = 0; for (Contact contact : contacts) { if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) { uris[urisCount++] = contact.getPhoneUri(); } } if (urisCount > 0) { intent.putExtra(Intents.EXTRA_PHONE_URIS, uris); } startActivityForResult(intent, REQUEST_CODE_PICK); } public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null) { // if shift key is down, then we want to insert the '\n' char in the TextView; // otherwise, the default action is to send the message. if (!event.isShiftPressed()) { if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } return true; } return false; } if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } return true; } private final TextWatcher mTextEditorWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { // This is a workaround for bug 1609057. Since onUserInteraction() is // not called when the user touches the soft keyboard, we pretend it was // called when textfields changes. This should be removed when the bug // is fixed. onUserInteraction(); mWorkingMessage.setText(s); updateSendButtonState(); updateCounter(s, start, before, count); ensureCorrectButtonHeight(); } public void afterTextChanged(Editable s) { } }; /** * Ensures that if the text edit box extends past two lines then the * button will be shifted up to allow enough space for the character * counter string to be placed beneath it. */ private void ensureCorrectButtonHeight() { int currentTextLines = mTextEditor.getLineCount(); if (currentTextLines <= 2) { mTextCounter.setVisibility(View.GONE); } else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) { // Making the counter invisible ensures that it is used to correctly // calculate the position of the send button even if we choose not to // display the text. mTextCounter.setVisibility(View.INVISIBLE); } } private final TextWatcher mSubjectEditorWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { mWorkingMessage.setSubject(s, true); } public void afterTextChanged(Editable s) { } }; //========================================================== // Private methods //========================================================== /** * Initialize all UI elements from resources. */ private void initResourceRefs() { mMsgListView = (MessageListView) findViewById(R.id.history); mMsgListView.setDivider(null); // no divider so we look like IM conversation. // called to enable us to show some padding between the message list and the // input field but when the message list is scrolled that padding area is filled // in with message content mMsgListView.setClipToPadding(false); // turn off children clipping because we draw the border outside of our own // bounds at the bottom. The background is also drawn in code to avoid drawing // the top edge. mMsgListView.setClipChildren(false); mBottomPanel = findViewById(R.id.bottom_panel); mTextEditor = (EditText) findViewById(R.id.embedded_text_editor); mTextEditor.setOnEditorActionListener(this); mTextEditor.addTextChangedListener(mTextEditorWatcher); mTextEditor.setFilters(new InputFilter[] { new LengthFilter(MmsConfig.getMaxTextLimit())}); mTextCounter = (TextView) findViewById(R.id.text_counter); mSendButtonMms = (TextView) findViewById(R.id.send_button_mms); mSendButtonSms = (ImageButton) findViewById(R.id.send_button_sms); mSendButtonMms.setOnClickListener(this); mSendButtonSms.setOnClickListener(this); mTopPanel = findViewById(R.id.recipients_subject_linear); mTopPanel.setFocusable(false); mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor); mAttachmentEditor.setHandler(mAttachmentEditorHandler); mAttachmentEditorScrollView = findViewById(R.id.attachment_editor_scroll_view); } private void confirmDeleteDialog(OnClickListener listener, boolean locked) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setMessage(locked ? R.string.confirm_delete_locked_message : R.string.confirm_delete_message); builder.setPositiveButton(R.string.delete, listener); builder.setNegativeButton(R.string.no, null); builder.show(); } void undeliveredMessageDialog(long date) { String body; if (date >= 0) { body = getString(R.string.undelivered_msg_dialog_body, MessageUtils.formatTimeStampString(this, date)); } else { // FIXME: we can not get sms retry time. body = getString(R.string.undelivered_sms_dialog_body); } Toast.makeText(this, body, Toast.LENGTH_LONG).show(); } private void startMsgListQuery() { Uri conversationUri = mConversation.getUri(); if (conversationUri == null) { log("##### startMsgListQuery: conversationUri is null, bail!"); return; } long threadId = mConversation.getThreadId(); if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("startMsgListQuery for " + conversationUri + ", threadId=" + threadId); } // Cancel any pending queries mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN); try { // Kick off the new query mBackgroundQueryHandler.startQuery( MESSAGE_LIST_QUERY_TOKEN, threadId /* cookie */, conversationUri, PROJECTION, null, null, null); } catch (SQLiteException e) { SqliteWrapper.checkSQLiteException(this, e); } } private void initMessageList() { if (mMsgListAdapter != null) { return; } String highlightString = getIntent().getStringExtra("highlight"); Pattern highlight = highlightString == null ? null : Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE); // Initialize the list adapter with a null cursor. mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight); mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener); mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler); mMsgListView.setAdapter(mMsgListAdapter); mMsgListView.setItemsCanFocus(false); mMsgListView.setVisibility(View.VISIBLE); mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener); mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view != null) { ((MessageListItem) view).onMessageListItemClick(); } } }); } private void loadDraft() { if (mWorkingMessage.isWorthSaving()) { Log.w(TAG, "called with non-empty working message"); return; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("call WorkingMessage.loadDraft"); } mWorkingMessage = WorkingMessage.loadDraft(this, mConversation); } private void saveDraft(boolean isStopping) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { LogTag.debug("saveDraft"); } // TODO: Do something better here. Maybe make discard() legal // to call twice and make isEmpty() return true if discarded // so it is caught in the clause above this one? if (mWorkingMessage.isDiscarded()) { return; } if (!mWaitingForSubActivity && !mWorkingMessage.isWorthSaving() && (!isRecipientsEditorVisible() || recipientCount() == 0)) { if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("not worth saving, discard WorkingMessage and bail"); } mWorkingMessage.discard(); return; } mWorkingMessage.saveDraft(isStopping); if (mToastForDraftSave) { Toast.makeText(this, R.string.message_saved_as_draft, Toast.LENGTH_SHORT).show(); } } private boolean isPreparedForSending() { int recipientCount = recipientCount(); return recipientCount > 0 && recipientCount <= MmsConfig.getRecipientLimit() && (mWorkingMessage.hasAttachment() || mWorkingMessage.hasText() || mWorkingMessage.hasSubject()); } private int recipientCount() { int recipientCount; // To avoid creating a bunch of invalid Contacts when the recipients // editor is in flux, we keep the recipients list empty. So if the // recipients editor is showing, see if there is anything in it rather // than consulting the empty recipient list. if (isRecipientsEditorVisible()) { recipientCount = mRecipientsEditor.getRecipientCount(); } else { recipientCount = getRecipients().size(); } return recipientCount; } private void sendMessage(boolean bCheckEcmMode) { if (bCheckEcmMode) { // TODO: expose this in telephony layer for SDK build String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE); if (Boolean.parseBoolean(inEcm)) { try { startActivityForResult( new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null), REQUEST_CODE_ECM_EXIT_DIALOG); return; } catch (ActivityNotFoundException e) { // continue to send message Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e); } } } if (!mSendingMessage) { if (LogTag.SEVERE_WARNING) { String sendingRecipients = mConversation.getRecipients().serialize(); if (!sendingRecipients.equals(mDebugRecipients)) { String workingRecipients = mWorkingMessage.getWorkingRecipients(); if (!mDebugRecipients.equals(workingRecipients)) { LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage" + " recipients in window: \"" + mDebugRecipients + "\" differ from recipients from conv: \"" + sendingRecipients + "\" and working recipients: " + workingRecipients, this); } } sanityCheckConversation(); } // send can change the recipients. Make sure we remove the listeners first and then add // them back once the recipient list has settled. removeRecipientsListeners(); mWorkingMessage.send(mDebugRecipients); mSentMessage = true; mSendingMessage = true; addRecipientsListeners(); } // But bail out if we are supposed to exit after the message is sent. if (mExitOnSent) { finish(); } } private void resetMessage() { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log(""); } // Make the attachment editor hide its view. mAttachmentEditor.hideView(); mAttachmentEditorScrollView.setVisibility(View.GONE); // Hide the subject editor. showSubjectEditor(false); // Focus to the text editor. mTextEditor.requestFocus(); // We have to remove the text change listener while the text editor gets cleared and // we subsequently turn the message back into SMS. When the listener is listening while // doing the clearing, it's fighting to update its counts and itself try and turn // the message one way or the other. mTextEditor.removeTextChangedListener(mTextEditorWatcher); // Clear the text box. TextKeyListener.clear(mTextEditor.getText()); mWorkingMessage.clearConversation(mConversation, false); mWorkingMessage = WorkingMessage.createEmpty(this); mWorkingMessage.setConversation(mConversation); hideRecipientEditor(); drawBottomPanel(); // "Or not", in this case. updateSendButtonState(); // Our changes are done. Let the listener respond to text changes once again. mTextEditor.addTextChangedListener(mTextEditorWatcher); // Close the soft on-screen keyboard if we're in landscape mode so the user can see the // conversation. if (mIsLandscape) { InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0); } mLastRecipientCount = 0; mSendingMessage = false; } private void updateSendButtonState() { boolean enable = false; if (isPreparedForSending()) { // When the type of attachment is slideshow, we should // also hide the 'Send' button since the slideshow view // already has a 'Send' button embedded. if (!mWorkingMessage.hasSlideshow()) { enable = true; } else { mAttachmentEditor.setCanSend(true); } } else if (null != mAttachmentEditor){ mAttachmentEditor.setCanSend(false); } View sendButton = showSmsOrMmsSendButton(mWorkingMessage.requiresMms()); sendButton.setEnabled(enable); sendButton.setFocusable(enable); } private long getMessageDate(Uri uri) { if (uri != null) { Cursor cursor = SqliteWrapper.query(this, mContentResolver, uri, new String[] { Mms.DATE }, null, null, null); if (cursor != null) { try { if ((cursor.getCount() == 1) && cursor.moveToFirst()) { return cursor.getLong(0) * 1000L; } } finally { cursor.close(); } } } return NO_DATE_FOR_DIALOG; } private void initActivityState(Intent intent) { // If we have been passed a thread_id, use that to find our conversation. long threadId = intent.getLongExtra("thread_id", 0); if (threadId > 0) { if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId); mConversation = Conversation.get(this, threadId, false); } else { Uri intentData = intent.getData(); if (intentData != null) { // try to get a conversation based on the data URI passed to our intent. if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData); mConversation = Conversation.get(this, intentData, false); mWorkingMessage.setText(getBody(intentData)); } else { // special intent extra parameter to specify the address String address = intent.getStringExtra("address"); if (!TextUtils.isEmpty(address)) { if (LogTag.VERBOSE) log("get mConversation by address " + address); mConversation = Conversation.get(this, ContactList.getByNumbers(address, false /* don't block */, true /* replace number */), false); } else { if (LogTag.VERBOSE) log("create new conversation"); mConversation = Conversation.createNew(this); } } } addRecipientsListeners(); mExitOnSent = intent.getBooleanExtra("exit_on_sent", false); if (intent.hasExtra("sms_body")) { mWorkingMessage.setText(intent.getStringExtra("sms_body")); } mWorkingMessage.setSubject(intent.getStringExtra("subject"), false); } private void initFocus() { if (!mIsKeyboardOpen) { return; } // If the recipients editor is visible, there is nothing in it, // and the text editor is not already focused, focus the // recipients editor. if (isRecipientsEditorVisible() && TextUtils.isEmpty(mRecipientsEditor.getText()) && !mTextEditor.isFocused()) { mRecipientsEditor.requestFocus(); return; } // If we decided not to focus the recipients editor, focus the text editor. mTextEditor.requestFocus(); } private final MessageListAdapter.OnDataSetChangedListener mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() { public void onDataSetChanged(MessageListAdapter adapter) { mPossiblePendingNotification = true; } public void onContentChanged(MessageListAdapter adapter) { if (LogTag.VERBOSE) { log("MessageListAdapter.OnDataSetChangedListener.onContentChanged"); } startMsgListQuery(); } }; private void checkPendingNotification() { if (mPossiblePendingNotification && hasWindowFocus()) { mConversation.markAsRead(); mPossiblePendingNotification = false; } } private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver contentResolver) { super(contentResolver); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { switch(token) { case MESSAGE_LIST_QUERY_TOKEN: // check consistency between the query result and 'mConversation' long tid = (Long) cookie; if (LogTag.VERBOSE) { log("##### onQueryComplete: msg history result for threadId " + tid); } if (tid != mConversation.getThreadId()) { log("onQueryComplete: msg history query result is for threadId " + tid + ", but mConversation has threadId " + mConversation.getThreadId() + " starting a new query"); startMsgListQuery(); return; } // check consistency b/t mConversation & mWorkingMessage.mConversation ComposeMessageActivity.this.sanityCheckConversation(); int newSelectionPos = -1; long targetMsgId = getIntent().getLongExtra("select_id", -1); if (targetMsgId != -1) { cursor.moveToPosition(-1); while (cursor.moveToNext()) { long msgId = cursor.getLong(COLUMN_ID); if (msgId == targetMsgId) { newSelectionPos = cursor.getPosition(); break; } } } mMsgListAdapter.changeCursor(cursor); if (newSelectionPos != -1) { mMsgListView.setSelection(newSelectionPos); } // Adjust the conversation's message count to match reality. The // conversation's message count is eventually used in // WorkingMessage.clearConversation to determine whether to delete // the conversation or not. mConversation.setMessageCount(mMsgListAdapter.getCount()); // Once we have completed the query for the message history, if // there is nothing in the cursor and we are not composing a new // message, we must be editing a draft in a new conversation (unless // mSentMessage is true). // Show the recipients editor to give the user a chance to add // more people before the conversation begins. if (cursor.getCount() == 0 && !isRecipientsEditorVisible() && !mSentMessage) { initRecipientsEditor(); } // FIXME: freshing layout changes the focused view to an unexpected // one, set it back to TextEditor forcely. mTextEditor.requestFocus(); mConversation.blockMarkAsRead(false); return; case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN: ArrayList<Long> threadIds = (ArrayList<Long>)cookie; ConversationList.confirmDeleteThreadDialog( new ConversationList.DeleteThreadListener(threadIds, mBackgroundQueryHandler, ComposeMessageActivity.this), threadIds, cursor != null && cursor.getCount() > 0, ComposeMessageActivity.this); break; } } @Override protected void onDeleteComplete(int token, Object cookie, int result) { switch(token) { case ConversationList.DELETE_CONVERSATION_TOKEN: mConversation.setMessageCount(0); // fall through case DELETE_MESSAGE_TOKEN: // Update the notification for new messages since they // may be deleted. MessagingNotification.nonBlockingUpdateNewMessageIndicator( ComposeMessageActivity.this, false, false); // Update the notification for failed messages since they // may be deleted. updateSendFailedNotification(); break; } // If we're deleting the whole conversation, throw away // our current working message and bail. if (token == ConversationList.DELETE_CONVERSATION_TOKEN) { mWorkingMessage.discard(); // Rebuild the contacts cache now that a thread and its associated unique // recipients have been deleted. Contact.init(ComposeMessageActivity.this); // Make sure the conversation cache reflects the threads in the DB. Conversation.init(ComposeMessageActivity.this); finish(); } } } private void showSmileyDialog() { if (mSmileyDialog == null) { int[] icons = SmileyParser.DEFAULT_SMILEY_RES_IDS; String[] names = getResources().getStringArray( SmileyParser.DEFAULT_SMILEY_NAMES); final String[] texts = getResources().getStringArray( SmileyParser.DEFAULT_SMILEY_TEXTS); final int N = names.length; List<Map<String, ?>> entries = new ArrayList<Map<String, ?>>(); for (int i = 0; i < N; i++) { // We might have different ASCII for the same icon, skip it if // the icon is already added. boolean added = false; for (int j = 0; j < i; j++) { if (icons[i] == icons[j]) { added = true; break; } } if (!added) { HashMap<String, Object> entry = new HashMap<String, Object>(); entry. put("icon", icons[i]); entry. put("name", names[i]); entry.put("text", texts[i]); entries.add(entry); } } final SimpleAdapter a = new SimpleAdapter( this, entries, R.layout.smiley_menu_item, new String[] {"icon", "name", "text"}, new int[] {R.id.smiley_icon, R.id.smiley_name, R.id.smiley_text}); SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() { public boolean setViewValue(View view, Object data, String textRepresentation) { if (view instanceof ImageView) { Drawable img = getResources().getDrawable((Integer)data); ((ImageView)view).setImageDrawable(img); return true; } return false; } }; a.setViewBinder(viewBinder); AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(getString(R.string.menu_insert_smiley)); b.setCancelable(true); b.setAdapter(a, new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public final void onClick(DialogInterface dialog, int which) { HashMap<String, Object> item = (HashMap<String, Object>) a.getItem(which); String smiley = (String)item.get("text"); if (mSubjectTextEditor != null && mSubjectTextEditor.hasFocus()) { mSubjectTextEditor.append(smiley); } else { mTextEditor.append(smiley); } dialog.dismiss(); } }); mSmileyDialog = b.create(); } mSmileyDialog.show(); } public void onUpdate(final Contact updated) { // Using an existing handler for the post, rather than conjuring up a new one. mMessageListItemHandler.post(new Runnable() { public void run() { ContactList recipients = isRecipientsEditorVisible() ? mRecipientsEditor.constructContactsFromInput(false) : getRecipients(); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("[CMA] onUpdate contact updated: " + updated); log("[CMA] onUpdate recipients: " + recipients); } updateTitle(recipients); // The contact information for one (or more) of the recipients has changed. // Rebuild the message list so each MessageItem will get the last contact info. ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged(); if (mRecipientsEditor != null) { mRecipientsEditor.populate(recipients); } } }); } private void addRecipientsListeners() { Contact.addListener(this); } private void removeRecipientsListeners() { Contact.removeListener(this); } private void clearPendingProgressDialog() { // remove any callback to display a progress spinner mAttachmentEditorHandler.removeCallbacks(mShowProgressDialogRunnable); // clear the dialog so any pending dialog.dismiss() call can be avoided mProgressDialog = null; } public static Intent createIntent(Context context, long threadId) { Intent intent = new Intent(context, ComposeMessageActivity.class); if (threadId > 0) { intent.setData(Conversation.getUri(threadId)); } return intent; } private String getBody(Uri uri) { if (uri == null) { return null; } String urlStr = uri.getSchemeSpecificPart(); if (!urlStr.contains("?")) { return null; } urlStr = urlStr.substring(urlStr.indexOf('?') + 1); String[] params = urlStr.split("&"); for (String p : params) { if (p.startsWith("body=")) { try { return URLDecoder.decode(p.substring(5), "UTF-8"); } catch (UnsupportedEncodingException e) { } } } return null; } }
418c1176d68d6bf3607ecbd39390755716c8339c
d0e74ff6e8d37984cea892dfe8508e2b44de5446
/logistics-wms-city-1.1.3.44.5/logistics-wms-city-service/src/main/java/com/yougou/logistics/city/service/BillStatusLogServiceImpl.java
092b9f77a4c542327c1c1eecc9b740b586534068
[]
no_license
heaven6059/wms
fb39f31968045ba7e0635a4416a405a226448b5a
5885711e188e8e5c136956956b794f2a2d2e2e81
refs/heads/master
2021-01-14T11:20:10.574341
2015-04-11T08:11:59
2015-04-11T08:11:59
29,462,213
1
4
null
null
null
null
UTF-8
Java
false
false
5,262
java
package com.yougou.logistics.city.service; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.yougou.logistics.base.common.annotation.DataAccessAuth; import com.yougou.logistics.base.common.enums.DataAccessRuleEnum; import com.yougou.logistics.base.common.exception.ServiceException; import com.yougou.logistics.base.common.model.AuthorityParams; import com.yougou.logistics.base.common.utils.SimplePage; import com.yougou.logistics.base.dal.database.BaseCrudMapper; import com.yougou.logistics.base.service.BaseCrudServiceImpl; import com.yougou.logistics.city.common.api.dto.BillStatusLogDto; import com.yougou.logistics.city.common.model.BillStatusLog; import com.yougou.logistics.city.dal.database.BillStatusLogMapper; @Service("billStatusLogService") class BillStatusLogServiceImpl extends BaseCrudServiceImpl implements BillStatusLogService { @Resource private BillStatusLogMapper billStatusLogMapper; @Override public BaseCrudMapper init() { return billStatusLogMapper; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = ServiceException.class) public void procInsertBillStatusLog(String locno, String billNo, String billType, String status, String description, String operator) throws ServiceException { try { if (StringUtils.isNotBlank(locno) && StringUtils.isNotBlank(billNo) && StringUtils.isNotBlank(billType) && StringUtils.isNotBlank(status) && StringUtils.isNotBlank(description) && StringUtils.isNotBlank(operator)) { Map<String, Object> params = new HashMap<String, Object>(); params.put("v_locno", locno); params.put("v_bill_no", billNo); params.put("v_bill_type", billType); params.put("v_status", status); params.put("v_description", description); params.put("v_operator", operator); billStatusLogMapper.procInsertBillStatusLog(params); String stroutmsg = String.valueOf(params.get("stroutmsg")); if (!"Y".equals(stroutmsg)) { throw new ServiceException("插入状态日志发生异常!"); } } else { throw new ServiceException("插入日志状态参数不合法!"); } } catch (Exception e) { throw new ServiceException(e.getMessage()); } } @Override public List<BillStatusLogDto> findBillStatusLogByPoNo(String poNo) throws ServiceException { try { return billStatusLogMapper.selectBillStatusLogByPoNo(poNo); } catch (Exception e) { throw new ServiceException(e); } } @Override public List<BillStatusLogDto> findBillStatusLogBySourceExpNo(String sourceExpNo) throws ServiceException { try { return billStatusLogMapper.selectBillStatusLogBySourceExpNo(sourceExpNo); } catch (Exception e) { throw new ServiceException(e); } } @Override @DataAccessAuth({DataAccessRuleEnum.BRAND}) public int findCountByIm(Map<String, Object> params, AuthorityParams authorityParams, DataAccessRuleEnum... dataAccessRuleEnum) throws ServiceException { try { return billStatusLogMapper.selectCountByIm(params, authorityParams); } catch (Exception e) { throw new ServiceException(e); } } @Override @DataAccessAuth({DataAccessRuleEnum.BRAND}) public List<BillStatusLog> findPageByIm(SimplePage page, Map<String, Object> params, AuthorityParams authorityParams, DataAccessRuleEnum... dataAccessRuleEnum) throws ServiceException { try { return billStatusLogMapper.selectPageByIm(page, params, authorityParams); } catch (Exception e) { throw new ServiceException(e); } } @Override @DataAccessAuth({DataAccessRuleEnum.BRAND}) public int findCountByOm(Map<String, Object> params, AuthorityParams authorityParams, DataAccessRuleEnum... dataAccessRuleEnum) throws ServiceException { try { return billStatusLogMapper.selectCountByOm(params, authorityParams); } catch (Exception e) { throw new ServiceException(e); } } @Override @DataAccessAuth({DataAccessRuleEnum.BRAND}) public List<BillStatusLog> findPageByOm(SimplePage page, Map<String, Object> params, AuthorityParams authorityParams, DataAccessRuleEnum... dataAccessRuleEnum) throws ServiceException { try { return billStatusLogMapper.selectPageByOm(page, params, authorityParams); } catch (Exception e) { throw new ServiceException(e); } } @Override @DataAccessAuth({DataAccessRuleEnum.BRAND}) public int findCountByUm(Map<String, Object> params, AuthorityParams authorityParams, DataAccessRuleEnum... dataAccessRuleEnum) throws ServiceException { try { return billStatusLogMapper.selectCountByUm(params, authorityParams); } catch (Exception e) { throw new ServiceException(e); } } @Override @DataAccessAuth({DataAccessRuleEnum.BRAND}) public List<BillStatusLog> findPageByUm(SimplePage page, Map<String, Object> params, AuthorityParams authorityParams, DataAccessRuleEnum... dataAccessRuleEnum) throws ServiceException { try { return billStatusLogMapper.selectPageByUm(page, params, authorityParams); } catch (Exception e) { throw new ServiceException(e); } } }
dcfce1332fee761ab1c3f54ecbb12b82aa56eeeb
134d824a3aa8518ce19019669d6bd7d06afddcfc
/src/tech/aistar/day03/LoadDemo.java
2f388d68142d9f7d388631de975420479edca68c
[]
no_license
likuisuper/core-java
c6c3debc64725b0313a2e3437467142d2ee7f9c0
b1c4e494c16dbf234f77459c2a7d26669e549e61
refs/heads/master
2023-01-08T08:47:55.560108
2020-10-31T08:15:22
2020-10-31T08:15:22
280,603,327
0
0
null
null
null
null
UTF-8
Java
false
false
913
java
package tech.aistar.day03; /** * 本类功能:重载的方法 * 前提:重载的方法肯定是出现在同一个类中 * 1.重载的方法的名臣肯定是一致的 * 2.重载的方法的参数列表肯定是不一样的 * 2-1.参数列表的个数不一样 * 2-2.个数一样的时候,参数类型肯定要不一样 * 3.重载的方法的返回类型可以不一样 * * @author cxylk * @date 2020/7/20 20:23 */ public class LoadDemo { public static void main(String[] args) { add(10); System.out.println("ok"); } public static void add() { System.out.println("add"); } public static void add(int i) { System.out.println("i:"+i); } public static void add(int i,String j){ System.out.println("i:"+i+",j"+j); } public static double add(double d){ System.out.println("double:"+d); return d; } }
22cf7adfd2f9ade507810dbdc8e7fbb0855a0ad4
d84f49de249d6693642dd150d7314c191f124af8
/HackerNG/src/crossBrowsers/BuyDresses.java
6486efcb8565617702ef6e313fecc89be7004efb
[]
no_license
domsqas-git/TestNGautomation
e75f00b23c573df435fd148fc5ac148499642850
8775d9ea2502ffa35843144a37e4e45f20730f92
refs/heads/master
2020-06-29T11:35:27.744407
2019-08-05T18:27:16
2019-08-05T18:27:16
200,523,419
0
0
null
null
null
null
UTF-8
Java
false
false
12,507
java
package crossBrowsers; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class BuyDresses { WebDriver driver; @BeforeTest @Parameters("browser") public void buyfiveDresses(String browserName) { if(browserName.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", "c:\\\\selenium\\\\chromedriver.exe"); driver=new ChromeDriver(); } else if(browserName.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver", "C:\\selenium\\geckodriver.exe"); driver=new FirefoxDriver(); } { driver.manage().window().maximize(); driver.get("http://automationpractice.com/index.php"); System.out.println(driver.getTitle()); } } @Test (priority=1) public void DressTab() { //Navigate to Dress page driver.findElement(By.xpath("//*[@id=\"block_top_menu\"]/ul/li[2]/a")).click(); } @Test(priority=2) public void firstDress() throws InterruptedException { Thread.sleep(2000); @SuppressWarnings("unused") JavascriptExecutor driver0; JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.scrollBy(0,1000)"); Actions action = new Actions(driver); //Add to Cart 1st Dress WebElement we = driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[2]/ul/li[1]")); action.moveToElement(we).build().perform(); Thread.sleep(2000); driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[2]/ul/li[1]/div/div[2]/div[2]/a[1]/span")).click(); Thread.sleep(2000); //Continue Shopping driver.findElement(By.xpath("//*[@id=\"layer_cart\"]/div[1]/div[2]/div[4]/span")).click(); } @Test(priority=3) public void secondDress() throws InterruptedException { Thread.sleep(2000); //Add to Cart 2nd Dress driver.findElement(By.xpath("//*[@id=\"center_column\"]/ul/li[2]/div/div[2]/div[2]/a[1]/span")).click(); Thread.sleep(2000); //Continue Shopping driver.findElement(By.xpath("//*[@id=\"layer_cart\"]/div[1]/div[2]/div[4]/span")).click(); } @Test(priority=4) public void thirdDress() throws InterruptedException { //3rd Dress Actions action = new Actions(driver); WebElement we1 = driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[2]/ul/li[3]")); action.moveToElement(we1).build().perform(); Thread.sleep(2000); //Click on "More" on 3rd Dress driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[2]/ul/li[3]/div/div[2]/div[2]/a[2]/span")).click(); Thread.sleep(2000); //Expand picture driver.findElement(By.id("bigpic")).click(); Thread.sleep(2000); //Scroll to other picture driver.findElement(By.xpath("//*[@id=\"product\"]/div[2]/div/div/a")).click(); Thread.sleep(2000); //Close picture driver.findElement(By.xpath("//*[@id=\"product\"]/div[2]/div/div/a")).click(); Thread.sleep(2000); //Add to cart 3rd dress driver.findElement(By.xpath("//*[@id=\"add_to_cart\"]/button/span")).click(); Thread.sleep(2000); //Continue Shopping driver.findElement(By.xpath("//*[@id=\"layer_cart\"]/div[1]/div[2]/div[4]/span")).click(); Thread.sleep(2000); //click Dresses on the "directory" above picture driver.findElement(By.xpath("//*[@id=\"columns\"]/div[1]/a[3]")).click(); } @Test(priority=5) public void fourthDress() throws InterruptedException { Thread.sleep(2000); driver.findElement(By.id("search_query_top")).sendKeys("Printed summer dress "); //enter to procede Thread.sleep(2000); driver.findElement(By.id("search_query_top")).sendKeys(Keys.ENTER); //click quick view Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"center_column\"]/ul/li[2]/div/div[1]/div/a[1]/img")).click(); //Add to cart Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"add_to_cart\"]/button/span")).click(); //Close popup Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"layer_cart\"]/div[1]/div[1]/span")).click(); //Click shopping Cart Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"header\"]/div[3]/div/div/div[3]/div/a")).click(); //Click picture of the Dress Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"product_6_31_0_0\"]/td[1]/a/img")).click(); Thread.sleep(2000); //Add quantity to Dress 4 driver.findElement(By.xpath("//*[@id=\"quantity_wanted_p\"]/a[2]/span/i")).click(); Thread.sleep(2000); //Clear box quantity on Dress 4 driver.findElement(By.id("quantity_wanted")).clear(); Thread.sleep(2000); //Change quantity to 3pc on Dress 4 driver.findElement(By.id("quantity_wanted")).sendKeys("3"); Thread.sleep(2000); //Select size in dropdown menu new Select (driver.findElement(By.id("group_1"))).selectByVisibleText("M"); Thread.sleep(2000); //Add to cart 4th dress driver.findElement(By.xpath("//*[@id=\"add_to_cart\"]/button/span")).click(); Thread.sleep(2000); //Close popup driver.findElement(By.xpath("//*[@id=\"layer_cart\"]/div[1]/div[1]/span")).click(); Thread.sleep(2000); //Go back to Dress by main tab driver.findElement(By.xpath("//*[@id=\"block_top_menu\"]/ul/li[2]/a")).click(); } @Test(priority=6) public void fifthChiffonDress() throws InterruptedException { //Search box (chiffon) Thread.sleep(2000); driver.findElement(By.id("search_query_top")).sendKeys("chiffon "); //Click search button Thread.sleep(2000); driver.findElement(By.name("submit_search")).click(); //Click image to access dress page Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"center_column\"]/ul/li[1]/div/div[1]/div/a[1]/img")).click(); Thread.sleep(2000); //Change color on Dress 5 driver.findElement(By.id("color_15")).click(); //Send email to friend Thread.sleep(2000); driver.findElement(By.id("send_friend_button")).click(); //Friend name driver.findElement(By.id("friend_name")).sendKeys("Beautiful Girl"); //Friend email driver.findElement(By.id("friend_email")).sendKeys("[email protected]"); //Cancel email send driver.findElement(By.xpath("//*[@id=\"send_friend_form_content\"]/p/a")).click(); //Add to cart 5th dress Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"add_to_cart\"]/button/span")).click(); //Close popup Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"layer_cart\"]/div[1]/div[1]/span")).click(); //Click on shopping cart Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"header\"]/div[3]/div/div/div[3]/div/a/b")).click(); //Delete extra dress Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"6_31_0_0\"]/i")).click(); } @Test(priority=7) public void contcatUs() throws InterruptedException { //Contact us Thread.sleep(2000); driver.findElement(By.id("contact-link")).click(); //Contact us form new Select(driver.findElement(By.id("id_contact"))).selectByVisibleText("Customer service"); //Email address driver.findElement(By.id("email")).sendKeys("[email protected]"); //Order reference driver.findElement(By.id("id_order")).sendKeys("7 dresses"); //Message driver.findElement(By.id("message")).sendKeys("I'm purchasing seven dresses, can I've an extra 20% off. Grazie!!"); //Send message driver.findElement(By.xpath("//*[@id=\"submitMessage\"]/span")).click(); //Back Home button driver.findElement(By.xpath("//*[@id=\"center_column\"]/ul/li/a/span")).click(); } @Test(priority=8) public void CartShopCost() throws InterruptedException { //Cart Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"header\"]/div[3]/div/div/div[3]/div/a")).click(); //Proceed to checkout Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"center_column\"]/p[2]/a[1]/span")).click(); //Click on shopping cart Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"header\"]/div[3]/div/div/div[3]/div/a/b")).click(); //Print dress 1 info System.out.println(driver.findElement(By.xpath("//*[@id=\"product_3_13_0_0\"]/td[2]/p/a")).getText()); System.out.println(driver.findElement(By.xpath("//*[@id=\"product_3_13_0_0\"]/td[2]/small[2]/a")).getText()); System.out.println(driver.findElement(By.id("total_product_price_3_13_0")).getText()); //Print dress 2 info System.out.println(driver.findElement(By.xpath("//*[@id=\"product_4_16_0_0\"]/td[2]/p/a")).getText()); System.out.println(driver.findElement(By.xpath("//*[@id=\"product_4_16_0_0\"]/td[2]/small[2]/a")).getText()); System.out.println(driver.findElement(By.id("total_product_price_4_16_0")).getText()); //Print dress 3 info System.out.println(driver.findElement(By.xpath("//*[@id=\"product_5_19_0_0\"]/td[2]/p/a")).getText()); System.out.println(driver.findElement(By.xpath("//*[@id=\"product_5_19_0_0\"]/td[2]/small[2]/a")).getText()); System.out.println(driver.findElement(By.id("total_product_price_5_19_0")).getText()); //Print dress 4 System.out.println(driver.findElement(By.xpath("//*[@id=\"product_6_31_0_198772\"]/td[2]/p/a")).getText()); System.out.println(driver.findElement(By.xpath("//*[@id=\"product_6_31_0_198772\"]/td[2]/small[2]/a")).getText()); System.out.println(driver.findElement(By.id("total_product_price_6_31_198772")).getText()); //Print dress 5 System.out.println(driver.findElement(By.xpath("//*[@id=\"product_7_34_0_198772\"]/td[2]/p/a")).getText()); System.out.println(driver.findElement(By.xpath("//*[@id=\"product_7_34_0_198772\"]/td[2]/small[2]/a")).getText()); System.out.println(driver.findElement(By.id("total_product_price_7_34_198772")).getText()); //Total System.out.println(driver.findElement(By.id("total_price")).getText()); } @Test(priority=9) public void SignInOut() throws InterruptedException { //Sign in Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/a")).click(); //Forgot Pass Thread.sleep(2000); driver.findElement(By.linkText("Forgot your password?")).click(); //Back to Login Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"center_column\"]/ul/li/a/span")).click(); //Email Thread.sleep(2000); driver.findElement(By.id("email")).sendKeys("[email protected]"); //Password driver.findElement(By.id("passwd")).sendKeys("Tusei1"); //Click Sign in button Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"SubmitLogin\"]/span")).click(); //Order History Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"center_column\"]/div/div[1]/ul/li[1]/a/span")).click(); //Click Logo to return home driver.findElement(By.xpath("//*[@id=\"header_logo\"]/a/img")).click(); //Sign out Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[2]/a")).click(); double i1 = 26.00; double i2 = 16.40; double i3 = 91.50; double i4 = 28.98; double i5 = 50.99; double d1= i1 + i2 +i3 +i4 +i5; System.out.println(d1); System.out.println("note: the total shows the summ of all of the dresses but dresses printed are just three. I wasn't able to print the other two and the total with any locators" ); } @AfterTest public void CloseBrowser() { driver.quit(); } }
89654dfbc3c5bdc3ee3995be9c9938fdcf01a1e7
a9d89e59494140adf03dd63c288ef21ec334be4e
/OCliente/FileSender.java
5b0e8663d125dc7e6e8469d7fdba8f89407395ff
[]
no_license
mnfsch/POO-chat
afacb16a4020942518c305e9e55dfd28c89d149c
db31f3b0378bfc6078e52a1c79a3b3a53a9ad06e
refs/heads/master
2020-09-21T22:04:09.632255
2019-11-30T02:29:07
2019-11-30T02:29:07
224,948,247
0
0
null
null
null
null
UTF-8
Java
false
false
1,113
java
package OCliente; import java.net.*; import java.io.*; public class FileSender implements Runnable { String fileName; FileSender(String file) { fileName=file; // socket criação } public void run() { try { ServerSocket servsock = new ServerSocket(13267); System.out.println("Aguarde.."); Socket sock = servsock.accept(); System.out.println("Conexão aceita : " + sock); // envia o arquivo File myFile = new File(fileName); byte[] mybytearray = new byte[(int) myFile.length()]; FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(mybytearray, 0, mybytearray.length); OutputStream os = sock.getOutputStream(); System.out.println("Enviando..."); os.write(mybytearray, 0, mybytearray.length); os.flush(); sock.close(); } catch (IOException ex) { } } }
04b2fd0e7ba6545740297e09408ddc489224240c
6b73a3a12125d1e132dc5f060c5aaea140a868e7
/用友nc/Main.java
bb2ec2cd85667e4a1619af4798ea78aacec1750d
[]
no_license
FunctFan/changeTools
844833e27761bcfc4aae95b236be79ddae291d17
bf0cb7a530507cc611b5440eede21f1780b229c4
refs/heads/main
2023-08-12T09:38:57.576610
2021-10-18T06:23:19
2021-10-18T06:23:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,069
java
import java.util.Scanner; public class Main { private static long key = 1231234234L; public Main() { } public static String decode(String s) { return decode(s, key); } public static String decode(String s, long k) { if (s == null) { return null; } else { DES des = new DES(k); byte[] sBytes = s.getBytes(); int bytesLength = sBytes.length / 16; byte[] byteList = new byte[bytesLength * 8]; for(int i = 0; i < bytesLength; ++i) { byte[] theBytes = new byte[8]; for(int j = 0; j <= 7; ++j) { byte byte1 = (byte)(sBytes[16 * i + 2 * j] - 97); byte byte2 = (byte)(sBytes[16 * i + 2 * j + 1] - 97); theBytes[j] = (byte)(byte1 * 16 + byte2); } long x = des.bytes2long(theBytes); byte[] result = new byte[8]; des.long2bytes(des.decrypt(x), result); System.arraycopy(result, 0, byteList, i * 8, 8); } String rtn = new String(subArr(byteList)); return rtn; } } public static byte[] subArr(byte[] a) { int al = a.length; int end = checkEnd(a); if (end == 0) { return a; } else { byte[] rtn = new byte[al - end]; System.arraycopy(a, 0, rtn, 0, al - end); return rtn; } } public static int checkEnd(byte[] arr) { int rtn = 0; for(int i = arr.length - 1; i > 0 && arr[i] == 32; --i) { ++rtn; } return rtn; } public static void main(String[] args) throws Exception { if(args.length>0) { String password = args[0]; String var1 = decode(password); System.out.print(var1); }else { System.out.print("java -jar main.jar [code]"); } } }
f8a7f8e96ebf8edff6bb9d212bb1981c16d1dfe7
86f26a81c66cf5d6cc9393448da5f5db68c657e5
/SudokuSolver/SudokuDLX.java
855b24c932bff8e72f997c55924555c50b171c14
[ "MIT" ]
permissive
hyoiutu/SudokuSolver
6a8fbd87be80cf1406d326a8cb7f421c71db18a9
8c173753c9b79ba329de4b2df48dea5e55ce55fd
refs/heads/master
2020-05-14T13:03:21.738984
2015-11-05T06:07:17
2015-11-05T06:07:17
42,745,049
0
0
null
null
null
null
UTF-8
Java
false
false
9,312
java
package SudokuSolver; import java.util.Arrays; public class SudokuDLX extends AbstractSudokuSolver{ // コンストラクタ public SudokuDLX(){ solvee = new int[S][S]; } // 数独問題をもとにEPC行列の初期値を決定する private int[][] makeExactCoverGrid(int[][] sudoku){ // EPC行列を生成する int[][] R = sudokuExactCover(); for(int i = 1; i <= S; i++){ for(int j = 1; j <= S; j++){ int n = sudoku[i - 1][j - 1]; // 数独問題において空白じゃないマスの場合 if (n != 0){ // nの値を探索 for(int num = 1; num <= S; num++){ // 探索用の変数numとnが一致しない場合 if (num != n){ // EPC行列のi行j列目のnumが値の場合の行を0で満たす Arrays.fill(R[getIdx(i, j, num)], 0); } } } } } return R; } // ECP行列の生成 private int[][] sudokuExactCover(){ int[][] R = new int[9 * 9 * 9][9 * 9 * 4]; int hBase = 0; // 1列目の9の倍数分1が入り2列目に移るあとは729列目まで繰り返し /* 1 2 3 4 5 6 7 8 9 ... 729 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * . * . * . * . * . * . * 1 * 1 * 1 * . * . * . * . * . * . * 1 * 1 * 1 */ // row-column constraints for(int r = 1; r <= S; r++){ for(int c = 1; c <= S; c++, hBase++){ for(int n = 1; n <= S; n++){ R[getIdx(r, c, n)][hBase] = 1; } } } //1列目から9列目まで階段状に1を代入 /* 1 2 3 4 5 6 7 8 9 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * ... * * . * . * . */ // row-number constraints for(int r = 1; r <= S; r++){ for(int n = 1; n <= S; n++, hBase++){ for(int c1 = 1; c1 <= S; c1++){ R[getIdx(r, c1, n)][hBase] = 1; } } } // 1列目から729行目まで階段状に1を代入 /* 1 2 3 4 5 6 7 8 9 ... 729 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * ... * 1 */ // column-number constraints for(int c = 1; c <= S; c++){ for(int n = 1; n <= S; n++, hBase++){ for(int r1 = 1; r1 <= S; r1++){ R[getIdx(r1, c, n)][hBase] = 1; } } } /* 1列目から9列目まで階段状に1を代入するのを3回繰り返したのち * 10列目から18列目まで階段状に1を代入するのを3回繰り返す。 * というのを3回繰り返したのち(つまりこの場合は27列目まで階段が及ぶ) * 28行目から36行目まで階段状に1を代入する.これを729行目に達するまで行う * 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ... 727 728 729 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * . * . * . * 1 * 1 * 1 * . * . * . * */ // box-number constraints for(int br = 1; br <= S; br += side){ for(int bc = 1; bc <= S; bc += side){ for(int n = 1; n <= S; n++, hBase++){ for(int rDelta = 0; rDelta < side; rDelta++){ for(int cDelta = 0; cDelta < side; cDelta++){ R[getIdx(br + rDelta, bc + cDelta, n)][hBase] = 1; } } } } } return R; } // 数独問題においてrow行col列目の値numがEPC行列における何行目かを返すメソッド private int getIdx(int row, int col, int num){ return (row - 1) * S * S + (col - 1) * S + (num - 1); } // 引数に取った数独問題の解読を行う protected void runSolver(int[][] sudoku){ // coverに数独問題を基に作られたEPC行列を代入 int[][] cover = makeExactCoverGrid(sudoku); // coverとSudokuHandlerを基にダンシングリンクを生成 DancingLinks dlx = new DancingLinks(cover, new SudokuHandler(S)); // Knuth's Algorithm Xで解読を行う dlx.runSolver(); } }
c290d095277157cc63bad5ac11842c51e35c5422
c1c9f2d81fa08cb1e4c247734ca00347d5f747e6
/TracyRoutes_V1.0-ejb/src/java/sessionsbeans/CarreraFacadeLocal.java
c54941b66c876b26df674cb0879188fbb78418f2
[]
no_license
unicesi/Aventon
9e530597a29096be603c3dade3a17b288995e6c7
85f3411b8965f0671ba8b6dedc568f9137fbbecd
refs/heads/master
2021-01-23T13:17:53.351781
2012-12-04T21:07:28
2012-12-04T21:07:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
504
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sessionsbeans; import entity.Carrera; import java.util.List; import javax.ejb.Local; /** * * @author Administrador */ @Local public interface CarreraFacadeLocal { void create(Carrera carrera); void edit(Carrera carrera); void remove(Carrera carrera); Carrera find(Object id); List<Carrera> findAll(); List<Carrera> findRange(int[] range); int count(); }
08c9352520eb45e9750f87c39c2948a9a14d0296
69bc461599aae868d6120295a16ceb93fe974559
/Tstech声级计_Pro0617功能演示终结版/src/com/tstech/soundlevelinstrument/util/NetStateUtil.java
2d5afb2a56690e233627498adda9e7368016def4
[]
no_license
muyouwoshi/soundlevel
eef10166bcaa63f3dad2cfbd0c264ffb547ea198
461522301fc088772060d4bac9a90a7bbae89d22
refs/heads/master
2020-02-26T15:01:05.085366
2017-06-12T11:14:39
2017-06-12T11:14:39
68,493,944
0
0
null
null
null
null
UTF-8
Java
false
false
1,231
java
package com.tstech.soundlevelinstrument.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.util.Log; /** * 网络状态判断工具<br/> * &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; */ public class NetStateUtil { private NetStateUtil(){} public static String getNetState(){ // 连接管理器-连接状态服务 ConnectivityManager manager = (ConnectivityManager) CtxApp.context.getSystemService(Context.CONNECTIVITY_SERVICE); if(null == manager) return null; // Wifi网络信息对象 NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(null != wifiInfo){ // 状态对象 State state = wifiInfo.getState(); if(state != null){ if(state.equals(State.CONNECTED)){ //wifi可用 return "wifi"; } } } // 移动网络 NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if(null != mobileInfo){ State state = mobileInfo.getState(); if(null != state){ if(state.equals(State.CONNECTED)){ return "mobile"; } } } return null; } }
1c36d5e512b0bec0697c498468f6204a9b12d4c3
f5889ba684c16e0807409f5a1a574ff6e5778136
/app/src/main/java/knf/animeflv/Suggestions/Algoritm/SuggestionDB.java
e691d6ae07c1ada4012cb3a6ceb5887a48e7aab6
[]
no_license
jordyamc/Animeflv
416ba73a3c9c469773acb38a9e49ad59643a8527
3b653ad13862f94185c0204b28e5ce3f1e164f90
refs/heads/master
2021-01-17T01:02:13.250567
2019-11-27T06:59:27
2019-11-27T06:59:27
40,563,645
55
18
null
null
null
null
UTF-8
Java
false
false
4,637
java
package knf.animeflv.Suggestions.Algoritm; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Created by Jordy on 02/01/2017. */ public class SuggestionDB { private static final String TABLE_NAME = "SUGGESTION_POINTS"; private static final String KEY_TABLE_ID = "_table_id"; private static final String KEY_GENRE = "_genre_name"; private static final String KEY_POINTS = "_points"; private static final String DATABASE_CREATE = "create table if not exists " + TABLE_NAME + "(" + KEY_TABLE_ID + " integer primary key autoincrement, " + KEY_GENRE + " text not null, " + KEY_POINTS + " integer" + ");"; private static final String DATABASE_NAME = "AUTO_LEARN_POINTS"; private static final String NEW_COUNT = "NEW_COUNT"; private static final String OLD_COUNT = "OLD_COUNT"; protected Context context; private SQLiteDatabase db; private SuggestionDB(Context context) { this.context = context; try { db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null, null); db.execSQL(DATABASE_CREATE); } catch (Exception e) { e.printStackTrace(); } } public static SuggestionDB get(Context context) { return new SuggestionDB(context); } public void close() { try { db.close(); } catch (NullPointerException e) { Log.e("On Close DB", "DB is Null!!!!!"); } } private boolean existGenre(String genre) { try { Cursor c = db.query(TABLE_NAME, new String[]{ KEY_GENRE }, KEY_GENRE + "='" + genre + "'", null, null, null, null); boolean result = c.getCount() > 0; c.close(); return result; } catch (Exception e) { e.printStackTrace(); return true; } } private void addGenre(String genre, int value) { ContentValues args = new ContentValues(); args.put(KEY_GENRE, genre); args.put(KEY_POINTS, value); db.insert(TABLE_NAME, null, args); } private void updateGenre(String genre, int value) { ContentValues args = new ContentValues(); args.put(KEY_POINTS, value); db.update(TABLE_NAME, args, KEY_GENRE + "='" + genre + "'", null); close(); } private int getCount(String genre) { try { Cursor c = db.query(TABLE_NAME, new String[]{ KEY_POINTS }, KEY_GENRE + "='" + genre + "'", null, null, null, null); if (c.getCount() > 0) { c.moveToFirst(); int count = c.getInt(0); c.close(); return count; } else { return 0; } } catch (Exception e) { e.printStackTrace(); return -1; } } void register(String genre, int value, boolean isOld) { int count = getCount(genre) + value; if (count < 0) count = 0; if (existGenre(genre)) { updateGenre(genre, count); } else { addGenre(genre, count); } close(); } List<Suggestion> getSuggestions(List<String> blacklist) { List<Suggestion> list = new ArrayList<>(); try { Cursor c = db.query(TABLE_NAME, new String[]{ KEY_GENRE, KEY_POINTS }, null, null, null, null, null); if (c.getCount() > 0) { while (c.moveToNext()) { if (!blacklist.contains(c.getString(0))) list.add(new Suggestion(c.getString(0), c.getInt(1))); } c.close(); close(); return list; } else { c.close(); close(); return list; } } catch (Exception e) { e.printStackTrace(); close(); return list; } } public void reset() { db.delete(TABLE_NAME, null, null); close(); } public class Suggestion { public String name; public int count; public Suggestion(String name, int count) { this.name = name; this.count = count; } } }
811a3ab6876bc90d92b68e2f90065b92953c3e6e
6be1e21938e1c043c94a22ee5cc8ff8dac9617df
/src/test/java/com/wbl/KayakFlights/AppTest.java
5c64f5847d201f007da3f8d407a9cfe7d919011f
[]
no_license
123usa/Selenium-Programs
bb37a0b1274af653d31879a02d8e13c72469f166
587ce222276500c843c3c9c16c3acea7cb7edbcf
refs/heads/master
2022-12-08T22:54:34.601533
2020-09-03T20:00:05
2020-09-03T20:00:05
292,667,032
0
0
null
null
null
null
UTF-8
Java
false
false
648
java
package com.wbl.KayakFlights; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
7aaab42ae1a1635b6b98eb524b2eaa1c96359dde
e7e03b23dee150b45b6c3f4c0dac931e00b1faa6
/app/src/main/java/itdeveapps/baustudents/WeatherActivity.java
314ce6839738fd4d932c570187660eb53c5c050b
[]
no_license
tamtom/BAUStudents
8c43c8c6aaa2bc369d9f1efa627f2fa9ac2966de
503d1bc4f5736b2c7e4bdd70729ad712f59243a7
refs/heads/master
2021-01-10T03:14:10.190099
2015-12-11T17:28:44
2015-12-11T17:28:44
43,182,710
0
1
null
2015-11-19T13:08:56
2015-09-26T00:33:44
Java
UTF-8
Java
false
false
8,551
java
package itdeveapps.baustudents; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import dataweather.Channel; import dataweather.Forcast; import dataweather.Item; import servicesweather.YahooServiceCallBack; import servicesweather.YahooWeatherService; public class WeatherActivity extends AppCompatActivity implements YahooServiceCallBack { Dialog dialogs; private ImageView img; private TextView temp; private TextView loctaion; private TextView condition; private YahooWeatherService service; private ProgressDialog dialog; private Day[] days; private ImageView im; private TextView h; private TextView l; private TextView d; private Button change; private Spinner li; private TextView current_weather; public void showDialog() { dialogs = new Dialog(this); dialogs.setContentView(R.layout.select); change = (Button) dialogs.findViewById(R.id.change); li = (Spinner) dialogs.findViewById(R.id.uni); dialogs.setCancelable(true); dialogs.show(); change.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogs.hide(); String c = li.getSelectedItem().toString(); Forcast.index = 0; service = new YahooWeatherService(WeatherActivity.this); dialog = new ProgressDialog(WeatherActivity.this); dialog.setMessage("Loading..."); dialog.show(); if (c.contains("المركز")) service.refreshWeather("Al Balqa, Yarqa"); else if (c.contains("العقبة")) service.refreshWeather("Al Aqaba, Jordan"); else if (c.contains("الهندسة")) service.refreshWeather("Amman, marka"); else if (c.contains("مادبا")) { temp.setText("\uD83D\uDC94"); loctaion.setText("No Madaba "); condition.setText("\uD83D\uDE22"); dialog.hide(); } else if (c.contains("الحصن")) service.refreshWeather("Irbid, Jordan"); else if (c.contains("إربد")) service.refreshWeather("Irbid, Jordan"); else if (c.contains("الزرقاء")) service.refreshWeather("Al Zarqa, Jordan"); else if (c.contains("المالية")) { service.refreshWeather("Amman, Jordan"); loctaion.setText("Sweifieh ,Amman"); } else if (c.contains("الكرك")) service.refreshWeather("Al Karak, Jordan"); else if (c.contains("معان")) service.refreshWeather("Maan, Jordan"); else if (c.contains("الشوبك")) service.refreshWeather("Maan, Alshoubak"); else if (c.contains("عجلون")) service.refreshWeather("Ajloun, Jordan"); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#009688"))); } current_weather = (TextView) findViewById(R.id.current_weather); SharedPreferences prefs = getApplicationContext().getSharedPreferences("weather_status", MODE_PRIVATE); String status = prefs.getString("status", ""); current_weather.setText(status); img = (ImageView) findViewById(R.id.img); temp = (TextView) findViewById(R.id.temp); loctaion = (TextView) findViewById(R.id.location); condition = (TextView) findViewById(R.id.condetion); Forcast.index = 0; days = new Day[5]; im = (ImageView) findViewById(R.id.img1); h = (TextView) findViewById(R.id.max1); l = (TextView) findViewById(R.id.low1); d = (TextView) findViewById(R.id.day1); days[0] = new Day(im, h, l, d); im = (ImageView) findViewById(R.id.img2); h = (TextView) findViewById(R.id.max2); l = (TextView) findViewById(R.id.low2); d = (TextView) findViewById(R.id.day2); days[1] = new Day(im, h, l, d); im = (ImageView) findViewById(R.id.img3); h = (TextView) findViewById(R.id.max3); l = (TextView) findViewById(R.id.low3); d = (TextView) findViewById(R.id.day3); days[2] = new Day(im, h, l, d); im = (ImageView) findViewById(R.id.img4); h = (TextView) findViewById(R.id.max4); l = (TextView) findViewById(R.id.low4); d = (TextView) findViewById(R.id.day4); days[3] = new Day(im, h, l, d); im = (ImageView) findViewById(R.id.img5); h = (TextView) findViewById(R.id.max5); l = (TextView) findViewById(R.id.low5); d = (TextView) findViewById(R.id.day5); days[4] = new Day(im, h, l, d); service = new YahooWeatherService(this); dialog = new ProgressDialog(this); dialog.setCancelable(false); dialog.setMessage("Loading..."); dialog.show(); service.refreshWeather("Al Balqa, Yarqa"); } @Override protected void onStop() { super.onStop(); } @Override protected void onPostResume() { super.onPostResume(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { super.onBackPressed(); Forcast.index = 0; finish(); } @Override protected void onPause() { super.onPause(); Forcast.index = 0; } @Override protected void onResume() { super.onResume(); } @Override public void servicesucsess(Channel channel) { dialog.hide(); Item item = channel.getItem(); int resources = getResources().getIdentifier("drawable/icon_" + item.getCondition().getCode(), null, getPackageName()); @SuppressWarnings("deprecation") Drawable imagdrawble = getResources().getDrawable(resources); this.img.setImageDrawable(imagdrawble); temp.setText(item.getCondition().getTemp() + " \u00b0 " + channel.getUnit().getTemperature()); condition.setText(item.getCondition().getDescription()); loctaion.setText(service.getLocation()); int cc[] = item.getForcast().getCodes(); int hh[] = item.getForcast().getHigh(); int ll[] = item.getForcast().getLow(); String da[] = item.getForcast().getDays(); for (int i = 0; i < 5; i++) { days[i].getD().setText(da[i]); days[i].h.setText(hh[i] + ""); days[i].getL().setText(ll[i] + ""); int res1 = getResources().getIdentifier("drawable/icon_" + cc[i], null, getPackageName()); //noinspection deprecation imagdrawble = getResources().getDrawable(res1); days[i].getImg().setImageDrawable(imagdrawble); } } @Override public void servicefail(Exception ex) { dialog.dismiss(); Intent i = new Intent(this, NoInternetConnectionActivity.class); finish(); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_weather, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.selectuni) { showDialog(); } return super.onOptionsItemSelected(item); } }
3ac9a93661d675b25266479fe96ddb5b8341a469
03570fa5a8a514b2ab1c52fc05c746187cac09c4
/8puzzle/Solver.java
3d78d9d2c5a2704d1a31393039a8c08906e45631
[]
no_license
vanosidor/Coursera-Algorithms-Part1
68fc30b67167bbe09ec91c091374687333321c74
7854c23122d094c3b521594f22fd13a073add354
refs/heads/master
2023-04-01T13:57:21.408072
2021-03-31T09:27:59
2021-03-31T09:27:59
339,327,739
0
0
null
null
null
null
UTF-8
Java
false
false
3,486
java
/* ***************************************************************************** * Name: * Date: * Description: **************************************************************************** */ import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.MinPQ; import edu.princeton.cs.algs4.Stack; import edu.princeton.cs.algs4.StdOut; public class Solver { private boolean solvable; private Stack<Board> solutionBoards; // find a solution to the initial board (using the A* algorithm) public Solver(Board initial) { if (initial == null) throw new IllegalArgumentException(); solutionBoards = new Stack<>(); MinPQ<SearchNode> searchNodes = new MinPQ<>(); searchNodes.insert(new SearchNode(initial, null)); searchNodes.insert(new SearchNode(initial.twin(), null)); while (!searchNodes.min().board.isGoal()) { SearchNode currentSearchNode = searchNodes.delMin(); for (Board b : currentSearchNode.board.neighbors()) { if (currentSearchNode.prevNode == null || !b .equals(currentSearchNode.prevNode.board)) { searchNodes.insert(new SearchNode(b, currentSearchNode)); } } } SearchNode current = searchNodes.min(); while (current.prevNode != null) { solutionBoards.push(current.board); current = current.prevNode; } solutionBoards.push(current.board); if (current.board.equals(initial)) solvable = true; } // is the initial board solvable? (see below) public boolean isSolvable() { return solvable; } // min number of moves to solve initial board; -1 if unsolvable public int moves() { if (isSolvable()) return solutionBoards.size() - 1; else return -1; } // sequence of boards in a shortest solution; null if unsolvable public Iterable<Board> solution() { if (solvable) return solutionBoards; else return null; } // test client (see below) public static void main(String[] args) { // create initial board from file In in = new In(args[0]); int n = in.readInt(); int[][] tiles = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) tiles[i][j] = in.readInt(); Board initial = new Board(tiles); // solve the puzzle Solver solver = new Solver(initial); // print solution to standard output if (!solver.isSolvable()) StdOut.println("No solution possible"); else { StdOut.println("Minimum number of moves = " + solver.moves()); for (Board board : solver.solution()) StdOut.println(board); } } private class SearchNode implements Comparable<SearchNode> { private final Board board; private final SearchNode prevNode; private int moves; private int manhattan; SearchNode(Board board, SearchNode prevNode) { this.board = board; this.prevNode = prevNode; this.manhattan = board.manhattan(); if (prevNode != null) moves = prevNode.moves + 1; else moves = 0; } public int compareTo(SearchNode that) { return this.moves + this.manhattan - (that.moves + that.manhattan); } } }
6c8a8b16452e4b09c95582716432cd29b0b69a0c
558ad40723ed9c8298ec52bd93aab94516c5b686
/Clase2020/src/tema4/runnerSinInterfaces/RunnerNaves.java
fad2e2c55cf04d6e4baa53cb355b8832361ffb0a
[]
no_license
andoni-eguiluz/ud-prog2-clase-2020
a46a9addf160974b7b28924f8180b7cc560dd941
92847a201d13920ff7b0308e8c07bb85e6fb8259
refs/heads/master
2021-07-17T02:53:41.199615
2021-02-14T16:37:25
2021-02-14T16:37:25
237,613,459
3
4
null
null
null
null
UTF-8
Java
false
false
13,155
java
package tema4.runnerSinInterfaces; import java.awt.Color; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Random; import tema3.VentanaGrafica; /** Juego runner ejercicio - con desplazamiento lateral de las naves añadido * Con bonus que funcionan como los asteroides pero en lugar de explotar la nave se gana tiempo de protección * @author andoni.eguiluz @ ingenieria.deusto.es */ public class RunnerNaves { private static final long MSGS_POR_FRAME = 20; // 20 msgs por frame = 50 frames por segundo aprox private static final double RADIO_NAVE = 25; // Radio de la nave (círculo imaginario) private static final int TAM_NAVE = 50; // Píxel de tamaño de cada nave private static final double RADIO_MIN_ASTER = 25; // Radio mínimo del asteroide (círculo imaginario) private static final double RADIO_MAX_ASTER = 50; // Radio máximo del asteroide (círculo imaginario) private static final double VEL_Y_NAVES = 500; // Velocidad (vertical) de desplazamiento de las naves private static final double VEL_X_NAVES = 400; // Velocidad (horizontal) de desplazamiento de las naves private static final int X_MIN_NAVES = 0; // Mínima x por la izquierda para las naves private static final int X_MAX_NAVES = 800; // Máxima x por la derecha para las naves private static final double INC_VEL_NAVES = 50; // Cada nave es un poquito más rápida que la anterior private static final int NUM_NAVES = 5; // Número de naves del juego private static final int DIST_NAVES = 60; // Píxels de distancia entre naves private static final int[] CANAL = { 100, 200, 300, 400, 500 }; // Píxels y de cada canal private static double VEL_MIN_ASTER = 200; // Velocidad mínima del asteroide (píxels por segundo) private static double VEL_MAX_ASTER = 300; // Velocidad máxima del asteroide (píxels por segundo) private static double PROB_NUEVO_AST = 0.02; // Probabilidad de que aparezca un nuevo asteroide cada frame (2%) private static double PROB_NUEVO_BONUS = 0.02; // Probabilidad de que aparezca un nuevo bonus cada frame (%) private static double VEL_JUEGO = 1.0; // 1.0 = tiempo real. Cuando mayor, más rápido pasa el tiempo y viceversa private static Random random; // Generador de aleatorios para creación de asteroides public static void main(String[] args) { RunnerNaves juego = new RunnerNaves(); juego.jugar(); } // ================================= // ATRIBUTOS Y MÉTODOS DE INSTANCIA (no static) // ================================= private VentanaGrafica vent; // Ventana del juego private ArrayList<ObjetoEspacial> elementos; // Elementos del juego (tanto naves como asteroides) private ArrayList<Nave> naves; // Naves del juego (solo las naves) private long tiempoNivel; // Tiempo inicial del nivel actual (milisegundos) public void jugar() { System.out.println( String.format( "Inicio juego. Asteroide %1$1.1f%% - Bonus %2$1.1f%%", PROB_NUEVO_AST*100.0, PROB_NUEVO_BONUS*100.0 ) ); random = new Random(); vent = new VentanaGrafica( 1200, 600, "Runner de naves" ); crearFondos(); crearNaves(); mover(); } // Crea los 3 fondos decorativos private void crearFondos() { elementos = new ArrayList<>(); Fondo fondo1 = new Fondo( "/tema3/img/UD-roller.jpg", 0, 333, 1.0, 0.35f, 1000 ); // Imagen 1000x666 píxels Fondo fondo2 = new Fondo( "/tema3/img/UD-roller.jpg", 1000, 333, 1.0, 0.35f, 1000 ); Fondo fondo3 = new Fondo( "/tema3/img/UD-roller.jpg", 2000, 333, 1.0, 0.35f, 1000 ); fondo1.setVX( -200 ); fondo2.setVX( -200 ); fondo3.setVX( -200 ); elementos.add( 0, fondo1 ); elementos.add( 1, fondo2 ); elementos.add( 2, fondo3 ); // Los tres primeros elementos son los fondos (se dibujan al principio de todo) } // Crea las 5 naves de inicio private void crearNaves() { int posNave = TAM_NAVE; naves = new ArrayList<>(); for (int numNave=0; numNave<NUM_NAVES; numNave++) { Nave nave = new Nave( posNave, CANAL[2] ); // Nueva nave en canal intermedio nave.setCanal( 2 ); elementos.add( nave ); naves.add( nave ); posNave += DIST_NAVES; } } // Bucle de movimiento private void mover() { long tiempoInicial = System.currentTimeMillis(); tiempoNivel = System.currentTimeMillis(); vent.setDibujadoInmediato( false ); while (!vent.estaCerrada() && naves.size()>0) { // Manejo de teclado gestionTecladoYMovtoNaves(); // Creación aleatoria de nuevo asteroide if (random.nextDouble()<PROB_NUEVO_AST) { creaNuevoAsteroide(); } // Creación aleatoria de nuevo bonus if (random.nextDouble()<PROB_NUEVO_BONUS) { creaNuevoBonus(); } // Movimiento de todos los elementos for (ObjetoEspacial objeto : elementos) { objeto.mueve( MSGS_POR_FRAME/1000.0 * VEL_JUEGO ); } // Rotación de los bonus y los asteroides for (ObjetoEspacial objeto : elementos) { if (objeto instanceof Asteroide) { ((Asteroide)objeto).rota( 0.1 ); } else if (objeto instanceof Bonus) { ((Bonus)objeto).rota( 0.1 ); } } // Comprobación de parada de naves (ver si han llegado a su canal) for (Nave nave : naves) { miraSiEstaEnSuCanal(nave); } // Control de salida de pantalla de los asteroides y los bonus (y cambio de los fondos) for (int i=elementos.size()-1; i>=0; i--) { ObjetoEspacial oe = elementos.get(i); if (oe instanceof Asteroide) { Asteroide a = (Asteroide) oe; if (a.seSalePorLaIzquierda( vent )) { elementos.remove( a ); } } else if (oe instanceof Bonus) { Bonus b = (Bonus) oe; if (b.seSalePorLaIzquierda( vent )) { elementos.remove( b ); } } else if (oe instanceof Fondo) { Fondo f = (Fondo) oe; if (f.seSalePorLaIzquierda( vent )) { f.setX( f.getX() + 3000 ); // 1000 píxels de ancho cada fondo } } } // Choque naves con asteroides (todos con todos) for (int i=naves.size()-1; i>=0; i--) { // OJO: Como se pueden borrar hay que recorrerlo en sentido inverso ObjetoEspacial oe = naves.get(i); if (oe instanceof Nave) { Nave nave = (Nave) oe; boolean choque = false; double tiempoBonus = 0.0; boolean cogeBonus = false; ArrayList<Bonus> lBonusChocan = new ArrayList<Bonus>(); for (ObjetoEspacial oe2 : elementos) { if (oe2 instanceof Asteroide) { Asteroide a = (Asteroide) oe2; if (hayChoque(nave, a)) { choque = true; // break; No acabar bucle (miramos más colisiones por si también hay un bonus que protege) } } else if (oe2 instanceof Bonus) { Bonus b = (Bonus) oe2; if (hayChoque(nave, b)) { cogeBonus = true; tiempoBonus += b.getTiempoProteccion(); lBonusChocan.add( b ); // break; No acabar bucle (puede haber varias colisiones) } } } for (Bonus b : lBonusChocan) elementos.remove( b ); // Quitar los bonus que chocan if (cogeBonus) { nave.addProteccion( tiempoBonus ); } if (choque && nave.getProteccion()<=0.0) { elementos.remove( nave ); // Fuera nave naves.remove( nave ); // Da igual aquí naves.remove( i ); } } } // Dibujado vent.borra(); int fondos = 0; for (ObjetoEspacial oe : elementos) { oe.dibuja( vent ); fondos++; if (fondos==3) { dibujaBordes(); } } vent.setMensaje( "Tiempo de juego: " + (System.currentTimeMillis() - tiempoInicial) ); vent.repaint(); // Ciclo de espera en cada bucle vent.espera( MSGS_POR_FRAME ); // Subida de nivel subeNivel(); } } private void gestionTecladoYMovtoNaves() { if (vent.isTeclaPulsada( KeyEvent.VK_PLUS )) { VEL_JUEGO *= 1.05; vent.setMensaje( "Nueva velocidad de juego: " + VEL_JUEGO ); } if (vent.isTeclaPulsada( KeyEvent.VK_MINUS )) { VEL_JUEGO /= 1.05; vent.setMensaje( "Nueva velocidad de juego: " + VEL_JUEGO ); } // Movimiento vertical jugador - mira a ver si están subiendo o bajando... boolean estanSubiendo = false; boolean estanBajando = false; for (Nave nave : naves) { if (nave.isSubiendo()) estanSubiendo = true; if (nave.isBajando()) estanBajando = true; } if (!estanSubiendo && !estanBajando) { // Si están bajando o subiendo las naves siguen su camino hasta que lleguen al canal // Si ni están subiendo ni bajando entonces... if (vent.isTeclaPulsada( KeyEvent.VK_UP )) { double velocidad = -VEL_Y_NAVES; for (Nave nave : naves) { if (nave.getCanal()>0) { // Si no está en el canal superior nave.setVY( velocidad ); nave.setSubiendo( true ); nave.setCanal( nave.getCanal()-1 ); } velocidad -= INC_VEL_NAVES; } } else if (vent.isTeclaPulsada( KeyEvent.VK_DOWN )) { double velocidad = +VEL_Y_NAVES; for (Nave nave : naves) { if (nave.getCanal()<CANAL.length-1) { // Si no está en el canal inferior nave.setVY( velocidad ); nave.setBajando( true ); nave.setCanal( nave.getCanal()+1 ); } velocidad += INC_VEL_NAVES; } } } // Movimiento horizontal jugador double velX = 0.0; if (vent.isTeclaPulsada( KeyEvent.VK_LEFT )) { velX = -VEL_X_NAVES; // Velocidad hacia la izquierda (negativa) } else if (vent.isTeclaPulsada( KeyEvent.VK_RIGHT )) { velX = VEL_X_NAVES; // Velocidad hacia la derecha (positiva) } // Comprobación de parada en los extremos if (naves.get(0).getX() <= X_MIN_NAVES && velX<0) velX = 0.0; if (naves.get(naves.size()-1).getX() >= X_MAX_NAVES && velX>0) velX = 0.0; for (Nave nave : naves) { nave.setVX( velX ); } } private void dibujaBordes() { int distCanales = (CANAL[1] - CANAL[0]) / 2; vent.dibujaRect( 0, distCanales, vent.getAnchura(), 2.0*CANAL.length*distCanales, 1.5f, Color.black ); for (int canal=0; canal<CANAL.length-1; canal++) { int vertical = CANAL[canal] + distCanales; vent.dibujaLinea( 0, vertical, vent.getAnchura(), vertical, 0.5f, Color.blue ); } } private void creaNuevoAsteroide() { double radioAleatorio = random.nextDouble() * (RADIO_MAX_ASTER - RADIO_MIN_ASTER ) + RADIO_MIN_ASTER; int canalAleatorio = random.nextInt( CANAL.length ); Asteroide asteroide = new Asteroide( radioAleatorio, vent.getAnchura() + radioAleatorio, CANAL[canalAleatorio] ); double velAleatoria = random.nextDouble() * (VEL_MAX_ASTER - VEL_MIN_ASTER ) + VEL_MIN_ASTER; asteroide.setVX( -velAleatoria ); elementos.add( 3, asteroide ); // Se añade al principio para que las naves sean lo último que se dibujen (0,1,2 son los fondos) } private void creaNuevoBonus() { double tiempo = random.nextDouble() * 5; // Entre 0 y 5 segundos de protección - podríamos ponerlo configurable double radio = tiempo*10; // Proporcional al tiempo del bonus int canalAleatorio = random.nextInt( CANAL.length ); Bonus bonus = new Bonus( radio, vent.getAnchura() + radio, CANAL[canalAleatorio], tiempo ); double velAleatoria = random.nextDouble() * (VEL_MAX_ASTER - VEL_MIN_ASTER ) + VEL_MIN_ASTER; bonus.setVX( -velAleatoria ); elementos.add( bonus ); } // Choque entre nave y asteroide (simplificado con envolventes círculos) private boolean hayChoque( Nave nave, Asteroide asteroide ) { double dist = Fisica.distancia(nave.x, nave.y, asteroide.x, asteroide.y ); return (dist < RADIO_NAVE + asteroide.getRadio()); } // Choque entre nave y bonus (simplificado con envolventes círculos) private boolean hayChoque( Nave nave, Bonus bonus ) { double dist = Fisica.distancia(nave.x, nave.y, bonus.x, bonus.y ); return (dist < RADIO_NAVE + bonus.getRadio()); } // Determina si una nave ha llegado ya a su canal y la para si es el caso private void miraSiEstaEnSuCanal( Nave nave ) { if (nave.isSubiendo()) { if (nave.getY() <= CANAL[nave.getCanal()]) { nave.setY( CANAL[nave.getCanal()]); nave.setVY( 0.0 ); nave.setSubiendo( false ); } } else if (nave.isBajando()) { if (nave.getY() >= CANAL[nave.getCanal()]) { nave.setY( CANAL[nave.getCanal()]); nave.setVY( 0.0 ); nave.setBajando( false ); } } } // Sube el nivel cada 15 segundos (mayor dificultad) private void subeNivel() { if (System.currentTimeMillis() - tiempoNivel > 15000) { PROB_NUEVO_AST += 0.01; // Sube un 1% la probabilidad de asteroide PROB_NUEVO_BONUS *= 0.8; // Se baja un 20% la probabilidad de nuevo bonus VEL_MAX_ASTER += 10; // Sube 10 píxels por segundo la velocidad máxima de asteroide tiempoNivel = System.currentTimeMillis(); // Nueva cuenta de tiempo System.out.println( String.format( "Nuevo nivel. Asteroide %1$1.1f%% - Bonus %2$1.1f%%", PROB_NUEVO_AST*100.0, PROB_NUEVO_BONUS*100.0 ) ); } } }
07d75cd4a39a8cd2f07f059c8cc4caf324bc8917
46fc1e3f8aa6dbdc86a838e3b3c6fb05bf076657
/src/test/java/com/kosta/jo3/getPriceTest.java
d32f0c3fc73fadf6cd43bf41161e796e9f03d361
[]
no_license
kkvn260/O2O2
2a33f32a5896ec55dfcb0eaefa504838a0e92d8a
580bfc30a6e0aa171d05148abe62761a9a1465e4
refs/heads/master
2023-09-03T21:35:49.689763
2021-10-21T04:56:46
2021-10-21T04:56:46
407,433,089
0
0
null
null
null
null
UTF-8
Java
false
false
1,719
java
package com.kosta.jo3; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.kosta.o2dao.O2WriteDAO; import com.kosta.o2writeservice.O2WriteService; import lombok.extern.slf4j.Slf4j; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src\\main\\webapp\\WEB-INF\\spring\\root-context.xml") @Slf4j public class getPriceTest { @Autowired private O2WriteService service; @Autowired private O2WriteDAO dao; @Test public void getDayPriceTest() { HashMap<String, Object> hm = new HashMap<>(); String itemProd = "아이폰8플러스 (64GB)"; String category = "item_name"; hm.put("itemProd", itemProd); hm.put("category", category); assertEquals("아이폰8플러스 (64GB)", dao.getDayPrice(hm).getItem_name()); } @Test public void getWeekPriceTest() { HashMap<String, Object> hm = new HashMap<>(); String itemProd = "아이폰13 미니"; String category = "item_name"; hm.put("itemProd", itemProd); hm.put("category", category); assertEquals("아이폰13 미니", dao.getWeekPrice(hm).getItem_name()); } @Test public void getMonthPriceTest() { HashMap<String, Object> hm = new HashMap<>(); String itemProd = "아이폰13 미니"; String category = "item_name"; hm.put("itemProd", itemProd); hm.put("category", category); assertEquals("아이폰13 미니 (128GB)", dao.getMonthPrice(hm).getItem_name()); } }
04dbcb7248587fa081826d8d6ba0ed54a20048c2
9cfeb4c61cdbcf3a9d11c34b4e3291763f9a55fa
/iot-infomgt/iot-infomgt-dao/src/main/java/org/iotp/infomgt/dao/sql/rule/JpaBaseRuleDao.java
d1dbc35f9a720ddf93d537301a928f4749f64379
[ "Apache-2.0" ]
permissive
soncd19/iotplatform
a6bbf73f381850fddba71a9356189d4c3a6a6a40
c3f5545f58944b06145fd737fd5a85dc5b97d019
refs/heads/master
2023-08-05T01:17:28.160724
2021-10-08T02:54:30
2021-10-08T02:54:30
414,826,433
0
0
null
null
null
null
UTF-8
Java
false
false
5,510
java
/******************************************************************************* * Copyright 2017 [email protected] * * 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. ******************************************************************************/ /** * Copyright © 2016-2017 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iotp.infomgt.dao.sql.rule; import static org.iotp.infomgt.dao.model.ModelConstants.NULL_UUID_STR; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.UUID; import org.iotp.infomgt.dao.DaoUtil; import org.iotp.infomgt.dao.model.sql.RuleMetaDataEntity; import org.iotp.infomgt.dao.rule.RuleDao; import org.iotp.infomgt.dao.sql.JpaAbstractSearchTextDao; import org.iotp.infomgt.dao.util.SqlDao; import org.iotp.infomgt.data.common.UUIDConverter; import org.iotp.infomgt.data.id.RuleId; import org.iotp.infomgt.data.id.TenantId; import org.iotp.infomgt.data.page.TextPageLink; import org.iotp.infomgt.data.rule.RuleMetaData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * Created by Valerii Sosliuk on 4/30/2017. */ @Slf4j @Component @SqlDao public class JpaBaseRuleDao extends JpaAbstractSearchTextDao<RuleMetaDataEntity, RuleMetaData> implements RuleDao { @Autowired private RuleMetaDataRepository ruleMetaDataRepository; @Override protected Class<RuleMetaDataEntity> getEntityClass() { return RuleMetaDataEntity.class; } @Override protected CrudRepository<RuleMetaDataEntity, String> getCrudRepository() { return ruleMetaDataRepository; } @Override public RuleMetaData findById(RuleId ruleId) { return findById(ruleId.getId()); } @Override public List<RuleMetaData> findRulesByPlugin(String pluginToken) { log.debug("Search rules by api token [{}]", pluginToken); return DaoUtil.convertDataList(ruleMetaDataRepository.findByPluginToken(pluginToken)); } @Override public List<RuleMetaData> findByTenantIdAndPageLink(TenantId tenantId, TextPageLink pageLink) { log.debug("Try to find rules by tenantId [{}] and pageLink [{}]", tenantId, pageLink); List<RuleMetaDataEntity> entities = ruleMetaDataRepository .findByTenantIdAndPageLink( UUIDConverter.fromTimeUUID(tenantId.getId()), Objects.toString(pageLink.getTextSearch(), ""), pageLink.getIdOffset() == null ? NULL_UUID_STR : UUIDConverter.fromTimeUUID(pageLink.getIdOffset()), new PageRequest(0, pageLink.getLimit())); if (log.isTraceEnabled()) { log.trace("Search result: [{}]", Arrays.toString(entities.toArray())); } else { log.debug("Search result: [{}]", entities.size()); } return DaoUtil.convertDataList(entities); } @Override public List<RuleMetaData> findAllTenantRulesByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find all tenant rules by tenantId [{}] and pageLink [{}]", tenantId, pageLink); List<RuleMetaDataEntity> entities = ruleMetaDataRepository .findAllTenantRulesByTenantId( UUIDConverter.fromTimeUUID(tenantId), NULL_UUID_STR, Objects.toString(pageLink.getTextSearch(), ""), pageLink.getIdOffset() == null ? NULL_UUID_STR : UUIDConverter.fromTimeUUID(pageLink.getIdOffset()), new PageRequest(0, pageLink.getLimit())); if (log.isTraceEnabled()) { log.trace("Search result: [{}]", Arrays.toString(entities.toArray())); } else { log.debug("Search result: [{}]", entities.size()); } return DaoUtil.convertDataList(entities); } @Override public void deleteById(UUID id) { log.debug("Delete rule meta-data entity by id [{}]", id); ruleMetaDataRepository.delete(UUIDConverter.fromTimeUUID(id)); } @Override public void deleteById(RuleId ruleId) { deleteById(ruleId.getId()); } }
319ab6c68e9f114e9e95e7cbe40b6f594ee0f1e8
36c2fad222b2d2c5f01b26b2fb8563dc0c2c6568
/app/src/main/java/com/noveogroup/teamzolotov/iwashere/util/ValidatorUtils.java
494a720418599d2bc0ebe40f3ac026894ec5a2ca
[]
no_license
WildWind03/IWasHere
b03cb6d759058f13769f441df80ce483dee8fb21
643fe8d55d1998d4c4499cc8556cff41e96531fb
refs/heads/master
2021-01-10T18:14:30.593428
2016-08-05T04:08:11
2016-08-05T04:08:11
65,951,730
0
0
null
null
null
null
UTF-8
Java
false
false
3,457
java
package com.noveogroup.teamzolotov.iwashere.util; import android.content.Context; import com.noveogroup.teamzolotov.iwashere.R; import com.noveogroup.teamzolotov.iwashere.validation.ValidationResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class ValidatorUtils { private static final int MIN_LENGTH_OF_PASSWORD = 6; private static final int MAX_LENGTH_OF_PASSWORD = 256; private static final int MIN_LENGTH_OF_USERNAME = 2; private static final int MAX_LENGTH_OF_USERNAME = 256; private ValidatorUtils() { throw new UnsupportedOperationException("Trying to create instance of utility class"); } private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); public static boolean validateEmail(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr); return matcher.find(); } public static void validatePassword(String password, ValidationResult validationResult) { if (null == password) { validationResult.addProblem(ValidationResult.ValidationProblem.NULL_REFERENCE); return; } if (password.length() < MIN_LENGTH_OF_PASSWORD) { validationResult.addProblem(ValidationResult.ValidationProblem.SHORT_PASSWORD); return; } if (password.length() > MAX_LENGTH_OF_PASSWORD) { validationResult.addProblem(ValidationResult.ValidationProblem.LONG_PASSWORD); } } public static void validateUsername(String username, ValidationResult validationResult) { if (null == username) { validationResult.addProblem(ValidationResult.ValidationProblem.NULL_REFERENCE); return; } if (username.length() < MIN_LENGTH_OF_USERNAME) { validationResult.addProblem(ValidationResult.ValidationProblem.SHORT_USERNAME); return; } if (username.length() > MAX_LENGTH_OF_USERNAME) { validationResult.addProblem(ValidationResult.ValidationProblem.LONG_USERNAME); } } public static void validateEmail(String email, ValidationResult validationResult) { if (!validateEmail(email)) { validationResult.addProblem(ValidationResult.ValidationProblem.INVALID_EMAIL); } } public static String getMessage(Context context, ValidationResult.ValidationProblem validationProblem) { String message = null; switch (validationProblem) { case NULL_REFERENCE: message = context.getString(R.string.unexpected_error_message); break; case SHORT_PASSWORD: message = context.getString(R.string.short_password_error_message); break; case LONG_PASSWORD: message = context.getString(R.string.long_password_error_message); break; case SHORT_USERNAME: message = context.getString(R.string.short_username_error_message); break; case LONG_USERNAME: message = context.getString(R.string.long_username_error_message); break; case INVALID_EMAIL: message = context.getString(R.string.invalid_email_error_message); } return message; } }
4124c6392613e5007c2e498776188255fd94cca5
bb44c804ec755ef239c324e1312b00c12e577f36
/InfoManage/src/cn/edu/info_manage/domain/User.java
12f5bc1bb63cf462180e69bea382b9d6d6e1c9ea
[]
no_license
androids7/myinfomanager
16c4ebe5b056fc4362364889b43c5c860f6de01f
73f4f424367bbb9320339715fde998834cce0c45
refs/heads/master
2020-03-10T10:31:43.336082
2018-04-13T02:13:37
2018-04-13T02:13:37
129,334,966
0
0
null
null
null
null
UTF-8
Java
false
false
2,669
java
package cn.edu.info_manage.domain; import java.io.File; import java.io.Serializable; import android.os.Environment; public class User implements Serializable{ public static final String ID = "id"; public static final String NAME = "username"; public static final String PASSWORD = "password"; public static final String EMAIL = "email"; public static final String AGE = "age"; public static final String SEX = "sex"; public static final String POTO = "poto"; public static final File PHOTO_DIR = //用户头像的默认存储路径 new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera"); private int id; //ID private String username; //用户名 private String password; //密码 private String email; //邮箱 private int age; //年龄 private String sex; //性别 private byte[] poto; //头像(保存本地的路径/非数据库) public User() { super(); // TODO Auto-generated constructor stub } public byte[] getPoto() { return poto; } public void setPoto(byte[] poto) { this.poto = poto; } public User(String username, String password, String email, int age, String sex, byte[] poto) { super(); this.username = username; this.password = password; this.email = email; this.age = age; this.sex = sex; this.poto = poto; } public User(int id, String username, String password, String email, int age, String sex, byte[] poto) { super(); this.id = id; this.username = username; this.password = password; this.email = email; this.age = age; this.sex = sex; this.poto = poto; } public String getEmail() { return email; } public void setEmail(String email) { if(email==null) email = ""; this.email = email; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { if(username==null) username=""; this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { if(password==null) password=""; this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { if(sex==null) sex="女"; this.sex = sex; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", email="+email+", age=" + age + ", sex=" + sex +", poto=" + poto + "]"; } }
d7d54f471b0903b8adec705de5b77f0961237c4d
180875ed8fdfb790ee7bb6bd750a989a38ef5724
/src/ThreeSum.java
0bf3de1a20e4893f3f54b7317e100d598e5ed8f4
[]
no_license
sinllychen/Leetcode
e75a08474989d363c3961543f0259b8f33c872b8
f959bcff8742d060397af7806b68d807e1c67c56
refs/heads/master
2020-11-26T09:48:04.048379
2018-06-14T03:01:08
2018-06-14T03:01:08
41,954,668
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
1,934
java
import java.util.ArrayList; import java.util.List; public class ThreeSum { public void insertSort(int[] nums) { int key; for(int i=1;i<nums.length;i++) { key=nums[i]; int j=i-1; while(j>=0 && key<nums[j]) { nums[j+1]=nums[j]; j--; } nums[j+1]=key; } } public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res=new ArrayList< List<Integer>>(); if(nums.length<3) return res; insertSort(nums); for(int i=0;i<nums.length;i++) { if(i!=0 && nums[i]==nums[i-1]) continue; int start=i+1; int end=nums.length-1; int sum=0; while(start<end) { sum=nums[i]+nums[start]+nums[end]; if(sum==0) { int[] tmpRes={nums[i],nums[start],nums[end]}; insertSort(tmpRes); List<Integer> tmp=new ArrayList<Integer>(); for(int j=0;j<tmpRes.length;j++) tmp.add(tmpRes[j]); res.add(tmp); while(++start<end && nums[start-1]==nums[start]) { continue; }; while(--end>start && nums[end+1]==nums[end]) { continue; } } else if(sum<0) { ++start; } else --end; } } return res; } public static void main(String[] args) { int[] nums={-1, 0, 1, 2, -1, -4}; List<List<Integer>> result=new ThreeSum().threeSum(nums); for(int i=0;i<result.size();i++) { System.out.println("µÚ"+(i+1)+"×é"); for(int j=0;j<result.get(i).size();j++) { System.out.print(result.get(i).get(j)+","); } System.out.println(); } } }
a35e558c5355889d10edf0a6f9ecc979065469b9
9ec4c781b6109069006943ad77245ecc08c84a23
/src/main/java/io/github/arqueue/api/beans/get/login/Role.java
449143541ec2cbdfe434867a87fe81cb3c4c755f
[]
no_license
demonus/arqueue
39339d1c34a436a3578f30a34149fd17588f6ed0
781367ac4770971218ca88592b3a98f0fa575485
refs/heads/master
2021-01-10T11:57:43.632382
2015-11-26T00:58:45
2015-11-26T00:58:45
44,297,058
0
0
null
2015-10-26T22:35:09
2015-10-15T06:05:53
Java
UTF-8
Java
false
false
696
java
package io.github.arqueue.api.beans.get.login; /** * Created by root on 11/11/15. */ public class Role { private String id; private String description; private String name; private String tenantId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
5c549ec5c63340b53677de9e103bca685e30c9db
24e14bf593753d3fe91609cbf9667ce595933a18
/src/com/ptc/tifworkbench/ui/DifferenceDialog.java
40dbd72c9efc8b17165c24643910d65914950761
[ "MIT" ]
permissive
rafichris/TIF
55f2503eb3e5a9d03e8021f53d2e9d9e379fdaa9
0781f37581af242f46dc992ae29745854e16679e
refs/heads/master
2021-12-10T05:58:06.124418
2015-08-05T14:43:26
2015-08-05T14:43:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,960
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ptc.tifworkbench.ui; import com.ptc.tifworkbench.jaxbbinding.ImSolution; import com.ptc.tifworkbench.model.SolutionDifferencer; import com.ptc.tifworkbench.worker.DifferenceWorker; import com.ptc.tifworkbench.worker.Status; import com.ptc.tifworkbench.worker.StatusReporter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author pbowden */ public class DifferenceDialog extends javax.swing.JDialog implements ActionListener{ private TifViewFrame view; private PrintWriter reportWriter; /** * Creates new form DifferenceDialog */ public DifferenceDialog(java.awt.Frame parent, boolean modal, TifViewFrame view) { super(parent, modal); initComponents(); this.view = view; } public String getDescription() { return "Difference"; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { diffProgress = new javax.swing.JProgressBar(); cancelBtn = new javax.swing.JButton(); diffBtn = new javax.swing.JButton(); combo1 = new javax.swing.JComboBox(); complbl = new javax.swing.JLabel(); withlbl = new javax.swing.JLabel(); combo2 = new javax.swing.JComboBox(); checkReport = new javax.swing.JCheckBox(); txtReport = new javax.swing.JTextField(); btnReportBrowse = new javax.swing.JButton(); summaryTextScroll = new javax.swing.JScrollPane(); summaryText = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Select two definitions to difference"); diffProgress.setStringPainted(true); cancelBtn.setText("Cancel"); cancelBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelBtnActionPerformed(evt); } }); diffBtn.setText("Difference"); diffBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { diffBtnActionPerformed(evt); } }); combo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); combo1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { combo1ActionPerformed(evt); } }); complbl.setText("Compare template"); withlbl.setText("with"); combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); combo2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { combo2ActionPerformed(evt); } }); checkReport.setText("Generate detail report"); checkReport.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { stateReportChanged(evt); } }); txtReport.setText("report.diff"); txtReport.setEnabled(false); btnReportBrowse.setText("..."); btnReportBrowse.setEnabled(false); btnReportBrowse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnReportBrowseActionPerformed(evt); } }); summaryText.setEditable(false); summaryText.setColumns(20); summaryText.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N summaryText.setLineWrap(true); summaryText.setRows(3); summaryText.setText("Generate difference to make Template 1 equivalent to Template 2"); summaryText.setWrapStyleWord(true); summaryText.setAutoscrolls(false); summaryTextScroll.setViewportView(summaryText); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(combo1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(combo2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(diffProgress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(summaryTextScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(complbl) .addComponent(withlbl) .addComponent(checkReport)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(diffBtn) .addGap(18, 18, 18) .addComponent(cancelBtn)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(txtReport) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnReportBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(complbl) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(withlbl) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(combo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(summaryTextScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(checkReport) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnReportBrowse)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(diffProgress, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(46, 46, 46)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelBtn) .addComponent(diffBtn)) .addContainerGap()))) ); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-445)/2, (screenSize.height-326)/2, 445, 326); }// </editor-fold>//GEN-END:initComponents private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed this.setVisible(true); this.dispose(); }//GEN-LAST:event_cancelBtnActionPerformed private void diffBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diffBtnActionPerformed if(!checkReportFile()) return; ImSolution sol1 = ((TifViewFrame)combo1.getSelectedItem()).getSolution(); ImSolution sol2 = ((TifViewFrame)combo2.getSelectedItem()).getSolution(); SolutionDifferencer diff = new SolutionDifferencer(sol1, sol2); DifferenceWorker diffWorker = new DifferenceWorker(diff, view); diff.setReporter(diffWorker); // The worker will fire Status property events when the differencer sets // any new status. diffWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (StatusReporter.STATUS_PROP.equals(evt.getPropertyName())) { Status stat = (Status)evt.getNewValue(); diffProgress.setValue(stat.getProgress()); diffProgress.setString(stat.getMessage()); } if (StatusReporter.DETAIL_PROP.equals(evt.getPropertyName())) { String message = (String)evt.getNewValue(); if(reportWriter != null) reportWriter.println(message); } if (StatusReporter.FINISHED_PROP.equals(evt.getPropertyName())) { if(reportWriter != null) reportWriter.close(); cancelBtn.setText("Close"); diffBtn.setEnabled(false); } } }); diffWorker.execute(); }//GEN-LAST:event_diffBtnActionPerformed private void stateReportChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_stateReportChanged this.txtReport.setEnabled(this.checkReport.isSelected()); this.btnReportBrowse.setEnabled(this.checkReport.isSelected()); }//GEN-LAST:event_stateReportChanged private void btnReportBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReportBrowseActionPerformed JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { String fname = chooser.getSelectedFile().getName(); this.txtReport.setText(fname); } }//GEN-LAST:event_btnReportBrowseActionPerformed private void combo1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo1ActionPerformed setSummaryText(); }//GEN-LAST:event_combo1ActionPerformed private void combo2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo2ActionPerformed setSummaryText(); }//GEN-LAST:event_combo2ActionPerformed private void setSummaryText() { summaryText.setText("Generate difference to make " + combo1.getSelectedItem().toString() + " equivalent to " + combo2.getSelectedItem().toString()); } /** * Check that the report file exists and that we can open it. */ private boolean checkReportFile() { if(this.checkReport.isSelected()) { String fpath = this.txtReport.getText(); File fout = new File(fpath); try { reportWriter = new PrintWriter(new FileWriter(fout)); }catch(Exception ex) { JOptionPane.showMessageDialog(null, "Could not open the report file " + fout.getAbsolutePath(), "Error - cannot open file.", JOptionPane.ERROR_MESSAGE); return false; } } return true; } public String getReportPath() { return this.txtReport.getText(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnReportBrowse; private javax.swing.JButton cancelBtn; private javax.swing.JCheckBox checkReport; private javax.swing.JComboBox combo1; private javax.swing.JComboBox combo2; private javax.swing.JLabel complbl; private javax.swing.JButton diffBtn; private javax.swing.JProgressBar diffProgress; private javax.swing.JTextArea summaryText; private javax.swing.JScrollPane summaryTextScroll; private javax.swing.JTextField txtReport; private javax.swing.JLabel withlbl; // End of variables declaration//GEN-END:variables public void setChoices(List<TifViewFrame>choices) { DefaultComboBoxModel model1 = new DefaultComboBoxModel(); DefaultComboBoxModel model2 = new DefaultComboBoxModel(); for(TifViewFrame view : choices) { model1.addElement(view); model2.addElement(view); } this.combo1.setModel(model1); this.combo2.setModel(model2); if(model2.getSize() > 1) combo2.setSelectedIndex(1); combo1.addActionListener(this); combo2.addActionListener(this); setSummaryText(); } @Override public void actionPerformed(ActionEvent e) { } }
86b6263cf201e008461f70fea2103cbbb13d9728
3daebb8be035124c1ccfe94546c15a37fa880914
/src/main/java/abstractFactoryDesignPattern/ICICIBank.java
419a57b30f451571754175134690a60f0adcb84f
[]
no_license
smyk009/springPractice
0dbb47cfa16baedfc09f2fc2dbb062de0da23cbf
fe0495f16b6d7a77dce0e10785aa7f44ac2c8aab
refs/heads/master
2022-05-29T21:40:37.097403
2019-08-28T11:41:54
2019-08-28T11:41:54
204,917,957
0
0
null
2022-04-23T02:04:26
2019-08-28T11:41:12
Java
UTF-8
Java
false
false
160
java
package abstractFactoryDesignPattern; public class ICICIBank implements Bank { @Override public void getBank() { System.out.println("ICICI Bank"); } }
edae205beb09b5e3b80e183b10f80d71c00f606b
980b91137b60025441c592350ccb9cfe6447d0d7
/Leetcode/Done/806_Number_of_Lines_To_Write_String.java
ebb2ff3c0b5356818bed74ccddcbb4220d89b5a3
[]
no_license
IlyaSamoylov45/Coding-Challenges-and-Exercises
07d7e448996e0c41b4e9c125613ccfdf2fb365d2
f2e2951c9fba7817785a778b320fdfbfb7172722
refs/heads/master
2021-12-14T23:09:50.723494
2021-12-05T21:39:33
2021-12-05T21:39:33
210,204,385
0
0
null
null
null
null
UTF-8
Java
false
false
2,027
java
// You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on. // // You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s. // // Return an array result of length 2 where: // // result[0] is the total number of lines. // result[1] is the width of the last line in pixels. // // // Example 1: // // Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz" // Output: [3,60] // Explanation: You can write s as follows: // abcdefghij // 100 pixels wide // klmnopqrst // 100 pixels wide // uvwxyz // 60 pixels wide // There are a total of 3 lines, and the last line is 60 pixels wide. // Example 2: // // Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa" // Output: [2,4] // Explanation: You can write s as follows: // bbbcccdddaa // 98 pixels wide // a // 4 pixels wide // There are a total of 2 lines, and the last line is 4 pixels wide. // // // Constraints: // // widths.length == 26 // 2 <= widths[i] <= 10 // 1 <= s.length <= 1000 // s contains only lowercase English letters. class Solution { public int[] numberOfLines(int[] widths, String s) { int lines = 1, width = 0; for(char c : s.toCharArray()){ int curr = widths[c - 'a']; width += curr; if(width > 100){ lines++; width = curr; } } return new int[]{lines, width}; } } // Time : O(N) // Space : O(1)
05540de5fa7062fbf4dfe7d7f07979e6a2ea7cbd
b8c1145502e07b5dea35c8dba4a6e1839779d005
/Input-Output-File-System-4.java
69019c86bea727cc7a1117c4e5b42f77d275fb27
[]
no_license
SunMingHomeworkTW/w3resource
be930be0adf89f60e96bccb7c003a20493567823
5f4ce1b48a8e0626ad0ebdd22ef002febf7df942
refs/heads/master
2020-03-21T15:04:39.050420
2018-06-26T06:20:34
2018-06-26T06:20:34
138,693,116
0
0
null
null
null
null
UTF-8
Java
false
false
704
java
import java.io.File; class InputOutputFileSystem4 { public static void main(String[] args){ // Create a File object File my_file_dir = new File("/home/students/abc.txt"); if (my_file_dir.canWrite()) { System.out.println(my_file_dir.getAbsolutePath() + " can write.\n"); } else { System.out.println(my_file_dir.getAbsolutePath() + " cannot write.\n"); } if (my_file_dir.canRead()) { System.out.println(my_file_dir.getAbsolutePath() + " can read.\n"); } else { System.out.println(my_file_dir.getAbsolutePath() + " cannot read.\n"); } } }
546a1cd39d5fd0ef6e7ac7b2539b7adb4287cc2a
3e90a56810e600d0a22ebba76a803a0f8fb2e730
/src/main/java/com/li/dbarc/common/database/BaseDao.java
4629731de8f5d28a8b3886a19c56a7a4dbcda087
[]
no_license
woniu4500/arc-db
21e853e668a9b2eb83e41ddc92a5bcf491df60f6
998f4814d1b6bb22c1018b358e2ec73409a5a443
refs/heads/master
2021-01-20T22:23:42.039724
2016-07-20T09:39:39
2016-07-20T09:39:39
63,769,418
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package com.li.dbarc.common.database; public interface BaseDao<T> { /** * 根据主键查找对象 * @param vo * @return */ T findByKey(T vo); /** * Update Object by Primary Key. * * @return effect rows. */ int updateByKey(T vo); /** * Insert Object. * * @return effect rows. */ int insert(T vo) ; }
f6d7d9e8a75893769b9570d442bcfe32ce13375a
cd15756c7e57947dd98eb3a8e4942b8ad3e694d9
/google-ads/src/main/java/com/google/ads/googleads/v0/services/MutateFeedsRequest.java
2502fc7008b23d4f39688704081dca60da378b35
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
DalavanCloud/google-ads-java
e4d967d3f36c4c9f0f06b98a74cd12cda90d5a85
70d951aa0202833b3e487fb909fd5294e1dda405
refs/heads/master
2020-04-21T13:07:19.440871
2019-02-06T13:54:21
2019-02-06T13:54:21
169,587,855
1
0
Apache-2.0
2019-02-07T14:49:54
2019-02-07T14:49:54
null
UTF-8
Java
false
true
40,160
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v0/services/feed_service.proto package com.google.ads.googleads.v0.services; /** * <pre> * Request message for [FeedService.MutateFeeds][google.ads.googleads.v0.services.FeedService.MutateFeeds]. * </pre> * * Protobuf type {@code google.ads.googleads.v0.services.MutateFeedsRequest} */ public final class MutateFeedsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v0.services.MutateFeedsRequest) MutateFeedsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MutateFeedsRequest.newBuilder() to construct. private MutateFeedsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateFeedsRequest() { customerId_ = ""; operations_ = java.util.Collections.emptyList(); partialFailure_ = false; validateOnly_ = false; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateFeedsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); customerId_ = s; break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { operations_ = new java.util.ArrayList<com.google.ads.googleads.v0.services.FeedOperation>(); mutable_bitField0_ |= 0x00000002; } operations_.add( input.readMessage(com.google.ads.googleads.v0.services.FeedOperation.parser(), extensionRegistry)); break; } case 24: { partialFailure_ = input.readBool(); break; } case 32: { validateOnly_ = input.readBool(); break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { operations_ = java.util.Collections.unmodifiableList(operations_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v0.services.FeedServiceProto.internal_static_google_ads_googleads_v0_services_MutateFeedsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v0.services.FeedServiceProto.internal_static_google_ads_googleads_v0_services_MutateFeedsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v0.services.MutateFeedsRequest.class, com.google.ads.googleads.v0.services.MutateFeedsRequest.Builder.class); } private int bitField0_; public static final int CUSTOMER_ID_FIELD_NUMBER = 1; private volatile java.lang.Object customerId_; /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } } /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OPERATIONS_FIELD_NUMBER = 2; private java.util.List<com.google.ads.googleads.v0.services.FeedOperation> operations_; /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public java.util.List<com.google.ads.googleads.v0.services.FeedOperation> getOperationsList() { return operations_; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public java.util.List<? extends com.google.ads.googleads.v0.services.FeedOperationOrBuilder> getOperationsOrBuilderList() { return operations_; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public int getOperationsCount() { return operations_.size(); } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperation getOperations(int index) { return operations_.get(index); } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperationOrBuilder getOperationsOrBuilder( int index) { return operations_.get(index); } public static final int PARTIAL_FAILURE_FIELD_NUMBER = 3; private boolean partialFailure_; /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> */ public boolean getPartialFailure() { return partialFailure_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> */ public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getCustomerIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_); } for (int i = 0; i < operations_.size(); i++) { output.writeMessage(2, operations_.get(i)); } if (partialFailure_ != false) { output.writeBool(3, partialFailure_); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getCustomerIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_); } for (int i = 0; i < operations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, operations_.get(i)); } if (partialFailure_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, partialFailure_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, validateOnly_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v0.services.MutateFeedsRequest)) { return super.equals(obj); } com.google.ads.googleads.v0.services.MutateFeedsRequest other = (com.google.ads.googleads.v0.services.MutateFeedsRequest) obj; boolean result = true; result = result && getCustomerId() .equals(other.getCustomerId()); result = result && getOperationsList() .equals(other.getOperationsList()); result = result && (getPartialFailure() == other.getPartialFailure()); result = result && (getValidateOnly() == other.getValidateOnly()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerId().hashCode(); if (getOperationsCount() > 0) { hash = (37 * hash) + OPERATIONS_FIELD_NUMBER; hash = (53 * hash) + getOperationsList().hashCode(); } hash = (37 * hash) + PARTIAL_FAILURE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getPartialFailure()); hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v0.services.MutateFeedsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Request message for [FeedService.MutateFeeds][google.ads.googleads.v0.services.FeedService.MutateFeeds]. * </pre> * * Protobuf type {@code google.ads.googleads.v0.services.MutateFeedsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v0.services.MutateFeedsRequest) com.google.ads.googleads.v0.services.MutateFeedsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v0.services.FeedServiceProto.internal_static_google_ads_googleads_v0_services_MutateFeedsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v0.services.FeedServiceProto.internal_static_google_ads_googleads_v0_services_MutateFeedsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v0.services.MutateFeedsRequest.class, com.google.ads.googleads.v0.services.MutateFeedsRequest.Builder.class); } // Construct using com.google.ads.googleads.v0.services.MutateFeedsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getOperationsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); customerId_ = ""; if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { operationsBuilder_.clear(); } partialFailure_ = false; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v0.services.FeedServiceProto.internal_static_google_ads_googleads_v0_services_MutateFeedsRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v0.services.MutateFeedsRequest getDefaultInstanceForType() { return com.google.ads.googleads.v0.services.MutateFeedsRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v0.services.MutateFeedsRequest build() { com.google.ads.googleads.v0.services.MutateFeedsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v0.services.MutateFeedsRequest buildPartial() { com.google.ads.googleads.v0.services.MutateFeedsRequest result = new com.google.ads.googleads.v0.services.MutateFeedsRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.customerId_ = customerId_; if (operationsBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002)) { operations_ = java.util.Collections.unmodifiableList(operations_); bitField0_ = (bitField0_ & ~0x00000002); } result.operations_ = operations_; } else { result.operations_ = operationsBuilder_.build(); } result.partialFailure_ = partialFailure_; result.validateOnly_ = validateOnly_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v0.services.MutateFeedsRequest) { return mergeFrom((com.google.ads.googleads.v0.services.MutateFeedsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v0.services.MutateFeedsRequest other) { if (other == com.google.ads.googleads.v0.services.MutateFeedsRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; onChanged(); } if (operationsBuilder_ == null) { if (!other.operations_.isEmpty()) { if (operations_.isEmpty()) { operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureOperationsIsMutable(); operations_.addAll(other.operations_); } onChanged(); } } else { if (!other.operations_.isEmpty()) { if (operationsBuilder_.isEmpty()) { operationsBuilder_.dispose(); operationsBuilder_ = null; operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000002); operationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getOperationsFieldBuilder() : null; } else { operationsBuilder_.addAllMessages(other.operations_); } } } if (other.getPartialFailure() != false) { setPartialFailure(other.getPartialFailure()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v0.services.MutateFeedsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v0.services.MutateFeedsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object customerId_ = ""; /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public Builder setCustomerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerId_ = value; onChanged(); return this; } /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); onChanged(); return this; } /** * <pre> * The ID of the customer whose feeds are being modified. * </pre> * * <code>string customer_id = 1;</code> */ public Builder setCustomerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerId_ = value; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v0.services.FeedOperation> operations_ = java.util.Collections.emptyList(); private void ensureOperationsIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { operations_ = new java.util.ArrayList<com.google.ads.googleads.v0.services.FeedOperation>(operations_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v0.services.FeedOperation, com.google.ads.googleads.v0.services.FeedOperation.Builder, com.google.ads.googleads.v0.services.FeedOperationOrBuilder> operationsBuilder_; /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public java.util.List<com.google.ads.googleads.v0.services.FeedOperation> getOperationsList() { if (operationsBuilder_ == null) { return java.util.Collections.unmodifiableList(operations_); } else { return operationsBuilder_.getMessageList(); } } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public int getOperationsCount() { if (operationsBuilder_ == null) { return operations_.size(); } else { return operationsBuilder_.getCount(); } } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperation getOperations(int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessage(index); } } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder setOperations( int index, com.google.ads.googleads.v0.services.FeedOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.set(index, value); onChanged(); } else { operationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder setOperations( int index, com.google.ads.googleads.v0.services.FeedOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.set(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder addOperations(com.google.ads.googleads.v0.services.FeedOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(value); onChanged(); } else { operationsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder addOperations( int index, com.google.ads.googleads.v0.services.FeedOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(index, value); onChanged(); } else { operationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder addOperations( com.google.ads.googleads.v0.services.FeedOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder addOperations( int index, com.google.ads.googleads.v0.services.FeedOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder addAllOperations( java.lang.Iterable<? extends com.google.ads.googleads.v0.services.FeedOperation> values) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, operations_); onChanged(); } else { operationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder clearOperations() { if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { operationsBuilder_.clear(); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public Builder removeOperations(int index) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.remove(index); onChanged(); } else { operationsBuilder_.remove(index); } return this; } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperation.Builder getOperationsBuilder( int index) { return getOperationsFieldBuilder().getBuilder(index); } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperationOrBuilder getOperationsOrBuilder( int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public java.util.List<? extends com.google.ads.googleads.v0.services.FeedOperationOrBuilder> getOperationsOrBuilderList() { if (operationsBuilder_ != null) { return operationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(operations_); } } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperation.Builder addOperationsBuilder() { return getOperationsFieldBuilder().addBuilder( com.google.ads.googleads.v0.services.FeedOperation.getDefaultInstance()); } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public com.google.ads.googleads.v0.services.FeedOperation.Builder addOperationsBuilder( int index) { return getOperationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v0.services.FeedOperation.getDefaultInstance()); } /** * <pre> * The list of operations to perform on individual feeds. * </pre> * * <code>repeated .google.ads.googleads.v0.services.FeedOperation operations = 2;</code> */ public java.util.List<com.google.ads.googleads.v0.services.FeedOperation.Builder> getOperationsBuilderList() { return getOperationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v0.services.FeedOperation, com.google.ads.googleads.v0.services.FeedOperation.Builder, com.google.ads.googleads.v0.services.FeedOperationOrBuilder> getOperationsFieldBuilder() { if (operationsBuilder_ == null) { operationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v0.services.FeedOperation, com.google.ads.googleads.v0.services.FeedOperation.Builder, com.google.ads.googleads.v0.services.FeedOperationOrBuilder>( operations_, ((bitField0_ & 0x00000002) == 0x00000002), getParentForChildren(), isClean()); operations_ = null; } return operationsBuilder_; } private boolean partialFailure_ ; /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> */ public boolean getPartialFailure() { return partialFailure_; } /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> */ public Builder setPartialFailure(boolean value) { partialFailure_ = value; onChanged(); return this; } /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> */ public Builder clearPartialFailure() { partialFailure_ = false; onChanged(); return this; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> */ public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> */ public Builder clearValidateOnly() { validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v0.services.MutateFeedsRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v0.services.MutateFeedsRequest) private static final com.google.ads.googleads.v0.services.MutateFeedsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v0.services.MutateFeedsRequest(); } public static com.google.ads.googleads.v0.services.MutateFeedsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateFeedsRequest> PARSER = new com.google.protobuf.AbstractParser<MutateFeedsRequest>() { @java.lang.Override public MutateFeedsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateFeedsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateFeedsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateFeedsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v0.services.MutateFeedsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
16726d9944570afef63671e164d2ae236cb90ddb
f91a5b92df78bdd2df55a841a777c4b16d2938a6
/DenysChevychelov/lesson_24/src/main/java/flyweight/FlyweightClient.java
0b2c0aa4a2a28bb57bbe6a26b8e1d8b08ff49de7
[]
no_license
rubfan/java-elementary-0804
a3f2209c8e616c96df0a684a69b02786adf33cbc
1cea7b2f1cd3a68d49972562498e991d5ad985f0
refs/heads/master
2023-03-11T14:45:47.823848
2020-08-20T00:09:05
2020-08-20T00:09:05
255,116,046
0
17
null
2020-12-29T02:27:41
2020-04-12T15:46:24
Java
UTF-8
Java
false
false
514
java
package flyweight; import java.util.ArrayList; import java.util.List; public class FlyweightClient { public static void main(String[] args) { HeroFactory heroFactory = new HeroFactory(); List<Hero> heroes = new ArrayList<Hero>(); for (int i = 0; i < 10; i++) { heroes.add(heroFactory.takeHeroByClassName("Archer")); heroes.add(heroFactory.takeHeroByClassName("Knight")); } for (Hero hero : heroes) { hero.move(); } } }
8dcfac43c5084a44ad1997bc489c5eedfde05905
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.qqlite/assets/exlibs.1.jar/classes.jar/bfz.java
5879878df77b83388bcc0b5324e0cd064bb3bfcf
[]
no_license
tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651957
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
2022-01-31T09:46:26
2022-01-31T02:43:22
Java
UTF-8
Java
false
false
904
java
import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mobileqq.activity.QQSettingMsgHistoryActivity; import com.tencent.mobileqq.app.ThreadManager; import com.tencent.mobileqq.statistics.ReportController; public class bfz implements DialogInterface.OnClickListener { public bfz(QQSettingMsgHistoryActivity paramQQSettingMsgHistoryActivity) {} public void onClick(DialogInterface paramDialogInterface, int paramInt) { ReportController.b(this.a.app, "CliOper", "", "", "Setting_tab", "Clk_clean_msg", 0, 0, "", "", "", ""); if (!this.a.isFinishing()) { this.a.showDialog(1); } ThreadManager.b(new bga(this)); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.qqlite\assets\exlibs.1.jar\classes.jar * Qualified Name: bfz * JD-Core Version: 0.7.0.1 */
874f33e288d72c277f5a9d95a1fff8c67e9aa7c5
7eae24bfa24294b20e8d46c5c5c849ea3a74b51d
/buildSrc/src/main/groovy/com/binzi/plugin/asm/CostClassVisitor.java
3729b59c35effd5be6fa27e24845aa5a7db7b650
[]
no_license
huangyoubin/Android-AOP
bf8333669bf46a6b84f539fbacb0d162c927d468
2849273422c1aa683baed44542c7a31a48a84635
refs/heads/master
2022-11-19T17:09:57.530717
2020-07-22T03:39:32
2020-07-22T03:39:32
259,379,516
1
0
null
null
null
null
UTF-8
Java
false
false
3,339
java
package com.binzi.plugin.asm; import com.binzi.aop.utils.Cost; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.AdviceAdapter; /** * @Author: huangyoubin * @Create: 2019/3/31 9:59 PM * @Description: */ public class CostClassVisitor extends ClassVisitor { public CostClassVisitor(ClassVisitor classVisitor) { super(Opcodes.ASM5, classVisitor); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions); mv = new AdviceAdapter(Opcodes.ASM5, mv, access, name, desc) { private boolean inject = false; @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { if (Type.getDescriptor(Cost.class).equals(desc)) { inject = true; } return super.visitAnnotation(desc, visible); } @Override protected void onMethodEnter() { if (inject) { //Log.d("CostTime", "========start========="); //TimeCache.setStartTime("newFunc", System.nanoTime()); mv.visitLdcInsn("CostTime"); mv.visitLdcInsn("========start========="); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)V", false); mv.visitLdcInsn(name); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "nanoTime", "()J", false); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/binzi/plugin/asm/TimeCache", "setStartTime", "(Ljava/lang/String;J)V", false); } } @Override protected void onMethodExit(int opcode) { // TimeCache.setEndTime("newFunc", System.nanoTime()); // Log.d("CostTime", TimeCache.getCostTime("newFunc")); // Log.d("CostTime", "========end========="); if (inject) { mv.visitLdcInsn(name); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "nanoTime", "()J", false); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/binzi/plugin/asm/TimeCache", "setEndTime", "(Ljava/lang/String;J)V", false); mv.visitLdcInsn("CostTime"); mv.visitLdcInsn(name); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/binzi/plugin/asm/TimeCache", "getCostTime", "(Ljava/lang/String;)Ljava/lang/String;", false); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)V", false); mv.visitLdcInsn(name); mv.visitLdcInsn("========end========="); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)V", false); } } }; return mv; } }
20c839de6fccb609eb14fd4a77f75069d7fac9af
74deb60009a24d4ca4a7e0335c612762b7dcbabf
/thread_0519/ThreadPoolDemo47.java
e1d240604606ed521d388c20fbf6d58adbf49ce0
[]
no_license
Xiaoyuer-6/Thread05
c014db2acd1204ea290364ec2bd475f523d2e247
efadebc16006be60c967b220885ea0b2cad7c65d
refs/heads/master
2023-04-12T16:28:23.355639
2021-05-23T09:38:34
2021-05-23T09:38:34
370,012,041
0
0
null
null
null
null
UTF-8
Java
false
false
684
java
package thread.thread_0519; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created with IntelliJ IDEA. * Description: * User: HuYu * Date: 2021-05-19 * Time: 20:06 */ public class ThreadPoolDemo47 { //创建带缓存的线程池 public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i <10 ; i++) { service.execute(new Runnable() { @Override public void run() { System.out.println("线程名" + Thread.currentThread().getName()); } }); } } }
3cf072dff1c200b0c01d2ac5088dec48771a86e6
dd6d3490baca0f73321603af88d11743ed3e1a56
/chapter_005/src/main/java/ru/job4j/map/SimpleMap.java
1ac3460d1975ed118f20d0a0784db0a3ed7d4137
[ "Apache-2.0" ]
permissive
alexander-pimenov/job4j
2d37343ce862e6bcd2e48bdac1d90b8bbb7cef2a
026b2e983c33ce47d68f84a14a72dccc41d13226
refs/heads/master
2023-07-11T00:42:21.930586
2023-06-30T22:46:19
2023-06-30T22:46:19
171,486,103
0
0
Apache-2.0
2022-09-08T01:12:05
2019-02-19T14:15:29
Java
UTF-8
Java
false
false
160
java
package ru.job4j.map; public interface SimpleMap<K, V> { boolean insert(K key, V value); V get(K key); boolean delete(K key); int size(); }
222721bc238a2ed24408bb1381fcdecad7a4e718
9f49b8cc4ba73ccc0ee98f9dc0fb544aeabe877a
/specialNumbers/StrongNum.java
c8d5b9c358f94c800ab18759648d94997382d794
[]
no_license
vetri-vel/My_programs
37f88370be569a1460cc7bad363237966463c75e
0101f76a33436cfd16e04c7f14eb49d7a1747826
refs/heads/master
2020-04-13T19:58:25.338656
2019-01-08T16:23:00
2019-01-08T16:23:00
163,417,328
1
0
null
null
null
null
UTF-8
Java
false
false
725
java
package specialNumbers; import java.util.Scanner; public class StrongNum { public static void main(String[]a ) { Scanner s = new Scanner(System.in); System.out.println("enter to check the number..: "); int n = s.nextInt(); boolean m = isStrong(n); if(m) System.out.println("this numbers is strong number"); else System.out.println("this number is not the strong number"); s.close(); } static boolean isStrong(int n) { int sum = 0; int t = n; while(n != 0) { int r = n % 10; sum = sum + fact(r); n= n /10; } return sum==t; } static int fact(int r) { int f = 1; while(r > 1) { f = f * r; r--; } return f; } }
45296e25cd4e26dcd4966c4d1dff115edd346fc9
b280a34244a58fddd7e76bddb13bc25c83215010
/scmv6/center-task1/src/main/java/com/smate/center/task/model/bdsp/BdspDataForm.java
74055b285b7dc9502a1af04d3da06d51cd0a3c56
[]
no_license
hzr958/myProjects
910d7b7473c33ef2754d79e67ced0245e987f522
d2e8f61b7b99a92ffe19209fcda3c2db37315422
refs/heads/master
2022-12-24T16:43:21.527071
2019-08-16T01:46:18
2019-08-16T01:46:18
202,512,072
2
3
null
2022-12-16T05:31:05
2019-08-15T09:21:04
Java
UTF-8
Java
false
false
476
java
package com.smate.center.task.model.bdsp; import com.smate.center.task.model.snsbak.bdsp.BdspProject; public class BdspDataForm { private BdspProject bdspProject; private Long insId; public Long getInsId() { return insId; } public void setInsId(Long insId) { this.insId = insId; } public BdspProject getBdspProject() { return bdspProject; } public void setBdspProject(BdspProject bdspProject) { this.bdspProject = bdspProject; } }
448db5f80236172441c7bd931cc6033ff8bb56a1
4fa9dd21dba7f99536416fc53cc9d34436f5e6f2
/src/datos/PersonaJDBC.java
2c183baff0569f21c2daffa9b036f0065eb8389f
[]
no_license
cjmedinag/EvaluacionCrud
655438119d8f4b4e671e3abc68fd6354da43f68f
9abbaa922de1b487313e4846373720d8d96bd62b
refs/heads/master
2022-12-04T16:07:05.585887
2020-08-26T17:37:44
2020-08-26T17:37:44
290,561,942
0
0
null
null
null
null
UTF-8
Java
false
false
3,704
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 datos; import domain.Persona; import java.sql.*; import java.util.*; /** * * @author user */ public class PersonaJDBC { private final String SQL_INSERT = "INSERT INTO persona(nombre, apellido) VALUES(?,?)"; private final String SQL_UPDATE = "UPDATE persona SET nombre=?, apellido=? WHERE idpersona=?"; private final String SQL_DELETE = "DELETE FROM persona WHERE idpersona = ?"; private final String SQL_SELECT = "SELECT idpersona, nombre, apellido FROM persona ORDER BY idpersona"; public int insert(String nombre, String apellido){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; int rows = 0; //registros afectados try{ conn = Conexion.getConnecion(); stmt = conn.prepareStatement(SQL_INSERT); int index = 1; //contador de columnas stmt.setString(index++, nombre); //param 1 => ? stmt.setString(index++, apellido); //param 2 => ? System.out.println("Ejecutando query:" + SQL_INSERT); rows = stmt.executeUpdate(); //no. registros afectados System.out.println("Registros afectados:" + rows); } catch (SQLException e){ e.printStackTrace(); } finally { Conexion.close(stmt); Conexion.close(conn); } return rows; } public int update(int idpersona, String nombre, String apellido){ Connection conn = null; PreparedStatement stmt = null; int rows = 0; try { conn = Conexion.getConnecion(); System.out.println("Ejecutando query:" + SQL_UPDATE); stmt = conn.prepareStatement(SQL_UPDATE); int index = 1; stmt.setString(index++, nombre); stmt.setString(index++, apellido); stmt.setInt(index, idpersona); rows = stmt.executeUpdate(); System.out.println("Registros actualizados:" + rows); } catch (SQLException e) { e.printStackTrace(); } finally { Conexion.close(stmt); Conexion.close(conn); } return rows; } public int delete(int idpersona){ Connection conn = null; PreparedStatement stmt = null; int rows = 0; try{ conn = Conexion.getConnecion(); System.out.println("Ejecutando query:" + SQL_DELETE); stmt = conn.prepareStatement(SQL_DELETE); stmt.setInt(1, idpersona); rows = stmt.executeUpdate(); System.out.println("Registros eliminados:" + rows); } catch (SQLException e){ e.printStackTrace(); } finally{ Conexion.close(stmt); Conexion.close(conn); } return rows; } public List<Persona> select(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Persona persona = null; List<Persona> personas = new ArrayList<Persona>(); try{ conn = Conexion.getConnecion(); stmt = conn.prepareStatement(SQL_SELECT); rs = stmt.executeQuery(); while (rs.next()){ int idpersona = rs.getInt(1); String nombre = rs.getString(2); String apellido = rs.getString(3); persona = new Persona(); persona.setId_persona(idpersona); persona.setNombre(nombre); persona.setApellido(apellido); personas.add(persona); } } catch (SQLException e) { e.printStackTrace(); } finally { Conexion.close(rs); Conexion.close(stmt); Conexion.close(conn); } return personas; } }
12d543549da3d6a706dedb9e193f1da8b94f9aeb
64372f560b064692f44260a6e2d2992022b82eb1
/RozkladJazdy/src/com/tomasz/rozkladjazdy/MinMaxInputFilter.java
36f35be3035a8dc6eca75fb17c6e27d829169bc8
[]
no_license
jk128/rozkladjazdy
ab04ec6046cdebb5539c9b87e10453eeba95b8c2
2a7ee7e64cba8ca9793c082e0124848e9032f01a
refs/heads/master
2021-01-15T20:22:57.874776
2015-03-07T09:50:25
2015-03-07T09:50:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
923
java
package com.tomasz.rozkladjazdy; import android.text.InputFilter; import android.text.Spanned; public class MinMaxInputFilter implements InputFilter { private int min, max; public MinMaxInputFilter(int min, int max) { this.min = min; this.max = max; } public MinMaxInputFilter(String min, String max) { this.min = Integer.parseInt(min); this.max = Integer.parseInt(max); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try { int input = Integer.parseInt(dest.toString() + source.toString()); if (isInRange(min, max, input)) return null; } catch (NumberFormatException nfe) { } return ""; } private boolean isInRange(int a, int b, int c) { return b > a ? c >= a && c <= b : c >= b && c <= a; } }
0fcd20e8c7b4ff9bcbe0e87533423d01a66b9c17
4041069fa0b0447e9a1efc4ceef26f4bf61fa732
/code/stats/restexpress/src/main/java/presentation/controller/SampleController.java
3c2da3e6e51cfe22a44eb03dcbd05d136394d90a
[]
no_license
codelotus/elixir_presentation
4015a723aad958681992e55fa76225daeba32e81
62034f41e3c45939add6298c6d0905bda213e25e
refs/heads/master
2021-01-02T09:32:36.302692
2014-03-06T23:52:28
2014-03-06T23:52:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
685
java
package presentation.controller; import org.restexpress.Request; import org.restexpress.Response; public class SampleController { public SampleController() { super(); } public Object create(Request request, Response response) { //TODO: Your 'POST' logic here... return null; } public Object read(Request request, Response response) { //TODO: Your 'GET' logic here... return "Hello World"; } public void update(Request request, Response response) { //TODO: Your 'PUT' logic here... response.setResponseNoContent(); } public void delete(Request request, Response response) { //TODO: Your 'DELETE' logic here... response.setResponseNoContent(); } }
b47e2e1242b7e5eea7cfc11fa54b77041c28c807
2f7c818ead049a0688e0a279ba127333cacd8674
/IFuture/src/com/sinoinnovo/plantbox/bean/areabean/MyAreaBean.java
c451da804ebf03ada0cc45a1040e9d2b94964dfe
[]
no_license
wxianing/PlantBox
30b8e3f359da1996e8a82f62cdf5d05a24379242
b721d700dee06875d653a802e63b370ea459fdd8
refs/heads/master
2020-12-24T21:01:27.350001
2016-06-01T11:02:41
2016-06-01T11:02:41
58,519,428
0
0
null
null
null
null
UTF-8
Java
false
false
6,786
java
package com.sinoinnovo.plantbox.bean.areabean; import java.io.Serializable; import java.util.List; /** * Created by Administrator on 2016/5/24 0024. */ public class MyAreaBean implements Serializable { /** * PageIndex : 1 * RecordCount : 3 * DataList : [{"Records":[],"Distincts":0,"Id":27,"UserId":187,"ProductId":11,"ProductEntityId":19,"Lat":22.577061,"Lon":113.892487,"CreateTime":"2016-05-24 17:32:54","CreateUserId":187,"Address":null,"Remark":"","ProductName":"植物盒子+玉兰","ProductCode":"123832","ThumbImg":"/upload/201605/680f5b584bb343268f011098a162bbcb.jpg","UserName":"wxn","CnName":"王显宁","PraiseCount":0,"SortId":1},{"Records":[],"Distincts":0,"Id":3,"UserId":186,"ProductId":1,"ProductEntityId":1,"Lat":22.7360635,"Lon":113.99764166666667,"CreateTime":"2016-05-14 00:00:00","CreateUserId":186,"Address":"深圳","Remark":"测试数据","ProductName":"发财树","ProductCode":"10013","ThumbImg":"/upload/201605/f410a8b6926840b8b7828f7d2093e41f.jpg","UserName":"ljc","CnName":"梁健聪","PraiseCount":1,"SortId":1},{"Records":[],"Distincts":0,"Id":1,"UserId":186,"ProductId":1,"ProductEntityId":1,"Lat":22.7360635,"Lon":113.99764166666667,"CreateTime":"2016-05-14 00:00:00","CreateUserId":186,"Address":"深圳","Remark":"测试数据","ProductName":"发财树","ProductCode":"10013","ThumbImg":"/upload/201605/f410a8b6926840b8b7828f7d2093e41f.jpg","UserName":"ljc","CnName":"梁健聪","PraiseCount":10,"SortId":1}] * TotalModel : */ private int PageIndex; private int RecordCount; private String TotalModel; /** * Records : [] * Distincts : 0 * Id : 27 * UserId : 187 * ProductId : 11 * ProductEntityId : 19 * Lat : 22.577061 * Lon : 113.892487 * CreateTime : 2016-05-24 17:32:54 * CreateUserId : 187 * Address : null * Remark : * ProductName : 植物盒子+玉兰 * ProductCode : 123832 * ThumbImg : /upload/201605/680f5b584bb343268f011098a162bbcb.jpg * UserName : wxn * CnName : 王显宁 * PraiseCount : 0 * SortId : 1 */ private List<DataListBean> DataList; public int getPageIndex() { return PageIndex; } public void setPageIndex(int PageIndex) { this.PageIndex = PageIndex; } public int getRecordCount() { return RecordCount; } public void setRecordCount(int RecordCount) { this.RecordCount = RecordCount; } public String getTotalModel() { return TotalModel; } public void setTotalModel(String TotalModel) { this.TotalModel = TotalModel; } public List<DataListBean> getDataList() { return DataList; } public void setDataList(List<DataListBean> DataList) { this.DataList = DataList; } public static class DataListBean { private int Distincts; private int Id; private int UserId; private int ProductId; private int ProductEntityId; private double Lat; private double Lon; private String CreateTime; private int CreateUserId; private Object Address; private String Remark; private String ProductName; private String ProductCode; private String ThumbImg; private String UserName; private String CnName; private int PraiseCount; private int SortId; private List<?> Records; public int getDistincts() { return Distincts; } public void setDistincts(int Distincts) { this.Distincts = Distincts; } public int getId() { return Id; } public void setId(int Id) { this.Id = Id; } public int getUserId() { return UserId; } public void setUserId(int UserId) { this.UserId = UserId; } public int getProductId() { return ProductId; } public void setProductId(int ProductId) { this.ProductId = ProductId; } public int getProductEntityId() { return ProductEntityId; } public void setProductEntityId(int ProductEntityId) { this.ProductEntityId = ProductEntityId; } public double getLat() { return Lat; } public void setLat(double Lat) { this.Lat = Lat; } public double getLon() { return Lon; } public void setLon(double Lon) { this.Lon = Lon; } public String getCreateTime() { return CreateTime; } public void setCreateTime(String CreateTime) { this.CreateTime = CreateTime; } public int getCreateUserId() { return CreateUserId; } public void setCreateUserId(int CreateUserId) { this.CreateUserId = CreateUserId; } public Object getAddress() { return Address; } public void setAddress(Object Address) { this.Address = Address; } public String getRemark() { return Remark; } public void setRemark(String Remark) { this.Remark = Remark; } public String getProductName() { return ProductName; } public void setProductName(String ProductName) { this.ProductName = ProductName; } public String getProductCode() { return ProductCode; } public void setProductCode(String ProductCode) { this.ProductCode = ProductCode; } public String getThumbImg() { return ThumbImg; } public void setThumbImg(String ThumbImg) { this.ThumbImg = ThumbImg; } public String getUserName() { return UserName; } public void setUserName(String UserName) { this.UserName = UserName; } public String getCnName() { return CnName; } public void setCnName(String CnName) { this.CnName = CnName; } public int getPraiseCount() { return PraiseCount; } public void setPraiseCount(int PraiseCount) { this.PraiseCount = PraiseCount; } public int getSortId() { return SortId; } public void setSortId(int SortId) { this.SortId = SortId; } public List<?> getRecords() { return Records; } public void setRecords(List<?> Records) { this.Records = Records; } } }
c1de4d7c989c9d8d9678534d89411edf6f6e57eb
90855dfbe1899e673908cb763113a4dd703b63ad
/app/src/main/java/com/example/cgpacalculator/Practical_Course.java
229f7ec159f56ca98a819fde555134c2be877130
[]
no_license
samir937/Campus_Guide
1add2e67a71796847b537ddf5e4a4914dd25123c
820fd93cf9496cb3da478511c28e0754b55f4f00
refs/heads/master
2020-08-27T08:14:04.333491
2019-12-08T21:27:25
2019-12-08T21:27:25
217,296,443
1
0
null
null
null
null
UTF-8
Java
false
false
13,377
java
package com.example.cgpacalculator; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import static java.lang.Math.ceil; public class Practical_Course extends AppCompatActivity { EditText Lab1_marks, Lab2_marks,Lab3_marks, lab_attendence_perc, lab_credit,Lab_ete_marks, lab_course_code; Button submit; Double ca_weightage, mte_weightage, ete_weightage, total_marks, ca, mte, ete; int marks_Lab1, marks_Lab2, marks_Lab3, marks_ete, attendence_percentage, course_credit, attendence_weightage, gpa; String Grade, semester, course; Spinner semspin; RelativeLayout relativeLayout; DatabaseReference mref; String userid; String sems[] = {"Semester1", "Semester2", "Semester3", "Semester4", "Semester5", "Semester6", "Semester7", "Semester8"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical__course); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } actionBar.setTitle("TGPA CALCULATOR"); actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2A3c58"))); lab_course_code = findViewById(R.id.course_code); lab_attendence_perc = findViewById(R.id.Attendence); lab_credit = findViewById(R.id.credits); Lab1_marks = findViewById(R.id.Lab1); Lab2_marks = findViewById(R.id.Lab2); Lab3_marks = findViewById(R.id.Lab3); Lab_ete_marks = findViewById(R.id.lab_ete); semspin = findViewById(R.id.semList1); relativeLayout = findViewById(R.id.Layout_normal_course); relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager inputMethodManager = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } }); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, sems); semspin.setAdapter(arrayAdapter); submit = findViewById(R.id.save); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(Lab1_marks.getText().toString())) { Lab1_marks.setError("Enter ca1 marks"); } else { marks_Lab1 = Integer.parseInt(Lab1_marks.getText().toString()); } if (marks_Lab1 > 50 ||marks_Lab1 < 0) { Lab1_marks.setError("Enter a valid ca marks"); } if (TextUtils.isEmpty(Lab2_marks.getText().toString())) { Lab2_marks.setError("Enter ca2 marks"); } else { marks_Lab2= Integer.parseInt(Lab2_marks.getText().toString()); } if (marks_Lab2 > 50 || marks_Lab2<0) { Lab2_marks.setError("Enter a valid ca marks"); } if (TextUtils.isEmpty(Lab3_marks.getText().toString())) { Lab3_marks.setError("Enter Lab3 marks"); } else { marks_Lab3 = Integer.parseInt(Lab3_marks.getText().toString()); } if (marks_Lab3 > 50 ||marks_Lab3<0) { Lab3_marks.setError("Enter a valid mte marks"); } if (TextUtils.isEmpty(Lab_ete_marks.getText().toString())) { Lab_ete_marks.setError("Enter ete marks"); } else { marks_ete = Integer.parseInt(Lab_ete_marks.getText().toString()); } if (marks_ete > 100 ||marks_ete<0) { Lab_ete_marks.setError("Enter a valid ete marks"); } if (TextUtils.isEmpty(lab_attendence_perc.getText().toString())) { lab_attendence_perc.setError("Enter your attendence"); } else { attendence_percentage = Integer.parseInt(lab_attendence_perc.getText().toString()); } if (attendence_percentage > 100) { lab_attendence_perc.setError("Enter a valid attendence"); } if (TextUtils.isEmpty(lab_course_code.getText().toString())) { lab_course_code.setError("Enter the course code"); } else { course = lab_course_code.getText().toString(); } if (TextUtils.isEmpty(lab_credit.getText().toString())) { lab_credit.setError("Enter the course credit"); } else { course_credit = Integer.parseInt(lab_credit.getText().toString()); } if (course_credit < 1) { lab_credit.setError("Enter a valid course credit"); } if(marks_Lab1<=50 && marks_Lab2<=50&& marks_Lab3<=50 && marks_ete<=100 && !Lab1_marks.getText().toString().equals("") && !lab_credit.getText().toString().equals("") && !Lab2_marks.getText().toString().equals("") && !Lab3_marks.getText().toString().equals("") && !lab_attendence_perc.getText().toString().equals("") && !lab_course_code.getText().toString().equals("") ) { ca_weightage = ((0.30 * marks_Lab1) + (0.30 * marks_Lab2)+(0.30 * marks_Lab3)); mte_weightage = 0.0d; ete_weightage = (0.50 * marks_ete); if (attendence_percentage >= 90) attendence_weightage = 5; else if (attendence_percentage >= 85) attendence_weightage = 4; else if (attendence_percentage >= 80) attendence_weightage = 3; else if (attendence_percentage >= 75) attendence_weightage = 2; else attendence_weightage = 0; ca = Math.round(ca_weightage * 100.0) / 100.0; mte = Math.round(mte_weightage * 100.0) / 100.0; ete = Math.round(ete_weightage * 100.0) / 100.0; total_marks = ca + ete + mte + attendence_weightage; total_marks = Math.round(total_marks * 100.0) / 100.0; if (total_marks > 85) Grade = "O"; else if (total_marks > 75) Grade = "A+"; else if (total_marks > 70) Grade = "A"; else if (total_marks > 65) Grade = "B+"; else if (total_marks > 58) Grade = "B"; else if (total_marks > 50) Grade = "C+"; else if (total_marks > 45) Grade = "C"; else if (total_marks > 40) Grade = "D"; else Grade = "E"; if (Grade.equals("O")) gpa = 10; else if (Grade.equals("A+")) gpa = 9; else if (Grade.equals("A")) gpa = 8; else if (Grade.equals("B+")) gpa = 7; else if (Grade.equals("B")) gpa = 6; else if (Grade.equals("C+")) gpa = 5; else if (Grade.equals("C")) gpa = 4; else if (Grade.equals("D")) gpa = 3; else gpa = 0; semester = semspin.getSelectedItem().toString().trim(); userid = FirebaseAuth.getInstance().getUid(); mref = FirebaseDatabase.getInstance().getReference("Users").child(userid).child("Semesters").child(semester); if (semester.equals("Semester1")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester2")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester3")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester4")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester5")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester6")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester7")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } else if (semester.equals("Semester8")) { SubjectDetails subjectDetails = new SubjectDetails(course, attendence_weightage, course_credit, ca, mte, ete, total_marks, Grade, gpa); mref.child("subjects").push().setValue(subjectDetails); Toast.makeText(Practical_Course.this, "Data inserted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Practical_Course.this,ShowData.class)); } } } }); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
4d5096923821b78720bf20afaad464b43cff355c
4bd41c52a8a00627e647b088dc4553cf24ad6b89
/HANDIN/SEP2_RE_Code/src/domain/model/Date/test.java
662c49bda51efce5d5b7d9c069f8ad746a8fe162
[]
no_license
Triesik/SEP2_RE
2f0b063da622e04b9a66e33f45a12a7b29ef0047
85b2ac36af88281df19e4ac3efb374b0c48fb74d
refs/heads/master
2020-07-06T10:33:05.883744
2019-08-16T08:47:52
2019-08-16T08:47:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
759
java
package domain.model.Date; import java.util.Calendar; public class test { public static void main(String args[]) { Calendar givenDate; int day = 0; Date date = new Date(Calendar.getInstance()); //System.out.print(date.getCurrentWeekDay()); int currentDay = date.getCurrentWeekDay(); //System.out.print(date.toString()); //System.out.print(date.getFirstDayOfWeek()); givenDate = date.getFirstDayOfWeek(); //for(int i = 0; i < 7; i++) //{ //Date newDate = new Date(givenDate); //System.out.print(newDate.toString() + " "); //givenDate.add(Calendar.DATE, +1); //} System.out.print(date.timeToString()); } }
220aa6782910b9a2db4c3c01bd0c4fa32c2dbe4f
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-13708-1-16-MOEAD-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/internal/template/TemplateListener_ESTest.java
50a27776c737a89679f2069aef23e4a9d2a8a517
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
570
java
/* * This file was automatically generated by EvoSuite * Tue Apr 07 23:46:06 UTC 2020 */ package com.xpn.xwiki.internal.template; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class TemplateListener_ESTest extends TemplateListener_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
af5b6d010456287df1d64fc2bb9d360635521472
8a6453cd49949798c11f57462d3f64a1fa2fc441
/aws-java-sdk-translate/src/main/java/com/amazonaws/services/translate/model/transform/EncryptionKeyMarshaller.java
851fc2b8dd25ecd8b7dbc58afec9b47c73e7690e
[ "Apache-2.0" ]
permissive
tedyu/aws-sdk-java
138837a2be45ecb73c14c0d1b5b021e7470520e1
c97c472fd66d7fc8982cb4cf3c4ae78de590cfe8
refs/heads/master
2020-04-14T14:17:28.985045
2019-01-02T21:46:53
2019-01-02T21:46:53
163,892,339
0
0
Apache-2.0
2019-01-02T21:38:39
2019-01-02T21:38:39
null
UTF-8
Java
false
false
2,200
java
/* * Copyright 2013-2018 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.translate.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.translate.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * EncryptionKeyMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class EncryptionKeyMarshaller { private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Type").build(); private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Id").build(); private static final EncryptionKeyMarshaller instance = new EncryptionKeyMarshaller(); public static EncryptionKeyMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(EncryptionKey encryptionKey, ProtocolMarshaller protocolMarshaller) { if (encryptionKey == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(encryptionKey.getType(), TYPE_BINDING); protocolMarshaller.marshall(encryptionKey.getId(), ID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
3e4e701752e893512303235b30afb8717e3c85aa
74539d9e911ccfd18b0c13a526810be052eec77b
/src/com/google/common/collect/CompoundOrdering.java
367ab019560be66d289f0dca9b1813762c7a9e56
[]
no_license
dovikn/inegotiate-android
723f12a3ee7ef46b980ee465b36a6a154e5adf6f
cea5e088b01ae4487d83cd1a84e6d2df78761a6e
refs/heads/master
2021-01-12T02:14:41.503567
2017-01-10T04:20:15
2017-01-10T04:20:15
78,492,148
0
1
null
null
null
null
UTF-8
Java
false
false
1,798
java
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableList.Builder; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.List; @GwtCompatible(serializable = true) final class CompoundOrdering<T> extends Ordering<T> implements Serializable { private static final long serialVersionUID = 0; final ImmutableList<Comparator<? super T>> comparators; CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) { this.comparators = ImmutableList.of(primary, secondary); } CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) { this.comparators = ImmutableList.copyOf((Iterable) comparators); } CompoundOrdering(List<? extends Comparator<? super T>> comparators, Comparator<? super T> lastComparator) { this.comparators = new Builder().addAll((Iterable) comparators).add((Object) lastComparator).build(); } public int compare(T left, T right) { Iterator i$ = this.comparators.iterator(); while (i$.hasNext()) { int result = ((Comparator) i$.next()).compare(left, right); if (result != 0) { return result; } } return 0; } public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof CompoundOrdering)) { return false; } return this.comparators.equals(((CompoundOrdering) object).comparators); } public int hashCode() { return this.comparators.hashCode(); } public String toString() { return "Ordering.compound(" + this.comparators + ")"; } }
7d5a04ead71ac1b9f589ca53d297bed8f2f8a8b4
56015a933a04e6754cf8680702b9378accdfb059
/src/UTF8_LF/myproject/application/winpe32/Section.java
be1d7f9c94cd59b08b75cd1ffbc7d79aee876212
[ "MIT" ]
permissive
shuichiro-endo/pplusviewer
b5bc8b445511f063c993574ff1a67701bbbf442e
8a5cd3a288b8495742d29b46ba1ee4546c8824cb
refs/heads/master
2023-01-12T12:22:18.240469
2019-07-16T20:31:40
2019-07-16T20:31:40
167,485,929
0
0
null
null
null
null
UTF-8
Java
false
false
2,547
java
package myproject.application.winpe32; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.xml.bind.DatatypeConverter; public class Section { String name; String strRawAddress; int rawAddress; int rawSize; String strVirtualAddress; int virtualAddress; int virtualSize; int diff; public Section(String name) { this.name = name; this.strRawAddress = ""; this.rawAddress = 0; this.rawSize = 0; this.strVirtualAddress = ""; this.virtualAddress = 0; this.virtualSize = 0; this.diff = 0; } public boolean addrCheck(String strStartAddr, int size) { //アドレスを数値に変換 int startAddr = getStringToInt(strStartAddr, false); int endAddr = startAddr + size; //比較 if((startAddr>=virtualAddress) && (endAddr<=virtualAddress+virtualSize)){ return true; }else { return false; } } private int getStringToInt(String str, boolean little) { int num = 0; byte[] bytes = null; ByteBuffer bytesBuf = null; bytes = DatatypeConverter.parseHexBinary(str); bytesBuf = ByteBuffer.wrap(bytes); if(little) { bytesBuf.order(ByteOrder.LITTLE_ENDIAN); } if(bytes.length == 2) { num = (int)bytesBuf.getShort(0); }else { num = bytesBuf.getInt(0); } return num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getStrRawAddress() { return strRawAddress; } public void setStrRawAddress(String strRawAddress) { this.strRawAddress = strRawAddress; this.rawAddress = getStringToInt(strRawAddress, false); } public int getRawAddress() { return rawAddress; } public void setRawAddress(int rawAddress) { this.rawAddress = rawAddress; } public int getRawSize() { return rawSize; } public void setRawSize(int rawSize) { this.rawSize = rawSize; } public String getStrVirtualAddress() { return strVirtualAddress; } public void setStrVirtualAddress(String strVirtualAddress) { this.strVirtualAddress = strVirtualAddress; this.virtualAddress = getStringToInt(strVirtualAddress, false); } public int getVirtualAddress() { return virtualAddress; } public void setVirtualAddress(int virtualAddress) { this.virtualAddress = virtualAddress; } public int getVirtualSize() { return virtualSize; } public void setVirtualSize(int virtualSize) { this.virtualSize = virtualSize; } public int getDiff() { return diff; } public void setDiff() { this.diff = virtualAddress-rawAddress; } }
7426c29a0d8b452a6129fc0da9818379a22e738d
1a3de9f86032b3c5771f086da63d3a97da50c73b
/review_manager/src/test/java/exort/review_manager/service/ApplicationServiceTest.java
2aa956d3151246baa8cdfac2ce32cf60c6cf3bbe
[]
no_license
exorteam/Exort
afab5764580ba0c6fa9190f0b93ed0bffa0e8546
9a99799b86cd584ddd45fcd830fe86674ab05061
refs/heads/master
2021-07-21T13:07:59.809212
2019-09-09T14:44:42
2019-09-09T14:44:42
181,691,175
3
1
null
2020-06-18T16:30:24
2019-04-16T13:07:27
Java
UTF-8
Java
false
false
829
java
package exort.review_manager.service; import exort.review_manager.entity.Application; import exort.review_manager.entity.IdGenEntity; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest @ActiveProfiles("test") class ApplicationServiceTest { @Autowired private MongoTemplate mt; @BeforeEach void setUp() { mt.dropCollection(Application.class); mt.dropCollection(IdGenEntity.class); } }
b8bb11914487d64c21f5e9432d7eb1069f3c6937
e7a8e09e33337f4532b7038a94fa7191a91cf251
/refatoracao/refatoracao/src/main/java/com/refatoracao/UsuarioComNomeVazioException.java
f1a6154ff0b0e98fc8628c0bad90fb00f58891b7
[]
no_license
KevinDaSilvaS/TDD-ITA
bbe13dd689585b242129cdd407c265537bcc34f2
c13af0cb71ca2fb5b0804b866be630b9b45f4c02
refs/heads/master
2022-12-28T06:38:09.622726
2020-07-28T22:56:57
2020-07-28T22:56:57
283,345,039
1
0
null
2020-10-14T00:01:19
2020-07-28T22:52:34
Java
UTF-8
Java
false
false
206
java
package com.refatoracao; @SuppressWarnings("serial") public class UsuarioComNomeVazioException extends Exception { public UsuarioComNomeVazioException(String message) { super(message); } }
c9586ca49ee68055fc236f02b0d865c012fdf579
d5825a3d35ed4d992274aa99d1335078e80ab9e1
/src/main/java/org/enviapramim/model/ml/ItemResponse.java
82a8612a3ac8692aacc1a9175856aa45d7c2e467
[]
no_license
glaucobarroso/envia-pra-mim
50d3748ecbef707635cc137ef9435cfa912886b9
649eb7b6fe0b6b594cfa7447698386de7ad5324f
refs/heads/master
2020-03-21T23:56:30.617348
2018-10-14T20:47:57
2018-10-14T20:47:57
139,214,466
0
0
null
null
null
null
UTF-8
Java
false
false
2,562
java
package org.enviapramim.model.ml; import java.util.List; /** * Created by Glauco on 13/03/2017. */ public class ItemResponse { public Boolean accepts_mercadopago; public Shipping shipping; public SellerAddress seller_address; public String id; public String site_id; public String title; public Object subtitle; public Integer seller_id; public String category_id; public Object official_store_id; public Float price; public Float base_price; public Object original_price; public String currency_id; public Integer initial_quantity; public Integer available_quantity; public Integer sold_quantity; public String buying_mode; public String listing_type_id; public String start_time; public String stop_time; public String end_time; public String expiration_time; public String condition; public String permalink; public String thumbnail; public String secure_thumbnail; public List<Picture> pictures; public Object video_id; public List<Description> descriptions; public List<Object> non_mercado_pago_payment_methods ; public String international_delivery_mode; public Object seller_contact; public Object location; public Geolocation geolocation; public List<Object> coverage_areas; public List<Attribute> attributes; public List<Object> warnings; public String listing_source; public List<Object> variations; public String status; public List<Object> sub_status; public List<String> tags; public String warranty; public Object catalog_product_id; public Object domain_id; public Object seller_custom_field; public Object parent_item_id; public Object differential_pricing; public List<Object> deal_ids; public Boolean automatic_relist; public String date_created; public String last_updated; public class Picture { public String source; public String id; public String url; public String secure_url; public String size; public String max_size; public String quality; } public class Attribute { public String id; public String name; public String value_id; public String value_name; public String attribute_group_id; public String attribute_group_name; } public class Description { public String id; } public class Geolocation { public Float latitude; public Float longitude; } }
0157c624d197410011ebd837be4e1edd462703c7
e6bbeb4ae2b5a8ad01a784dba55113a9a50ec3c3
/vehicles/src/test/java/mk/gp/emt/vehicles/VehiclesApplicationTests.java
7f56ace833a0534f74cb1c2599ba2c8e72d3e92d
[]
no_license
gpodyt/ddd-emt-car-rental
d9ac66dab47fd42391c26da5c367560f36edd2a4
ad0377535450ea06f618d449ea2bce8924cd2dff
refs/heads/master
2023-07-19T06:04:26.787521
2021-09-22T22:38:41
2021-09-22T22:38:41
409,355,969
0
0
null
null
null
null
UTF-8
Java
false
false
221
java
package mk.gp.emt.vehicles; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class VehiclesApplicationTests { @Test void contextLoads() { } }
97a23eb94ca14d628acb1cc0466f746800eed766
159cc4be111159b8940f0b5dbfca7f79df51edfe
/src/main/java/solutions/ValidParentheses.java
0e64c0332af6b8c0618ff77b13d551815029254d
[]
no_license
h4ever/LintCodeSolution
e7d5527d9fa27613f2214564e73e274212d1fb30
6d1d8cef05b4948511ba74d5001f4a83a43719e4
refs/heads/master
2023-08-23T23:33:22.857007
2023-08-03T10:05:57
2023-08-03T10:05:57
213,806,653
0
0
null
2020-10-13T23:30:08
2019-10-09T02:54:25
Java
UTF-8
Java
false
false
445
java
package solutions; import java.util.Stack; public class ValidParentheses { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else if (stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty(); } }
eebb5b67c0e842e54285a321cb0c6bdfc7085f8e
e1e9b038b7e54edf20df4310b546f9b3fab67dcd
/jydudailib/src/main/java/com/jiyou/jydudailib/thirdtools/http/okhttp3/Authenticator.java
b54ffeb127d09e8f7ca8ee5e04aabca24b982419
[]
no_license
fyc/Dudai
bfff0697271e20cb5794b4ee616dc940c960f26f
075d89c80dc95c07ad43f1befa5d7ddce963057c
refs/heads/master
2020-06-13T20:05:37.073800
2019-06-26T13:23:12
2019-06-26T13:23:12
194,774,032
0
0
null
null
null
null
UTF-8
Java
false
false
3,030
java
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jiyou.jydudailib.thirdtools.http.okhttp3; import java.io.IOException; import javax.annotation.Nullable; /** * Responds to an authentication challenge from either a remote web server or a proxy server. * Implementations may either attempt to satisfy the challenge by returning a request that includes * an authorization header, or they may refuse the challenge by returning null. In this case the * unauthenticated response will be returned to the caller that triggered it. * * <p>Implementations should check if the initial request already included an attempt to * authenticate. If so it is likely that further attempts will not be useful and the authenticator * should give up. * * <p>When authentication is requested by an origin server, the response code is 401 and the * implementation should respond with a new request that sets the "Authorization" header. * <pre> {@code * * if (response.request().header("Authorization") != null) { * return null; // Give up, we've already failed to authenticate. * } * * String credential = Credentials.basic(...) * return response.request().newBuilder() * .header("Authorization", credential) * .build(); * }</pre> * * <p>When authentication is requested by a proxy server, the response code is 407 and the * implementation should respond with a new request that sets the "Proxy-Authorization" header. * <pre> {@code * * if (response.request().header("Proxy-Authorization") != null) { * return null; // Give up, we've already failed to authenticate. * } * * String credential = Credentials.basic(...) * return response.request().newBuilder() * .header("Proxy-Authorization", credential) * .build(); * }</pre> * * <p>Applications may configure OkHttp with an authenticator for origin servers, or proxy servers, * or both. */ public interface Authenticator { /** An authenticator that knows no credentials and makes no attempt to authenticate. */ Authenticator NONE = new Authenticator() { @Override public Request authenticate(Route route, Response response) { return null; } }; /** * Returns a request that includes a credential to satisfy an authentication challenge in {@code * response}. Returns null if the challenge cannot be satisfied. */ @Nullable Request authenticate(Route route, Response response) throws IOException; }
eee32f5f4771f6c4244fa42813a87fa75ecce9ca
e0284f5f6503660524b2847927bae0e11bed2242
/src/chat/lesson4/online/ClientGUI.java
dbebf3d508ee19262072f0669b024ee1364889b5
[]
no_license
njakimov/secondCourseOOP
00b6616c5d4cc4fa78ec90d0ede851aee262eb69
558ed7553c1acc19f06826f81a320490f2a65680
refs/heads/master
2023-01-31T16:05:35.902893
2020-12-17T14:43:02
2020-12-17T14:43:02
318,315,554
0
0
null
2020-12-14T17:16:43
2020-12-03T20:46:48
Java
UTF-8
Java
false
false
5,947
java
package chat.lesson4.online; import lesson6.MyFile; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class ClientGUI extends JFrame implements ActionListener, Thread.UncaughtExceptionHandler { private static final int WIDTH = 400; private static final int HEIGHT = 300; private final JTextArea log = new JTextArea(); private final JPanel panelTop = new JPanel(new GridLayout(2, 3)); private final JTextField tfIPAddress = new JTextField("127.0.0.1"); private final JTextField tfPort = new JTextField("8189"); private final JCheckBox cbAlwaysOnTop = new JCheckBox("Always on top"); private final JTextField tfLogin = new JTextField("ivan"); private final JPasswordField tfPassword = new JPasswordField("123"); private final JButton btnLogin = new JButton("Login"); private final JPanel panelBottom = new JPanel(new BorderLayout()); private final JButton btnDisconnect = new JButton("<html><b>Disconnect</b></html>"); private final JTextField tfMessage = new JTextField(); private final JButton btnSend = new JButton("Send"); private final JList<String> userList = new JList<>(); public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new ClientGUI(); } }); } private ClientGUI() { Thread.setDefaultUncaughtExceptionHandler(this); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); setSize(WIDTH, HEIGHT); log.setEditable(false); JScrollPane scrollLog = new JScrollPane(log); JScrollPane scrollUsers = new JScrollPane(userList); String[] users = {"user1", "user2", "user3", "user4", "user5", "user6", "user_with_an_exceptionally_long_nickname"}; userList.setListData(users); scrollUsers.setPreferredSize(new Dimension(100, 0)); cbAlwaysOnTop.addActionListener(this); panelTop.add(tfIPAddress); panelTop.add(tfPort); panelTop.add(cbAlwaysOnTop); panelTop.add(tfLogin); panelTop.add(tfPassword); panelTop.add(btnLogin); panelBottom.add(btnDisconnect, BorderLayout.WEST); panelBottom.add(tfMessage, BorderLayout.CENTER); panelBottom.add(btnSend, BorderLayout.EAST); add(scrollLog, BorderLayout.CENTER); add(scrollUsers, BorderLayout.EAST); add(panelTop, BorderLayout.NORTH); add(panelBottom, BorderLayout.SOUTH); btnSend.addActionListener(this); tfMessage.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { sendMessage(); // отправляем сообщение } } }); userList.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ESCAPE) { userList.clearSelection(); // сброс выбора пользователя, которому отправляем сообщение } } }); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == cbAlwaysOnTop) { setAlwaysOnTop(cbAlwaysOnTop.isSelected()); } else if (src == btnSend) { sendMessage(); } else { throw new RuntimeException("Undefined source: " + src); } } /** * отправка сообщений в список сообщений */ public void sendMessage() { System.out.println(tfMessage.getText()); if(tfMessage.getText()!="") { String reciever = "Всем"; if (!userList.isSelectionEmpty()) { reciever = userList.getSelectedValue(); } String message = tfLogin.getText() + "->" + reciever + ": " + tfMessage.getText() + "\n"; log.append(message); printLogToFile(message); tfMessage.setText(""); } else { System.out.println("Сообщение пустое"); } } /** * сохранение лога файлов * @param text - сообщение, которое нужно вывести в лог */ public static void printLogToFile(String text) { try { File file = new File("chat.log"); if(!file.isFile() && !file.createNewFile()) { throw new IOException("Не удалось создать файл. Проверьте существование директории и наличие прав доступа"); } Files.write(Paths.get("chat.log"), text.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } } @Override public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); StackTraceElement[] ste = e.getStackTrace(); String msg = String.format("Exception in thread \"%s\" %s: %s\n\tat %s", t.getName(), e.getClass().getCanonicalName(), e.getMessage(), ste[0]); JOptionPane.showMessageDialog(this, msg, "Exception", JOptionPane.ERROR_MESSAGE); System.exit(1); } }
503404a5779c8d87ac793a075ad71454db19ad60
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/java/java-tests/testData/compileServer/incremental/membersChange/deleteSAMInterfaceMethod/src/ServiceClient.java
c7b2308c51450ba32188810e3275ef2ca76bcdbf
[ "Apache-2.0" ]
permissive
JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560889
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
2023-09-12T07:41:58
2011-09-30T13:33:05
null
UTF-8
Java
false
false
119
java
public class ServiceClient { public void execute() { Util.invokeService(() -> System.out.println("Hello")); } }
cc5743b8fed16b68b70f875f47e001304eaaf733
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/23/23_62d0276a0d60f7db875d94efb262cfd379a5f9c6/MonacaPageActivity/23_62d0276a0d60f7db875d94efb262cfd379a5f9c6_MonacaPageActivity_t.java
a998901f2249e86449ddf68a4fde83e8a5feff5e
[]
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
37,950
java
package mobi.monaca.framework; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import mobi.monaca.framework.bootloader.LocalFileBootloader; import mobi.monaca.framework.nativeui.UIBuilder; import mobi.monaca.framework.nativeui.UIBuilder.ResultSet; import mobi.monaca.framework.nativeui.UIContext; import mobi.monaca.framework.nativeui.UIUtil; import mobi.monaca.framework.nativeui.UpdateStyleQuery; import mobi.monaca.framework.nativeui.component.Component; import mobi.monaca.framework.nativeui.container.ToolbarContainer; import mobi.monaca.framework.nativeui.menu.MenuRepresentation; import mobi.monaca.framework.psedo.R; import mobi.monaca.framework.transition.BackgroundDrawable; import mobi.monaca.framework.transition.ClosePageIntent; import mobi.monaca.framework.transition.TransitionParams; import mobi.monaca.framework.util.AssetUriUtil; import mobi.monaca.framework.util.BenchmarkTimer; import mobi.monaca.framework.util.InputStreamLoader; import mobi.monaca.framework.util.MyLog; import mobi.monaca.framework.util.UrlUtil; import mobi.monaca.framework.view.MonacaPageGingerbreadWebViewClient; import mobi.monaca.framework.view.MonacaPageHoneyCombWebViewClient; import mobi.monaca.framework.view.MonacaWebView; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.cordova.CordovaChromeClient; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebViewClient; import org.apache.cordova.DroidGap; import org.apache.cordova.api.CordovaInterface; import org.json.JSONException; import org.json.JSONObject; import receiver.ScreenReceiver; import android.R.color; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.webkit.JsPromptResult; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; /** * This class represent a page of Monaca application. */ public class MonacaPageActivity extends DroidGap { public static final String TRANSITION_PARAM_NAME = "monaca.transition"; public static final String URL_PARAM_NAME = "monaca.url"; public static final String TAG = MonacaPageActivity.class.getSimpleName(); protected MonacaURI currentMonacaUri; protected Drawable background = null; protected HashMap<String, Component> dict; protected Handler handler = new Handler(); protected UIBuilder.ResultSet uiBuilderResult = null; protected int pageIndex = 0; protected JSONObject appJson; protected Dialog monacaSplashDialog; protected BroadcastReceiver closePageReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra("level", 0); if (pageIndex >= level) { finish(); } MyLog.d(MonacaPageActivity.this.getClass().getSimpleName(), "close intent received: " + getCurrentUriWithoutQuery()); MyLog.d(MonacaPageActivity.this.getClass().getSimpleName(), "page index: " + pageIndex); } }; /** If this flag is true, activity is capable of transition. */ protected boolean isCapableForTransition = true; protected UIContext uiContext = null; protected TransitionParams transitionParams; protected JSONObject infoForJavaScript = new JSONObject(); protected String mCurrentHtml; private ScreenReceiver mScreenReceiver; @Override public void onCreate(Bundle savedInstance) { prepare(); // initialize receiver IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mScreenReceiver = new ScreenReceiver(); registerReceiver(mScreenReceiver, filter); super.onCreate(savedInstance); // to clear getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); in DroidGap class getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); MyLog.v(TAG, "MonacaApplication.getPages().size():" + MonacaApplication.getPages().size()); //currentMonacaUri is set in prepare() if (MonacaApplication.getPages().size() == 1) { init(); loadUri(currentMonacaUri.getUrlWithQuery(), false); } else { init(); loadUiFile(getCurrentUriWithoutQuery()); handler.postDelayed(new Runnable() { @Override public void run() { loadUri(currentMonacaUri.getUrlWithQuery(), true); } }, 100); } // dirty fix for android4's strange bug if (transitionParams.animationType == TransitionParams.TransitionAnimationType.MODAL) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_dialog_open_enter, mobi.monaca.framework.psedo.R.anim.monaca_dialog_open_exit); } else if (transitionParams.animationType == TransitionParams.TransitionAnimationType.TRANSIT) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_slide_open_enter, mobi.monaca.framework.psedo.R.anim.monaca_slide_open_exit); } else if (transitionParams.animationType == TransitionParams.TransitionAnimationType.NONE) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_none, mobi.monaca.framework.psedo.R.anim.monaca_none); } } protected Drawable getSplashDrawable() throws IOException { InputStream is = getResources().getAssets().open(MonacaSplashActivity.SPLASH_IMAGE_PATH); return Drawable.createFromStream(is, "splash_default"); } protected int getSplashBackgroundColor() { try { InputStream stream = getResources().getAssets().open("app.json"); byte[] buffer = new byte[stream.available()]; stream.read(buffer); JSONObject appJson = new JSONObject(new String(buffer,"UTF-8")); String backgroundColorString = appJson.getJSONObject("splash").getJSONObject("android").getString("background"); if(!backgroundColorString.startsWith("#")){ backgroundColorString = "#" + backgroundColorString; } int backbroundColor = Color.parseColor(backgroundColorString); return backbroundColor; } catch (JSONException e) { MyLog.e(TAG, e.getMessage()); }catch (IllegalArgumentException e) { MyLog.e(TAG, e.getMessage()); } catch (IOException e) { // TODO 自動生成された catch ブロック MyLog.e(TAG, e.getMessage()); } return Color.TRANSPARENT; } public void showMonacaSplash() { final MonacaPageActivity activity = this; Runnable runnable = new Runnable() { public void run() { // Get reference to display Display display = activity.getWindowManager().getDefaultDisplay(); // Create the layout for the dialog FrameLayout root = new FrameLayout(activity.getActivity()); root.setMinimumHeight(display.getHeight()); root.setMinimumWidth(display.getWidth()); root.setBackgroundColor(activity.getSplashBackgroundColor()); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F)); try { ImageView splashImageView; splashImageView = new ImageView(MonacaPageActivity.this); splashImageView.setImageDrawable(activity.getSplashDrawable()); splashImageView.setScaleType(ScaleType.FIT_CENTER); root.addView(splashImageView); } catch (IOException e) { MyLog.e(TAG, e.getMessage()); } // Create and show the dialog monacaSplashDialog = new Dialog(MonacaPageActivity.this, android.R.style.Theme_Translucent_NoTitleBar); // check to see if the splash screen should be full screen if ((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) { monacaSplashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } monacaSplashDialog.setContentView(root); monacaSplashDialog.setCancelable(false); monacaSplashDialog.show(); } }; this.runOnUiThread(runnable); } public void removeMonacaSplash() { if (monacaSplashDialog != null && monacaSplashDialog.isShowing()) { monacaSplashDialog.dismiss(); monacaSplashDialog = null; } } @Override public boolean onPrepareOptionsMenu(Menu menu) { MyLog.v(TAG, "onPrepareOptionMenu()"); if (uiBuilderResult != null) { MyLog.v(TAG, "building menu"); menu.clear(); MenuRepresentation menuRepresentation = MonacaApplication.findMenuRepresentation(uiBuilderResult.menuName); MyLog.v(TAG, "menuRepresentation:" + menuRepresentation); if (menuRepresentation != null) { menuRepresentation.configureMenu(uiContext, menu); } return true; } else { return false; } } protected void prepare() { Bundle bundle = getIntent().getExtras(); if (bundle != null && bundle.getBoolean(MonacaSplashActivity.SHOWS_SPLASH_KEY, false)) { showMonacaSplash(); getIntent().getExtras().remove(MonacaSplashActivity.SHOWS_SPLASH_KEY); } loadParams(); MonacaApplication.addPage(this); pageIndex = MonacaApplication.getPages().size() - 1; registerReceiver(closePageReceiver, ClosePageIntent.createIntentFilter()); uiContext = new UIContext(getCurrentUriWithoutQuery(), this); // override theme if (transitionParams.animationType == TransitionParams.TransitionAnimationType.NONE) { } else if (transitionParams.animationType == TransitionParams.TransitionAnimationType.MODAL) { setTheme(mobi.monaca.framework.psedo.R.style.MonacaDialogTheme); } else if (transitionParams.animationType == TransitionParams.TransitionAnimationType.TRANSIT) { setTheme(mobi.monaca.framework.psedo.R.style.MonacaSlideTheme); } else { } try { infoForJavaScript.put("display", createDisplayInfo()); } catch (JSONException e) { throw new RuntimeException(e); } loadBackground(getResources().getConfiguration()); } /** Load background drawable from transition params and device orientation. */ protected void loadBackground(Configuration config) { MyLog.v(TAG, "loadBackground()."); if (transitionParams != null && transitionParams.hasBackgroundImage()) { String path = null; String preferedPath = "www/" + UIContext.getPreferredPath(transitionParams.backgroundImagePath); if (AssetUriUtil.existsAsset(this, preferedPath)) { path = preferedPath; } else { path = "www/" + transitionParams.backgroundImagePath; } MyLog.v(TAG, "loadBackground(). path:" + path); try { Bitmap bitmap = BitmapFactory.decodeStream(LocalFileBootloader.openAsset(this.getApplicationContext(), path)); background = new BackgroundDrawable(bitmap, getWindowManager().getDefaultDisplay(), config.orientation); } catch (Exception e) { MyLog.e(TAG, e.getMessage()); } } } /** Release background drawable. */ protected void unloadBackground() { if (background != null) { appView.setBackgroundDrawable(null); root.setBackgroundDrawable(null); background.setCallback(null); background = null; System.gc(); } } public void initMonaca() { appView.setFocusable(true); appView.setFocusableInTouchMode(true); loadUrl("about:blank?"); root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { try { int height = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight() - root.getHeight(); infoForJavaScript.put("statusbarHeight", height); } catch (JSONException e) { MyLog.e(getClass().getSimpleName(), "fail to get statusbar height."); } } }); setupBackground(); // for focus problem between native component and webView appView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!v.hasFocus()) { v.requestFocus(); } break; } return false; } }); } @Override public void init() { CordovaWebView webView = new MonacaWebView(this); CordovaWebViewClient webViewClient = (CordovaWebViewClient) createWebViewClient(getCurrentUriWithoutQuery(), this, webView); MonacaChromeClient webChromeClient = new MonacaChromeClient(this, webView); this.init(webView, webViewClient, webChromeClient); this.initMonaca(); } protected class MonacaChromeClient extends CordovaChromeClient { public MonacaChromeClient(CordovaInterface ctx) { super(ctx); } public MonacaChromeClient(MonacaPageActivity monacaPageActivity, CordovaWebView webView) { super(monacaPageActivity, webView); } @Override public boolean onJsPrompt(WebView webView, String url, String message, String defaultValue, JsPromptResult jsPromtResult) { MyLog.v(TAG, "onJsPromt:arg1:" + url + ", arg2:" + message + ", arg3:" + defaultValue); if (url.equalsIgnoreCase("uri")) { // MyLog.v(TAG, "url null-> return true"); return true; } return super.onJsPrompt(webView, url, message, defaultValue, jsPromtResult); } } /** Setup background drawable for app View and root view. */ protected void setupBackground() { MyLog.v(TAG, "setupBackground()"); if (background != null) { MyLog.v(TAG, "background != null"); if (appView != null) { MyLog.v(TAG, "appview and background not null -> set to appview"); appView.setBackgroundDrawable(background); } if (root != null) { root.setBackgroundDrawable(background); MyLog.v(TAG, "set background to root"); if (root.getParent() == null) { setContentView(root); } } } else { if (appView != null) { MyLog.v(TAG, "setDefaultBackground"); // Default background appView.setBackgroundResource(color.white); } } } protected void loadLayoutInformation() { appView.loadUrl("javascript: window.__layout = " + infoForJavaScript.toString()); } protected JSONObject createDisplayInfo() { JSONObject result = new JSONObject(); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); Display display = getWindowManager().getDefaultDisplay(); try { result.put("width", display.getWidth()); result.put("height", display.getHeight()); } catch (JSONException e) { } return result; } protected void loadParams() { Intent intent = getIntent(); transitionParams = (TransitionParams) intent.getSerializableExtra(TRANSITION_PARAM_NAME); if (transitionParams == null) { transitionParams = TransitionParams.createDefaultParams(this.getRequestedOrientation()); } setCurrentUri(intent.hasExtra(URL_PARAM_NAME) ? intent.getStringExtra(URL_PARAM_NAME) : "file:///android_asset/www/index.html"); MyLog.v(TAG, "uri without query:" + getCurrentUriWithoutQuery()); MyLog.v(TAG, "uri with query:" + currentMonacaUri.getUrlWithQuery()); } protected boolean usingTemplatgeEngine() { try { ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); if (appInfo.metaData == null || !appInfo.metaData.containsKey("disable_monaca_template_engine")) { return true; } return !appInfo.metaData.getBoolean("disable_monaca_template_engine"); } catch (NameNotFoundException e) { return true; } } public JSONObject getInfoForJavaScript() { return infoForJavaScript; } protected boolean hasOpacityBar(ResultSet resultSet) { if (resultSet.top != null && ToolbarContainer.isTransparent(resultSet.top.getStyle().optDouble("opacity", 1.0))) { return true; } if (resultSet.bottom != null && ToolbarContainer.isTransparent(resultSet.bottom.getStyle().optDouble("opacity", 1.0))) { return true; } return false; } /** Load local ui file */ protected void loadUiFile(String uri) { MyLog.v(TAG, "loadUiFile()"); String uiString = null; try { uiString = getUIFile(UrlUtil.getUIFileUrl(uri)); } catch (IOException e1) { MyLog.d(TAG, "UI file not found"); return; } JSONObject uiJSON; ResultSet result = null; try { uiJSON = new JSONObject(uiString); result = new UIBuilder(uiContext, uiJSON).build(); } catch (JSONException e) { UIUtil.reportJSONParseError(getApplicationContext(), e.getMessage()); return; }catch (Exception e) { MyLog.e(TAG, e.getMessage()); MyLog.sendBloadcastDebugLog(getApplicationContext(), "NativeComponent:" + e.getMessage(), "error", "error"); return; } applyUiToView(result); } protected void applyUiToView(ResultSet result) { uiBuilderResult = result; this.dict = result.dict; JSONObject pageStyle = uiBuilderResult.pageStyle; processPageStyle(pageStyle); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(0, 0, 0, 0); if (result.bottomView != null || result.topView != null) { MyLog.v(TAG, "result.bottomView != null || result.topView != null"); if (hasOpacityBar(result)) { MyLog.v(TAG, "hasOpacityBar"); FrameLayout frame = new FrameLayout(this); LinearLayout newRoot = new LinearLayout(this); newRoot.setOrientation(LinearLayout.VERTICAL); root.removeAllViews(); MyLog.v(TAG, "root.removeAllViews()"); root.addView(frame, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); ViewGroup appViewParent = ((ViewGroup) appView.getParent()); if (appViewParent != null) { appViewParent.removeAllViews(); } frame.addView(appView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); frame.addView(newRoot, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); // top bar view newRoot.addView(result.topView != null ? result.topView : new FrameLayout(this), 0, params); // center newRoot.addView(new LinearLayout(this), 1, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f)); // bottom bar view newRoot.addView(result.bottomView != null ? result.bottomView : new FrameLayout(this), 2, params); if (result.topView != null) { MyLog.v(TAG, "result.topView != null"); result.topView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int topViewHeight = result.topView.getMeasuredHeight(); try { infoForJavaScript.put("topViewHeight", topViewHeight); } catch (JSONException e) { MyLog.e(TAG, e.getMessage()); } } if (result.bottomView != null) { MyLog.v(TAG, "result.bottomView != null"); result.bottomView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int bottomViewHeight = result.bottomView.getMeasuredHeight(); try { infoForJavaScript.put("bottomViewHeight", bottomViewHeight); } catch (JSONException e) { MyLog.e(TAG, e.getMessage()); } } } else { MyLog.v(TAG, "noOpacityBar"); root.removeAllViews(); MyLog.v(TAG, "root.removeAllViews()"); // top bar view root.addView(result.topView != null ? result.topView : new FrameLayout(this), 0, params); // center ViewGroup appViewParent = (ViewGroup) appView.getParent(); if (appViewParent != null) { appViewParent.removeView(appView); } root.addView(appView, 1, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f)); // bottom bar view root.addView(result.bottomView != null ? result.bottomView : new FrameLayout(this), 2, params); } } else { MyLog.v(TAG, "Reverse of result.bottomView != null || result.topView != null"); ((ViewGroup) appView.getParent()).removeView(appView); root.removeAllViews(); MyLog.v(TAG, "root.removeAllViews()"); root.addView(appView); this.dict = new HashMap<String, Component>(); } } private void processPageStyle(JSONObject pageStyle) { if(uiBuilderResult.pageStyle != null){ ArrayList<Drawable> layerList = new ArrayList<Drawable>(); // background color String backgroundColor = pageStyle.optString("backgroundColor"); if(!backgroundColor.equalsIgnoreCase("")){ ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor(backgroundColor)); layerList.add(colorDrawable); } String backgroundImageFile = pageStyle.optString("backgroundImage"); if(!backgroundImageFile.equalsIgnoreCase("")){ MyLog.w(TAG, "backgroundImage:" + backgroundImageFile); String path = null; String preferedPath = "www/" + UIContext.getPreferredPath(backgroundImageFile); if (AssetUriUtil.existsAsset(this, preferedPath)) { path = preferedPath; } else { path = "www/" + backgroundImageFile; } MyLog.v(TAG, "loadBackground(). path:" + path); try { Bitmap bitmap = BitmapFactory.decodeStream(LocalFileBootloader.openAsset(this.getApplicationContext(), path)); BackgroundDrawable backgroundImage = new BackgroundDrawable(bitmap, getWindowManager().getDefaultDisplay(), getResources().getConfiguration().orientation); layerList.add(backgroundImage); } catch (Exception e) { MyLog.e(TAG, e.getMessage()); } } Drawable[] layers = new Drawable[layerList.size()]; LayerDrawable layerDrawable = new LayerDrawable(layerList.toArray(layers)); background = layerDrawable; } } protected String getUIFile(String path) throws IOException { Reader reader; InputStream stream = null; if (path == null) { return ""; } MyLog.d(getClass().getSimpleName(), "ui file loading: " + path); if (path.startsWith("file:///android_asset/")) { stream = LocalFileBootloader.openAsset( this.getApplicationContext(), path.substring("file:///android_asset/".length())); reader = new InputStreamReader(stream); } else if (path.startsWith("file://")) { path = new File(path.substring(7)).getCanonicalPath(); reader = new FileReader(new File(path)); } else { stream = InputStreamLoader.loadAssetFile(this, path); reader = new InputStreamReader(stream, "UTF-8"); } Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { reader.close(); if (stream != null) { stream.close(); } } return writer.toString(); } /** Retrieve a style of Native UI Framework component. */ public JSONObject getStyle(String componentId) { if (dict.containsKey(componentId)) { return dict.get(componentId).getStyle(); } return null; } /** Update a style of Native UI Framework component. */ public void updateStyle(final UpdateStyleQuery query) { List<UpdateStyleQuery> queries = new ArrayList<UpdateStyleQuery>(); queries.add(query); updateStyleBulkily(queries); } /** Update bulkily the styles of Native UI Framework components. */ public void updateStyleBulkily(final List<UpdateStyleQuery> queries) { handler.post(new Runnable() { @Override public void run() { MyLog.d(MonacaPageActivity.class.getSimpleName(), "updateStyleBulkily() start"); for (UpdateStyleQuery query : queries) { for (int i = 0; i < query.ids.length(); i++) { String componentId = query.ids.optString(i, ""); if (dict != null && dict.containsKey(componentId)) { Component component = dict.get(componentId); if (component != null) { component.updateStyle(query.style); MyLog.d(MonacaPageActivity.class.getSimpleName(), "updated => id: " + componentId + ", style: " + query.style.toString()); } else { Log.e(MonacaPageActivity.class.getSimpleName(), "update fail => id: " + componentId + ", style: " + query.style.toString()); } } else { Log.e(MonacaPageActivity.class.getSimpleName(), "no such component id: " + componentId); } } } MyLog.d(MonacaPageActivity.class.getSimpleName(), "updateStyleBulkily() done"); } }); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(hasFocus){ BenchmarkTimer.mark("visible"); BenchmarkTimer.finish(); // Debug.stopMethodTracing(); } } public void onPageFinished(View view, String url) { BenchmarkTimer.mark("page finish:" + url); // if(!url.startsWith("about:blank")){ // BenchmarkTimer.finish(); // } // for android4's strange bug. sendJavascript("console.log(' ');"); // check if this is 404 page String errorUrl = getIntent().getStringExtra("error_url"); if (errorUrl != null && url.endsWith("/404/404.html")) { String backButtonText = getString(R.string.back_button_text); errorUrl = UrlUtil.cutHostInUri(errorUrl); MyLog.v(TAG, "error url:" + errorUrl); appView.loadUrl("javascript:$('#url').html(\"" + errorUrl + "\"); $('#backButton').html('" + backButtonText + "')"); } } public void onPageStarted(View view, String url) { ViewGroup.LayoutParams params = this.appView.getLayoutParams(); params.width = ViewGroup.LayoutParams.MATCH_PARENT; params.height = ViewGroup.LayoutParams.MATCH_PARENT; this.appView.setLayoutParams(params); } @Override protected void onRestart() { MyLog.i(TAG, "onRestart"); super.onRestart(); loadBackground(getResources().getConfiguration()); setupBackground(); if (background != null) { background.invalidateSelf(); } } @Override protected void onResume() { MyLog.i(TAG, "onResume"); try { WebView.class.getMethod("onResume").invoke(this); } catch (Exception e) { } // only when screen turns on if (!ScreenReceiver.wasScreenOn) { // this is when onResume() is called due to a screen state change System.out.println("SCREEN TURNED ON"); } else { // this is when onResume() is called when the screen state has not // changed // if (appView != null && appView.callbackServer != null && appView.pluginManager != null) { if (appView != null && appView.pluginManager != null) { appView.loadUrl("javascript: window.onReactivate && onReactivate();"); } } isCapableForTransition = true; super.onResume(); } @Override protected void onPause() { MyLog.i(TAG, "onPause"); super.onPause(); this.removeMonacaSplash(); } @Override public void onDestroy() { MyLog.i(TAG, "onDestroy"); appView.setBackgroundDrawable(null); root.setBackgroundDrawable(null); this.removeMonacaSplash(); super.onDestroy(); MonacaApplication.removePage(this); unregisterReceiver(closePageReceiver); if (background != null) { background.setCallback(null); background = null; } if (dict != null) { dict.clear(); } dict = null; uiBuilderResult = null; appView.setBackgroundDrawable(null); root.setBackgroundDrawable(null); closePageReceiver = null; unregisterReceiver(mScreenReceiver); } /** Reload current URI. */ public void reload() { appView.stopLoading(); loadUri(getCurrentUriWithoutQuery(), false); } public String getCurrentHtml() { return mCurrentHtml; } protected String buildCurrentUriHtml() throws IOException { String html = AssetUriUtil.assetToString(this, getCurrentUriWithoutQuery()); if (UrlUtil.isMonacaUri(this, currentMonacaUri.getUrlWithQuery()) && currentMonacaUri.hasQueryParams()) { html = currentMonacaUri.getQueryParamsContainingHtml(html); } return html; } /** Load current URI. */ public void loadUri(String uri, final boolean withoutUIFile) { MyLog.v(TAG, "loadUri() uri:" + getCurrentUriWithoutQuery()); setCurrentUri(uri); // check for 404 if (getCurrentUriWithoutQuery().equalsIgnoreCase("file:///android_asset/www/404/404.html")) { String failingUrl = getIntent().getStringExtra("error_url"); show404Page(failingUrl); return; } if (!withoutUIFile) { loadUiFile(getCurrentUriWithoutQuery()); } try { mCurrentHtml = buildCurrentUriHtml(); appView.loadDataWithBaseURL(getCurrentUriWithoutQuery(), mCurrentHtml, "text/html", "UTF-8", this.getCurrentUriWithoutQuery()); } catch (IOException e) { MyLog.d(TAG, "Maybe Not MonacaURI : " + e.getMessage()); MyLog.d(TAG, "load as nomal url"); appView.setBackgroundColor(0x00000000); setupBackground(); loadLayoutInformation(); appView.loadUrl(currentMonacaUri.getUrlWithQuery()); appView.clearView(); appView.invalidate(); } } public void show404Page(String failingUrl) { try { InputStream is = getResources().openRawResource(R.raw.error404); String html = IOUtils.toString(is); html = html.replaceFirst("url_place_holder", UrlUtil.cutHostInUri(failingUrl)); html = html.replaceFirst("back_button_text", getString(R.string.back_button_text)); appView.loadDataWithBaseURL("file:///android_res/raw/error404.html", html, "text/html", "utf-8", null); } catch (IOException e) { MyLog.e(TAG, e.getMessage()); } } public void push404Page(String errorUrl) { Intent intent = new Intent(this, getClass()); intent.putExtra(URL_PARAM_NAME, "file:///android_asset/www/404/404.html"); intent.putExtra("error_url", errorUrl); TransitionParams params = TransitionParams.from(new JSONObject(), "none"); intent.putExtra(TRANSITION_PARAM_NAME, params); startActivity(intent); finish(); } public void pushPageWithIntent(String url, TransitionParams params) { if (isCapableForTransition) { Intent intent = createIntentForNextPage(url, params); isCapableForTransition = false; startActivity(intent); } } protected Intent createIntentForNextPage(String url, TransitionParams params) { Intent intent = new Intent(this, getClass()); intent.putExtra(URL_PARAM_NAME, UrlUtil.getResolvedUrl(url)); if (params != null) { intent.putExtra(TRANSITION_PARAM_NAME, params); } return intent; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { MyLog.d(TAG, "debug - onKeyDown"); if (keyCode == KeyEvent.KEYCODE_BACK) { if (uiBuilderResult != null && uiBuilderResult.eventer.hasOnTapBackButtonAction()) { MyLog.d(TAG, "debug - Run backButtonEventer.onTapBackButtonAction()"); uiBuilderResult.eventer.onTapBackButton(); } else if (uiBuilderResult != null && uiBuilderResult.backButtonEventer != null) { MyLog.d(TAG, "debug - Run backButtonEventer.onTap()"); uiBuilderResult.backButtonEventer.onTap(); } else { MyLog.d(TAG, "debug - Run popPage()"); popPage(); } return true; } return false; } public void pushPageAsync(String relativePath, final TransitionParams params) { final String url = getCurrentUriWithoutQuery() + "/../" + relativePath; BenchmarkTimer.start(); BenchmarkTimer.mark("pushPageAsync"); handler.postAtFrontOfQueue(new Runnable() { @Override public void run() { BenchmarkTimer.mark("monaca.pushPageAsync.run"); pushPageWithIntent(url, params); } }); } public void popPage() { int pageNum = MonacaApplication.getPages().size(); finish(); if (pageNum > 1) { // dirty fix for android4's strange bug if (transitionParams.animationType == TransitionParams.TransitionAnimationType.MODAL) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_dialog_close_enter, mobi.monaca.framework.psedo.R.anim.monaca_dialog_close_exit); } else if (transitionParams.animationType == TransitionParams.TransitionAnimationType.TRANSIT) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_slide_close_enter, mobi.monaca.framework.psedo.R.anim.monaca_slide_close_exit); } else if (transitionParams.animationType == TransitionParams.TransitionAnimationType.NONE) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_none, mobi.monaca.framework.psedo.R.anim.monaca_none); } } } public void _popPage() { int pageNum = MonacaApplication.getPages().size(); finish(); if (pageNum > 1) { // dirty fix for android4's strange bug overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_slide_close_enter, mobi.monaca.framework.psedo.R.anim.monaca_slide_close_exit); } } public void dismissPage() { int pageNum = MonacaApplication.getPages().size(); finish(); if (pageNum > 1) { overridePendingTransition(mobi.monaca.framework.psedo.R.anim.monaca_dialog_close_enter, mobi.monaca.framework.psedo.R.anim.monaca_dialog_close_exit); } } public void popPageAsync(final TransitionParams params) { handler.postAtFrontOfQueue(new Runnable() { @Override public void run() { if (params.animationType == TransitionParams.TransitionAnimationType.POP) { _popPage(); } else if (params.animationType == TransitionParams.TransitionAnimationType.DISMISS) { dismissPage(); } else { _popPage(); } } }); } public void goHomeAsync(JSONObject options) { final String homeUrl = getHomeUrl(options); MyLog.v(TAG, "homeurl:" + homeUrl); handler.post(new Runnable() { @Override public void run() { int numPages = MonacaApplication.getPages().size(); for(int i=numPages -1; i>0; i--){ MonacaPageActivity page = MonacaApplication.getPages().get(i); page.finish(); } } }); } protected WebViewClient createWebViewClient(String url, MonacaPageActivity page, CordovaWebView webView) { MonacaPageGingerbreadWebViewClient client = null; if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 11) { client = new MonacaPageGingerbreadWebViewClient(url, page, webView); } else { client = new MonacaPageHoneyCombWebViewClient(url, page, webView); } return client; } protected String getHomeUrl(JSONObject options) { if (options == null) { return "file:///android_asset/www/index.html"; } return options.optString("url", "").equals("") ? "file:///android_asset/www/index.html" : getCurrentUriWithoutQuery() + "/../" + options.optString("url"); } @Override protected void onStop() { super.onStop(); unloadBackground(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); MyLog.d(getClass().getSimpleName(), "onConfigurationChanged()"); // handling orieantation change for background image. if (background != null) { loadBackground(newConfig); setupBackground(); if (background != null) { background.invalidateSelf(); } } uiContext.fireOnRotateListeners(newConfig.orientation); appView.clearView(); appView.invalidate(); Display display = getWindowManager().getDefaultDisplay(); MyLog.d(getClass().getSimpleName(), "metrics width: " + display.getWidth() + ", height: " + display.getHeight()); } /* * Called from WebViewClient -> can be used in DeubggerPageActivity to * publish log message */ public void onLoadResource(WebView view, String url) { } public MonacaURI getCurrentMonacaUri() { return currentMonacaUri; } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { } public String getCurrentUriWithoutQuery() { return currentMonacaUri.getUrlWithoutQuery(); } /** * update uri and currentMonacaURI * @param uri */ public void setCurrentUri(String uri) { currentMonacaUri = new MonacaURI(uri); } }