blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
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
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
8d1f07fc9519c26056369da183123830ee7b0f56
a7bd32eac5b9923256ab273a4d1be5bc1871ab97
/ATM livro java como programar deitel/src/Transaction.java
85a799d804e6e520729f9b6051ed94d53f9a7cf6
[]
no_license
rogertecnic/workspace-java
e17f0ac604fb7a48b48e2652d2781113922ccef1
d626d62f082fbf3683f9cab29dcab50e42e1ed8f
refs/heads/master
2020-07-02T14:27:38.262840
2017-05-06T01:07:14
2017-05-06T01:07:14
74,300,014
0
0
null
null
null
null
UTF-8
Java
false
false
2,246
java
// Transaction.java // Abstract superclass Transaction represents an ATM transaction public abstract class Transaction { private int accountNumber; // indicates account involved private Screen screen; // ATM's screen private BankDatabase bankDatabase; // account info database // Transaction constructor invoked by subclasses using super() public Transaction( int userAccountNumber, Screen atmScreen, BankDatabase atmBankDatabase ) { accountNumber = userAccountNumber; screen = atmScreen; bankDatabase = atmBankDatabase; } // end Transaction constructor // return account number public int getAccountNumber() { return accountNumber; } // end method getAccountNumber // return reference to screen public Screen getScreen() { return screen; } // end method getScreen // return reference to bank database public BankDatabase getBankDatabase() { return bankDatabase; } // end method getBankDatabase // perform the transaction (overridden by each subclass) abstract public void execute(); } // end class Transaction /************************************************************************** * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
[ "roger_tecnic@hotmail.com" ]
roger_tecnic@hotmail.com
ef9f5dce3bb64710005b491a61755e6165d444f5
814169b683b88f1b7498f1edf530a8d1bec2971f
/mall-search/src/main/java/com/bootx/mall/config/ElasticSearchConfig.java
3352bddef2a99219af39d31d557d5bf2b42c034b
[]
no_license
springwindyike/mall-auth
fe7f216c7241d8fd9247344e40503f7bc79fe494
3995d258955ecc3efbccbb22ef4204d148ec3206
refs/heads/master
2022-10-20T15:12:19.329363
2020-07-05T13:04:29
2020-07-05T13:04:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
833
java
package com.bootx.mall.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticSearchConfig { public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); COMMON_OPTIONS = builder.build(); } @Bean public RestHighLevelClient restHighLevelClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"))); return client; } }
[ "a12345678" ]
a12345678
17afc8a5b44523a307caf2feeaa45af0bd9c5072
19e6ca9b34a063985f417ecf02e60a08fa56d50d
/service-azure/src/main/java/com/example/demo-azure-spring-cloud/SourceExample.java
7eef2c10f2365ccac7d6da4616331e23e947a35a
[]
no_license
fabianorosa1/demo-azure-spring-cloud
5bafe27f1985512a3bbbfa5e1f4f5b2891476a0c
2461c18b4150f6e2c15985f45c121027c9b7f044
refs/heads/master
2020-04-06T18:19:58.423106
2018-11-15T10:36:17
2018-11-15T10:36:17
157,694,313
0
0
null
null
null
null
UTF-8
Java
false
false
879
java
package com.example.demo-azure-spring-cloud; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Source; import org.springframework.messaging.support.GenericMessage; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController @RequestMapping("/eventhub") @EnableBinding(Source.class) public class SourceExample { @Autowired private Source source; @PostMapping("/messages") public String postMessage(@RequestParam String message) { this.source.output().send(new GenericMessage<>(message)); return message; } }
[ "fabianorosa1@gmail.com" ]
fabianorosa1@gmail.com
834f245b3cd69787c5927a91a19c0e2e3aa182b2
63330b7c9232b828a91dee24044353c082e83658
/Java_023_ScoreManager/src/com/callor/score/files/FileReader_01.java
03e705122aae11b6bd92ed64a1263eaf0c70eb46
[]
no_license
ksoyoun02/Biz_2021_01_403_java
0dbc110eaff86b25b1a0d4e4ad3b9a4b22ea8a68
d37e9511d943bec308f77fab81c9ac876307fd8a
refs/heads/master
2023-06-07T17:16:34.789399
2021-06-27T07:40:49
2021-06-27T07:40:49
334,835,412
0
0
null
null
null
null
UTF-8
Java
false
false
2,338
java
package com.callor.score.files; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.callor.score.model.ScoreVO; import com.callor.score.values.Values; public class FileReader_01 { public static void main(String[] args) { List<ScoreVO> scoreList = new ArrayList<ScoreVO>(); List<String> strLines = new ArrayList<String>(); String scoreFile = "src/com/callor/score/files/nums_rnd.txt"; FileReader fileReader = null; BufferedReader buffer = null; try { fileReader = new FileReader(scoreFile); buffer = new BufferedReader(fileReader); while (true) { String str = buffer.readLine(); if (str == null) { break; } strLines.add(str); } buffer.close(); fileReader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(String str : strLines) { String[] scores = str.split(":"); ScoreVO scoreVO = new ScoreVO(); scoreVO.setKor(Integer.valueOf(scores[0])); scoreVO.setEng(Integer.valueOf(scores[1])); scoreVO.setMath(Integer.valueOf(scores[2])); scoreVO.setHistory(Integer.valueOf(scores[3])); scoreVO.setMusic(Integer.valueOf(scores[4])); scoreList.add(scoreVO); } for(ScoreVO vo : scoreList) { int sum = vo.getKor(); sum += vo.getEng(); sum += vo.getMath(); sum += vo.getMusic(); sum += vo.getHistory(); float avg = (float)sum / 5; vo.setTotal(sum); vo.setAvg(avg); } System.out.println(Values.dLine); System.out.println("순번\t국어\t영어\t수학\t음악\t국사\t총점\t평균"); System.out.println(Values.sLine); int nSize = scoreList.size(); for(int i = 0 ; i < nSize; i++) { ScoreVO vo = scoreList.get(i); int num = i + 1; System.out.print(num + "\t"); System.out.print(vo.getKor() + "\t"); System.out.print(vo.getEng() + "\t"); System.out.print(vo.getMath() + "\t"); System.out.print(vo.getMusic() + "\t"); System.out.print(vo.getHistory() + "\t"); System.out.print(vo.getTotal() + "\t"); System.out.print(vo.getAvg() + "\n"); } System.out.println(Values.dLine); } }
[ "ksoyoun95@naver.com" ]
ksoyoun95@naver.com
9cd4378f909362bf2d78c2443bbfeeefb113a02b
896cca57024190fc3fbb62f2bd0188fff24b24c8
/2.7.x/choicemaker-cm/choicemaker-modeling/com.choicemaker.cm.matching.en.us.train/src/main/java/com/choicemaker/cm/matching/en/us/train/name/NameGrammarTrainer.java
27f0ffbdb61b4227ff349e8e9fe7f2e56138e195
[]
no_license
fgregg/cm
0d4f50f92fde2a0bed465f2bec8eb7f2fad8362c
c0ab489285938f14cdf0a6ed64bbda9ac4d04532
refs/heads/master
2021-01-10T11:27:00.663407
2015-08-11T19:35:00
2015-08-11T19:35:00
55,807,163
0
1
null
null
null
null
UTF-8
Java
false
false
1,937
java
/* * Copyright (c) 2001, 2009 ChoiceMaker Technologies, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License * v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * ChoiceMaker Technologies, Inc. - initial API and implementation */ package com.choicemaker.cm.matching.en.us.train.name; import java.io.FileInputStream; import com.choicemaker.cm.core.util.CommandLineArguments; import com.choicemaker.cm.matching.cfg.ContextFreeGrammar; import com.choicemaker.cm.matching.cfg.SymbolFactory; import com.choicemaker.cm.matching.cfg.train.GrammarTrainer; import com.choicemaker.cm.matching.cfg.train.ParsedDataReader; import com.choicemaker.cm.matching.cfg.xmlconf.ContextFreeGrammarXmlConf; import com.choicemaker.cm.matching.en.us.name.NameSymbolFactory; import com.choicemaker.e2.CMPlatformRunnable; /** * . * * @author Adam Winkel * @version $Revision: 1.1.1.1 $ $Date: 2009/05/03 16:03:04 $ */ public class NameGrammarTrainer implements CMPlatformRunnable { public Object run(Object argObj) throws Exception { String[] args = CommandLineArguments.eclipseArgsMapper(argObj); if (args.length < 2) { System.err.println("Need at least two arguments: grammar file and parsed data file(s)"); System.exit(1); } String grammarFileName = args[0]; SymbolFactory factory = new NameSymbolFactory(); ContextFreeGrammar grammar = ContextFreeGrammarXmlConf.readFromFile(grammarFileName, factory); GrammarTrainer trainer = new GrammarTrainer(grammar); for (int i = 1; i < args.length; i++) { FileInputStream is = new FileInputStream(args[i]); ParsedDataReader rdr = new ParsedDataReader(is, factory, grammar); trainer.readParseTrees(rdr); is.close(); } trainer.writeAll(); return null; } }
[ "rick@rphall.com" ]
rick@rphall.com
ae80460a1f5a3a5abda8976a2413a425365271e7
fc459675a329244b920bdc37375f72286c0f3d2e
/src/main/java/com/merlin/merlinsblog/po/Type.java
dba4208486bdfeb2f6bc5399313729aabd331734
[ "MIT" ]
permissive
DustMerlin/MerlinsBlog
2a6f8fa8194b9400493086b718af3df86ca17f81
48437c1dbc723b4ef1eb0b4d369feba1ed377cc0
refs/heads/master
2023-02-12T09:39:15.858972
2021-01-08T09:13:03
2021-01-08T09:13:03
295,615,783
1
0
null
2020-09-23T08:27:34
2020-09-15T04:38:30
Java
UTF-8
Java
false
false
2,107
java
package com.merlin.merlinsblog.po; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.util.ArrayList; import java.util.List; //import org.hibernate.validator.constraints.NotBlank; //此处的校验功能已废弃,需要使用以下依赖才能完成相应的功能 //import javax.validation.constraints.NotBlank; 使用这种写法 //博客地址 caorui.net/blog/111848631920754688.html //经常查找文档发现,validation-api 只是一套标准, //而具体是实现是依赖 hibernate-validator 库,所以在引用 validation-api 库的前提下, //还要引用 hibernate-validator 库才能正常使用,具体的 pom 信息如下 //<dependency> //<groupId>javax.validation</groupId> //<artifactId>validation-api</artifactId> //<version>2.0.1.Final</version> //</dependency> //<dependency> //<groupId>org.hibernate</groupId> //<artifactId>hibernate-validator</artifactId> //<version>6.0.13.Final</version> //</dependency> @Entity @Table(name="type") public class Type { @Id @GeneratedValue private Long id; @NotBlank(message = "分类名不能为空") private String name; // 此处一(类型)对多(博客),在一端使用mappedBy = "type",type被维护,blog 维护 @OneToMany(mappedBy = "type") private List<Blog> blogs = new ArrayList<>(); public Type() { } public Type(Long id, String name, List<Blog> blogs) { this.id = id; this.name = name; this.blogs = blogs; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Blog> getBlogs() { return blogs; } public void setBlogs(List<Blog> blogs) { this.blogs = blogs; } @Override public String toString() { return "Type{" + "id=" + id + ", name='" + name + '\'' + ", blogs=" + blogs + '}'; } }
[ "1723978237@qq.com" ]
1723978237@qq.com
7df511032924ab6c1ac712203a2c386205d85728
1dee501f84622ef0d515e0b32b064320f5649792
/biz.db/src/main/java/com/leeon/biz/db/module/servicelocator/AbstractServiceLocator.java
112b1b74cd547d0a09497a9b077787d83d69a8a7
[]
no_license
lunatiKoid/spring-mvc-ibatis-web
37ccf0c6b106377174ad9895c0feadc06ad2deb4
53e2dabc457a003f17d51f06a27231fa1d9981b8
refs/heads/master
2021-01-10T07:38:35.633959
2015-06-07T02:35:39
2015-06-07T02:35:39
36,935,938
0
0
null
null
null
null
UTF-8
Java
false
false
936
java
package com.leeon.biz.db.module.servicelocator; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by liang.yaol on 5/1/15. */ public class AbstractServiceLocator { private static String servicesLocation = "classpath:spring_services_locator.xml"; protected static BeanFactory beanFactory; private static Exception initException; static { try { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(servicesLocation); beanFactory = applicationContext; } catch (Exception e) { e.printStackTrace(); initException = e; } } protected static BeanFactory getBeanFactory() { return beanFactory; } }
[ "liang.yaol@alibaba-inc.com" ]
liang.yaol@alibaba-inc.com
a9809ed622a07eeb0678a1d8fa75046171920c6b
c97dffb0478522877f1a1c188a823296c75e1b87
/self_spring_read_demo/src/main/java/com/learn/springread/springevent/UserRegisterEvent.java
41ab06fefe96651da10d6291c4abf0e229d0656e
[]
no_license
zoro000/2021_learn_project
1e728a30b381dc3af104631d90e5466abc665962
464c58e19fddaa1860880f3c0cfc3e8086fd9b4d
refs/heads/master
2023-07-14T00:55:52.997305
2021-08-21T13:18:55
2021-08-21T13:18:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
509
java
package com.learn.springread.springevent; import org.springframework.context.ApplicationEvent; /** * autor:liman * createtime:2021/6/6 * comment: */ public class UserRegisterEvent extends ApplicationEvent { /** * Create a new {@code ApplicationEvent}. * * @param source the object on which the event initially occurred or with * which the event is associated (never {@code null}) */ public UserRegisterEvent(Object source) { super(source); } }
[ "657271181@qq.com" ]
657271181@qq.com
7e8265ee3d103946f2f5dda1e5a2b2cd01e38564
5b4553efa42bfc8992795cbf5de5eda7a876701b
/src/main/java/org/killbill/billing/plugin/dwolla/util/JsonHelper.java
fc56b80b8cefa9467e7f6472f77d3243735016ef
[ "Apache-2.0" ]
permissive
matias-aguero-hs/killbill-dwolla-plugin
dfef27e9e21128e0523a980d9de21d5c463b6d44
c8548430f32de0c743cd7edfe6988002bea5a42c
refs/heads/master
2020-05-30T13:56:01.690884
2016-10-11T18:01:45
2016-10-11T18:01:45
66,856,403
0
0
null
2016-08-29T15:35:09
2016-08-29T15:35:09
null
UTF-8
Java
false
false
1,550
java
/* * Copyright 2016 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.plugin.dwolla.util; import com.fasterxml.jackson.databind.ObjectMapper; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; public class JsonHelper { /** * Convert servlet request (in json string format) into a java object * * @param jsonString * @param clazz * @return */ public static <T> T getObjectFromRequest(final String jsonString, final Class<T> clazz) throws PaymentPluginApiException { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, clazz); } catch (Exception e) { throw new PaymentPluginApiException("Exception during generation of the Object from JSON", e.getCause()); } } public static String getIdFromUrl(final String url) { return url.substring(url.lastIndexOf("/") + 1); } }
[ "matias.aguero@hootsuite.com" ]
matias.aguero@hootsuite.com
0ed76af0db04d587dd937b3151829b6c73fc5743
685e3097d073a5a948e26f15936897a126cfabdd
/FindAnagramMappings/Solution.java
0d0921cc1da4d7f00213f98c456e6429146824d7
[]
no_license
flyPisces/LeetCodeSolution
2ae0b48c149bb1eb20c180647feaabd392120e4e
e4399fc8791491082934b634a60caa2a1e350fbd
refs/heads/master
2021-01-10T22:36:23.241283
2020-08-22T07:01:38
2020-08-22T07:01:38
69,706,033
1
0
null
null
null
null
UTF-8
Java
false
false
1,056
java
package FindAnagramMappings; import java.util.*; /** * Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by * randomizing the order of the elements in A. We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j. These lists A and B may contain duplicates. If there are multiple answers, output any of them. For example, given A = [12, 28, 46, 32, 50] B = [50, 12, 32, 46, 28] We should return [1, 4, 3, 2, 0] as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on. */ public class Solution { public int[] anagramMappings(int[] A, int[] B) { Map<Integer, Integer> mapping = new HashMap<>(); for (int i = 0;i < B.length;++ i) { mapping.put(B[i], i); } int[] results = new int[A.length]; for (int i = 0;i < A.length;++ i) { results[i] = mapping.get(A[i]); } return results; } }
[ "!Pat381mort686" ]
!Pat381mort686
67dbc5cf3b61f9f66e309c0394f30deb9f576748
13dd186b1a87191c91e6f16375e9fa60962e2037
/server/sundeinfo.core/src/main/java/com/sundeinfo/core/token/Token.java
5f3be98df4cf680bfb5730f35609dece96d1dd4a
[]
no_license
libiao1205/WenXin
b019233e0eca4be5643491a85a085ea5fa3a09e5
ed7dc18f10a69bb04cb4eebf0a2211c018fb5f6f
refs/heads/master
2022-11-30T12:42:06.616151
2020-08-18T10:36:28
2020-08-18T10:36:28
286,409,937
0
1
null
null
null
null
UTF-8
Java
false
false
307
java
package com.sundeinfo.core.token; import org.springframework.web.bind.annotation.Mapping; import java.lang.annotation.*; @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Mapping public @interface Token { TokenType[] types() default {TokenType.ALL}; }
[ "15137327109@163.com" ]
15137327109@163.com
fda0db885f98c1a95dc1cfa8e4de666ec0271915
dc0b8d47d0f59f3d2c7bab3a03573ddb388440cf
/src/main/java/pl/ioprojekt/wypozyczalniarowerow/service/BikeService.java
63c1562aa9e6d0e6cc2a70f3456db43c8da15e58
[]
no_license
OskWal048/wypozyczalniarowerow
5a714a4eb55f6dfdb3ab1c435be8b5b2b33a879d
e6c98d2f26ded56238487a938b0ed9773027eba6
refs/heads/master
2023-03-08T02:24:05.512972
2021-02-23T11:20:35
2021-02-23T11:20:35
321,037,808
1
0
null
null
null
null
UTF-8
Java
false
false
715
java
package pl.ioprojekt.wypozyczalniarowerow.service; import org.javatuples.Pair; import pl.ioprojekt.wypozyczalniarowerow.entity.Bike; import java.time.LocalDate; import java.util.List; public interface BikeService { List<Bike> findAll(); Bike findById(int id); void save(Bike bike); List<String> findColumnValues(String columnName); List<Bike> findFiltered(String brand, String color, String type); List<Bike> findFiltered(String brand, String color, String type, LocalDate date1, LocalDate date2); List<Pair<LocalDate, LocalDate>> findReservations(int id); List<Bike> filterByUsername(List<Bike> list, String username); List<Bike> filterUnusable(List<Bike> list); }
[ "oskar2walczak@gmail.com" ]
oskar2walczak@gmail.com
bee81679f62d11ab0f8937af74749d01efbbf8f9
19e0171e2f512d3d6e64497ce818872da3b7c78e
/source/server/nourriture-web/src/main/java/edu/bjtu/nourriture_web/restfulservice/CustomerRestfulService.java
2be6506a5160f907dc1dfaba300db3828a521ea1
[]
no_license
FreeDao/nourriture
6639ce9190f29ecef81b833a3bdd4a7492c81046
3075e2a117272b51adb1a4f5239635035d45888c
refs/heads/master
2021-01-18T09:18:05.921836
2014-12-19T07:47:19
2014-12-19T07:47:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
19,190
java
package edu.bjtu.nourriture_web.restfulservice; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import edu.bjtu.nourriture_web.bean.Customer; import edu.bjtu.nourriture_web.common.JsonUtil; import edu.bjtu.nourriture_web.common.RestfulServiceUtil; import edu.bjtu.nourriture_web.idao.ICustomerDao; import edu.bjtu.nourriture_web.idao.IFlavourDao; import edu.bjtu.nourriture_web.idao.IFoodCategoryDao; import edu.bjtu.nourriture_web.idao.IRecipeCategoryDao; @Path("customer") @Produces("application/json;charset=UTF-8") public class CustomerRestfulService { //dao private ICustomerDao customerDao; private IFlavourDao flavourDao; private IFoodCategoryDao foodCategoryDao; private IRecipeCategoryDao recipeCategoryDao; //direct children links private JsonArray customerChildrenLinks; private JsonArray searchChildrenLinks; private JsonArray loginChildrenLinks; private JsonArray idChildrenLinks; private JsonArray interestChildrenLinks; //get set method for spring IOC public ICustomerDao getCustomerDao() { return customerDao; } public void setCustomerDao(ICustomerDao customerDao) { this.customerDao = customerDao; } public IFlavourDao getFlavourDao() { return flavourDao; } public void setFlavourDao(IFlavourDao flavourDao) { this.flavourDao = flavourDao; } public IFoodCategoryDao getFoodCategoryDao() { return foodCategoryDao; } public void setFoodCategoryDao(IFoodCategoryDao foodCategoryDao) { this.foodCategoryDao = foodCategoryDao; } public IRecipeCategoryDao getRecipeCategoryDao() { return recipeCategoryDao; } public void setRecipeCategoryDao(IRecipeCategoryDao recipeCategoryDao) { this.recipeCategoryDao = recipeCategoryDao; } { //initialize direct children links customerChildrenLinks = new JsonArray(); RestfulServiceUtil.addChildrenLinks(customerChildrenLinks, "search customer", "/search", "GET"); RestfulServiceUtil.addChildrenLinks(customerChildrenLinks, "login", "/login", "GET"); RestfulServiceUtil.addChildrenLinks(customerChildrenLinks, "get customer according to id", "/{id}", "GET"); RestfulServiceUtil.addChildrenLinks(customerChildrenLinks, "update customer according to id", "/{id}", "PUT"); searchChildrenLinks = new JsonArray(); loginChildrenLinks = new JsonArray(); idChildrenLinks = new JsonArray(); RestfulServiceUtil.addChildrenLinks(idChildrenLinks, "get customer interests", "/{interest}", "GET"); RestfulServiceUtil.addChildrenLinks(idChildrenLinks, "add a customer interest", "/{interest}", "POST"); RestfulServiceUtil.addChildrenLinks(idChildrenLinks, "delete a customer interest", "/{interest}", "DELETE"); interestChildrenLinks = new JsonArray(); } /** add a customer **/ @POST public String addCustomer(@FormParam("name") String name,@FormParam("password") String password, @FormParam("sex") int sex,@FormParam("age") int age){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_USER_EXIST = -1; final int ERROR_CODE_BAD_PARAM = -2; //check request parameters if(name == null || name.equals("") || password == null || password.equals("") || (sex != 0 && sex != 1) || age < 0){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", customerChildrenLinks); return ret.toString(); } //check if user name is already exist if(customerDao.isNameExist(name)){ ret.addProperty("errorCode", ERROR_CODE_USER_EXIST); ret.add("links", customerChildrenLinks); return ret.toString(); } //add one row to database Customer customer = new Customer(); customer.setName(name); customer.setPassword(password); customer.setSex(sex); customer.setAge(age); ret.addProperty("id", customerDao.add(customer)); ret.add("links", customerChildrenLinks); return ret.toString(); } /** search customer by name **/ @GET @Path("search") public String searchByName(@QueryParam("name") String name){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_NO_RESULT = -1; final int ERROR_CODE_BAD_PARAM = -2; //check request parameters if(name == null || name.equals("")){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", searchChildrenLinks); return ret.toString(); } //search in the database List<Customer> list = customerDao.searchByName(name); if(list.isEmpty()){ ret.addProperty("errorCode", ERROR_CODE_NO_RESULT); ret.add("links", searchChildrenLinks); return ret.toString(); } JsonArray customers = new JsonArray(); for(Customer customer : list){ JsonObject jCustomer = transformCustomer(customer); customers.add(jCustomer); } ret.add("customers", customers); ret.add("links", searchChildrenLinks); return ret.toString(); } /** login by name and password **/ @GET @Path("login") public String login(@QueryParam("name")String name,@QueryParam("password") String password){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_USER_NOT_EXIST = -1; final int ERROR_CODE_PASSWORD_NOT_VALIDATED = -2; final int ERROR_CODE_BAD_PARAM = -3; //check request parameters if(name == null || name.equals("") || password == null || password.equals("")){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", loginChildrenLinks); return ret.toString(); } //check if user name is exsit if(!customerDao.isNameExist(name)){ ret.addProperty("errorCode", ERROR_CODE_USER_NOT_EXIST); ret.add("links", loginChildrenLinks); return ret.toString(); } //check password int loginResult = customerDao.login(name, password); if(loginResult == -1){ ret.addProperty("errorCode", ERROR_CODE_PASSWORD_NOT_VALIDATED); ret.add("links", loginChildrenLinks); return ret.toString(); } ret.addProperty("id", loginResult); ret.add("links", loginChildrenLinks); return ret.toString(); } /** get detail information about a customer by id **/ @GET @Path("{id}") public String getById(@PathParam("id") int id){ JsonObject ret = new JsonObject(); //select from database Customer customer = customerDao.getById(id); if(customer != null) { JsonObject jCustomer = transformCustomer(customer); ret.add("customer", jCustomer); } ret.add("links", idChildrenLinks); return ret.toString(); } /** update customer basic information **/ @PUT @Path("{id}") public String updateCustomer(@PathParam("id") int id, @FormParam("age") @DefaultValue("-1") int age, @FormParam("sex") @DefaultValue("-1") int sex){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_USER_NOT_EXIST = -1; final int ERROR_CODE_BAD_PARAM = -2; //check request parameters if((sex != 0 && sex != 1) && age < 0){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", idChildrenLinks); return ret.toString(); } //check if user exsit Customer customer = customerDao.getById(id); if(customer == null){ ret.addProperty("errorCode", ERROR_CODE_USER_NOT_EXIST); ret.add("links", idChildrenLinks); return ret.toString(); } if(age >= 0) customer.setAge(age); if(sex == 0 || sex == 1) customer.setSex(sex); customerDao.update(customer); ret.addProperty("result", 0); ret.add("links", idChildrenLinks); return ret.toString(); } /** get insterests **/ @GET @Path("{id}/{interest}") public String getInterests(@PathParam("id") int id,@PathParam("interest") String interest){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_USER_NOT_EXIST = -1; final int ERROR_CODE_INTEREST_NOT_SET = -2; final int ERROR_CODE_BAD_PARAM = -3; //check request parameters if(id <= 0 || interest == null || interest.equals("") || (!interest.equals("flavour") && !interest.equals("foodCategory") && !interest.equals("recipeCategory"))){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if user exsit Customer customer = customerDao.getById(id); if(customer == null){ ret.addProperty("errorCode", ERROR_CODE_USER_NOT_EXIST); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if interest is not setted if(interest.equals("flavour")){ String sIds = customer.getInterestFlavourIds(); if(sIds == null || sIds.equals("")){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } else { JsonArray flavours = new JsonArray(); String[] ids = sIds.split(","); for(String sid : ids){ int fId = Integer.parseInt(sid); JsonObject flavour = JsonUtil.beanToJson(flavourDao.getById(fId)); flavour.remove("topFlavour"); flavour.remove("superiorFlavourId"); flavours.add(flavour); } ret.add("flavours", flavours); ret.add("links", interestChildrenLinks); return ret.toString(); } } else if(interest.equals("foodCategory")){ String sIds = customer.getInterestFoodCategoryIds(); if(sIds == null || sIds.equals("")){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } else { JsonArray foodCategorys = new JsonArray(); String[] ids = sIds.split(","); for(String sid : ids){ int fId = Integer.parseInt(sid); JsonObject foodCategory = JsonUtil.beanToJson(foodCategoryDao.getById(fId)); foodCategory.remove("topCategory"); foodCategory.remove("superiorCategoryId"); foodCategorys.add(foodCategory); } ret.add("foodCategorys", foodCategorys); ret.add("links", interestChildrenLinks); return ret.toString(); } } else { String sIds = customer.getInterestRecipeCategoryIds(); if(sIds == null || sIds.equals("")){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } else { JsonArray recipeCategorys = new JsonArray(); String[] ids = sIds.split(","); for(String sid : ids){ int fId = Integer.parseInt(sid); JsonObject recipeCategory = JsonUtil.beanToJson(recipeCategoryDao.getById(fId)); recipeCategory.remove("topCategory"); recipeCategory.remove("superiorCategoryId"); recipeCategorys.add(recipeCategory); } ret.add("foodCategorys", recipeCategorys); ret.add("links", interestChildrenLinks); return ret.toString(); } } } /** add a interest **/ @POST @Path("{id}/{interest}") public String addInterest(@PathParam("id") int id,@PathParam("interest") String interest, @FormParam("id") int InId){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_USER_NOT_EXIST = -1; final int ERROR_CODE_INTEREST_NOT_EXIST = -2; final int ERROR_CODE_INTEREST_ALREADY_SET = -3; final int ERROR_CODE_BAD_PARAM = -4; //check request parameters if(id <= 0 || interest == null || interest.equals("") || (!interest.equals("flavour") && !interest.equals("foodCategory") && !interest.equals("recipeCategory")) || InId < 0){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if user exsit Customer customer = customerDao.getById(id); if(customer == null){ ret.addProperty("errorCode", ERROR_CODE_USER_NOT_EXIST); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if interest exsit if((interest.equals("flavour") && flavourDao.getById(InId) == null) || (interest.equals("foodCategory") && foodCategoryDao.getById(InId) == null) || (interest.equals("recipeCategory") && recipeCategoryDao.getById(InId) == null)){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_EXIST); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if interest is already setted if(interest.equals("flavour")){ String sIds = customer.getInterestFlavourIds(); if(sIds != null){ if(sIds.contains(String.valueOf(InId))){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_ALREADY_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } } } else if(interest.equals("foodCategory")){ String sIds = customer.getInterestFoodCategoryIds(); if(sIds != null){ if(sIds.contains(String.valueOf(InId))){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_ALREADY_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } } } else { String sIds = customer.getInterestRecipeCategoryIds(); if(sIds != null){ if(sIds.contains(String.valueOf(InId))){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_ALREADY_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } } } //add interest to database if(interest.equals("flavour")){ String sIds = customer.getInterestFlavourIds(); if(sIds == null || sIds.equals("")) sIds = String.valueOf(InId); else sIds += ("," + InId); customer.setInterestFlavourIds(sIds); } else if(interest.equals("foodCategory")){ String sIds = customer.getInterestFoodCategoryIds(); if(sIds == null || sIds.equals("")) sIds = String.valueOf(InId); else sIds += ("," + InId); customer.setInterestFoodCategoryIds(sIds); } else { String sIds = customer.getInterestRecipeCategoryIds(); if(sIds == null || sIds.equals("")) sIds = String.valueOf(InId); else sIds += ("," + InId); customer.setInterestRecipeCategoryIds(sIds); } customerDao.update(customer); ret.addProperty("result", 0); ret.add("links", interestChildrenLinks); return ret.toString(); } /** delete a interest **/ @DELETE @Path("{id}/{interest}") public String deleteInterest(@PathParam("id") int id,@PathParam("interest") String interest, @FormParam("id") int InId){ JsonObject ret = new JsonObject(); //define error code final int ERROR_CODE_USER_NOT_EXIST = -1; final int ERROR_CODE_INTEREST_NOT_EXIST = -2; final int ERROR_CODE_INTEREST_NOT_SET = -3; final int ERROR_CODE_BAD_PARAM = -4; //check request parameters if(id <= 0 || interest == null || interest.equals("") || (!interest.equals("flavour") && !interest.equals("foodCategory") && !interest.equals("recipeCategory")) || InId < 0){ ret.addProperty("errorCode", ERROR_CODE_BAD_PARAM); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if user exsit Customer customer = customerDao.getById(id); if(customer == null){ ret.addProperty("errorCode", ERROR_CODE_USER_NOT_EXIST); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if interest exsit if((interest.equals("flavour") && flavourDao.getById(InId) == null) || (interest.equals("foodCategory") && foodCategoryDao.getById(InId) == null) || (interest.equals("recipeCategory") && recipeCategoryDao.getById(InId) == null)){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_EXIST); ret.add("links", interestChildrenLinks); return ret.toString(); } //check if interest is already setted if(interest.equals("flavour")){ String sIds = customer.getInterestFlavourIds(); if(sIds == null || sIds.equals("") || !sIds.contains(String.valueOf(InId))){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } } else if(interest.equals("foodCategory")){ String sIds = customer.getInterestFoodCategoryIds(); if(sIds == null || sIds.equals("") || !sIds.contains(String.valueOf(InId))){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } } else { String sIds = customer.getInterestRecipeCategoryIds(); if(sIds == null || sIds.equals("") || !sIds.contains(String.valueOf(InId))){ ret.addProperty("errorCode", ERROR_CODE_INTEREST_NOT_SET); ret.add("links", interestChildrenLinks); return ret.toString(); } } //delete interest to database if(interest.equals("flavour")){ String sIds = customer.getInterestFlavourIds(); customer.setInterestFlavourIds(RestfulServiceUtil.deleteIdFromIdList(InId, sIds)); } else if(interest.equals("foodCategory")){ String sIds = customer.getInterestFoodCategoryIds(); customer.setInterestFoodCategoryIds(RestfulServiceUtil.deleteIdFromIdList(InId, sIds)); } else { String sIds = customer.getInterestRecipeCategoryIds(); customer.setInterestRecipeCategoryIds(RestfulServiceUtil.deleteIdFromIdList(InId, sIds)); } customerDao.update(customer); ret.addProperty("result", 0); ret.add("links", interestChildrenLinks); return ret.toString(); } /** * transform customer from bean to json,customer interest ids will be transformed to detail information * @param bean form of customer * @return json form of customer */ private JsonObject transformCustomer(Customer customer){ JsonObject jCustomer = JsonUtil.beanToJson(customer); //get flavour infomations String str = customer.getInterestFlavourIds(); JsonArray flavours = new JsonArray(); if(str != null && !str.equals("")) { String[] ids = str.split(","); for(String id : ids){ int fId = Integer.parseInt(id); JsonObject flavour = JsonUtil.beanToJson(flavourDao.getById(fId)); flavour.remove("topFlavour"); flavour.remove("superiorFlavourId"); flavours.add(flavour); } } jCustomer.remove("interestFlavourIds"); jCustomer.add("interestFlavours", flavours); //get food category informations str = customer.getInterestFoodCategoryIds(); JsonArray foodCategorys = new JsonArray(); if(str != null && !str.equals("")) { String[] ids = str.split(","); for(String id : ids){ int fId = Integer.parseInt(id); JsonObject foodCategory = JsonUtil.beanToJson(foodCategoryDao.getById(fId)); foodCategory.remove("topCategory"); foodCategory.remove("superiorCategoryId"); flavours.add(foodCategory); } } jCustomer.remove("interestFoodCategoryIds"); jCustomer.add("interestFoodCategorys", foodCategorys); //get food recipe informations str = customer.getInterestRecipeCategoryIds(); JsonArray recipeCategorys = new JsonArray(); if(str != null && !str.equals("")) { String[] ids = str.split(","); for(String id : ids){ int fId = Integer.parseInt(id); JsonObject recipeCategory = JsonUtil.beanToJson(recipeCategoryDao.getById(fId)); recipeCategory.remove("topCategory"); recipeCategory.remove("superiorCategoryId"); flavours.add(recipeCategory); } } jCustomer.remove("interestRecipeCategoryIds"); jCustomer.add("interestRecipeCategorys", recipeCategorys); return jCustomer; } }
[ "wanbabb1@126.com" ]
wanbabb1@126.com
ee4dffee968bfb052cb53c6a01c779ae31a9bc8a
1b422ba91dc8315ba0f6ecdcb5b4c96d6da37524
/src/com/jude/controller/TaskController.java
0ca8491323700e41b71bdffc8460e12d240770cb
[ "Apache-2.0" ]
permissive
hairlun/customer-visit-web
b02580196e97b746588c2a888685b2fc2463b794
b9200f78abe3a33710503c43af6211d524164221
refs/heads/master
2020-04-15T13:38:36.221967
2016-12-22T02:15:00
2016-12-22T02:15:00
59,732,623
0
0
null
null
null
null
UTF-8
Java
false
false
10,782
java
package com.jude.controller; import com.jude.entity.Customer; import com.jude.entity.CustomerManager; import com.jude.entity.RecordDetail; import com.jude.entity.Task; import com.jude.json.JSONObject; import com.jude.service.CustomerManagerService; import com.jude.service.CustomerService; import com.jude.service.TaskService; import com.jude.util.ExtJS; import com.jude.util.HttpUtils; import com.jude.util.IdUtil; import com.jude.util.PagingSet; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping({ "/task.do" }) public class TaskController { private static final Logger log = LoggerFactory.getLogger(TaskController.class); @Autowired private CustomerService customerService; @Autowired private CustomerManagerService managerService; @Autowired private TaskService taskService; private SimpleDateFormat sf; public TaskController() { this.sf = new SimpleDateFormat("yyyy年MM月dd日"); } @RequestMapping(params = { "action=forwardIndex" }) public String forwardIndex() { return "task/index.jsp"; } @RequestMapping(params = { "action=normal" }) @ResponseBody public JSONObject normalTask(HttpServletRequest request, HttpServletResponse response) throws ParseException { try { if ((LoginInfo.getUser(request) == null) || (!"admin".equals(LoginInfo.getUser(request).getUsername()))) { return ExtJS.ok("非admin用户不能发放任务!"); } Date start = this.sf.parse(request.getParameter("start")); Date end = this.sf.parse(request.getParameter("end")); if (start.after(end)) { return ExtJS.ok("起始时间不能大于任务完成时间!"); } List<Task> tasks = new ArrayList<Task>(); for (Customer customer : this.customerService.getCustomers(0, 1000000).getList()) { if (customer.getCustomerManager() == null) { continue; } Task task = new Task(); task.setContent(request.getParameter("content")); task.setCustomer(customer); task.setManager(customer.getCustomerManager()); task.setStart(start); task.setEnd(end); task.setId(IdUtil.getId()); tasks.add(task); } if (tasks.size() < 1) { return ExtJS.ok("无客户,请添加客户后重试!"); } List cs = new ArrayList(); Map map = HttpUtils.getRequestParam(request); Set<String> keySet = map.keySet(); for (String s : keySet) { if ((s.matches("^content.+")) && (!s.equals("content"))) { RecordDetail detail = new RecordDetail(); detail.setContent(map.get(s) + ""); cs.add(detail); } } this.taskService.addTask(tasks, cs); return ExtJS.ok("发放成功!"); } catch (Exception e) { log.error("error", e); } return ExtJS.ok("发放常规任务失败,请重试!"); } // @RequestMapping(params = { "action=indevi" }) // @ResponseBody // public JSONObject indeviTask(String mids, String content, HttpServletRequest request, // HttpServletResponse response) { // try { // if ((LoginInfo.getUser(request) == null) // || (!"admin".equals(LoginInfo.getUser(request).getUsername()))) { // return ExtJS.ok("非admin用户不能发放任务!"); // } // // mids = mids.substring(1, mids.length()); // // Date start = this.sf.parse(request.getParameter("start")); // Date end = this.sf.parse(request.getParameter("end")); // if (start.after(end)) { // return ExtJS.ok("起始时间不能大于任务完成时间!"); // } // // List<Customer> list = this.customerService.getCustomersByManagerIds(mids); // List tasks = new ArrayList(); // int idx = 0; // for (Customer customer : list) { // if (customer.getCustomerManager() == null) { // continue; // } // idx++; // Task task = new Task(); // task.setContent(request.getParameter("content")); // task.setCustomer(customer); // task.setManager(customer.getCustomerManager()); // task.setStart(start); // task.setEnd(end); // task.setId(IdUtil.getId() + idx); // tasks.add(task); // } // // if (tasks.size() < 1) { // return ExtJS.ok("无客户,请添加客户后重试!"); // } // List cs = new ArrayList(); // Map map = HttpUtils.getRequestParam(request); // Set<String> keySet = map.keySet(); // for (String s : keySet) { // if ((s.matches("^content.+")) && (!s.equals("content"))) { // RecordDetail detail = new RecordDetail(); // detail.setContent(map.get(s) + ""); // cs.add(detail); // } // } // this.taskService.addTask(tasks, cs); // return ExtJS.ok("发放成功!"); // } catch (Exception e) { // log.error("error", e); // } // return ExtJS.fail("发放个别任务失败,请重试!"); // } @RequestMapping(params = { "action=group" }) @ResponseBody public JSONObject groupTask(String gids, String content, HttpServletRequest request, HttpServletResponse response) { try { if ((LoginInfo.getUser(request) == null) || (!"admin".equals(LoginInfo.getUser(request).getUsername()))) { return ExtJS.ok("非admin用户不能发放任务!"); } gids = gids.substring(1, gids.length()); Date start = this.sf.parse(request.getParameter("start")); Date end = this.sf.parse(request.getParameter("end")); if (start.after(end)) { return ExtJS.ok("起始时间不能大于任务完成时间!"); } List<Customer> list = this.customerService.getCustomersByGroupIds(gids); List tasks = new ArrayList(); for (Customer customer : list) { if (customer.getCustomerManager() == null) { continue; } Task task = new Task(); task.setContent(request.getParameter("content")); task.setCustomer(customer); task.setManager(customer.getCustomerManager()); task.setStart(start); task.setEnd(end); task.setId(IdUtil.getId()); tasks.add(task); } if (tasks.size() < 1) { return ExtJS.ok("无客户,请添加客户后重试!"); } List cs = new ArrayList(); Map map = HttpUtils.getRequestParam(request); Set<String> keySet = map.keySet(); for (String s : keySet) { if ((s.matches("^content.+")) && (!s.equals("content"))) { RecordDetail detail = new RecordDetail(); detail.setContent(map.get(s) + ""); cs.add(detail); } } this.taskService.addTask(tasks, cs); return ExtJS.ok("发放成功!"); } catch (Exception e) { log.error("error", e); } return ExtJS.fail("发放个别任务失败,请重试!"); } @RequestMapping(params = { "action=customerTask" }) @ResponseBody public JSONObject customerTask(String cids, String content, HttpServletRequest request, HttpServletResponse response) { try { if ((LoginInfo.getUser(request) == null) || (!"admin".equals(LoginInfo.getUser(request).getUsername()))) { return ExtJS.ok("非admin用户不能发放任务!"); } cids = cids.substring(1, cids.length()); Date start = this.sf.parse(request.getParameter("start")); Date end = this.sf.parse(request.getParameter("end")); if (start.after(end)) { return ExtJS.ok("起始时间不能大于任务完成时间!"); } List<Customer> list = this.customerService.getCustomersByIds(cids); List tasks = new ArrayList(); for (Customer customer : list) { if (customer.getCustomerManager() == null) { continue; } Task task = new Task(); task.setContent(request.getParameter("content")); task.setCustomer(customer); task.setManager(customer.getCustomerManager()); task.setStart(start); task.setEnd(end); task.setId(IdUtil.getId()); tasks.add(task); } if (tasks.size() < 1) { return ExtJS.ok("无客户,请添加客户后重试!"); } List cs = new ArrayList(); Map map = HttpUtils.getRequestParam(request); Set<String> keySet = map.keySet(); for (String s : keySet) { if ((s.matches("^content.+")) && (!s.equals("content"))) { RecordDetail detail = new RecordDetail(); detail.setContent(map.get(s) + ""); cs.add(detail); } } this.taskService.addTask(tasks, cs); return ExtJS.ok("发放成功!"); } catch (Exception e) { log.error("error", e); } return ExtJS.fail("发放客户任务失败,请重试!"); } @RequestMapping(params = { "action=newCustomerTask" }) @ResponseBody public JSONObject newCustomerTask(String cids, String mid, String content, HttpServletRequest request, HttpServletResponse response) { try { if ((LoginInfo.getUser(request) == null) || (!"admin".equals(LoginInfo.getUser(request).getUsername()))) { return ExtJS.ok("非admin用户不能发放任务!"); } cids = cids.substring(1, cids.length()); Date start = this.sf.parse(request.getParameter("start")); Date end = this.sf.parse(request.getParameter("end")); if (start.after(end)) { return ExtJS.ok("起始时间不能大于任务完成时间!"); } String[] cIdArr = cids.split(","); int size = cIdArr.length; List tasks = new ArrayList(); for (int idx = 1; idx <= size; idx++) { Task task = new Task(); task.setContent(request.getParameter("content")); Customer customer = new Customer(); customer.setId(Long.parseLong(cIdArr[idx - 1])); task.setCustomer(customer); CustomerManager manager = new CustomerManager(); manager.setId(Long.parseLong(mid)); task.setManager(manager); task.setStart(start); task.setEnd(end); task.setId(IdUtil.getId()); tasks.add(task); } List cs = new ArrayList(); Map map = HttpUtils.getRequestParam(request); Set<String> keySet = map.keySet(); for (String s : keySet) { if ((s.matches("^content.+")) && (!s.equals("content"))) { RecordDetail detail = new RecordDetail(); detail.setContent(map.get(s) + ""); cs.add(detail); } } this.taskService.addTask(tasks, cs); return ExtJS.ok("发放成功!"); } catch (Exception e) { log.error("error", e); } return ExtJS.fail("发放新客户任务失败,请重试!"); } }
[ "hairlun@qq.com" ]
hairlun@qq.com
35383cad7f684d9b5e3150c610899e939159d5ef
69072dc8587d053542783dcf594118a07ae97f4a
/ancun-data-subscribe-mybatis/src/main/java/com/ancun/common/persistence/mapper/dx/EntUserInfoMapper.java
cd745ed7fa7ad5fd25a5329df1589b4888c06af8
[]
no_license
hejunling/boss-dts
f5dac435796b95ada7e965b60b586eb9a45f14b9
fa4f6caef355805938412e503d15f1f10cda4efd
refs/heads/master
2022-12-20T12:35:41.683426
2019-05-23T12:21:15
2019-05-23T12:21:15
94,403,799
1
2
null
2022-12-16T03:42:19
2017-06-15T05:40:09
Java
UTF-8
Java
false
false
1,101
java
package com.ancun.common.persistence.mapper.dx; import com.ancun.common.persistence.model.dx.EntUserInfo; import com.ancun.common.persistence.model.master.BizTimerConfig; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface EntUserInfoMapper extends Mapper<EntUserInfo> { /** * 查询企业用户,与汇工作兼容 * * @param userNo * @param userTel * @param rpCode * @return */ List<EntUserInfo> selectEntUserInfos(@Param("userNo") String userNo, @Param("userTel") String userTel, @Param("rpCode") String rpCode); /** * 更新,退订时间清空 * * @param entUserInfo */ void updateSelective(EntUserInfo entUserInfo); /** * 查询 所有rpcode * * @param config * @return */ List<String> selectAllEntRpcodes(BizTimerConfig config); /** * 查询 所有数量 * * @param config * @return */ int selectAllEntCount(BizTimerConfig config); }
[ "hechuan@ancun.com" ]
hechuan@ancun.com
ce0b5ecc20203703a180bbf45dcd33e6f8bd24a9
f18ecaea4fded21e5c6be80289c87d99838b65a7
/os-pm-main/src/main/java/com/jukusoft/os/pm/main/Application.java
2bf75caf902e7d3f0462b450eaa1e55fe43c06e5
[ "Apache-2.0" ]
permissive
JuKu/os-pm-tool
30b12b64b0e24787a844c49660f7f1875e45e58f
689f7cd1c898648493b4f50876b1b93a87f43551
refs/heads/master
2020-06-20T07:31:44.981546
2019-07-15T18:09:35
2019-07-15T18:09:35
197,044,081
0
0
null
null
null
null
UTF-8
Java
false
false
477
java
package com.jukusoft.os.pm.main; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication(scanBasePackages = "com.jukusoft.os.pm") public class Application extends SpringBootServletInitializer { public static void main (String[] args) { SpringApplication.run(Application.class, args); } }
[ "kuenzel.justin@t-online.de" ]
kuenzel.justin@t-online.de
9b7011c9f7f1f720d6469d4f0870a32d72a6cd6b
a85740bfb7def38be54ed1425b7a4a06f9bdcf6a
/mybatis-generator-systests-ibatis2-java5/target/generated-sources/mybatis-generator/mbg/test/ib2j5/generated/hierarchical/dao/PkfieldsblobsDAO.java
eca0df3fb1c094b3d9e24ee1a9217503ef9247d0
[ "Apache-2.0" ]
permissive
tianbohao1010/generator-mybatis-generator-1.3.2
148841025fa9d52bcda4d529227092892ff2ee89
f917b1ae550850b76e7ac0c967da60dc87fc6eb5
refs/heads/master
2020-03-19T07:18:35.135680
2018-06-05T01:41:21
2018-06-05T01:41:21
136,103,685
0
0
null
null
null
null
UTF-8
Java
false
false
4,081
java
package mbg.test.ib2j5.generated.hierarchical.dao; import java.util.List; import mbg.test.ib2j5.generated.hierarchical.model.Pkfieldsblobs; import mbg.test.ib2j5.generated.hierarchical.model.PkfieldsblobsExample; import mbg.test.ib2j5.generated.hierarchical.model.PkfieldsblobsKey; import mbg.test.ib2j5.generated.hierarchical.model.PkfieldsblobsWithBLOBs; public interface PkfieldsblobsDAO { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int countByExample(PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int deleteByExample(PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int deleteByPrimaryKey(PkfieldsblobsKey _key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ void insert(PkfieldsblobsWithBLOBs record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ void insertSelective(PkfieldsblobsWithBLOBs record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ List<PkfieldsblobsWithBLOBs> selectByExampleWithBLOBs(PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ List<Pkfieldsblobs> selectByExampleWithoutBLOBs(PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ PkfieldsblobsWithBLOBs selectByPrimaryKey(PkfieldsblobsKey _key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int updateByExampleSelective(PkfieldsblobsWithBLOBs record, PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int updateByExample(PkfieldsblobsWithBLOBs record, PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int updateByExample(Pkfieldsblobs record, PkfieldsblobsExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int updateByPrimaryKeySelective(PkfieldsblobsWithBLOBs record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int updateByPrimaryKey(PkfieldsblobsWithBLOBs record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PKFIELDSBLOBS * * @mbggenerated Thu Dec 21 14:43:57 CST 2017 */ int updateByPrimaryKey(Pkfieldsblobs record); }
[ "unicode1027@163.com" ]
unicode1027@163.com
996cca68020f1f4cab70d79091ae2b647ffe4dea
1eb67e3a7bda49814855d4958b82c1e5d878a3fa
/app/src/main/java/com/example/allu/srp_psnacet/Layout_handler/Org_list.java
7b68ce6fd0312974674a90882213130aeb5d7480
[]
no_license
Alluajay/SRP
5ca8dd6d6ff470868436d178fb20cfe8c4868029
57aacb80bf43877e777a1f81500996569b7a4f56
refs/heads/master
2020-09-13T09:34:05.736711
2016-09-15T18:02:42
2016-09-15T18:02:42
67,407,394
0
0
null
null
null
null
UTF-8
Java
false
false
5,471
java
package com.example.allu.srp_psnacet.Layout_handler; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.example.allu.srp_psnacet.Adapters.Org_adapter; import com.example.allu.srp_psnacet.Connector.Navigation_connector; import com.example.allu.srp_psnacet.Dataclasses.Org_class; import com.example.allu.srp_psnacet.R; import java.util.ArrayList; public class Org_list extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { RecyclerView Org_list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_org_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Org_list=(RecyclerView)findViewById(R.id.Org_list); Org_list.setHasFixedSize(true); Org_list.setLayoutManager(new GridLayoutManager(this,1)); Org_list.setItemAnimator(new DefaultItemAnimator()); Org_adapter org_adapter=new Org_adapter(this,getArray()); Org_list.setAdapter(org_adapter); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Navigation_connector navigation_connector=new Navigation_connector(id,this); Intent i=navigation_connector.GetIntend(); startActivity(i); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public ArrayList<Org_class> getArray(){ ArrayList<Org_class> orgArray=new ArrayList<>(); Org_class org_class=new Org_class("Alpha", "Alpha to Omega Learning Centre\r\n16, Valliammal Street,\r\n", "chennai", "This is a non profitable organisation which helps physically chalenged students to learn in their natural environment", "", 446443090, 44616257, "krishenterprises@gems.vsnl.net.in"); Org_class org_class1=new Org_class( "Helen keller service society for the disabled", "Helen Keller Service Society for the Disabled\r\nVizhiyagam, Viswanathapuram,\r\n", "madurai", "This is a non?profit, charitable, voluntary organization established in the year 1979. The organization implements service projects for the welfare of the disabled in Tamil Nadu, founded by Dr. G Thiruvasagam for the service of people in the field of welfare of the disabled in rural areas.\r\n", "", 452641446, 452640735, "hkssd@md3.vsnl.net.in"); Org_class org_class2=new Org_class( "Amar Seva Sangam", "Amar Seva Sangam\r\nSulochana Gardens, Post Box No. 001, Tenkasi Road,\r\nAyikudi", "Dindigul", "Physically challenged children from the age of five to seventeen are provided with free shelter, food, clothing, medical aid and appliances at our Home so that they can pursue their education at our School without any financial worry. If they opt for higher education outside the campus, they are also provided free transport. The children are also given special coaching.\r\n", "",448274035, 8240402, "amarseva@md3.vsnl.net.in"); orgArray.add(org_class); orgArray.add(org_class1); orgArray.add(org_class2); return orgArray; } }
[ "alludajay@gmail.com" ]
alludajay@gmail.com
e376c8fde483898bda14e4bd992050fb17c0d6f4
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/JetBrains--intellij-community/d79b719bc730f529a522c83fe8bcb0e243faa76d/after/PyParameterListImpl.java
94e7d9dcaf048befc050978bc544725fbc07122d
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
5,085
java
package com.jetbrains.python.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.stubs.PyParameterListStub; import com.jetbrains.python.toolbox.ArrayIterable; import org.jetbrains.annotations.NotNull; /** * @author yole */ public class PyParameterListImpl extends PyBaseElementImpl<PyParameterListStub> implements PyParameterList { public PyParameterListImpl(ASTNode astNode) { super(astNode); } public PyParameterListImpl(final PyParameterListStub stub) { super(stub, PyElementTypes.PARAMETER_LIST); } @Override protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyParameterList(this); } public PyParameter[] getParameters() { return getStubOrPsiChildren(PyElementTypes.PARAMETERS, new PyParameter[0]); } public void addParameter(final PyNamedParameter param) { PsiElement paren = getLastChild(); if (paren != null && ")".equals(paren.getText())) { PyUtil.ensureWritable(this); ASTNode beforeWhat = paren.getNode(); // the closing paren will be this PyParameter[] params = getParameters(); PyUtil.addListNode(this, param, beforeWhat, true, params.length == 0); } } public boolean hasPositionalContainer() { for (PyParameter parameter: getParameters()) { if (parameter instanceof PyNamedParameter && ((PyNamedParameter) parameter).isPositionalContainer()) { return true; } } return false; } public boolean hasKeywordContainer() { for (PyParameter parameter: getParameters()) { if (parameter instanceof PyNamedParameter && ((PyNamedParameter) parameter).isKeywordContainer()) { return true; } } return false; } public boolean isCompatibleTo(@NotNull PyParameterList another) { PyParameter[] parameters = getParameters(); final PyParameter[] anotherParameters = another.getParameters(); final int parametersLength = parameters.length; final int anotherParametersLength = anotherParameters.length; if (parametersLength == anotherParametersLength) { if (hasPositionalContainer() == another.hasPositionalContainer() && hasKeywordContainer() == another.hasKeywordContainer()) { return true; } } int i = 0; int j = 0; while (i < parametersLength && j < anotherParametersLength) { PyParameter parameter = parameters[i]; PyParameter anotherParameter = anotherParameters[j]; if (parameter instanceof PyNamedParameter && anotherParameter instanceof PyNamedParameter) { PyNamedParameter namedParameter = (PyNamedParameter)parameter; PyNamedParameter anotherNamedParameter = (PyNamedParameter)anotherParameter; if (namedParameter.isPositionalContainer()) { while (j < anotherParametersLength && !anotherNamedParameter.isPositionalContainer() && !anotherNamedParameter.isKeywordContainer()) { anotherParameter = anotherParameters[j++]; anotherNamedParameter = (PyNamedParameter) anotherParameter; } ++i; continue; } if (anotherNamedParameter.isPositionalContainer()) { while (i < parametersLength && !namedParameter.isPositionalContainer() && !namedParameter.isKeywordContainer()) { parameter = parameters[i++]; namedParameter = (PyNamedParameter) parameter; } ++j; continue; } if (namedParameter.isKeywordContainer() || anotherNamedParameter.isKeywordContainer()) { break; } } // both are simple parameters ++i; ++j; } if (i < parametersLength) { if (parameters[i] instanceof PyNamedParameter) { if (((PyNamedParameter) parameters[i]).isKeywordContainer()) { ++i; } } } if (j < anotherParametersLength) { if (anotherParameters[j] instanceof PyNamedParameter) { if (((PyNamedParameter) anotherParameters[j]).isKeywordContainer()) { ++j; } } } return (i >= parametersLength) && (j >= anotherParametersLength); // //if (weHaveStarred && parameters.length - 1 <= anotherParameters.length) { // if (weHaveDoubleStarred == anotherHasDoubleStarred) { // return true; // } //} //if ((anotherHasDoubleStarred && parameters.length == anotherParameters.length - 1) // || (weHaveDoubleStarred && parameters.length == anotherParameters.length + 1)) { // return true; //} //return false; } @NotNull public Iterable<PyElement> iterateNames() { return new ArrayIterable<PyElement>(getParameters()); } public PyElement getElementNamed(final String the_name) { return IterHelper.findName(iterateNames(), the_name); } public boolean mustResolveOutside() { return false; // we don't exactly have children to resolve, but if we did... } }
[ "fraczwojciech@gmail.com" ]
fraczwojciech@gmail.com
f659277e84d0effb665042248f7379b1b212d35e
b8dbde714f888308b79123d19c2e87def4afed88
/src/java/org/apache/cassandra/utils/ByteBufferUtil.java
55dbceb91efca7cffc09c09fe05ba2b5357e32ce
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
eddy20062010/apache-cassandra
38d077113a3d5d2058a1ff0ff2f290e409ec3ff8
62c27b226620a1e7dac88e2695e3fcd33f541aa5
refs/heads/master
2021-01-21T08:24:58.736708
2013-11-12T13:10:53
2013-11-12T13:10:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,622
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.utils; import java.io.DataInput; import java.io.DataOutput; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.util.Arrays; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.FileUtils; import org.apache.commons.lang.ArrayUtils; /** * Utility methods to make ByteBuffers less painful * The following should illustrate the different ways byte buffers can be used * * public void testArrayOffet() * { * * byte[] b = "test_slice_array".getBytes(); * ByteBuffer bb = ByteBuffer.allocate(1024); * * assert bb.position() == 0; * assert bb.limit() == 1024; * assert bb.capacity() == 1024; * * bb.put(b); * * assert bb.position() == b.length; * assert bb.remaining() == bb.limit() - bb.position(); * * ByteBuffer bb2 = bb.slice(); * * assert bb2.position() == 0; * * //slice should begin at other buffers current position * assert bb2.arrayOffset() == bb.position(); * * //to match the position in the underlying array one needs to * //track arrayOffset * assert bb2.limit()+bb2.arrayOffset() == bb.limit(); * * * assert bb2.remaining() == bb.remaining(); * * } * * } * */ public class ByteBufferUtil { public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(ArrayUtils.EMPTY_BYTE_ARRAY); private static final Charset UTF_8 = Charset.forName("UTF-8"); public static int compareUnsigned(ByteBuffer o1, ByteBuffer o2) { assert o1 != null; assert o2 != null; int minLength = Math.min(o1.remaining(), o2.remaining()); for (int x = 0, i = o1.position(), j = o2.position(); x < minLength; x++, i++, j++) { if (o1.get(i) == o2.get(j)) continue; // compare non-equal bytes as unsigned return (o1.get(i) & 0xFF) < (o2.get(j) & 0xFF) ? -1 : 1; } return (o1.remaining() == o2.remaining()) ? 0 : ((o1.remaining() < o2.remaining()) ? -1 : 1); } public static int compare(byte[] o1, ByteBuffer o2) { return compareUnsigned(ByteBuffer.wrap(o1), o2); } public static int compare(ByteBuffer o1, byte[] o2) { return compareUnsigned(o1, ByteBuffer.wrap(o2)); } /** * Decode a String representation. * This method assumes that the encoding charset is UTF_8. * * @param buffer a byte buffer holding the string representation * @return the decoded string */ public static String string(ByteBuffer buffer) throws CharacterCodingException { return string(buffer, UTF_8); } /** * Decode a String representation. * This method assumes that the encoding charset is UTF_8. * * @param buffer a byte buffer holding the string representation * @param position the starting position in {@code buffer} to start decoding from * @param length the number of bytes from {@code buffer} to use * @return the decoded string */ public static String string(ByteBuffer buffer, int position, int length) throws CharacterCodingException { return string(buffer, position, length, UTF_8); } /** * Decode a String representation. * * @param buffer a byte buffer holding the string representation * @param position the starting position in {@code buffer} to start decoding from * @param length the number of bytes from {@code buffer} to use * @param charset the String encoding charset * @return the decoded string */ public static String string(ByteBuffer buffer, int position, int length, Charset charset) throws CharacterCodingException { ByteBuffer copy = buffer.duplicate(); copy.position(position); copy.limit(copy.position() + length); return string(copy, charset); } /** * Decode a String representation. * * @param buffer a byte buffer holding the string representation * @param charset the String encoding charset * @return the decoded string */ public static String string(ByteBuffer buffer, Charset charset) throws CharacterCodingException { return charset.newDecoder().decode(buffer.duplicate()).toString(); } /** * You should almost never use this. Instead, use the write* methods to avoid copies. */ public static byte[] getArray(ByteBuffer buffer) { int length = buffer.remaining(); if (buffer.hasArray()) { int start = buffer.position(); if (buffer.arrayOffset() == 0 && start == 0 && length == buffer.array().length) return buffer.array(); else return Arrays.copyOfRange(buffer.array(), start + buffer.arrayOffset(), start + length + buffer.arrayOffset()); } // else, DirectByteBuffer.get() is the fastest route byte[] bytes = new byte[length]; buffer.duplicate().get(bytes); return bytes; } /** * ByteBuffer adaptation of org.apache.commons.lang.ArrayUtils.lastIndexOf method * * @param buffer the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index (i.e. BB position) to travers backwards from * @return the last index (i.e. BB position) of the value within the array * [between buffer.position() and buffer.limit()]; <code>-1</code> if not found. */ public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex) { assert buffer != null; if (startIndex < buffer.position()) { return -1; } else if (startIndex >= buffer.limit()) { startIndex = buffer.limit() - 1; } for (int i = startIndex; i >= buffer.position(); i--) { if (valueToFind == buffer.get(i)) return i; } return -1; } /** * Encode a String in a ByteBuffer using UTF_8. * * @param s the string to encode * @return the encoded string */ public static ByteBuffer bytes(String s) { return ByteBuffer.wrap(s.getBytes(UTF_8)); } /** * Encode a String in a ByteBuffer using the provided charset. * * @param s the string to encode * @param charset the String encoding charset to use * @return the encoded string */ public static ByteBuffer bytes(String s, Charset charset) { return ByteBuffer.wrap(s.getBytes(charset)); } /** * @return a new copy of the data in @param buffer * USUALLY YOU SHOULD USE ByteBuffer.duplicate() INSTEAD, which creates a new Buffer * (so you can mutate its position without affecting the original) without copying the underlying array. */ public static ByteBuffer clone(ByteBuffer buffer) { assert buffer != null; if (buffer.remaining() == 0) return EMPTY_BYTE_BUFFER; ByteBuffer clone = ByteBuffer.allocate(buffer.remaining()); if (buffer.hasArray()) { System.arraycopy(buffer.array(), buffer.arrayOffset() + buffer.position(), clone.array(), 0, buffer.remaining()); } else { clone.put(buffer.duplicate()); clone.flip(); } return clone; } public static void arrayCopy(ByteBuffer buffer, int position, byte[] bytes, int offset, int length) { if (buffer.hasArray()) System.arraycopy(buffer.array(), buffer.arrayOffset() + position, bytes, offset, length); else ((ByteBuffer) buffer.duplicate().position(position)).get(bytes, offset, length); } /** * Transfer bytes from one ByteBuffer to another. * This function acts as System.arrayCopy() but for ByteBuffers. * * @param src the source ByteBuffer * @param srcPos starting position in the source ByteBuffer * @param dst the destination ByteBuffer * @param dstPos starting position in the destination ByteBuffer * @param length the number of bytes to copy */ public static void arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) { if (src.hasArray() && dst.hasArray()) { System.arraycopy(src.array(), src.arrayOffset() + srcPos, dst.array(), dst.arrayOffset() + dstPos, length); } else { if (src.limit() - srcPos < length || dst.limit() - dstPos < length) throw new IndexOutOfBoundsException(); for (int i = 0; i < length; i++) { dst.put(dstPos++, src.get(srcPos++)); } } } public static void writeWithLength(ByteBuffer bytes, DataOutput out) throws IOException { out.writeInt(bytes.remaining()); write(bytes, out); // writing data bytes to output source } public static void write(ByteBuffer buffer, DataOutput out) throws IOException { if (buffer.hasArray()) { out.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } else { for (int i = buffer.position(); i < buffer.limit(); i++) { out.writeByte(buffer.get(i)); } } } /* @return An unsigned short in an integer. */ private static int readShortLength(DataInput in) throws IOException { int length = (in.readByte() & 0xFF) << 8; return length | (in.readByte() & 0xFF); } /** * Convert a byte buffer to an integer. * Does not change the byte buffer position. * * @param bytes byte buffer to convert to integer * @return int representation of the byte buffer */ public static int toInt(ByteBuffer bytes) { return bytes.getInt(bytes.position()); } public static long toLong(ByteBuffer bytes) { return bytes.getLong(bytes.position()); } public static float toFloat(ByteBuffer bytes) { return bytes.getFloat(bytes.position()); } public static double toDouble(ByteBuffer bytes) { return bytes.getDouble(bytes.position()); } public static ByteBuffer bytes(int i) { return ByteBuffer.allocate(4).putInt(0, i); } public static ByteBuffer bytes(long n) { return ByteBuffer.allocate(8).putLong(0, n); } public static ByteBuffer bytes(float f) { return ByteBuffer.allocate(4).putFloat(0, f); } public static ByteBuffer bytes(double d) { return ByteBuffer.allocate(8).putDouble(0, d); } public static InputStream inputStream(ByteBuffer bytes) { final ByteBuffer copy = bytes.duplicate(); return new InputStream() { public int read() throws IOException { if (!copy.hasRemaining()) return -1; return copy.get() & 0xFF; } @Override public int read(byte[] bytes, int off, int len) throws IOException { if (!copy.hasRemaining()) return -1; len = Math.min(len, copy.remaining()); copy.get(bytes, off, len); return len; } @Override public int available() throws IOException { return copy.remaining(); } }; } public static ByteBuffer hexToBytes(String str) { return ByteBuffer.wrap(FBUtilities.hexToBytes(str)); } /** * Compare two ByteBuffer at specified offsets for length. * Compares the non equal bytes as unsigned. * @param bytes1 First byte buffer to compare. * @param offset1 Position to start the comparison at in the first array. * @param bytes2 Second byte buffer to compare. * @param offset2 Position to start the comparison at in the second array. * @param length How many bytes to compare? * @return -1 if byte1 is less than byte2, 1 if byte2 is less than byte1 or 0 if equal. */ public static int compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length) { if ( null == bytes1 ) { if ( null == bytes2) return 0; else return -1; } if (null == bytes2 ) return 1; assert bytes1.limit() >= offset1 + length : "The first byte array isn't long enough for the specified offset and length."; assert bytes2.limit() >= offset2 + length : "The second byte array isn't long enough for the specified offset and length."; for ( int i = 0; i < length; i++ ) { byte byte1 = bytes1.get(offset1 + i); byte byte2 = bytes2.get(offset2 + i); if ( byte1 == byte2 ) continue; // compare non-equal bytes as unsigned return (byte1 & 0xFF) < (byte2 & 0xFF) ? -1 : 1; } return 0; } }
[ "oa@odnoklassniki.ru" ]
oa@odnoklassniki.ru
1859f557a4e78cb63230b49c5bcd298acdd012f9
f207f8c663b1abd0af23e10e243fa31e67a881af
/app/src/main/java/com/example/danilserbin/baking/ui/view/MainView.java
667fd56caa8f0d89d4487b744ea2d4fbc0c2f7b9
[]
no_license
OlegSheliakin/BakingApp
b5afb7558f11c7c7594b2787e6944996eb470148
f9e3a4ea81aecb1f7eefeedb5c7489b0155636e1
refs/heads/master
2021-08-15T20:45:39.212285
2017-11-18T08:12:41
2017-11-18T08:12:41
111,188,064
0
0
null
null
null
null
UTF-8
Java
false
false
252
java
package com.example.danilserbin.baking.ui.view; import com.example.danilserbin.baking.model.pojo.Recipe; import java.util.List; public interface MainView { void fill(List<Recipe> recipes); void showError(String s); void updateWidget(); }
[ "oshelyakin@smedialink.com" ]
oshelyakin@smedialink.com
0b603b413a0c3cc64c376f74ea6bab1c9c2cb01a
cd63684aed7c31493c5c14bc7cef0d0508048dac
/server/src/main/java/com/thoughtworks/go/server/service/JobResolverService.java
d48029f3d9ba6170189613befd0297fe5b5f22d3
[ "MIT", "Apache-2.0" ]
permissive
zzz222zzz/gocd
cb1765d16840d96c991b8a9308c01cb37eb3ea7c
280175df42d13e6cd94386a7af6fdac966b2e875
refs/heads/master
2020-05-09T20:25:48.079858
2019-04-15T02:53:33
2019-04-15T02:53:33
181,407,372
1
0
Apache-2.0
2019-04-15T03:41:28
2019-04-15T03:41:26
null
UTF-8
Java
false
false
1,445
java
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.server.service; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.server.dao.JobInstanceDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @understands resolving actual job in case of copy-for-rerun */ @Service public class JobResolverService { private final JobInstanceDao jobDao; @Autowired public JobResolverService(JobInstanceDao jobDao) { this.jobDao = jobDao; } public JobIdentifier actualJobIdentifier(JobIdentifier oldId) { return jobDao.findOriginalJobIdentifier(oldId.getStageIdentifier(), oldId.getBuildName()); } }
[ "godev@thoughtworks.com" ]
godev@thoughtworks.com
51777346195e20431019a51a4495afe94aa5e575
2fbd01a415130b738726b00817f236df46e0c52b
/MDPnPBloodPump/src/main/java/rosetta/MDC_DIM_MICRO_G_PER_M_SQ_PER_MIN.java
c7d0bb096e755560ea35335ae219941de39442e4
[]
no_license
DylanBagshaw/CPM
e60c34716e6fcbccaab831ba58368485d472492f
c00ad41f46dae40800fa97de4279876c8861fbba
refs/heads/master
2020-03-11T20:05:47.618502
2018-09-13T16:08:35
2018-09-13T16:08:35
130,227,287
0
0
null
null
null
null
UTF-8
Java
false
false
450
java
/* WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY. This file was generated from .idl using "rtiddsgen". The rtiddsgen tool is part of the RTI Connext distribution. For more information, type 'rtiddsgen -help' at a command shell or consult the RTI Connext manual. */ package rosetta; public class MDC_DIM_MICRO_G_PER_M_SQ_PER_MIN { public static final String VALUE = "MDC_DIM_MICRO_G_PER_M_SQ_PER_MIN"; }
[ "dmbagshaw@yahoo.com" ]
dmbagshaw@yahoo.com
7404e82b59481a77df171b3ac820aa1b8ed9b34e
0103f095c4280cdc0e98cf425b7b06a053bcc502
/src/il/ac/shenkar/ToDoList/TaskAlarmManager/AlarmReceiver.java
62036dd22171fac5ff68337b5c85d998b49660cc
[]
no_license
eranaltay/FinalProject
c236fc88d778e04a9fa91951f575bbb1455a55b1
074646f962a83a000397a60c7f474e56002d6952
refs/heads/master
2016-09-06T11:33:09.449820
2013-03-17T08:43:49
2013-03-17T08:43:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,925
java
/* * AlarmReceiver.java * * Copyright 2013 Eran Altay * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 1.13 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package il.ac.shenkar.ToDoList.TaskAlarmManager; import il.ac.shenkar.ToDoList.R; import il.ac.shenkar.ToDoList.ShowTask.ShowTaskActivity; import il.ac.shenkar.ToDoList.TaskDAO.TaskObject; import il.ac.shenkar.ToDoList.TaskList.TaskListActivity; import android.app.Notification; import android.app.Notification.Builder; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; /** * ReminderReciver, activate the following, when user get the alarm on his device * @author EranAltay * */ public class AlarmReceiver extends BroadcastReceiver { private NotificationManager notificationManager; private TaskObject taskToNotify; private Builder builder; private Notification notification; private Intent taskListIntent; private PendingIntent taskListPendingIntent; private Intent showTaskIntent; private PendingIntent showTaskPendingIntent; /** * Configure the the title of the notification, icon, message string, and which activity * to launch when tapping the received notification */ @Override public void onReceive(Context context, Intent intent) { taskToNotify = intent.getParcelableExtra("taskToSetAlarm"); buildNotification(context); } public void buildNotification(Context context) { try { //get the Serializable object from the createactivity int id = (int) taskToNotify.getTaskId(); //Configure which alarm will show up, in this case notification notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); taskListIntent = new Intent(context, TaskListActivity.class); taskListPendingIntent = PendingIntent.getActivity(context, id, taskListIntent, 0); showTaskIntent = new Intent(context,ShowTaskActivity.class); showTaskIntent.putExtra("tasktoshow", taskToNotify); showTaskPendingIntent = PendingIntent.getActivity(context, id, showTaskIntent, 0); builder = new Notification.Builder(context) .setContentIntent(showTaskPendingIntent) .setTicker(context.getString(R.string.appName)) .setContentTitle(taskToNotify.getTaskTitle()) .setSmallIcon(R.drawable.notifybell) .setDefaults(Notification.DEFAULT_ALL) .addAction(R.drawable.notificationicon, "Launch " + context.getString(R.string.appName), taskListPendingIntent) .setAutoCancel(true); notification = new Notification.InboxStyle(builder) .build(); //sending the notification and id of the task notificationManager.notify(id, notification); Log.i(getClass().getSimpleName(), "notification was sent from the system for task id " + id); //cancel the alarm after receiving it if(taskToNotify.getTaskInterval() == 0) { Intent sender = new Intent(context, TaskAlarmService.class); sender.putExtra("taskToRemoveIndicator", taskToNotify); context.startService(sender); } } catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Broadcast receiver error"); e.printStackTrace(); } } }
[ "eranaltay@gmail.com" ]
eranaltay@gmail.com
90b5e7d85971c5b080eb8d064a6e81b30176b8d4
defd4ffeb636a0a238d84d554348c61b77294a39
/src/main/java/stupaq/cloudatlas/messaging/MessageListener.java
55ffa65e46ad8f4c544d5be0eccf35df5adcb67a
[]
no_license
stupaq/cloud-atlas
8927f47be20a8a8dac366015ce2da24ae335f3e5
4ffb3397ff2f2c3876c51c72fb9818b7b5159493
refs/heads/master
2021-01-17T12:30:39.539203
2014-06-22T08:26:53
2014-06-22T08:26:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
851
java
package stupaq.cloudatlas.messaging; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListeningExecutorService; public interface MessageListener { Class<?> contract(); public ListeningExecutorService executor(); public static abstract class AbstractMessageListener implements MessageListener { private final ListeningExecutorService executor; private final Class<?> contract; protected AbstractMessageListener(ListeningExecutorService executor, Class<?> contract) { Preconditions.checkArgument(contract.isAssignableFrom(this.getClass())); this.executor = executor; this.contract = contract; } @Override public Class<?> contract() { return contract; } @Override public ListeningExecutorService executor() { return executor; } } }
[ "mateuszmachalica@gmail.com" ]
mateuszmachalica@gmail.com
08e911ee54a8db9db5de20283e565c708299579c
435666caea9b28a9ea78b9daf9aad6a0afb88eb0
/day_2/Solution5.java
d4a609bdde6161c0dde46391c25cf18c03be10a0
[]
no_license
kohegen/geecon2019
ad3bdc86dd252fc36249a6c3865439b99289de1f
1abdddbf46db5426e9a56e6567002b6a18aee72a
refs/heads/master
2020-06-10T21:05:34.128170
2019-06-25T22:36:10
2019-06-25T22:36:10
193,747,244
0
0
null
null
null
null
UTF-8
Java
false
false
2,457
java
package day_2; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class Solution5 { public static void main(String[] args) { // is a composite natural number with an even number of digits, // that can be factored into two natural numbers each with half as many digits as the original number // and not both with trailing zeroes, where the two factors contain precisely all the digits of the original number, // in any order, counting multiplicity. The first vampire number is 1260 = 21 × 60. int N = Integer.parseInt(args[0]); int numbersFound = 0; int lastFoundNumber = 0; int number = 1259; while (true) { number++; String numberStr = String.valueOf(number); if (numberStr.length() % 2 != 0) { //need to be even continue; } int factorial = factorial(numberStr.length()); List<Character> numberAsList = numberStr.chars().mapToObj(c -> (char) c).collect(Collectors.toList()); for (int i=0;i<factorial*4;i++) { //this is really nasty but I don't have time to implement permutations Collections.shuffle(numberAsList); String factor1 = toString(numberAsList.subList(0, numberAsList.size() / 2)); String factor2 = toString(numberAsList.subList(numberAsList.size() / 2, numberAsList.size())); if (factor1.endsWith("0") & factor2.endsWith("0")) { //both cannot have trailing zeroes continue; } if (Integer.valueOf(factor1) * Integer.valueOf(factor2) == number) { //found vampire!! numbersFound++; lastFoundNumber = number; break; } } if (numbersFound == N) { System.out.println(lastFoundNumber); break; } } } private static int factorial(int n) { int factorial = 1; for (int i=1;i<=n;i++) { factorial*=i; } return factorial; } private static String toString(List<Character> chars) { return chars.toString() .substring(1, 3 * chars.size() - 1) .replaceAll(", ", ""); } }
[ "wilczek256@gmail.com" ]
wilczek256@gmail.com
86ae2c831384508cd677041ffee71e97dde8b72d
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipsejdt_cluster/15815/tar_0.java
0f1bf48b2a34124dbe91afe11e29396705792314
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,406
java
package org.eclipse.jdt.internal.core.search.indexing; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.compiler.*; import org.eclipse.jdt.internal.core.index.*; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.parser.InvalidInputException; import org.eclipse.jdt.internal.compiler.parser.Scanner; import org.eclipse.jdt.internal.compiler.parser.TerminalSymbols; import org.eclipse.jdt.internal.compiler.problem.*; import org.eclipse.jdt.internal.core.jdom.CompilationUnit; import java.io.*; import java.util.*; /** * A SourceIndexer indexes java files using a java parser. The following items are indexed: * Declarations of: * - Classes<br> * - Interfaces; <br> * - Methods;<br> * - Fields;<br> * References to: * - Methods (with number of arguments); <br> * - Fields;<br> * - Types;<br> * - Constructors. */ public class SourceIndexer extends AbstractIndexer { public static final String[] FILE_TYPES= new String[] {"java"}; //$NON-NLS-1$ protected DefaultProblemFactory problemFactory= new DefaultProblemFactory(Locale.getDefault()); /** * Returns the file types the <code>IIndexer</code> handles. */ public String[] getFileTypes(){ return FILE_TYPES; } protected void indexFile(IDocument document) throws IOException { // Add the name of the file to the index output.addDocument(document); // Create a new Parser SourceIndexerRequestor requestor = new SourceIndexerRequestor(this, document); SourceElementParser parser = new SourceElementParser(requestor, problemFactory, new CompilerOptions(JavaCore.getOptions()), true); // index local declarations // Launch the parser char[] source = null; char[] name = null; try { source = document.getCharContent(); name = document.getName().toCharArray(); } catch(Exception e){ } if (source == null || name == null) return; // could not retrieve document info (e.g. resource was discarded) CompilationUnit compilationUnit = new CompilationUnit(source, name); try { parser.parseCompilationUnit(compilationUnit, true); } catch (Exception e) { e.printStackTrace(); } } /** * Sets the document types the <code>IIndexer</code> handles. */ public void setFileTypes(String[] fileTypes){} }
[ "375833274@qq.com" ]
375833274@qq.com
e979dd55c61731334feea623ba6083e56a33ec03
98f43214d6056c6687673a84f6aee4c0898c9f88
/trunk/f1-distribuito/src/log/java/Driver.java
5816204e4d714c4a43a6f62ed37966acc3599294
[]
no_license
BGCX067/f1sim-scd-svn-to-git
cfb226c467c4bb93f6d27b7fce0c6bafa62366f0
07adf304b9ed2972be6b4fe0d25aaa4e51ab8123
refs/heads/master
2016-09-01T08:52:31.912713
2015-12-28T14:15:56
2015-12-28T14:15:56
48,833,928
0
0
null
null
null
null
UTF-8
Java
false
false
3,951
java
import java.util.Date; /** * * @author daniele */ public class Driver implements Comparable{ private String name; private short id; private String team; private short position; private short currentLap; private int currentSegment; private float maxSpeed; private float Speed = 0; private long lastEndLap = 0; private long bestLap = Integer.MAX_VALUE; private long lastLap = 0; /* Possible states:<br> * 0: running<br> * 1: at box<br> * 2: race finished<br> * -1: out<br> * -2: not started yet<br> */ private short state = -2; private long difference = 0; private long totalTime = 0; public Driver(String name, short id, String team, short position, short currentSegment) { this.name = name; this.id = id; this.team = team; this.position = position; this.currentSegment = currentSegment; this.currentLap = 0; this.maxSpeed = 0; } public void setCurrentSegment(int Segment) { currentSegment = Segment; } public void updateMaxSpeed(float Speed) { this.Speed = Speed; if(Speed > maxSpeed){ maxSpeed = Speed; } } void setStartTime(long startTime){ this.lastEndLap = startTime; } public void setLastEndLap(long lastEndLap) { if(this.lastEndLap != 0){ lastLap = lastEndLap - this.lastEndLap; totalTime = totalTime + lastLap; if(lastLap < bestLap){ bestLap = lastLap; } } this.lastEndLap = lastEndLap; } public void setCurrentLap(short currentLap) { this.currentLap = currentLap; } public void setPosition(short position) { this.position = position; } public short getCurrentLap() { return currentLap; } public long getBestLap() { return bestLap; } public long getCurrentSegment() { return currentSegment; } public short getId() { return id; } /** Possible states:<br> * 0: running<br> * 1: at box<br> * 2: race finished<br> * -1: out<br> * -2: not started yet<br> * * @return current state */ public short getState() { return state; } public float getTopSpeed() { return Math.round(maxSpeed*100)/100; } public String getName() { return name; } public short getPosition() { return position; } public String getTeam() { return team; } long getDifference() { return difference; } long getLastLap() { return lastLap; } long getTotalTime() { return totalTime; } public float getSpeed() { return Math.round(Speed*100)/100; } public long getLastEndLap() { return lastEndLap; } /** Possible states:<br> * 0: running<br> * 1: at box<br> * 2: race finished<br> * -1: out<br> * -2: not started yet<br> * */ public void setState(short s) { state = s; //out if(state == -1){ this.Speed = (float) 0.0; totalTime = new Date().getTime() - lastEndLap + totalTime; } //race finished if(state == 2){ updateMaxSpeed((float) 0.0); } } void updateDifference(long firstDriversTime) { this.difference = this.lastEndLap - firstDriversTime; } boolean precede(Driver other){ if(currentLap > other.currentLap || (currentLap == other.currentLap && currentSegment > other.currentSegment)){ return true; } return false; } public int compareTo(Object o) { if(this.precede((Driver) o)){ return -1; } else { return 1; } } }
[ "you@example.com" ]
you@example.com
7f7ef93e553fb6b28350f815e73c1dce3354db30
0d9fe88bf842079e7702ddde96d9a4a5e31cccdd
/app/src/main/java/com/maiyu/hrssc/home/activity/applying/adapter/YWCPageAdapter.java
1b9002902397b91bbfae30c627f3e2caf45487b9
[]
no_license
xiongningwan/hrssc
859fbcbc84474f915288d4fa61c30e2556f42cce
b3b727a5f9736a73e54878c4903f6911c2da70af
refs/heads/master
2021-01-23T00:06:39.304993
2017-08-31T07:17:15
2017-08-31T07:17:15
85,697,183
0
0
null
null
null
null
UTF-8
Java
false
false
4,015
java
package com.maiyu.hrssc.home.activity.applying.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.maiyu.hrssc.R; import com.maiyu.hrssc.home.activity.applying.ApplyingDetialActivity; import com.maiyu.hrssc.home.activity.applying.bean.Apply; import com.maiyu.hrssc.util.AppUtil; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 申请 已完成 */ public class YWCPageAdapter extends RecyclerView.Adapter<YWCPageAdapter.TodoPageViewHolder>{ private List<Apply> mList = new ArrayList(); private final Context mContext; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public YWCPageAdapter(Context context) { mContext = context; } public void setData(List list) { mList.clear(); mList.addAll(list); notifyDataSetChanged(); } public void loadMoreData(List list) { int startPosition = mList.size(); mList.addAll(list); notifyItemRangeChanged(startPosition, list.size()); } @Override public TodoPageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(mContext, R.layout.list_item_list_applying_item, null); return new TodoPageViewHolder(view); } @Override public void onBindViewHolder(TodoPageViewHolder holder, int position) { holder.onBindView(); } @Override public int getItemCount() { return mList.size(); } class TodoPageViewHolder extends RecyclerView.ViewHolder { private TextView title; private TextView status; private TextView time; private Button btn; private TextView reason; public TodoPageViewHolder(View itemView) { super(itemView); title = (TextView) itemView.findViewById(R.id.title); status = (TextView) itemView.findViewById(R.id.status); time = (TextView) itemView.findViewById(R.id.time); btn = (Button) itemView.findViewById(R.id.btn_item); reason = (TextView) itemView.findViewById(R.id.reason); } void onBindView() { final Apply apply = (Apply) mList.get(getAdapterPosition()); if(apply == null) { return; } title.setText(apply.getName()); if ("0".equals(apply.getStatus())) { status.setText("待审核"); } else if ("1".equals(apply.getStatus())) { status.setText("待办理"); } else if ("2".equals(apply.getStatus())) { status.setText("待领取"); } else if ("3".equals(apply.getStatus())) { status.setText("待评价"); } else if ("4".equals(apply.getStatus())) { status.setText("已完成"); } else if ("5".equals(apply.getStatus())) { status.setText("已驳回"); } Date dateTime = null; try { dateTime = sdf.parse(apply.getCreate_time()); } catch (ParseException e) { e.printStackTrace(); } time.setText(AppUtil.setTime(dateTime)); btn.setVisibility(View.GONE); reason.setVisibility(View.GONE); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, ApplyingDetialActivity.class); intent.putExtra("id", apply.getId()); intent.putExtra("title", "申请详情"); mContext.startActivity(intent); } }); } } }
[ "222" ]
222
0f4300156a3037e5ab3310857a0034524dfec1d1
40cd4da5514eb920e6a6889e82590e48720c3d38
/desktop/applis/apps/bean/bean_games/pokemonbean/src/main/java/aiki/beans/abilities/AbilityBeanMultEvtRateSecEffectOwnerGet.java
a089a2e8b5c9aba259618b7c8369e4fde90ae017
[]
no_license
Cardman/projects
02704237e81868f8cb614abb37468cebb4ef4b31
23a9477dd736795c3af10bccccb3cdfa10c8123c
refs/heads/master
2023-08-17T11:27:41.999350
2023-08-15T07:09:28
2023-08-15T07:09:28
34,724,613
4
0
null
2020-10-13T08:08:38
2015-04-28T10:39:03
Java
UTF-8
Java
false
false
409
java
package aiki.beans.abilities; import aiki.beans.PokemonBeanStruct; import code.bean.nat.*; import code.bean.nat.RtSt; import code.bean.nat.*; public class AbilityBeanMultEvtRateSecEffectOwnerGet implements NatCaller{ @Override public NaSt re(NaSt _instance, NaSt[] _args){ return new RtSt(( (AbilityBean) ((PokemonBeanStruct)_instance).getInstance()).getMultEvtRateSecEffectOwner()); } }
[ "f.desrochettes@gmail.com" ]
f.desrochettes@gmail.com
28c8162acb6e7359a82e2d854464873eced804f1
d7c5121237c705b5847e374974b39f47fae13e10
/airspan.netspan/src/main/java/Netspan/NBI_17_5/Inventory/NodeResetForcedColdFactoryResponse.java
5b3085dcccca0f19b883c2161c6d5db77582dcfa
[]
no_license
AirspanNetworks/SWITModules
8ae768e0b864fa57dcb17168d015f6585d4455aa
7089a4b6456621a3abd601cc4592d4b52a948b57
refs/heads/master
2022-11-24T11:20:29.041478
2020-08-09T07:20:03
2020-08-09T07:20:03
184,545,627
1
0
null
2022-11-16T12:35:12
2019-05-02T08:21:55
Java
UTF-8
Java
false
false
1,926
java
package Netspan.NBI_17_5.Inventory; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="NodeResetForcedColdFactoryResult" type="{http://Airspan.Netspan.WebServices}NodeActionResult" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "nodeResetForcedColdFactoryResult" }) @XmlRootElement(name = "NodeResetForcedColdFactoryResponse") public class NodeResetForcedColdFactoryResponse { @XmlElement(name = "NodeResetForcedColdFactoryResult") protected NodeActionResult nodeResetForcedColdFactoryResult; /** * Gets the value of the nodeResetForcedColdFactoryResult property. * * @return * possible object is * {@link NodeActionResult } * */ public NodeActionResult getNodeResetForcedColdFactoryResult() { return nodeResetForcedColdFactoryResult; } /** * Sets the value of the nodeResetForcedColdFactoryResult property. * * @param value * allowed object is * {@link NodeActionResult } * */ public void setNodeResetForcedColdFactoryResult(NodeActionResult value) { this.nodeResetForcedColdFactoryResult = value; } }
[ "ggrunwald@airspan.com" ]
ggrunwald@airspan.com
dfd3ae68ba41fe6b316e0a41fec96f284920f4f4
9e084510fe512bb613d9e4d61052cdaeb5b21e9e
/src/main/java/com/example/pojo/Passage.java
9139359069ac063bca93b6947af450cbd0f3246e
[]
no_license
zixiaoshuixin/salephone-java
753f3cb3664f3e4d8bfc84703a93c6dff1cceb38
7e998eb001919991b812e6e4c967c06333775c66
refs/heads/master
2023-03-22T10:07:24.743171
2021-03-02T12:18:07
2021-03-02T12:18:07
343,754,361
0
0
null
null
null
null
UTF-8
Java
false
false
2,413
java
package com.example.pojo; import java.util.Date; public class Passage { /* * 文章标识符 */ private String postID; /** * 文章标题 */ private String postTitle; /** * 文章内容 */ private String postText; /** * 浏览人数 */ private int postPageviews; /** * 文章合成语音URL地址 */ private String postAudio; /** * 文章发表时间 */ private Date postTime; /** * 点赞数 */ private int postPageSupport; /** * 最后评论时间 */ private Date lastCmTime; /** * 作者用户名 */ private String userName; /** * 作者 */ private User user; public Passage() { super(); // TODO Auto-generated constructor stub } public String getPostID() { return postID; } public void setPostID(String postID) { this.postID = postID; } public String getPostTitle() { return postTitle; } public void setPostTitle(String postTitle) { this.postTitle = postTitle; } public String getPostText() { return postText; } public void setPostText(String postText) { this.postText = postText; } public int getPostPageviews() { return postPageviews; } public void setPostPageviews(int postPageviews) { this.postPageviews = postPageviews; } public String getPostAudio() { return postAudio; } public void setPostAudio(String postAudio) { this.postAudio = postAudio; } public Date getPostTime() { return postTime; } public void setPostTime(Date postTime) { this.postTime = postTime; } public int getPostPageSupport() { return postPageSupport; } public void setPostPageSupport(int postPageSupport) { this.postPageSupport = postPageSupport; } public Date getLastCmTime() { return lastCmTime; } public void setLastCmTime(Date lastCmTime) { this.lastCmTime = lastCmTime; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Passage [postID=" + postID + ", postTitle=" + postTitle + ", postText=" + postText + ", postPageviews=" + postPageviews + ", postAudio=" + postAudio + ", postTime=" + postTime + ", postPageSupport=" + postPageSupport + ", lastCmTime=" + lastCmTime + ", userName=" + userName + ", user=" + user + "]"; } }
[ "1843122304@qq.com" ]
1843122304@qq.com
1945834c8dc5374833e469a5f484077aa3f82c2b
2935dbf542f4798e6046d460f093bd83a4579deb
/src/net/ion/radon/cload/problems/CompilationProblem.java
570137cb732b70a8298b9121a329d8d672a0c111
[]
no_license
bleujin/aradon311
2a3d8c8d89956a34d2ce0ca322d14da0dde2ac0b
0d94113b398d5e70379068ef533479f09d7c1778
refs/heads/master
2020-04-12T03:09:56.589488
2017-02-17T05:41:02
2017-02-17T05:41:02
22,242,059
1
1
null
null
null
null
UTF-8
Java
false
false
1,882
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ion.radon.cload.problems; /** * An abstract definition of a compilation problem * * @author tcurdt */ public interface CompilationProblem { /** * is the problem an error and compilation cannot continue * or just a warning and compilation can proceed * * @return true if the problem is an error */ boolean isError(); /** * name of the file where the problem occurred * * @return name of the file where the problem occurred */ String getFileName(); /** * position of where the problem starts in the source code * * @return position of where the problem starts in the source code */ int getStartLine(); int getStartColumn(); /** * position of where the problem stops in the source code * * @return position of where the problem stops in the source code */ int getEndLine(); int getEndColumn(); /** * the description of the problem * * @return the description of the problem */ String getMessage(); }
[ "bleujin@gmail.com" ]
bleujin@gmail.com
82a66e7d1f419b95b6398437b3f077d51f7b0b1a
9bbe56fc6d8fbbc9af8e1401e75b5a6fd4683a8b
/FinalLCRANN/app/src/androidTest/java/com/example/android/finallcrann/ExampleInstrumentedTest.java
2c0c1e0212fd54e9c5a1698234c9750256779546
[]
no_license
lcrann12/lcrannCsci372
9260f969c388432d47bfd9214147bdb378f13586
5dc5f01b9c81ae144d423eaa405221dfb32a7637
refs/heads/master
2021-05-08T11:17:12.749477
2018-05-10T23:39:43
2018-05-10T23:39:43
119,888,771
0
0
null
null
null
null
UTF-8
Java
false
false
763
java
package com.example.android.finallcrann; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.android.finallcrann", appContext.getPackageName()); } }
[ "android@yoda.cs.widener.edu" ]
android@yoda.cs.widener.edu
7502eebde0f2b56f9bf1be94f50c870ef997ed93
201636f109d8de3d3dab649367c161afc61dfa7a
/Distributed-Whiteboard/src/whiteboard/comms/WhiteboardInterface.java
aa864d8435e0cdc47ac635965b044ab803e251ec
[]
no_license
kabi/Distributed-Whiteboard
12b3d0cf769b99df2f25ea499b9fb5fc95c669a7
3028e317c712eec9278192377407b9d31908cb67
refs/heads/master
2021-01-16T20:48:12.894470
2011-10-12T14:52:41
2011-10-12T14:52:41
2,431,286
1
0
null
null
null
null
UTF-8
Java
false
false
1,175
java
package whiteboard.comms; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.ArrayList; import whiteboard.object.AWhiteboardObject; // Remote interface for the server to be able to access the client methods public interface WhiteboardInterface extends Remote { /** * Synchronizes the client shapes when new shapes are drawn/ deleted * @param globalShapeList ShapeInfo object to be appended * @throws java.rmi.RemoteException exception */ public void setShapeList(ArrayList<AWhiteboardObject> globalShapeList) throws RemoteException; /** * Server calls this method to send a new object to the clients * @param item shape object received from the Whiteboard server * @throws java.rmi.RemoteException exception */ public void appendChartItem(AWhiteboardObject item) throws RemoteException; /** * Server calls this method to send messages to the clients * @param serverMessage message the server wishes to communicate with the clients * @throws java.rmi.RemoteException exception */ public void setServerMessage(String serverMessage) throws RemoteException; }
[ "Kabi@Kabiz" ]
Kabi@Kabiz
393a9a4fb6589a81ec91270339b926adf11bb71c
2be4eac50faddb7170b9008ccdfc3175a86d70f5
/src/ajmas74/daylighttracker/MapLayer.java
e6bd5bcc1a883e29cb37eaacb473886e866d8517
[]
no_license
ajmas/Daylight-Tracker
004895997dd795e47fc69a9977c54bf5b631320c
efff4a053b0285bac610ea16767df7cc9ca9aafd
refs/heads/master
2020-05-18T16:59:53.999561
2012-04-06T20:15:05
2012-04-06T20:15:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
944
java
package ajmas74.daylighttracker; import java.util.Date; import java.awt.*; public interface MapLayer { //would implementing an applet type interface be useful //with init, stop, refresh, etc? /** Get the short name of the layer */ public String getShortName(); /** Get the long name of the layer */ public String getLongName(); /** Indicates whether this layer is time dependant */ public boolean isTimeDependant(); /** The date and time for time based data */ public void setDateTime ( Date theDateTime ); /** The map rectangle that matches the component Rectangle */ public void setCoordRect ( MapCoordRect theRect ); /* Maybe create a configurable interface and place these here? */ /** Returns whether this layer is configurable */ public boolean isConfigurable(); /** get the Panel need for configuring this element */ public Component getConfigurationPanel(); }
[ "andrejohn.mas@gmail.com" ]
andrejohn.mas@gmail.com
124dc3fb3d1e307df2373b7602e2b0aeb02cc3a2
3e49e08ed83b5e3be344a07a7764cc458fe5510c
/Server/src/main/java/view/graphics/SettingController.java
1fec3957a4a2f08b0ab477244790693266c4ecda
[]
no_license
Advanced-Programming-2021/project-team-09
9f48a0f714e7127df54dd8f9dc700d29698c0fc0
796b3fcb104191d141f8e0572d400bde23282687
refs/heads/main
2023-06-28T13:38:22.147328
2021-07-21T20:08:01
2021-07-21T20:08:01
355,936,327
0
1
null
null
null
null
UTF-8
Java
false
false
3,526
java
package view.graphics; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Slider; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.AnchorPane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.stage.Stage; import model.enums.Cursor; import model.enums.VoiceEffects; import java.net.URL; import java.util.ResourceBundle; public class SettingController extends Menu implements Initializable { private final static MediaPlayer PLAYER = new MediaPlayer(getVoice("BackGroundMusic","mp3")); private static boolean isMute = false; private static double sfxVolume = 0.5; private static double volume = 0.5; @FXML private AnchorPane mainPane; @FXML private Button exitButton; @FXML private Button importExport; @FXML private Slider sfxSlider; @FXML private Slider volumeSlider; @FXML private ToggleButton muteToggle; public static double getSFX() { return sfxVolume; } @Override public void initialize(URL url, ResourceBundle resourceBundle) { initToggle(); exitButton.setOnMouseEntered(mouseEvent -> changeCursor(Cursor.CANCEL,mouseEvent)); exitButton.setOnMouseExited(mouseEvent -> changeCursor(Cursor.DEFAULT,mouseEvent)); justifyButton(importExport,Cursor.TRASH); importExport.setOnMouseClicked(mouseEvent -> { playMedia(VoiceEffects.CLICK); goToImportExport(); }); exitButton.setOnMouseClicked(mouseEvent -> { playMedia(VoiceEffects.EXPLODE); close(); }); volumeSlider.valueProperty().addListener((observableValue, number, t1) -> PLAYER.setVolume(t1.doubleValue())); sfxSlider.valueProperty().addListener((observableValue, number, t1) -> { sfxVolume = t1.doubleValue(); playMedia(VoiceEffects.KEYBOARD_HIT); }); volumeSlider.setValue(PLAYER.getVolume()); sfxSlider.setValue(sfxVolume); } private void initToggle() { muteToggle.setSelected(isMute); ToggleGroup group = new ToggleGroup(); group.getToggles().add(muteToggle); onSelectToggle(muteToggle,group); muteToggle.setOnAction(actionEvent -> { playMedia(VoiceEffects.CLICK); onSelectToggle(muteToggle,group); if (muteToggle.isSelected()) mute(); else unMute(); }); } private void close() { Scene scene = mainPane.getScene(); setCurrentScene(Menu.getSceneBuffer()); setSceneBuffer(null); ((Stage)scene.getWindow()).close(); } public static void playBG() { PLAYER.setVolume(0.5); PLAYER.setCycleCount(-1); PLAYER.play(); } private void mute() { isMute = true; PLAYER.setMute(true); PLAYER.pause(); } private void unMute() { isMute = false; PLAYER.setMute(false); PLAYER.play(); } private void goToImportExport() { Scene scene = new Scene(getNode("ImportExportMenu"),-1,-1,true); scene.setFill(Color.TRANSPARENT); Menu.setCurrentScene(scene); ((Stage)mainPane.getScene().getWindow()).setScene(scene); } }
[ "73402569+Mir-Abedi@users.noreply.github.com" ]
73402569+Mir-Abedi@users.noreply.github.com
5ea3826b40b35ab691be6bf7037e3133a93741a6
32b72e1dc8b6ee1be2e80bb70a03a021c83db550
/ast_results/zxing_zxing/core/src/main/java/com/google/zxing/ResultPoint.java
8b26fd132c620eac19341926de7a40c6b48fddca
[]
no_license
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
d90c41a17e88fcd99d543124eeb6e93f9133cb4a
0564143d92f8024ff5fa6b659c2baebf827582b1
refs/heads/master
2020-07-13T13:53:40.297493
2019-01-11T11:51:18
2019-01-11T11:51:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,521
java
// isComment package com.google.zxing; import com.google.zxing.common.detector.MathUtils; /** * isComment */ public class isClassOrIsInterface { private final float isVariable; private final float isVariable; public isConstructor(float isParameter, float isParameter) { this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; } public final float isMethod() { return isNameExpr; } public final float isMethod() { return isNameExpr; } @Override public final boolean isMethod(Object isParameter) { if (isNameExpr instanceof ResultPoint) { ResultPoint isVariable = (ResultPoint) isNameExpr; return isNameExpr == isNameExpr.isFieldAccessExpr && isNameExpr == isNameExpr.isFieldAccessExpr; } return true; } @Override public final int isMethod() { return isIntegerConstant * isNameExpr.isMethod(isNameExpr) + isNameExpr.isMethod(isNameExpr); } @Override public final String isMethod() { return "isStringConstant" + isNameExpr + 'isStringConstant' + isNameExpr + 'isStringConstant'; } /** * isComment */ public static void isMethod(ResultPoint[] isParameter) { // isComment float isVariable = isMethod(isNameExpr[isIntegerConstant], isNameExpr[isIntegerConstant]); float isVariable = isMethod(isNameExpr[isIntegerConstant], isNameExpr[isIntegerConstant]); float isVariable = isMethod(isNameExpr[isIntegerConstant], isNameExpr[isIntegerConstant]); ResultPoint isVariable; ResultPoint isVariable; ResultPoint isVariable; // isComment if (isNameExpr >= isNameExpr && isNameExpr >= isNameExpr) { isNameExpr = isNameExpr[isIntegerConstant]; isNameExpr = isNameExpr[isIntegerConstant]; isNameExpr = isNameExpr[isIntegerConstant]; } else if (isNameExpr >= isNameExpr && isNameExpr >= isNameExpr) { isNameExpr = isNameExpr[isIntegerConstant]; isNameExpr = isNameExpr[isIntegerConstant]; isNameExpr = isNameExpr[isIntegerConstant]; } else { isNameExpr = isNameExpr[isIntegerConstant]; isNameExpr = isNameExpr[isIntegerConstant]; isNameExpr = isNameExpr[isIntegerConstant]; } // isComment if (isMethod(isNameExpr, isNameExpr, isNameExpr) < isDoubleConstant) { ResultPoint isVariable = isNameExpr; isNameExpr = isNameExpr; isNameExpr = isNameExpr; } isNameExpr[isIntegerConstant] = isNameExpr; isNameExpr[isIntegerConstant] = isNameExpr; isNameExpr[isIntegerConstant] = isNameExpr; } /** * isComment */ public static float isMethod(ResultPoint isParameter, ResultPoint isParameter) { return isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr); } /** * isComment */ private static float isMethod(ResultPoint isParameter, ResultPoint isParameter, ResultPoint isParameter) { float isVariable = isNameExpr.isFieldAccessExpr; float isVariable = isNameExpr.isFieldAccessExpr; return ((isNameExpr.isFieldAccessExpr - isNameExpr) * (isNameExpr.isFieldAccessExpr - isNameExpr)) - ((isNameExpr.isFieldAccessExpr - isNameExpr) * (isNameExpr.isFieldAccessExpr - isNameExpr)); } }
[ "matheus@melsolucoes.net" ]
matheus@melsolucoes.net
eaa7e87b17f87f52b0d6586d01eacbaa36d7f4ea
2b675fd33d8481c88409b2dcaff55500d86efaaa
/infinispan/core/src/test/java/org/infinispan/distribution/DistSyncCacheStoreNotSharedNotConcurrentTest.java
c352a41471a892a7d05cac6929da8202e83fd6a9
[ "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
nmldiegues/stibt
d3d761464aaf97e41dcc9cc1d43f0e3234a1269b
1ee662b7d4ed1f80e6092c22e235a3c994d1d393
refs/heads/master
2022-12-21T23:08:11.452962
2015-09-30T16:01:43
2015-09-30T16:01:43
42,459,902
0
2
Apache-2.0
2022-12-13T19:15:31
2015-09-14T16:02:52
Java
UTF-8
Java
false
false
1,472
java
/* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.infinispan.distribution; import org.testng.annotations.Test; @Test(groups = "functional", testName = "distribution.DistSyncCacheStoreNotSharedNotConcurrentTest") public class DistSyncCacheStoreNotSharedNotConcurrentTest extends DistSyncCacheStoreNotSharedTest { public DistSyncCacheStoreNotSharedNotConcurrentTest() { supportConcurrentWrites = false; } public void testExpectedConfig() { assert !c1.getCacheConfiguration().locking().supportsConcurrentUpdates(); } }
[ "nmld@ist.utl.pt" ]
nmld@ist.utl.pt
0baab6b7238d0271f9159618efa7a1b5ac1b2ebe
3f6904ddd220e0cc9d17a95b546fbec146f18e43
/src/WeekThree/VisitAction.java
d25086db81fe7c924193384af9c514a67be3b05a
[]
no_license
dlnrodriguez/CSC180-class
1e5cc6ded72ecfada0f73f02d2c6b5373bf86cf8
1c55a533588d3eee18896f72785d22639d2ba5b2
refs/heads/master
2020-05-29T14:39:15.405690
2016-08-22T20:28:25
2016-08-22T20:28:25
62,110,443
0
0
null
null
null
null
UTF-8
Java
false
false
118
java
package WeekThree; /** * Created by DLN on 8/3/16. */ public interface VisitAction { void visit(String url); }
[ "dylonrodriguez.phd@gmail.com" ]
dylonrodriguez.phd@gmail.com
414e4af4ba9f1ebbd12515c182297e8122f719db
54a24781a7a09311456cb685f63f0e6d2bab4bab
/src/l1j/server/server/clientpackets/C_TaxRate.java
667c4f3f3417d70e5644e68eca75fa365982ebd1
[]
no_license
crazyidol9/L1J-KR_3.80
b1c2d849a0daad99fd12166611e82b6804d2b26d
43c5da32e1986082be6f1205887ffc4538baa2c6
refs/heads/master
2021-08-16T13:50:50.570172
2017-11-20T01:20:52
2017-11-20T01:20:52
111,041,969
0
0
null
2017-11-17T01:24:24
2017-11-17T01:24:24
null
UHC
Java
false
false
2,024
java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package l1j.server.server.clientpackets; import server.LineageClient; import l1j.server.server.model.L1Clan; import l1j.server.server.model.L1World; import l1j.server.server.model.Instance.L1PcInstance; import l1j.server.server.serverpackets.S_SystemMessage; // Referenced classes of package l1j.server.server.clientpackets: // ClientBasePacket public class C_TaxRate extends ClientBasePacket { private static final String C_TAX_RATE = "[C] C_TaxRate"; public C_TaxRate(byte abyte0[], LineageClient clientthread) throws Exception { super(abyte0); int i = readD(); int j = readC(); L1PcInstance player = clientthread.getActiveChar(); if (player == null) { return; } if (i == player.getId()) { L1Clan clan = L1World.getInstance().getClan(player.getClanname()); if (clan != null) { int castle_id = clan.getCastleId(); if (castle_id != 0) { player.sendPackets(new S_SystemMessage("세금 조정을 할수없습니다.")); //L1Castle l1castle = CastleTable.getInstance() // .getCastleTable(castle_id); //if (j >= 10 && j <= 50) { //l1castle.setTaxRate(j); //CastleTable.getInstance().updateCastle(l1castle); //} } } } } @Override public String getType() { return C_TAX_RATE; } }
[ "wantedgaming.net@gmail.com" ]
wantedgaming.net@gmail.com
74c9673244155396aee3b2dda8622d2d3b9c7a5e
84c697df35ca32253229b6a9fa6c0f1e9cce4723
/dyson/src/main/java/com/artigile/homestats/sensor/dyson/model/DysonPureCoolData.java
0b97d54ca9774e567eb93dd704c11e51abbd9b3a
[]
no_license
ioanbsu/homestats
925c6269020322fda1beae987fea36eab2f956f7
4835d62cc0f8d00b0114a1fe787d934f9238fd39
refs/heads/master
2021-01-18T14:20:12.023339
2020-02-27T04:04:49
2020-02-27T04:04:49
32,686,455
4
0
null
null
null
null
UTF-8
Java
false
false
1,133
java
package com.artigile.homestats.sensor.dyson.model; import java.time.Instant; /** * Dyson pure cool data. */ public class DysonPureCoolData { public final SensorData currentSensorData; public final State currentState; public final Instant lastRefreshed; public DysonPureCoolData(final Builder builder) { this.currentSensorData = builder.currentSensorData; this.currentState = builder.currentState; this.lastRefreshed = builder.lastRefreshed; } public static class Builder { private SensorData currentSensorData; private State currentState; private Instant lastRefreshed; public Builder withCurrentSensorData(final SensorData currentSensorData) { this.currentSensorData = currentSensorData; return this; } public Builder withCurrentState(final State currentState) { this.currentState = currentState; return this; } public DysonPureCoolData build() { this.lastRefreshed = Instant.now(); return new DysonPureCoolData(this); } } }
[ "ibahdanau@fitbit.com" ]
ibahdanau@fitbit.com
329d6348e76b24f0d4449d5c6b95175fca0de599
52f80c552ed5c18a7b6662244f7ea0708ba65869
/MyApplication4/app/src/main/java/com/example/myapplication/Model/User.java
62876d740978ab54c73032cc7e368d037df55ac0
[]
no_license
mrbossgame/Music-app-mobile
dbcd4cd4e80b280d65481140305496dc43345a63
2dbfa40fc1be2c3115a0fa2b1b738076ac2fdc3c
refs/heads/master
2022-10-05T10:14:29.290339
2020-06-06T15:36:27
2020-06-06T15:36:27
270,020,616
0
0
null
null
null
null
UTF-8
Java
false
false
1,279
java
package com.example.myapplication.Model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class User { @SerializedName("idUser") @Expose private String idUser; @SerializedName("TenUser") @Expose private String tenUser; @SerializedName("PassWord") @Expose private String passWord; @SerializedName("idBaiHat") @Expose private String idBaiHat; @SerializedName("idComMent") @Expose private String idComMent; public String getIdUser() { return idUser; } public void setIdUser(String idUser) { this.idUser = idUser; } public String getTenUser() { return tenUser; } public void setTenUser(String tenUser) { this.tenUser = tenUser; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public String getIdBaiHat() { return idBaiHat; } public void setIdBaiHat(String idBaiHat) { this.idBaiHat = idBaiHat; } public String getIdComMent() { return idComMent; } public void setIdComMent(String idComMent) { this.idComMent = idComMent; } }
[ "boylapdi.kr@gmail.com" ]
boylapdi.kr@gmail.com
0f19642adfc8ee3d5b6ee43e4b7475b214eb2c8f
477e1a631bd4e093d511b9ea3f53a7a4807c4d1e
/Android实现悬浮式顶部和底部标题栏效果/MyTitleBar02/src/com/yangyu/mytitlebar02/MentionActivity.java
a0c9b9a999c187cee8fe85fe86155d181b84cb6a
[]
no_license
sunnyvv/Mixingdrinks
765fe22f00bc96cbeeefc130f504ed980d3e55e6
d98b994833be6422da3412d2741fa85cd21aa5ba
refs/heads/master
2021-01-18T11:23:15.551258
2015-01-04T09:25:43
2015-01-04T09:25:43
28,742,889
0
0
null
2015-01-03T12:14:15
2015-01-03T12:14:14
null
IBM852
Java
false
false
377
java
package com.yangyu.mytitlebar02; import android.app.Activity; import android.os.Bundle; /** * @author yangyu * ╣Ž─▄├Ŕ╩÷ú║╠ßđĐActivityĎ│├Š */ public class MentionActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mention_activity); } }
[ "qingtiangw@163.com" ]
qingtiangw@163.com
2324030454bd9b84349040b4317e330dbed6ead0
6b2ac9d51867059829797e2be084e952287932a0
/WebApplication1/src/java/com/Msg.java
41dc82290eba2827474a51a4d98f4e3d734aa420
[]
no_license
salu2303/The-Classy-Events
6be0fe445eb1e5f882f3d70992a82d5a617cc47e
ebcca7ac8b8f7955643f0376bf99b9426ec286f9
refs/heads/master
2022-11-14T18:58:23.794055
2020-06-19T16:41:39
2020-06-19T16:41:39
273,541,097
0
0
null
null
null
null
UTF-8
Java
false
false
4,907
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Dell */ public class Msg extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { Cookie cookie = null; Cookie[] c = null; String vid =null; c = request.getCookies(); for (Cookie c1 : c) { cookie = c1; if ((cookie.getName()).equals("1")) { vid = (cookie.getValue()); } } int flag=0; //out.println(id); try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/se?[root on Default schema]", "root", ""); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("select id from status where id ="+vid); //out.println(rs.getString("id")); // out.println(rs.next()); while(rs.next()) { out.println("<h3>"+"...............................confirmation message..................................\n" + "\n" +"</br>"+ "Dear Customer,\n" +"</br>"+ "Thank you for choosing us for managing your event.\n" +"</br>"+ "This is Saloni from EVENTO .This is confirmation message that we will look forward for managing your events and we will contact soon for further formalities."+"</h3>"); javax.servlet.RequestDispatcher rs3 = request.getRequestDispatcher("show.html"); rs3.include(request, response); flag=1; } if(flag==0) { out.println("<h3>"+"Dear Customer,\n" + "Thank you for visiting our site.\n" +"</br>"+ "Your current status should one of this:\n"+"</br>" + " 1.You have not registered any event.\n" +"</br>"+ "2.Your event registration may be in pending list.We will inform you soon with confirmation massage."+"</h3>"); javax.servlet.RequestDispatcher rs3 = request.getRequestDispatcher("show.html"); rs3.include(request, response); } } catch (ClassNotFoundException e) { out.println(e); } catch (SQLException e) { out.println(e); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
[ "saloni230301@gmail.com" ]
saloni230301@gmail.com
b89dd4b592221b2ed8d7e9d83464b5ce25ca1a54
275c5bda1294283cb7c007fea0b6d1a43761e2bb
/raven-compiler/src/main/java/org/raven/antlr/ast/Return.java
ef929504d250afd56f22e60643995eb510e5f573
[ "MIT" ]
permissive
BradleyWood/Raven-Lang
5956bd480bc14d4481969dfec79312a66576855e
8ad3bf166a33b71975f2b87ba8ec67245289fad3
refs/heads/master
2021-07-10T22:03:25.246892
2019-01-06T10:24:12
2019-01-06T10:24:12
102,515,994
2
0
MIT
2018-07-03T17:56:53
2017-09-05T18:27:34
Java
UTF-8
Java
false
false
862
java
package org.raven.antlr.ast; import java.util.Objects; public class Return extends Statement { private final Expression value; public Return(final Expression value) { this.value = value; } public Expression getValue() { return value; } @Override public void accept(final TreeVisitor visitor) { visitor.visitReturn(this); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Return aReturn = (Return) o; return Objects.equals(value, aReturn.value); } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return "return" + (value != null ? " " + value.toString() : "") + ";"; } }
[ "bradley.wood@uoit.net" ]
bradley.wood@uoit.net
8757873a2597bfecd0e4d56034a64411372bbde4
aa3202384507fc99d83cfa3e3f957a9f16de1dc6
/src/forms/PnFabricante.java
a082c5fbb3b053229b71e3bbc722b055d7e61cb9
[]
no_license
vilmarschmelzer/poo2-rick
61f99c06e79fe41af5bd44ca4c68b075ca02e42b
9e8dcef655794e9b8a06cca19091355c4d5b03e2
refs/heads/master
2021-01-23T21:36:19.458854
2013-12-19T11:35:56
2013-12-19T11:35:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,736
java
package forms; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.ParseException; import java.util.ArrayList; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import javax.swing.text.MaskFormatter; import models.*; public class PnFabricante extends JPanel { private JFormattedTextField txtCnpj; private JTextField txtNome; private JTextField txtNome_fantasia; private DefaultTableModel tableModel; private JTable table; public JFormattedTextField getTxtCnpj(){ return txtCnpj; } public JTextField getTxtNome(){ return txtNome; } public JTextField getTxtNome_fantasia(){ return txtNome_fantasia; } public DefaultTableModel getTableModel(){ return tableModel; } public PnFabricante(){ setLayout(null); JLabel lblCnpj = new JLabel("CNPJ *"); lblCnpj.setBounds(10, 5, 120, 30); lblCnpj.setHorizontalAlignment(JLabel.RIGHT); add(lblCnpj); JLabel lblNome = new JLabel("Nome *"); lblNome.setBounds(10, 35, 120, 30); lblNome.setHorizontalAlignment(JLabel.RIGHT); add(lblNome); JLabel lblNome_fantasia = new JLabel("Nome fantasia"); lblNome_fantasia.setBounds(10, 65, 120, 30); lblNome_fantasia.setHorizontalAlignment(JLabel.RIGHT); add(lblNome_fantasia); MaskFormatter mask=new MaskFormatter(); try { mask = new MaskFormatter("##.###.###/####-##"); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } txtCnpj=new JFormattedTextField(mask); txtCnpj.setBounds(135, 5, 150, 25); add(txtCnpj); txtNome=new JTextField(); txtNome.setBounds(135, 35, 150, 25); add(txtNome); txtNome_fantasia=new JTextField(); txtNome_fantasia.setBounds(135, 65, 150, 25); add(txtNome_fantasia); String[] colunas = new String []{"CNPJ","Nome","Nome fantasia"}; tableModel = new DefaultTableModel(null,colunas); table = new JTable(tableModel){ public boolean isCellEditable(int rowIndex, int colIndex) { return false; } }; JScrollPane scrollPane = new JScrollPane(table); scrollPane.setBounds(10, 100, 300, 200); add(scrollPane); LimparCampos(); //add linha //model.addRow(new String[]{"t3","t4"}); table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int row = table.getSelectedRow(); txtCnpj.setText((String)tableModel.getValueAt(row, 0)); txtNome.setText((String)tableModel.getValueAt(row, 1)); txtNome_fantasia.setText((String)tableModel.getValueAt(row, 2)); txtCnpj.setEditable(false); } }); } public void LimparCampos(){ txtCnpj.setText(""); txtCnpj.setEditable(true); txtNome.setText(""); txtNome_fantasia.setText(""); } public void AtualizaTabela(ArrayList<Fabricante> list){ int rows = tableModel.getRowCount(); for(int i = rows - 1; i >=0; i--) { tableModel.removeRow(i); } for (Fabricante fabricante : list) { tableModel.addRow(new String[] {fabricante.getCnpj()+"",fabricante.getNome(),fabricante.getNome_fantasia()}); } } public Fabricante getObjetoTela(){ System.out.println(txtCnpj.getText()); String cnpj=txtCnpj.getText(); System.out.println("cnpj "+cnpj); cnpj=cnpj.replace(".", "").replace("-", "").replace("/", ""); System.out.println(cnpj); return new Fabricante(cnpj,txtNome.getText(),txtNome_fantasia.getText()); } public boolean ValidarCampos(){ if(txtCnpj.getText().equals("")||txtNome.getText().equals("")) return false; return true; } }
[ "vilmarsss@gmail.com" ]
vilmarsss@gmail.com
9eeaf8eb1d5fa069354e21d3cbf29bb755365e9b
2298c4b740fd996c0538840fb3a0fa76cb0d0ded
/src/main/java/com/team/manage/common/util/secert/DESSecret.java
7a2c9c8a7f9f6887306c4bf0ab79e3dee2da4192
[]
no_license
EliteCollection/server
50756146eea75dfd91fa8658fd94b58b0797d28e
0f843b338fc523b235b8fe49939dec49840e7324
refs/heads/feature-v1.0.0
2022-07-09T12:48:30.083657
2019-06-05T08:25:54
2019-06-05T08:25:54
166,790,373
3
0
null
2022-06-17T02:03:30
2019-01-21T09:56:13
Java
UTF-8
Java
false
false
5,123
java
package com.team.manage.common.util.secert; import com.team.manage.enums.SecretType; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.Key; import java.security.SecureRandom; /** * DES对称加密算法 * * @author tcyu */ public class DESSecret extends Secret { // 算法名称 public static final String KEY_ALGORITHM = "DES"; public static final String KEY_DES_NOPADDING = "DES/ECB/NoPadding"; // 算法名称/加密模式/填充方式 // DES共有四种工作模式-->>ECB:电子密码本模式、CBC:加密分组链接模式、CFB:加密反馈模式、OFB:输出反馈模式 public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding"; /** * 生成密钥 * * @param keyStr * @return * @throws Exception */ private SecretKey keyGenerator(String keyStr) throws Exception { MD5Secret md5Secret = (MD5Secret) SecretFactory.getInstance().getSecret(SecretType.MD5); byte input[] = HexString2Bytes(md5Secret.encode(keyStr)); DESKeySpec desKey = new DESKeySpec(input); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); return securekey; } private int parse(char c) { if (c >= 'a') return (c - 'a' + 10) & 0x0f; if (c >= 'A') return (c - 'A' + 10) & 0x0f; return (c - '0') & 0x0f; } // 从十六进制字符串到字节数组转换 public byte[] HexString2Bytes(String hexstr) { byte[] b = new byte[hexstr.length() / 2]; int j = 0; for (int i = 0; i < b.length; i++) { char c0 = hexstr.charAt(j++); char c1 = hexstr.charAt(j++); b[i] = (byte) ((parse(c0) << 4) | parse(c1)); } return b; } public static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } @Override public String encode(String str, String coded) throws SecretException { throw new SecretException("DES接密需要密钥"); } @Override public String decode(String str, String coded) throws SecretException { throw new SecretException("DES加密,需要密钥"); } @Override public String decodeWithKey(String str, String coded, String key) throws Exception { Key deskey = keyGenerator(key); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); // 初始化Cipher对象,设置为解密模式 cipher.init(Cipher.DECRYPT_MODE, deskey); // 执行解密操作 BASE64Decoder deceode = new BASE64Decoder(); return new String(cipher.doFinal(deceode.decodeBuffer(str))); } @Override public String encodeWithKey(String str, String coded, String key) throws Exception { Key deskey = keyGenerator(key); // 实例化Cipher对象,它用于完成实际的加密操作 Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); SecureRandom random = new SecureRandom(); // 初始化Cipher对象,设置为加密模式 cipher.init(Cipher.ENCRYPT_MODE, deskey, random); byte[] results = cipher.doFinal(str.getBytes()); // 该部分是为了与加解密在线测试网站(http://tripledes.online-domain-tools.com/)的十六进制结果进行核对 for (int i = 0; i < results.length; i++) { //System.out.print(results[i] + " "); } // 执行加密操作。加密后的结果通常都会用Base64编码进行传输 BASE64Encoder encode = new BASE64Encoder(); return encode.encode(results); } /** * @param args */ public static void main(String[] args) throws Exception { DESSecret desSecret = new DESSecret(); String permission = "2,3,4,5,6,7,8,9,10,11,12,13,14,15,84,96,98,104,105,117"; String permission1 = "2,3,4,5,6,7,8,9,10,11,12,13,14,15,96,98"; // String macAddress = "40-B0-34-52-FB-79"; //jjwu专属有线 // String macAddress = "C8-21-58-7E-BC-D3"; //jjwu专属无线 String macAddress = "AC-DE-48-00-11-22"; String secretKey = desSecret.encodeWithKey(permission1, "utf-8", "47174063-8" + macAddress + "jh520"); System.out.println(secretKey); System.out.println(desSecret.decodeWithKey(secretKey, "utf-8", "47174063-8" + macAddress + "jh520")); // eM0hSe6np5E= } }
[ "yutc93@qq.com" ]
yutc93@qq.com
62df924ca94683969fc47e4ed0b88fbf8e0c4f31
e9a6574e6ec50c39a6923ade3743da1401776f6f
/Training/src/Threads/ThreadsBasics/Problem.java
781163616db92064499dd10552d54d02936c1dad
[]
no_license
bardas-oleksandr/Homeworks_All
bc1a6658c5c70aca94c5a5345ba42f00caf9de40
bf24021afcb4d0287469762761fdfff1d816a329
refs/heads/master
2020-04-28T06:47:36.046027
2019-03-11T19:34:51
2019-03-11T19:34:51
175,071,275
0
0
null
null
null
null
UTF-8
Java
false
false
901
java
package Threads.ThreadsBasics; import Interfaces.IProblem; public class Problem implements IProblem { @Override public void solve() { System.out.println("EXAMPLE #1"); Thread thread = Thread.currentThread(); System.out.println(thread); thread.setName("My thread"); thread.setPriority(Thread.NORM_PRIORITY + 5); System.out.println(thread); try { for (int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException е){ System.out. println( "Глaвный поток исполнения прерван"); } //Пример по синхронизации Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }
[ "iskander0119@gmail.com" ]
iskander0119@gmail.com
25eaa3ce17d3691ec17fa4d0bf33138736a3ffdd
1c126f978f9a01c751837ea7a6cb42823dceb140
/app/src/main/java/br/com/asb/activity/BackupSQLActivity.java
702a910d150d8e3c471d7957c09cda91669ac3ce
[]
no_license
Felssca/Burn_out
30b3fbbb1465ce2f45fd1914ea22df09cb9ceec2
77b88d64b8c538a96515c9292db7ca16a84a9d14
refs/heads/master
2022-11-12T19:27:35.175713
2020-06-29T04:15:19
2020-06-29T04:15:19
265,431,879
0
0
null
null
null
null
UTF-8
Java
false
false
7,197
java
package br.com.asb.activity; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import br.com.asb.R; import br.com.asb.dialog.GeneralSysDialog; import br.com.asb.util.UtilDate; import static android.support.v4.content.FileProvider.getUriForFile; public class BackupSQLActivity extends Activity { TextView nomeBakup; Button btnBackup; Button btnCompartilhar; final String caminhoBancoIn = "/data/data/com.aplication.asb.asb/databases/ASB.db"; GeneralSysDialog generalSysDialog; String nomeArquivoBackup = ""; String arquivoBackupType = ""; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_backup); intiView(); acaoButton(); } void intiView(){ nomeBakup = (TextView) findViewById(R.id.txt_nome_ultimo_backup); btnBackup = (Button) findViewById(R.id.btn_novo_backup); btnCompartilhar = (Button) findViewById(R.id.btn_compartilhar_backup); PermissoesActivity.verifyStoragePermissions(this); try { if(criarPastaDadosSQLiteBakcup()){ backupBaseDados(); }else{ } }catch(Exception ex){ ex.printStackTrace(); } } private void acaoButton() { btnBackup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { backupBaseDados(); } catch (Exception e) { e.printStackTrace(); } } }); btnCompartilhar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { compartilharBancoDados(); } catch (Exception e) { e.printStackTrace(); } } }); } private boolean criarPastaDadosSQLiteBakcup(){ PermissoesActivity.verifyStoragePermissions(this); boolean success = false; try { File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "ASB"); success = true; if (!folder.exists()) { success = folder.mkdirs(); } if (success) { // Do something on success } else { generalSysDialog = new GeneralSysDialog(BackupSQLActivity.this); generalSysDialog.setDialog(R.string.dialog_corpo_backup_sql_erro_01,R.string.dialog_corpo_backup_sql_erro_01,1); } } catch (Exception e) { generalSysDialog = new GeneralSysDialog(BackupSQLActivity.this); generalSysDialog.setDialog(e.getMessage(),e.getCause().toString(),1); } finally { } return success; } /* Persiste os dados no celular "Efetua o Backup da base de dados" */ private void backupBaseDados()throws IOException{ OutputStream output = null; FileInputStream fis = null; UtilDate utilDate = new UtilDate(); PermissoesActivity.verifyStoragePermissions(this); try { File dbFile = new File(caminhoBancoIn); fis = new FileInputStream(dbFile); String numeroAliatorio = utilDate.gerarNumeroAliatorio(); nomeArquivoBackup = "ASB_copy_"+utilDate.dataAtual()+"-"+numeroAliatorio+".db"; String outFileName = Environment.getExternalStorageDirectory() +"/ASB/"+nomeArquivoBackup; // Open the empty db as the output stream output = new FileOutputStream(outFileName); nomeBakup.setText(outFileName); // Transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { output.write(buffer, 0, length); } generalSysDialog = new GeneralSysDialog(BackupSQLActivity.this); generalSysDialog.setDialog(R.string.dialog_titulo_backup_sql,R.string.dialog_corpo_backup_sql,2); }catch(IOException ex){ ex.printStackTrace(); generalSysDialog = new GeneralSysDialog(BackupSQLActivity.this); generalSysDialog.setDialog(ex.getMessage(),ex.getCause().toString(),1); }finally { output.flush(); output.close(); fis.close(); } } /* Preparar arquivo */ private void compartilharBancoDados()throws IOException{ PermissoesActivity.verifyStoragePermissions(this); InputStream inputStream = null; FileOutputStream fileOutputStream = null; FileInputStream fileInputStream = null; File bancoBkp; try { String arquivo = nomeBakup.getText().toString(); bancoBkp = new File(Environment.getExternalStorageDirectory()+"/ASB/",nomeArquivoBackup); compartilharBancoDadosShare(bancoBkp); /* fileInputStream = openFileInput(bancoBkp.toString()); int size = fileInputStream.available(); byte[]buffer = new byte[size]; fileInputStream.read(buffer); bancoBkp = new File(fileInputStream.toString()); */ }catch(Exception ex){ ex.printStackTrace(); generalSysDialog = new GeneralSysDialog(BackupSQLActivity.this); generalSysDialog.setDialog(ex.getMessage(),ex.getCause().toString(),1); }finally { inputStream.close(); fileOutputStream.close(); } } /* Compartilhar o arquivo */ private void compartilharBancoDadosShare(File file)throws IOException{ PermissoesActivity.verifyStoragePermissions(this); try { Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setAction(Intent.ACTION_SEND); Uri fileUri = getUriForFile(getApplicationContext(),"br.com.asb",file); shareIntent.putExtra (Intent.EXTRA_STREAM, fileUri); shareIntent.setType("application/vnd.sqlite3"); startActivity(shareIntent); }catch( Exception ex){ ex.printStackTrace(); generalSysDialog = new GeneralSysDialog(BackupSQLActivity.this); generalSysDialog.setDialog(ex.toString(),ex.getCause().toString(),1); } } }
[ "felipessca@gmail.com" ]
felipessca@gmail.com
8ee78b38b275efd10b7421de8861fca5d07600f7
55787868f10d29caf64dede77ce5499a94c9cad8
/java/springbootvue/official/chapter09/rediscache/src/main/java/org/sang/rediscache/Book.java
86fc74e8c240abddc88f3fd71dbede6fed399ea0
[]
no_license
JavaAIer/NotesAndCodes
d4d14c9809c871142af6a6eec79b61ea760d15fb
83ebbc0ee75d06ead6cb60ec7850989ee796ba6f
refs/heads/master
2022-12-13T02:27:01.960050
2019-12-24T01:57:10
2019-12-24T01:57:10
158,776,818
3
1
null
2022-12-09T10:11:57
2018-11-23T03:32:43
Java
UTF-8
Java
false
false
791
java
package org.sang.rediscache; import java.io.Serializable; public class Book implements Serializable { private Integer id; private String name; private String author; @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
[ "cuteui@qq.com" ]
cuteui@qq.com
5926e5f5b4d0a0d8c17d4ae4eb419668991c354f
b34d2f5e8918be98d9ac88ea1350f64ea3e8c171
/test/com/java/controller/gameplay/GameplayTestSuite.java
75329b933199bb26f6023d2dac9478139abc1e03
[]
no_license
heis-en-berg/RISK
bf04b09cfa27e3060b3a5e844445f3346213c637
24c54884812130e43cbcfa6402bc1ead2dc90912
refs/heads/master
2020-05-12T18:24:35.873739
2019-04-15T18:22:17
2019-04-15T18:22:17
181,540,377
0
0
null
null
null
null
UTF-8
Java
false
false
490
java
package com.java.controller.gameplay; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ReinforcementTest.class, AttackTest.class, FortificationTest.class}) /** * This class is the suit to run the test cases of every test class. * * @author Arnav Bhardwaj * @author Karan Dhingra * @author Ghalia Elkerdi * @author Sahil Singh Sodhi * @author Cristian Rodriguez * @version 2.0.0 * */ public class GameplayTestSuite { }
[ "sahilsodhi@sahils-MacBook-Pro.local" ]
sahilsodhi@sahils-MacBook-Pro.local
c83561fff0a5bb40e24c83f061aab4fb42dcc870
d4735ee8c30d52aa4756264101d140e0db0288aa
/web/src/main/java/com/coded2/infra/message/Message.java
ef56dad1e3bb31f7c32ab4f0fd4f2b11bc33cb31
[]
no_license
rogerioAnderson/sas
e7b5007707eab155f8b8c5ff3103e3d5110d0bcb
280e176b0ad6792bd7c10856c78a85005dc8fb98
refs/heads/master
2020-05-22T04:20:36.356285
2016-11-09T00:32:05
2016-11-09T00:32:05
60,915,269
0
2
null
null
null
null
UTF-8
Java
false
false
623
java
package com.coded2.infra.message; import java.io.Serializable; public class Message implements Serializable{ private static final long serialVersionUID = 1L; private ReturnCode returnCode ; private Object result; private String text[]; public String[] getText() { return text; } public void setText(String... text) { this.text = text; } public ReturnCode getReturnCode() { return returnCode; } public void setReturnCode(ReturnCode returnCode) { this.returnCode = returnCode; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } }
[ "rogerioanderson@gmail.com" ]
rogerioanderson@gmail.com
80c04564bad104fc883b04c5362fe94ef39db765
b87f3ed116debdbb40f892e6a0216f4ded829cd4
/src/main/java/com/freshdesk/clientapi/wrapper/UserResponseWrapper.java
bd73949e24ecf645b2b5e7275ed539c88772fbe1
[]
no_license
rchincho/clientfreshdesk
8f00ae1d6087a645a12e0535f4268a2437d58869
18eba4f1cbf8a6eebf9f5052f536c9c67d08d689
refs/heads/master
2020-05-16T04:33:06.262786
2016-11-12T13:20:47
2016-11-12T13:20:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package com.freshdesk.clientapi.wrapper; import com.google.gson.annotations.SerializedName; import com.freshdesk.clientapi.domain.User; /** * Created by usuario on 29/03/16. */ public class UserResponseWrapper { @SerializedName("user") private User user; public UserResponseWrapper(User user){ this.user = user; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
[ "viny.md@hotmail.com" ]
viny.md@hotmail.com
447ceb0cd3eb19b3b843f0b848bd0b4a93a5e684
34e55a7531813c219c191f084196ebfe0d3d0b4c
/level07/lesson04/task04/Solution.java
67eb9d27fa5b21f1cd75b52a536f4fdd584433df
[]
no_license
bezobid/javarush
c5b8f09e78bc7020c00810ea4a82267ea30dab9f
20a8b7e90a14a406b4fa02fc1b75707297d06428
refs/heads/master
2021-01-21T06:53:33.411811
2017-05-17T15:16:28
2017-05-17T15:16:28
91,590,091
0
0
null
null
null
null
UTF-8
Java
false
false
1,061
java
package com.javarush.test.level07.lesson04.task04; import java.io.BufferedReader; import java.io.InputStreamReader; /* Массив из чисел в обратном порядке 1. Создать массив на 10 чисел. 2. Ввести с клавиатуры 10 чисел и записать их в массив. 3. Расположить элементы массива в обратном порядке. 4. Вывести результат на экран, каждое значение выводить с новой строки. */ public class Solution { public static void main(String[] args) throws Exception { int[] ar = new int[10]; BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); for (int a = 0; a < ar.length; a++){ ar[a] = Integer.parseInt(read.readLine()); } int[] ar1 = new int [10]; for (int a = 0; a < ar.length; a++){ ar1[a] = ar[ar.length - 1 - a]; System.out.println(ar1[a]); } } }
[ "sugubo@gmail.com" ]
sugubo@gmail.com
2382c06840d87d5f86819ed9d3e0936fb4e83940
fadd499cb9c1e8085958670c2e698606f176048f
/src/main/java/flink2hive.java
35cd880075e0b90db513bf593a3648df9d729810
[]
no_license
SChao625/flinkStreaming
eaf8781aa039ecff3181f6576576090be554cde8
22a552447bd0c12f23b91a963f02d0fe01c8b3c8
refs/heads/master
2022-12-06T05:29:14.215783
2020-09-03T06:26:12
2020-09-03T06:26:12
292,482,177
0
0
null
null
null
null
UTF-8
Java
false
false
1,445
java
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.TableEnvironment; import org.apache.flink.table.api.java.StreamTableEnvironment; import org.apache.flink.table.catalog.hive.HiveCatalog; import org.apache.flink.types.Row; public class flink2hive { public static void main(String[] args) { EnvironmentSettings settings = EnvironmentSettings.newInstance().inBatchMode().build(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env,settings); String name = "myhive"; String defaultDatabase = "default"; String hiveConfDir = "E:\\idea\\IDEApro\\src\\main\\conf"; // a local path String version = "1.1.0"; HiveCatalog hive = new HiveCatalog(name, defaultDatabase, hiveConfDir, version); tableEnv.registerCatalog("myhive", hive); // set the HiveCatalog as the current catalog of the session tableEnv.useCatalog("myhive"); Table sql = tableEnv.sqlQuery("select * from dept"); tableEnv.toAppendStream(sql, Row.class).print(); try { tableEnv.execute("adas"); } catch (Exception e) { e.printStackTrace(); } } }
[ "shancaho0625@163.com" ]
shancaho0625@163.com
c247de930a5655c0db83046b28675364b12e212a
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-14227-10-22-NSGA_II-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/store/migration/AbstractDataMigrationManager_ESTest.java
f56dc66621094b643df23fe99c6df7608be571a6
[]
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
592
java
/* * This file was automatically generated by EvoSuite * Sat Jan 18 19:13:13 UTC 2020 */ package com.xpn.xwiki.store.migration; 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 AbstractDataMigrationManager_ESTest extends AbstractDataMigrationManager_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
4a70c7ebe981f7e3e8cb861476789200473983b0
53b8fa1d5d3d6fc99a5e95adc5c7157b0ccfd9d6
/club-java/src/main/java/club/entity/EventDetail.java
28eebd56d005535862d38d91f1323b8554d1e273
[]
no_license
Spencer0115/club-app
76a914236bb2c849314fb29a4f117675d643e321
641569614f549acd455a353d3c297493c510ec4f
refs/heads/master
2022-11-29T14:18:40.343086
2020-08-01T03:49:09
2020-08-01T03:49:09
284,178,127
0
0
null
null
null
null
UTF-8
Java
false
false
1,805
java
package club.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="user_eventDetail") public class EventDetail { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "eventDetail_id") private Long id; @Column(name="eventDetail_eventId") private Long eventId; @Column(name="eventDetail_playerId") private Long playerId; @Column(name="eventDetail_clubId") private Long clubId; public Long getClubId() { return clubId; } public void setClubId(Long clubId) { this.clubId = clubId; } @Column(name="eventDetail_teamId") private Long teamId; @Column(name="eventDetail_status") private String status;//0:sent 1: accepted 2:declined 3:expired @Column(name="eventDetail_score") private Integer score; @Column(name="eventDetail_isFlag") private String isFlag; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getEventId() { return eventId; } public void setEventId(Long eventId) { this.eventId = eventId; } public Long getPlayerId() { return playerId; } public void setPlayerId(Long playerId) { this.playerId = playerId; } public Long getTeamId() { return teamId; } public void setTeamId(Long teamId) { this.teamId = teamId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public String getIsFlag() { return isFlag; } public void setIsFlag(String isFlag) { this.isFlag = isFlag; } }
[ "spencerhu0115@gmail.com" ]
spencerhu0115@gmail.com
817d99678620c15bfe47f4737d59bf05239902c0
bda304e0d37517d192ce716ff1063e76513f770d
/src/main/java/pl/fintech/solidlending/solidlendigplatform/domain/common/values/Rating.java
6954eedf5da07d7a9d94d675181a75a9aea10ec6
[]
no_license
bartflor/social-lending-app
e20908ec7f5397aa6f4824c97bae2476971525df
bc0b27ceee43f7e2b863877c66688245940709a6
refs/heads/master
2023-01-24T03:50:30.704091
2020-12-07T17:44:23
2020-12-07T17:44:23
319,388,773
2
0
null
null
null
null
UTF-8
Java
false
false
1,026
java
package pl.fintech.solidlending.solidlendigplatform.domain.common.values; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import java.util.ArrayList; import java.util.List; import java.util.Optional; @ToString @EqualsAndHashCode @AllArgsConstructor @Getter public class Rating { Double totalRating; List<Opinion> opinions; public Rating(){ this.totalRating = 1.0; this.opinions = new ArrayList<>(); } public void saveOpinion(Opinion newOpinion) { Optional<Opinion> oldOpinion = opinions.stream() .filter(opinion -> opinion.getInvestmentId().equals(newOpinion.getInvestmentId())) .findAny(); oldOpinion.ifPresentOrElse(opinion -> {opinion.setOpinionRating(newOpinion.getOpinionRating()); opinion.setOpinionText(newOpinion.getOpinionText());}, () -> opinions.add(newOpinion)); totalRating = (opinions.stream() .mapToDouble(opinionEntity -> opinionEntity.getOpinionRating()) .average().orElse(0)); } }
[ "bartflor@gmail.com" ]
bartflor@gmail.com
ede792acb61d7a152185583e6c7bbb7646026a7d
b9941e03805d9f82ed4d37c0699ae8f682965198
/CoreJavaPracticeExample/src/collection/HashMapDemo.java
1d422556405a3ae6d8ad425c004cb0e1b3658932
[]
no_license
alokkumar-github/CoreJava-DS-DP-Practice
3fef84f868640ce92e4b309edd39a2ee4c072a0b
7a3f7b5558c949966116108ebd6094209fffbc0b
refs/heads/master
2021-01-19T15:49:29.430197
2018-09-14T06:01:01
2018-09-14T06:01:01
88,231,919
1
0
null
null
null
null
UTF-8
Java
false
false
15,128
java
package collection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.WeakHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; public class HashMapDemo { private static void hashSetTest() { Set<String> hm = new HashSet<String>(2); hm.add("a"); hm.add("b"); hm.add("a"); hm.add(null); System.out.println("sizeNow 1 ::" + hm.size()); hm.add("c"); System.out.println("sizeNow 2 ::" + hm.size()); hm.add("a"); System.out.println("sizeNow 3 ::" + hm.size()); hm.add("d"); System.out.println("sizeNow 4 ::" + hm.size()); hm.add(null); System.out.println(hm); System.out.println("sizeNow 5 ::" + hm.size()); Iterator<String> itr=hm.iterator(); while(itr.hasNext()){ String str=(String)itr.next(); System.out.println(str); } /* * public boolean add(E e) { return map.put(e, PRESENT)==null; }Now if you closely examine the return map.put(e, PRESENT)==null; of add(e, E) method. There can be two possibilities : * if map.put(k,v) returns null ,then map.put(e, PRESENT)==null; will return true and element will be added. if map.put(k,v) returns old value for the key ,then map.put(e, PRESENT)==null; will return false and element will not be added. 1. null, if the key is unique and added to the map 2. Old value of the key, if key is duplicate*/ } public static void whystringbuffernotoverrideequalhascode() { String str1 = new String("sunil"); String str2 = new String("sunil"); HashMap hm = new HashMap(); hm.put(str1,"hello"); hm.put(str2,"bye"); // hm = { sunil=bye } System.out.println("stringbuilder::: "+hm); StringBuilder sb1 = new StringBuilder("sunil"); StringBuilder sb2 = new StringBuilder("sunil"); HashMap hm1 = new HashMap(); hm1.put(sb1,"hello");//sb1 and sb2 will return different HashCode hm1.put(sb2,"bye");// StringBuffer/StringBuilder does not override hashCode/equals methods System.out.println("stringbuilder::: "+hm1); } public static void concurentModificationException(){ //concept 6: we concurrent modificationException //occur if we remove element while iterate list. List<Integer> ls=new ArrayList<Integer>(); for(int i=1;i<10;i++){ ls.add(i); } System.out.println("Before Deleting List::"+ls); Iterator<Integer> itr=ls.iterator(); while(itr.hasNext()){ int i=4, j=4; if(i==4) ls.remove(i); } //or /*for(Integer i:ls){ if(i==1) ls.remove(i); }*/ // using iter we can remove the element for (Iterator<Integer> iter = ls.iterator(); iter.hasNext();) { Integer s = iter.next(); if (s==1) { iter.remove(); } else { System.out.println(s); } } System.out.println("After Deleting List ::: "+ls); } public static void main(String str[]) { // hashSetTest(); hashSetCoustomKey(); // hashMapT(); // hashMapsortBykey(); // hashMapCoustomKey(); // hashMapCoustomKeySortKey(); treemap(); // treemapCustomKey(); // terreMapCusomkeyByComparator(); // treeset(); //concurentModificationException(); //sortByValues(); // SortByKey(); // whystringbuffernotoverrideequalhascode(); // weakMapTest(); } private static void hashMapsortBykey() { HashMap<String, Integer> hm = new HashMap<String, Integer>(); Integer m1 = hm.put("a1", 21); //Integer m2 = hm.put(null, 11); // nullpointerExcption Integer m3 = hm.put("c1", null); Integer m4 = hm.put("b1", 31); Integer m5 = hm.put("a1", 32); sortbykey(hm); } private static void hashMapCoustomKeySortKey() { hashMapCoustomKey(); } // Function to sort map by Key public static void sortbykey(Map map) { ArrayList<String> sortedKeys = new ArrayList<String>(map.keySet()); Collections.sort(sortedKeys); // Display the TreeMap which is naturally sorted for (String x : sortedKeys) System.out.println("Key = " + x + ", Value = " + map.get(x)); } private static void treemap() { Map<String,Integer> tm = new TreeMap<>(); tm.put("a", 1); tm.put("b", 2); // tm.put(null, null); // nullpointerexceptoin , not allow null as key tm.put("c", null); // but allow many value as key System.out.println(tm); // key sorted as natual order. red black tree implementation } private static void terreMapCusomkeyByComparator() { // Concept 4:By using name comparator (String comparison); TreeMap<Empl, Integer> tm = new TreeMap<Empl, Integer>(new MyNameComp()); tm.put(new Empl("A"), 9); // pass the comparator constructor; tm.put(new Empl("L"), 90); tm.put(new Empl("R"), 80); tm.put(new Empl("B"), 99); Set<Empl> keys = tm.keySet(); for (Empl key : keys) { System.out.println(key + " ==> " + tm.get(key)); } } private static void sortbyvalue(){ HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(5, "A"); hmap.put(11, "C"); hmap.put(4, "Z"); hmap.put(77, "Y"); hmap.put(9, "P"); hmap.put(66, "Q"); hmap.put(0, "R"); System.out.println("Before Sorting:"); Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry me = (Map.Entry)iterator.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } Map<Integer, String> map = sortByValues(hmap); System.out.println("After Sorting:"); Set set2 = map.entrySet(); Iterator iterator2 = set2.iterator(); while(iterator2.hasNext()) { Map.Entry me2 = (Map.Entry)iterator2.next(); System.out.print(me2.getKey() + ": "); System.out.println(me2.getValue()); } } private static HashMap sortByValues(HashMap map) { List list = new LinkedList(map.entrySet()); // Defined Custom Comparator here Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); // Here I am copying the sorted list in HashMap // using LinkedHashMap to preserve the insertion order HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } private static void SortByKey() { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(5, "A"); hmap.put(11, "C"); hmap.put(4, "Z"); hmap.put(77, "Y"); hmap.put(9, "P"); hmap.put(66, "Q"); hmap.put(0, "R"); System.out.println("Before Sorting:"); Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry me = (Map.Entry) iterator.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } /* * for(Entry<String, String> entry : entries){ * System.out.println(entry.getKey() + " ==> " + entry.getValue()); } */ Map<Integer, String> map = new TreeMap<Integer, String>(hmap); System.out.println("After Sorting:"); Set set2 = map.entrySet(); Iterator iterator2 = set2.iterator(); while (iterator2.hasNext()) { Map.Entry me2 = (Map.Entry) iterator2.next(); System.out.print(me2.getKey() + ": "); System.out.println(me2.getValue()); } } private static void arryrlist() { } private static void linkeeedlist() { } private static void CopyOnWriteArrayListll() { List ll = new CopyOnWriteArrayList(); } private static void CopyOnWritesetll() { Set ll = new CopyOnWriteArraySet(); } /* * 1. TreeMap in Java using natural ordering of keys TreeMap naturalOrderMap = new TreeMap(); 2. TreeMap with custom sorting order TreeMap customSortingMap = new TreeMap(Comparator comparator) Objects stored in this TreeMap will be ordered according to given Comparator. 3. TreeMap from existing SortedMap TreeMap sameOrderMap = new TreeMap(SortedMap sm) */ private static void treemapCustomKey() { Map<Employee, Integer> ll = new TreeMap<Employee, Integer>(); ll.put(new Employee("a"), 3);// Concept 1 :: // java.lang.ClassCastException: // collection.Employee cannot be cast to // java.lang.Comparable. // so employee class should implements // Comparable interface or use Comparator // (see .terreMapCusomkeyByComparator example) ll.put(new Employee("b"), 0); ll.put(new Employee("c"), 8); ll.put(new Employee("d"), 10); ll.put(new Employee("d"), null); ll.put(new Employee("d"), 6); // ll.put(null, 6); does not allow null System.out.println(ll); } private static void hashMapCoustomKey() { Map map = new HashMap(); map.put(new Employee("a"), 1); map.put(new Employee("b"), 1); map.put(new Employee("c"), 1); map.put(new Employee("d"), 6); map.put(new Employee("e"), 1); map.put(new Employee("a"), 19); // and duplicate key will be added. System.out.println(map); System.out.println(map.get(new Employee("d"))); // **Concept 2. this will return null .if we have not to ovrride // hashcode and equal method } private static void hashMapT() { // unorder, HashMap<String, Integer> hm = new HashMap<String, Integer>(); Integer m1 = hm.put("a1", 21); Integer m2 = hm.put(null, 11); Integer m3 = hm.put(null, null); Integer m4 = hm.put("b1", 31); Integer m5 = hm.put("a1", 32); Integer m6 = hm.put("a1", 51); Integer m7 = hm.put(null, 53);// Integer m8 = hm.put("a1", null);// Integer m9 = hm.put("a1", 52); Integer m10 = hm.put("a1", 50); System.out.println("m1="+m1 + "\t" + "m2="+m2 + "\t" + "m3="+m3 + "\t" + "m4="+m4 + "\t" + "m5="+m5 + "\t" + "m6="+m6 + "\t" + "m7="+m7 + "\t" + "m8="+m8 + "\t"+ "m9="+m9 + "\t"+ "m10="+m10 + "\t"); // m1=null m2=null m3=11 m4=null m5=21 m6=32 m7=null m8=53 m9=51 m10=52 System.out.println(hm); // {a1=50, null=53, b1=31} that mean last value added.(value override) HashMap newmap = new HashMap(); // populate hash map newmap.put(1, "tutorials"); newmap.put(2, "point"); String newvalue= (String) newmap.put(3, "is best"); System.out.println("Map value before change: "+ newmap); // put new values at key 3 String prevvalue=(String)newmap.put(3,"is great"); // check returned previous value System.out.println("newvalue\t"+newvalue+"\tReturned previous value: "+ prevvalue); newmap.put(4,"is great"); System.out.println("Map value after change: "+ newmap); } private static void hashSetCoustomKey() { Set map = new HashSet(); map.add(new Employee("a")); map.add(new Employee("b")); map.add(new Employee("c")); map.add(new Employee("a")); map.add(null); map.add(null); // null will be added once // Concept 3 :: Set will add duplicate value . if you don't override // hashcode and equal System.out.println(map); } private static void identiyhashmapTest() { Map ihm = new IdentityHashMap<>(); } private static void weakMapTest() { Map weak = new WeakHashMap(); Map map = new HashMap(); { String weakkey = new String("weakkey"); weak.put(weakkey, 3); String key1 = new String("key"); map.put(key1, 5); //map.remove(key1); weakkey = null; key1 = null; } System.gc(); System.out.println("weak:: "+weak); System.out.println("map:: "+map); /* * Concept 4 :: You can see that there is no entry in weak Map. reason * is that as we make weakkey as null the corresponsing value is no * longer referred from any part of program and eligible for GC. But in * case of map key and value remain seated present in map. */ } } class Employee implements Comparable<Employee> { private String name; private String jobTitle; private int age; private int salary; public Employee(String name) { this.name = name; } public Employee(String name, String jobTitle, int age, int salary) { this.name = name; this.jobTitle = jobTitle; this.age = age; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } /* @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }*/ public String toString() { return String.format("%s\t%s\t%d\t%d", name, jobTitle, age, salary); } @Override public int compareTo(Employee o) { return this.name.compareTo(o.getName()); } } class EmployeeNameCompartor implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { return o1.getName().compareTo(o2.getName()); } } class MyNameComp implements Comparator<Empl> { /* * @Override // accending order public int compare(Empl e1, Empl e2) { * return e1.getName().compareTo(e2.getName()); } */ @Override // Decending Order public int compare(Empl e1, Empl e2) { return e2.getName().compareTo(e1.getName()); } } class Empl { private String name; Empl(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Empl [name=" + name + "]"; } }
[ "alokkumar.here@gmail.com" ]
alokkumar.here@gmail.com
1cb90feeb863ae2dbb706007168672842bf19531
f738ca66a5bd4122df3fc1d6355aa094cfbe180f
/day16_String/substring_Practice.java
0da071ff9919dc976807163004f158d2a7b17cb0
[]
no_license
ElkemEmet/GitPractice
a7fd6ca33157882dabf772db7e53bb6f8c126bba
a06ce556b78248fa498a3b81ca5da3bd7f839191
refs/heads/master
2022-12-08T02:09:49.828056
2020-08-05T03:13:44
2020-08-05T03:13:44
285,164,255
0
0
null
null
null
null
UTF-8
Java
false
false
1,158
java
package day16_String; import java.util.Scanner; /*1. Ask user to enter two words. Print first word without its first character then print the second word without its first character. Input: apple banana Output: ppleanana */ public class substring_Practice{ public static void main(String[] args) { //extra task String str = "I like to drink Pepsi"; String drink = str.substring(16); System.out.println(drink); String action=str.substring(10,15);// ending index must gives one extra index(14+1) System.out.println(action); System.out.println("======================================"); Scanner scan = new Scanner(System.in); System.out.println("Enter your first word"); String str1 = scan.next();//"Apple" System.out.println("Enter your second word"); String str2 = scan.next();//"Banana" //String result = str1.substring(1).concat(str2.substring(1));// another way to use ==> concat String result = str1.substring(1)+str2.substring(1); System.out.println(result); } }
[ "elkem131@gmail.com" ]
elkem131@gmail.com
f55e1a0a93b56f6ea11e03623f3e0087e02f1aa6
881d43b5ee517b253a0ac2e9152fc3edd3add5f1
/jLeetCode/src/main/java/me/sevenleaves/medium/p075/Problem075_v2.java
7bcfaf25b190e5834e317996aab8d1fb1584045b
[]
no_license
MonkeyDeKing/leetCode
45f1a322210f9b496c956f0b8b40b667ef9d2847
193d72133129e5000e1da52f992634f93cce70bf
refs/heads/master
2021-01-19T22:40:17.448184
2017-06-02T14:49:21
2017-06-02T14:49:21
88,836,677
0
0
null
null
null
null
UTF-8
Java
false
false
670
java
/** * @author Victor Young */ package me.sevenleaves.medium.p075; /** * @author Victor Young * @Todo: 75. Sort Colors * https://leetcode.com/problems/sort-colors/#/description * Medium */ public class Problem075_v2 { public void sortColors(int[] nums) { int idx = 0, lo = 0, hi = nums.length-1; while (idx <= hi) { if (nums[idx] == 2) swap(nums, idx, hi--); else if (nums[idx] == 0) swap(nums, idx++, lo++); else idx++; } } private void swap (int[] nums, int i, int j) { if (i == j) return; int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } } // end of class.
[ "13272436992@163.com" ]
13272436992@163.com
f62eaffd1b5ca61fdc344be026160e91e8100981
d7d286a58d97a44569654a0acf9e575d3dfc6444
/forum/src/main/java/com/example/demo/domain/LoginLog.java
3ee7e834565494209bd5bfce32987eca64b7fc75
[]
no_license
yangdongchao/forum
5acff2f453e7ec6c1b343d22f49c27b4ebc35456
ce677c09ae6a1f0f3a22b8a82f1539f4f18d625a
refs/heads/master
2020-04-14T07:34:43.837727
2019-01-14T15:59:23
2019-01-14T15:59:23
163,716,374
4
2
null
2019-01-11T08:43:26
2019-01-01T05:58:43
Java
UTF-8
Java
false
false
1,302
java
package com.example.demo.domain; import org.springframework.context.annotation.ComponentScan; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * @ClassName LoginLog * @Description TODO * @Auther ydc * @Date 2019/1/7 20:09 * @Version 1.0 **/ @Entity @Table(name = "login_log") public class LoginLog extends BaseDomain implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "login_log_id") private int loginLogId; @Column(name = "user_id") private int userId; @Column(name = "ip") private String ip; @Column(name = "login_time") private Date loginDate; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Date getLoginDate() { return loginDate; } public void setLoginDate(Date loginDate) { this.loginDate = loginDate; } public int getLoginLogId() { return loginLogId; } public void setLoginLogId(int loginLogId) { this.loginLogId = loginLogId; } public LoginLog(int userId, String ip, Date loginDate) { this.userId=userId; this.ip = ip; this.loginDate = loginDate; } public LoginLog() { } }
[ "15087581161@163.com" ]
15087581161@163.com
98af823c1877646f90604ce12a9776b2a819d8bb
0684920dce43af50e0c34d5e99bf592db94c7ee2
/src/Map.java
3f1447d67a3b43b9b789a725b1548c693653a9e6
[]
no_license
robbiesollie/CSC312Mario
300260a9f56acc3bc401f73f751cad09b201a99f
d72f5679faf0ced8fcffb45d8b9a4e65113fd78b
refs/heads/master
2021-05-18T19:56:45.730305
2020-03-30T18:16:34
2020-03-30T18:16:34
251,390,765
0
0
null
null
null
null
UTF-8
Java
false
false
3,830
java
import java.awt.*; import java.util.LinkedList; import java.util.Random; /** * Robbie Sollie - Map.java - CSC313 - CBU - 2020-03-02 */ public class Map { public LinkedList<Rectangle> walls; public LinkedList<Enemy> enemies; public int goombaKills; public Map() { walls = new LinkedList<>(); walls.add(new Rectangle(0, 200, 1104, 24)); walls.add(new Rectangle(1136, 200, 240, 24)); walls.add(new Rectangle(1424, 200, 2447-1424, 24)); walls.add(new Rectangle(2480, 200, 3391-2480, 24)); walls.add(new Rectangle(256, 136, 16, 16)); walls.add(new Rectangle(320, 136, 80, 16)); walls.add(new Rectangle(352, 72, 16, 16)); walls.add(new Rectangle(448, 168, 32, 32)); walls.add(new Rectangle(608, 152, 32, 48)); walls.add(new Rectangle(736, 136, 32, 64)); walls.add(new Rectangle(912, 136, 32, 64)); walls.add(new Rectangle(1232, 136, 48, 16)); walls.add(new Rectangle(1280, 72, 128, 16)); walls.add(new Rectangle(1456, 72, 64, 16)); walls.add(new Rectangle(1504, 136, 16, 16)); walls.add(new Rectangle(1600, 136, 32, 16)); walls.add(new Rectangle(1696, 136, 16, 16)); walls.add(new Rectangle(1744, 72, 16, 16)); walls.add(new Rectangle(1744, 136, 16, 16)); walls.add(new Rectangle(1792, 136, 16, 16)); walls.add(new Rectangle(1888, 136, 16, 16)); walls.add(new Rectangle(1936, 72, 48, 16)); walls.add(new Rectangle(2048, 72, 64, 16)); walls.add(new Rectangle(2064, 136, 32, 16)); walls.add(new Rectangle(2144, 184, 64, 16)); walls.add(new Rectangle(2160, 168, 48, 16)); walls.add(new Rectangle(2176, 152, 32, 16)); walls.add(new Rectangle(2192, 136, 16, 16)); walls.add(new Rectangle(2240, 136, 16, 16)); walls.add(new Rectangle(2240, 152, 32, 16)); walls.add(new Rectangle(2240, 168, 48, 16)); walls.add(new Rectangle(2240, 184, 64, 16)); walls.add(new Rectangle(2368, 184, 80, 16)); walls.add(new Rectangle(2384, 168, 64, 16)); walls.add(new Rectangle(2400, 152, 48, 16)); walls.add(new Rectangle(2416, 136, 32, 16)); walls.add(new Rectangle(2480, 184, 64, 16)); walls.add(new Rectangle(2480, 168, 48, 16)); walls.add(new Rectangle(2480, 152, 32, 16)); walls.add(new Rectangle(2480, 136, 16, 16)); walls.add(new Rectangle(2608, 168, 32, 32)); walls.add(new Rectangle(2688, 136, 64, 16)); walls.add(new Rectangle(2864, 168, 32, 32)); walls.add(new Rectangle(2896, 184, 144, 16)); walls.add(new Rectangle(2912, 168, 128, 16)); walls.add(new Rectangle(2928, 152, 112, 16)); walls.add(new Rectangle(2944, 136, 96, 16)); walls.add(new Rectangle(2960, 120, 80, 16)); walls.add(new Rectangle(2976, 104, 64, 16)); walls.add(new Rectangle(2992, 88, 48, 16)); walls.add(new Rectangle(3008, 72, 32, 16)); walls.add(new Rectangle(3168, 184, 16, 16)); enemies = new LinkedList<>(); enemies.add(new Enemy(300, 184)); enemies.add(new Enemy(800, 184)); enemies.add(new Enemy(2318, 184)); enemies.add(new Enemy(2700, 184)); enemies.add(new Enemy(3090, 184)); } public Rectangle collides(Rectangle r) { for (Rectangle e : walls) { if (e.intersects(r)) { return e; } } return null; } public Enemy enemyCollides(Rectangle r) { for (Enemy e : enemies) { if (e.hitbox.intersects(r)) { return e; } } return null; } public void kill(Enemy e) { enemies.remove(e); goombaKills++; } }
[ "robbiesollie@gmail.com" ]
robbiesollie@gmail.com
9946a8547b1658a981f61d1faa309d3ef4282da0
ddfbf587afdcf5a691da8e9a5a4d344c52e69a76
/app/src/main/java/com/hackathon/cardboardsense/util/SystemUiHider.java
e7bf303fe0ce26903635ffe0d406715120b909d3
[]
no_license
snigavig/CardboardSense
8b2085d0b95091a78e2bfe48774d57f111163cce
b4b12197136cca3482d79ed4febf0a88c7e6f1b7
refs/heads/master
2016-08-04T13:02:28.387364
2015-07-25T10:56:01
2015-07-25T10:56:01
39,665,085
0
0
null
null
null
null
UTF-8
Java
false
false
5,854
java
package com.hackathon.cardboardsense.util; import android.app.Activity; import android.os.Build; import android.view.View; /** * A utility class that helps with showing and hiding system UI such as the * status bar and navigation/system bar. This class uses backward-compatibility * techniques described in <a href= * "http://developer.android.com/training/backward-compatible-ui/index.html"> * Creating Backward-Compatible UIs</a> to ensure that devices running any * version of ndroid OS are supported. More specifically, there are separate * implementations of this abstract class: for newer devices, * {@link #getInstance} will return a {@link SystemUiHiderHoneycomb} instance, * while on older devices {@link #getInstance} will return a * {@link SystemUiHiderBase} instance. * <p/> * For more on system bars, see <a href= * "http://developer.android.com/design/get-started/ui-overview.html#system-bars" * > System Bars</a>. * * @see android.view.View#setSystemUiVisibility(int) * @see android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN */ public abstract class SystemUiHider { /** * When this flag is set, the * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} * flag will be set on older devices, making the status bar "float" on top * of the activity layout. This is most useful when there are no controls at * the top of the activity layout. * <p/> * This flag isn't used on newer devices because the <a * href="http://developer.android.com/design/patterns/actionbar.html">action * bar</a>, the most important structural element of an Android app, should * be visible and not obscured by the system UI. */ public static final int FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES = 0x1; /** * When this flag is set, {@link #show()} and {@link #hide()} will toggle * the visibility of the status bar. If there is a navigation bar, show and * hide will toggle low profile mode. */ public static final int FLAG_FULLSCREEN = 0x2; /** * When this flag is set, {@link #show()} and {@link #hide()} will toggle * the visibility of the navigation bar, if it's present on the device and * the device allows hiding it. In cases where the navigation bar is present * but cannot be hidden, show and hide will toggle low profile mode. */ public static final int FLAG_HIDE_NAVIGATION = FLAG_FULLSCREEN | 0x4; /** * The activity associated with this UI hider object. */ protected Activity mActivity; /** * The view on which {@link View#setSystemUiVisibility(int)} will be called. */ protected View mAnchorView; /** * The current UI hider flags. * * @see #FLAG_FULLSCREEN * @see #FLAG_HIDE_NAVIGATION * @see #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES */ protected int mFlags; /** * The current visibility callback. */ protected OnVisibilityChangeListener mOnVisibilityChangeListener = sDummyListener; /** * Creates and returns an instance of {@link SystemUiHider} that is * appropriate for this device. The object will be either a * {@link SystemUiHiderBase} or {@link SystemUiHiderHoneycomb} depending on * the device. * * @param activity The activity whose window's system UI should be * controlled by this class. * @param anchorView The view on which * {@link View#setSystemUiVisibility(int)} will be called. * @param flags Either 0 or any combination of {@link #FLAG_FULLSCREEN}, * {@link #FLAG_HIDE_NAVIGATION}, and * {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES}. */ public static SystemUiHider getInstance(Activity activity, View anchorView, int flags) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new SystemUiHiderHoneycomb(activity, anchorView, flags); } else { return new SystemUiHiderBase(activity, anchorView, flags); } } protected SystemUiHider(Activity activity, View anchorView, int flags) { mActivity = activity; mAnchorView = anchorView; mFlags = flags; } /** * Sets up the system UI hider. Should be called from * {@link Activity#onCreate}. */ public abstract void setup(); /** * Returns whether or not the system UI is visible. */ public abstract boolean isVisible(); /** * Hide the system UI. */ public abstract void hide(); /** * Show the system UI. */ public abstract void show(); /** * Toggle the visibility of the system UI. */ public void toggle() { if (isVisible()) { hide(); } else { show(); } } /** * Registers a callback, to be triggered when the system UI visibility * changes. */ public void setOnVisibilityChangeListener(OnVisibilityChangeListener listener) { if (listener == null) { listener = sDummyListener; } mOnVisibilityChangeListener = listener; } /** * A dummy no-op callback for use when there is no other listener set. */ private static OnVisibilityChangeListener sDummyListener = new OnVisibilityChangeListener() { @Override public void onVisibilityChange(boolean visible) { } }; /** * A callback interface used to listen for system UI visibility changes. */ public interface OnVisibilityChangeListener { /** * Called when the system UI visibility has changed. * * @param visible True if the system UI is visible. */ public void onVisibilityChange(boolean visible); } }
[ "kozyrevsergey89@gmail.com" ]
kozyrevsergey89@gmail.com
2cc24201073516e83d600d40d0e13dbc770cf10d
cc16a38859a219a0688ef179babd31160ff0fcd4
/src/shortest_word_distance_3/Solution.java
83456a37b644b0d700c41c630d1c81f2dd9eaafb
[]
no_license
harperjiang/LeetCode
f1ab4ee796b3de1b2f0ec03ceb443908c20e68b1
83edba731e0070ab175e5cb42ea4ac3c0b1a90c8
refs/heads/master
2023-06-12T20:19:24.988389
2023-06-01T13:47:22
2023-06-01T13:47:22
94,937,003
0
0
null
null
null
null
UTF-8
Java
false
false
1,789
java
package shortest_word_distance_3; import java.util.HashMap; import java.util.List; import java.util.Map; public class Solution { public int shortestWordDistance(String[] wordsDict, String word1, String word2) { int min = Integer.MAX_VALUE; if (word1.compareTo(word2) == 0) { int lastpos = -1; for (int i = 0; i < wordsDict.length; i++) { String word = wordsDict[i]; if (word.compareTo(word1) == 0) { if (lastpos == -1) { lastpos = i; } else { min = Math.min(min, i - lastpos); lastpos = i; } } } } else { int lastpos1 = -1; int lastpos2 = -1; for (int i = 0; i < wordsDict.length; i++) { String word = wordsDict[i]; if (word.compareTo(word1) == 0) { if (lastpos1 == -1) { lastpos1 = i; } if (lastpos2 != -1) { min = Integer.min(Math.abs(i - lastpos2), min); } lastpos1 = i; } if (word.compareTo(word2) == 0) { if (lastpos2 == -1) { lastpos2 = i; } if (lastpos1 != -1) { min = Integer.min(Math.abs(i - lastpos1), min); } lastpos2 = i; } } } return min; } public static void main(String[] args) { new Solution().shortestWordDistance(new String[]{"a", "c", "a", "b"}, "a", "b"); } }
[ "harperjiang@msn.com" ]
harperjiang@msn.com
476a24864fd92aa8fecf97fbe63074fba3dec4d6
d0536669bb37019e766766461032003ad045665b
/jdk1.4.2_src/javax/swing/text/BoxView.java
691289929caf1c57a8ea57fbba23de9d7b727e7e
[]
no_license
eagle518/jdk-source-code
c0d60f0762bce0221c7eeb1654aa1a53a3877313
91b771140de051fb843af246ab826dd6ff688fe3
refs/heads/master
2021-01-18T19:51:07.988541
2010-09-09T06:36:02
2010-09-09T06:36:02
38,047,470
11
23
null
null
null
null
UTF-8
Java
false
false
40,645
java
/* * @(#)BoxView.java 1.59 03/01/23 * * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package javax.swing.text; import java.io.PrintStream; import java.util.Vector; import java.awt.*; import javax.swing.event.DocumentEvent; import javax.swing.SizeRequirements; /** * A view that arranges its children into a box shape by tiling * its children along an axis. The box is somewhat like that * found in TeX where there is alignment of the * children, flexibility of the children is considered, etc. * This is a building block that might be useful to represent * things like a collection of lines, paragraphs, * lists, columns, pages, etc. The axis along which the children are tiled is * considered the major axis. The orthoginal axis is the minor axis. * <p> * Layout for each axis is handled separately by the methods * <code>layoutMajorAxis</code> and <code>layoutMinorAxis</code>. * Subclasses can change the layout algorithm by * reimplementing these methods. These methods will be called * as necessary depending upon whether or not there is cached * layout information and the cache is considered * valid. These methods are typically called if the given size * along the axis changes, or if <code>layoutChanged</code> is * called to force an updated layout. The <code>layoutChanged</code> * method invalidates cached layout information, if there is any. * The requirements published to the parent view are calculated by * the methods <code>calculateMajorAxisRequirements</code> * and <code>calculateMinorAxisRequirements</code>. * If the layout algorithm is changed, these methods will * likely need to be reimplemented. * * @author Timothy Prinzing * @version 1.59 01/23/03 */ public class BoxView extends CompositeView { /** * Constructs a <code>BoxView</code>. * * @param elem the element this view is responsible for * @param axis either <code>View.X_AXIS</code> or <code>View.Y_AXIS</code> */ public BoxView(Element elem, int axis) { super(elem); tempRect = new Rectangle(); this.majorAxis = axis; majorOffsets = new int[0]; majorSpans = new int[0]; majorReqValid = false; majorAllocValid = false; minorOffsets = new int[0]; minorSpans = new int[0]; minorReqValid = false; minorAllocValid = false; } /** * Fetches the tile axis property. This is the axis along which * the child views are tiled. * * @return the major axis of the box, either * <code>View.X_AXIS</code> or <code>View.Y_AXIS</code> * * @since 1.3 */ public int getAxis() { return majorAxis; } /** * Sets the tile axis property. This is the axis along which * the child views are tiled. * * @param axis either <code>View.X_AXIS</code> or <code>View.Y_AXIS</code> * * @since 1.3 */ public void setAxis(int axis) { boolean axisChanged = (axis != majorAxis); majorAxis = axis; if (axisChanged) { preferenceChanged(null, true, true); } } /** * Invalidates the layout along an axis. This happens * automatically if the preferences have changed for * any of the child views. In some cases the layout * may need to be recalculated when the preferences * have not changed. The layout can be marked as * invalid by calling this method. The layout will * be updated the next time the <code>setSize</code> method * is called on this view (typically in paint). * * @param axis either <code>View.X_AXIS</code> or <code>View.Y_AXIS</code> * * @since 1.3 */ public void layoutChanged(int axis) { if (axis == majorAxis) { majorAllocValid = false; } else { minorAllocValid = false; } } /** * Determines if the layout is valid along the given axis. * * @param axis either <code>View.X_AXIS</code> or <code>View.Y_AXIS</code> * * @since 1.4 */ protected boolean isLayoutValid(int axis) { if (axis == majorAxis) { return majorAllocValid; } else { return minorAllocValid; } } /** * Paints a child. By default * that is all it does, but a subclass can use this to paint * things relative to the child. * * @param g the graphics context * @param alloc the allocated region to paint into * @param index the child index, >= 0 && < getViewCount() */ protected void paintChild(Graphics g, Rectangle alloc, int index) { View child = getView(index); child.paint(g, alloc); } // --- View methods --------------------------------------------- /** * Invalidates the layout and resizes the cache of * requests/allocations. The child allocations can still * be accessed for the old layout, but the new children * will have an offset and span of 0. * * @param index the starting index into the child views to insert * the new views; this should be a value >= 0 and <= getViewCount * @param length the number of existing child views to remove; * This should be a value >= 0 and <= (getViewCount() - offset) * @param elems the child views to add; this value can be * <code>null</code>to indicate no children are being added * (useful to remove) */ public void replace(int index, int length, View[] elems) { super.replace(index, length, elems); // invalidate cache int nInserted = (elems != null) ? elems.length : 0; majorOffsets = updateLayoutArray(majorOffsets, index, nInserted); majorSpans = updateLayoutArray(majorSpans, index, nInserted); majorReqValid = false; majorAllocValid = false; minorOffsets = updateLayoutArray(minorOffsets, index, nInserted); minorSpans = updateLayoutArray(minorSpans, index, nInserted); minorReqValid = false; minorAllocValid = false; } /** * Resizes the given layout array to match the new number of * child views. The current number of child views are used to * produce the new array. The contents of the old array are * inserted into the new array at the appropriate places so that * the old layout information is transferred to the new array. * * @param oldArray the original layout array * @param offset location where new views will be inserted * @param nInserted the number of child views being inserted; * therefore the number of blank spaces to leave in the * new array at location <code>offset</code> * @return the new layout array */ int[] updateLayoutArray(int[] oldArray, int offset, int nInserted) { int n = getViewCount(); int[] newArray = new int[n]; System.arraycopy(oldArray, 0, newArray, 0, offset); System.arraycopy(oldArray, offset, newArray, offset + nInserted, n - nInserted - offset); return newArray; } /** * Forwards the given <code>DocumentEvent</code> to the child views * that need to be notified of the change to the model. * If a child changed its requirements and the allocation * was valid prior to forwarding the portion of the box * from the starting child to the end of the box will * be repainted. * * @param ec changes to the element this view is responsible * for (may be <code>null</code> if there were no changes) * @param e the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see #insertUpdate * @see #removeUpdate * @see #changedUpdate */ protected void forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f) { boolean wasValid = isLayoutValid(majorAxis); super.forwardUpdate(ec, e, a, f); // determine if a repaint is needed if (wasValid && (! isLayoutValid(majorAxis))) { // Repaint is needed because one of the tiled children // have changed their span along the major axis. If there // is a hosting component and an allocated shape we repaint. Component c = getContainer(); if ((a != null) && (c != null)) { int pos = e.getOffset(); int index = getViewIndexAtPosition(pos); Rectangle alloc = getInsideAllocation(a); if (majorAxis == X_AXIS) { alloc.x += majorOffsets[index]; alloc.width -= majorOffsets[index]; } else { alloc.y += minorOffsets[index]; alloc.height -= minorOffsets[index]; } c.repaint(alloc.x, alloc.y, alloc.width, alloc.height); } } } /** * This is called by a child to indicate its * preferred span has changed. This is implemented to * throw away cached layout information so that new * calculations will be done the next time the children * need an allocation. * * @param child the child view * @param width true if the width preference should change * @param height true if the height preference should change */ public void preferenceChanged(View child, boolean width, boolean height) { boolean majorChanged = (majorAxis == X_AXIS) ? width : height; boolean minorChanged = (majorAxis == X_AXIS) ? height : width; if (majorChanged) { majorReqValid = false; majorAllocValid = false; } if (minorChanged) { minorReqValid = false; minorAllocValid = false; } super.preferenceChanged(child, width, height); } /** * Gets the resize weight. A value of 0 or less is not resizable. * * @param axis may be either <code>View.X_AXIS</code> or * <code>View.Y_AXIS</code> * @return the weight * @exception IllegalArgumentException for an invalid axis */ public int getResizeWeight(int axis) { checkRequests(axis); if (axis == majorAxis) { if ((majorRequest.preferred != majorRequest.minimum) || (majorRequest.preferred != majorRequest.maximum)) { return 1; } } else { if ((minorRequest.preferred != minorRequest.minimum) || (minorRequest.preferred != minorRequest.maximum)) { return 1; } } return 0; } /** * Sets the size of the view along an axis. This should cause * layout of the view along the given axis. * * @param axis may be either <code>View.X_AXIS</code> or * <code>View.Y_AXIS</code> * @param span the span to layout to >= 0 */ void setSpanOnAxis(int axis, float span) { if (axis == majorAxis) { if (majorSpan != (int) span) { majorAllocValid = false; } if (! majorAllocValid) { // layout the major axis majorSpan = (int) span; checkRequests(majorAxis); layoutMajorAxis(majorSpan, axis, majorOffsets, majorSpans); majorAllocValid = true; // flush changes to the children updateChildSizes(); } } else { if (((int) span) != minorSpan) { minorAllocValid = false; } if (! minorAllocValid) { // layout the minor axis minorSpan = (int) span; checkRequests(axis); layoutMinorAxis(minorSpan, axis, minorOffsets, minorSpans); minorAllocValid = true; // flush changes to the children updateChildSizes(); } } } /** * Propagates the current allocations to the child views. */ void updateChildSizes() { int n = getViewCount(); if (majorAxis == X_AXIS) { for (int i = 0; i < n; i++) { View v = getView(i); v.setSize((float) majorSpans[i], (float) minorSpans[i]); } } else { for (int i = 0; i < n; i++) { View v = getView(i); v.setSize((float) minorSpans[i], (float) majorSpans[i]); } } } /** * Returns the size of the view along an axis. This is implemented * to return zero. * * @param axis may be either <code>View.X_AXIS</code> or * <code>View.Y_AXIS</code> * @return the current span of the view along the given axis, >= 0 */ float getSpanOnAxis(int axis) { if (axis == majorAxis) { return majorSpan; } else { return minorSpan; } } /** * Sets the size of the view. This should cause * layout of the view if the view caches any layout * information. This is implemented to call the * layout method with the sizes inside of the insets. * * @param width the width >= 0 * @param height the height >= 0 */ public void setSize(float width, float height) { layout((int)(width - getLeftInset() - getRightInset()), (int)(height - getTopInset() - getBottomInset())); } /** * Renders the <code>BoxView</code> using the given * rendering surface and area * on that surface. Only the children that intersect * the clip bounds of the given <code>Graphics</code> * will be rendered. * * @param g the rendering surface to use * @param allocation the allocated region to render into * @see View#paint */ public void paint(Graphics g, Shape allocation) { Rectangle alloc = (allocation instanceof Rectangle) ? (Rectangle)allocation : allocation.getBounds(); int n = getViewCount(); int x = alloc.x + getLeftInset(); int y = alloc.y + getTopInset(); Rectangle clip = g.getClipBounds(); for (int i = 0; i < n; i++) { tempRect.x = x + getOffset(X_AXIS, i); tempRect.y = y + getOffset(Y_AXIS, i); tempRect.width = getSpan(X_AXIS, i); tempRect.height = getSpan(Y_AXIS, i); if (tempRect.intersects(clip)) { paintChild(g, tempRect, i); } } } /** * Fetches the allocation for the given child view. * This enables finding out where various views * are located. This is implemented to return * <code>null</code> if the layout is invalid, * otherwise the superclass behavior is executed. * * @param index the index of the child, >= 0 && < getViewCount() * @param a the allocation to this view * @return the allocation to the child; or <code>null</code> * if <code>a</code> is <code>null</code>; * or <code>null</code> if the layout is invalid */ public Shape getChildAllocation(int index, Shape a) { if (a != null) { Shape ca = super.getChildAllocation(index, a); if ((ca != null) && (! isAllocationValid())) { // The child allocation may not have been set yet. Rectangle r = (ca instanceof Rectangle) ? (Rectangle) ca : ca.getBounds(); if ((r.width == 0) && (r.height == 0)) { return null; } } return ca; } return null; } /** * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. This makes * sure the allocation is valid before calling the superclass. * * @param pos the position to convert >= 0 * @param a the allocated region to render into * @return the bounding box of the given position * @exception BadLocationException if the given position does * not represent a valid location in the associated document * @see View#modelToView */ public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { if (! isAllocationValid()) { Rectangle alloc = a.getBounds(); setSize(alloc.width, alloc.height); } return super.modelToView(pos, a, b); } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param x x coordinate of the view location to convert >= 0 * @param y y coordinate of the view location to convert >= 0 * @param a the allocated region to render into * @return the location within the model that best represents the * given point in the view >= 0 * @see View#viewToModel */ public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { if (! isAllocationValid()) { Rectangle alloc = a.getBounds(); setSize(alloc.width, alloc.height); } return super.viewToModel(x, y, a, bias); } /** * Determines the desired alignment for this view along an * axis. This is implemented to give the total alignment * needed to position the children with the alignment points * lined up along the axis orthoginal to the axis that is * being tiled. The axis being tiled will request to be * centered (i.e. 0.5f). * * @param axis may be either <code>View.X_AXIS</code> * or <code>View.Y_AXIS</code> * @return the desired alignment >= 0.0f && <= 1.0f; this should * be a value between 0.0 and 1.0 where 0 indicates alignment at the * origin and 1.0 indicates alignment to the full span * away from the origin; an alignment of 0.5 would be the * center of the view * @exception IllegalArgumentException for an invalid axis */ public float getAlignment(int axis) { checkRequests(axis); if (axis == majorAxis) { return majorRequest.alignment; } else { return minorRequest.alignment; } } /** * Determines the preferred span for this view along an * axis. * * @param axis may be either <code>View.X_AXIS</code> * or <code>View.Y_AXIS</code> * @return the span the view would like to be rendered into >= 0; * typically the view is told to render into the span * that is returned, although there is no guarantee; * the parent may choose to resize or break the view * @exception IllegalArgumentException for an invalid axis type */ public float getPreferredSpan(int axis) { checkRequests(axis); float marginSpan = (axis == X_AXIS) ? getLeftInset() + getRightInset() : getTopInset() + getBottomInset(); if (axis == majorAxis) { return ((float)majorRequest.preferred) + marginSpan; } else { return ((float)minorRequest.preferred) + marginSpan; } } /** * Determines the minimum span for this view along an * axis. * * @param axis may be either <code>View.X_AXIS</code> * or <code>View.Y_AXIS</code> * @return the span the view would like to be rendered into >= 0; * typically the view is told to render into the span * that is returned, although there is no guarantee; * the parent may choose to resize or break the view * @exception IllegalArgumentException for an invalid axis type */ public float getMinimumSpan(int axis) { checkRequests(axis); float marginSpan = (axis == X_AXIS) ? getLeftInset() + getRightInset() : getTopInset() + getBottomInset(); if (axis == majorAxis) { return ((float)majorRequest.minimum) + marginSpan; } else { return ((float)minorRequest.minimum) + marginSpan; } } /** * Determines the maximum span for this view along an * axis. * * @param axis may be either <code>View.X_AXIS</code> * or <code>View.Y_AXIS</code> * @return the span the view would like to be rendered into >= 0; * typically the view is told to render into the span * that is returned, although there is no guarantee; * the parent may choose to resize or break the view * @exception IllegalArgumentException for an invalid axis type */ public float getMaximumSpan(int axis) { checkRequests(axis); float marginSpan = (axis == X_AXIS) ? getLeftInset() + getRightInset() : getTopInset() + getBottomInset(); if (axis == majorAxis) { return ((float)majorRequest.maximum) + marginSpan; } else { return ((float)minorRequest.maximum) + marginSpan; } } // --- local methods ---------------------------------------------------- /** * Are the allocations for the children still * valid? * * @return true if allocations still valid */ protected boolean isAllocationValid() { return (majorAllocValid && minorAllocValid); } /** * Determines if a point falls before an allocated region. * * @param x the X coordinate >= 0 * @param y the Y coordinate >= 0 * @param innerAlloc the allocated region; this is the area * inside of the insets * @return true if the point lies before the region else false */ protected boolean isBefore(int x, int y, Rectangle innerAlloc) { if (majorAxis == View.X_AXIS) { return (x < innerAlloc.x); } else { return (y < innerAlloc.y); } } /** * Determines if a point falls after an allocated region. * * @param x the X coordinate >= 0 * @param y the Y coordinate >= 0 * @param innerAlloc the allocated region; this is the area * inside of the insets * @return true if the point lies after the region else false */ protected boolean isAfter(int x, int y, Rectangle innerAlloc) { if (majorAxis == View.X_AXIS) { return (x > (innerAlloc.width + innerAlloc.x)); } else { return (y > (innerAlloc.height + innerAlloc.y)); } } /** * Fetches the child view at the given coordinates. * * @param x the X coordinate >= 0 * @param y the Y coordinate >= 0 * @param alloc the parents inner allocation on entry, which should * be changed to the childs allocation on exit * @return the view */ protected View getViewAtPoint(int x, int y, Rectangle alloc) { int n = getViewCount(); if (majorAxis == View.X_AXIS) { if (x < (alloc.x + majorOffsets[0])) { childAllocation(0, alloc); return getView(0); } for (int i = 0; i < n; i++) { if (x < (alloc.x + majorOffsets[i])) { childAllocation(i - 1, alloc); return getView(i - 1); } } childAllocation(n - 1, alloc); return getView(n - 1); } else { if (y < (alloc.y + majorOffsets[0])) { childAllocation(0, alloc); return getView(0); } for (int i = 0; i < n; i++) { if (y < (alloc.y + majorOffsets[i])) { childAllocation(i - 1, alloc); return getView(i - 1); } } childAllocation(n - 1, alloc); return getView(n - 1); } } /** * Allocates a region for a child view. * * @param index the index of the child view to * allocate, >= 0 && < getViewCount() * @param alloc the allocated region */ protected void childAllocation(int index, Rectangle alloc) { alloc.x += getOffset(X_AXIS, index); alloc.y += getOffset(Y_AXIS, index); alloc.width = getSpan(X_AXIS, index); alloc.height = getSpan(Y_AXIS, index); } /** * Perform layout on the box * * @param width the width (inside of the insets) >= 0 * @param height the height (inside of the insets) >= 0 */ protected void layout(int width, int height) { setSpanOnAxis(X_AXIS, width); setSpanOnAxis(Y_AXIS, height); } /** * Returns the current width of the box. This is the width that * it was last allocated. * @return the current width of the box */ public int getWidth() { int span; if (majorAxis == X_AXIS) { span = majorSpan; } else { span = minorSpan; } span += getLeftInset() - getRightInset(); return span; } /** * Returns the current height of the box. This is the height that * it was last allocated. * @return the current height of the box */ public int getHeight() { int span; if (majorAxis == Y_AXIS) { span = majorSpan; } else { span = minorSpan; } span += getTopInset() - getBottomInset(); return span; } /** * Performs layout for the major axis of the box (i.e. the * axis that it represents). The results of the layout should * be placed in the given arrays which represent the allocations * to the children along the major axis. * * @param targetSpan the total span given to the view, which * would be used to layout the children * @param axis the axis being layed out * @param offsets the offsets from the origin of the view for * each of the child views; this is a return value and is * filled in by the implementation of this method * @param spans the span of each child view; this is a return * value and is filled in by the implementation of this method * @return the offset and span for each child view in the * offsets and spans parameters */ protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) { /* * first pass, calculate the preferred sizes * and the flexibility to adjust the sizes. */ long minimum = 0; long maximum = 0; long preferred = 0; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); spans[i] = (int) v.getPreferredSpan(axis); preferred += spans[i]; minimum += v.getMinimumSpan(axis); maximum += v.getMaximumSpan(axis); } /* * Second pass, expand or contract by as much as possible to reach * the target span. */ // determine the adjustment to be made long desiredAdjustment = targetSpan - preferred; float adjustmentFactor = 0.0f; if (desiredAdjustment != 0) { float maximumAdjustment = (desiredAdjustment > 0) ? maximum - preferred : preferred - minimum; if (maximumAdjustment == 0.0f) { adjustmentFactor = 0.0f; } else { adjustmentFactor = desiredAdjustment / maximumAdjustment; adjustmentFactor = Math.min(adjustmentFactor, 1.0f); adjustmentFactor = Math.max(adjustmentFactor, -1.0f); } } // make the adjustments int totalOffset = 0; for (int i = 0; i < n; i++) { View v = getView(i); offsets[i] = totalOffset; int availableSpan = (adjustmentFactor > 0.0f) ? (int) v.getMaximumSpan(axis) - spans[i] : spans[i] - (int) v.getMinimumSpan(axis); float adjF = adjustmentFactor * availableSpan; if (adjF < 0) { adjF -= .5f; } else { adjF += .5f; } int adj = (int)adjF; spans[i] += adj; totalOffset = (int) Math.min((long) totalOffset + (long) spans[i], Integer.MAX_VALUE); } } /** * Performs layout for the minor axis of the box (i.e. the * axis orthoginal to the axis that it represents). The results * of the layout should be placed in the given arrays which represent * the allocations to the children along the minor axis. * * @param targetSpan the total span given to the view, which * would be used to layout the children * @param axis the axis being layed out * @param offsets the offsets from the origin of the view for * each of the child views; this is a return value and is * filled in by the implementation of this method * @param spans the span of each child view; this is a return * value and is filled in by the implementation of this method * @return the offset and span for each child view in the * offsets and spans parameters */ protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) { int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); int min = (int) v.getMinimumSpan(axis); int max = (int) v.getMaximumSpan(axis); if (max < targetSpan) { // can't make the child this wide, align it float align = v.getAlignment(axis); offsets[i] = (int) ((targetSpan - max) * align); spans[i] = max; } else { // make it the target width, or as small as it can get. offsets[i] = 0; spans[i] = Math.max(min, targetSpan); } } } /** * Calculates the size requirements for the major axis * </code>axis</code>. * * @param axis the axis being studied * @param r the <code>SizeRequirements</code> object; * if <code>null</code> one will be created * @return the newly initialized <code>SizeRequirements</code> object * @see javax.swing.SizeRequirements */ protected SizeRequirements calculateMajorAxisRequirements(int axis, SizeRequirements r) { // calculate tiled request float min = 0; float pref = 0; float max = 0; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); min += v.getMinimumSpan(axis); pref += v.getPreferredSpan(axis); max += v.getMaximumSpan(axis); } if (r == null) { r = new SizeRequirements(); } r.alignment = 0.5f; r.minimum = (int) min; r.preferred = (int) pref; r.maximum = (int) max; return r; } /** * Calculates the size requirements for the minor axis * <code>axis</code>. * * @param axis the axis being studied * @param r the <code>SizeRequirements</code> object; * if <code>null</code> one will be created * @return the newly initialized <code>SizeRequirements</code> object * @see javax.swing.SizeRequirements */ protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) { int min = 0; long pref = 0; int max = Integer.MAX_VALUE; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); min = Math.max((int) v.getMinimumSpan(axis), min); pref = Math.max((int) v.getPreferredSpan(axis), pref); max = Math.max((int) v.getMaximumSpan(axis), max); } if (r == null) { r = new SizeRequirements(); r.alignment = 0.5f; } r.preferred = (int) pref; r.minimum = min; r.maximum = max; return r; } /** * Checks the request cache and update if needed. * @param axis the axis being studied * @exception IllegalArgumentException if <code>axis</code> is * neither <code>View.X_AXIS</code> nor </code>View.Y_AXIS</code> */ void checkRequests(int axis) { if ((axis != X_AXIS) && (axis != Y_AXIS)) { throw new IllegalArgumentException("Invalid axis: " + axis); } if (axis == majorAxis) { if (!majorReqValid) { majorRequest = calculateMajorAxisRequirements(axis, majorRequest); majorReqValid = true; } } else if (! minorReqValid) { minorRequest = calculateMinorAxisRequirements(axis, minorRequest); minorReqValid = true; } } /** * Computes the location and extent of each child view * in this <code>BoxView</code> given the <code>targetSpan</code>, * which is the width (or height) of the region we have to * work with. * * @param targetSpan the total span given to the view, which * would be used to layout the children * @param axis the axis being studied, either * <code>View.X_AXIS</code> or <code>View.Y_AXIS</code> * @param offsets an empty array filled by this method with * values specifying the location of each child view * @param spans an empty array filled by this method with * values specifying the extent of each child view */ protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); int viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible int minSpan = (int)v.getMinimumSpan(axis); // the largest span possible int maxSpan = (int)v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into int fitSpan = (int)Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = (int)v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = viewSpan; } } /** * Calculates the size requirements for this <code>BoxView</code> * by examining the size of each child view. * * @param axis the axis being studied * @param r the <code>SizeRequirements</code> object; * if <code>null</code> one will be created * @return the newly initialized <code>SizeRequirements</code> object */ protected SizeRequirements baselineRequirements(int axis, SizeRequirements r) { SizeRequirements totalAscent = new SizeRequirements(); SizeRequirements totalDescent = new SizeRequirements(); if (r == null) { r = new SizeRequirements(); } r.alignment = 0.5f; int n = getViewCount(); // loop through all children calculating the max of all their ascents and // descents at minimum, preferred, and maximum sizes for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); int span; int ascent; int descent; // find the maximum of the preferred ascents and descents span = (int)v.getPreferredSpan(axis); ascent = (int)(align * span); descent = span - ascent; totalAscent.preferred = Math.max(ascent, totalAscent.preferred); totalDescent.preferred = Math.max(descent, totalDescent.preferred); if (v.getResizeWeight(axis) > 0) { // if the view is resizable then do the same for the minimum and // maximum ascents and descents span = (int)v.getMinimumSpan(axis); ascent = (int)(align * span); descent = span - ascent; totalAscent.minimum = Math.max(ascent, totalAscent.minimum); totalDescent.minimum = Math.max(descent, totalDescent.minimum); span = (int)v.getMaximumSpan(axis); ascent = (int)(align * span); descent = span - ascent; totalAscent.maximum = Math.max(ascent, totalAscent.maximum); totalDescent.maximum = Math.max(descent, totalDescent.maximum); } else { // otherwise use the preferred totalAscent.minimum = Math.max(ascent, totalAscent.minimum); totalDescent.minimum = Math.max(descent, totalDescent.minimum); totalAscent.maximum = Math.max(ascent, totalAscent.maximum); totalDescent.maximum = Math.max(descent, totalDescent.maximum); } } // we now have an overall preferred, minimum, and maximum ascent and descent // calculate the preferred span as the sum of the preferred ascent and preferred descent r.preferred = (int)Math.min((long)totalAscent.preferred + (long)totalDescent.preferred, Integer.MAX_VALUE); // calculate the preferred alignment as the preferred ascent divided by the preferred span if (r.preferred > 0) { r.alignment = (float)totalAscent.preferred / r.preferred; } if (r.alignment == 0.0f) { // if the preferred alignment is 0 then the minimum and maximum spans are simply // the minimum and maximum descents since there's nothing above the baseline r.minimum = totalDescent.minimum; r.maximum = totalDescent.maximum; } else if (r.alignment == 1.0f) { // if the preferred alignment is 1 then the minimum and maximum spans are simply // the minimum and maximum ascents since there's nothing below the baseline r.minimum = totalAscent.minimum; r.maximum = totalAscent.maximum; } else { // we want to honor the preferred alignment so we calculate two possible minimum // span values using 1) the minimum ascent and the alignment, and 2) the minimum // descent and the alignment. We'll choose the larger of these two numbers. r.minimum = Math.max((int)(totalAscent.minimum / r.alignment), (int)(totalDescent.minimum / (1.0f - r.alignment))); // a similar calculation is made for the maximum but we choose the smaller number. r.maximum = Math.min((int)(totalAscent.maximum / r.alignment), (int)(totalDescent.maximum / (1.0f - r.alignment))); } return r; } /** * Fetches the offset of a particular child's current layout. * @param axis the axis being studied * @param childIndex the index of the requested child * @return the offset (location) for the specified child */ protected int getOffset(int axis, int childIndex) { int[] offsets = (axis == majorAxis) ? majorOffsets : minorOffsets; return offsets[childIndex]; } /** * Fetches the span of a particular childs current layout. * @param axis the axis being studied * @param childIndex the index of the requested child * @return the span (width or height) of the specified child */ protected int getSpan(int axis, int childIndex) { int[] spans = (axis == majorAxis) ? majorSpans : minorSpans; return spans[childIndex]; } /** * Determines in which direction the next view lays. * Consider the View at index n. Typically the <code>View</code>s * are layed out from left to right, so that the <code>View</code> * to the EAST will be at index n + 1, and the <code>View</code> * to the WEST will be at index n - 1. In certain situations, * such as with bidirectional text, it is possible * that the <code>View</code> to EAST is not at index n + 1, * but rather at index n - 1, or that the <code>View</code> * to the WEST is not at index n - 1, but index n + 1. * In this case this method would return true, * indicating the <code>View</code>s are layed out in * descending order. Otherwise the method would return false * indicating the <code>View</code>s are layed out in ascending order. * <p> * If the receiver is laying its <code>View</code>s along the * <code>Y_AXIS</code>, this will will return the value from * invoking the same method on the <code>View</code> * responsible for rendering <code>position</code> and * <code>bias</code>. Otherwise this will return false. * * @param position position into the model * @param bias either <code>Position.Bias.Forward</code> or * <code>Position.Bias.Backward</code> * @return true if the <code>View</code>s surrounding the * <code>View</code> responding for rendering * <code>position</code> and <code>bias</code> * are layed out in descending order; otherwise false */ protected boolean flipEastAndWestAtEnds(int position, Position.Bias bias) { if(majorAxis == Y_AXIS) { int testPos = (bias == Position.Bias.Backward) ? Math.max(0, position - 1) : position; int index = getViewIndexAtPosition(testPos); if(index != -1) { View v = getView(index); if(v != null && v instanceof CompositeView) { return ((CompositeView)v).flipEastAndWestAtEnds(position, bias); } } } return false; } // --- variables ------------------------------------------------ int majorAxis; int majorSpan; int minorSpan; /* * Request cache */ boolean majorReqValid; boolean minorReqValid; SizeRequirements majorRequest; SizeRequirements minorRequest; /* * Allocation cache */ boolean majorAllocValid; int[] majorOffsets; int[] majorSpans; boolean minorAllocValid; int[] minorOffsets; int[] minorSpans; /** used in paint. */ Rectangle tempRect; }
[ "kzhaicn@e8197d6f-d431-fb3f-3203-916d138821fd" ]
kzhaicn@e8197d6f-d431-fb3f-3203-916d138821fd
a76368851d3ccd5d5daa260cb7a522e52d5b0558
75edf9c7d5d1e666135ab0d797a292f9781790b6
/sld_enterprise_app/release/pagecompile/ish/cartridges/sld_005fenterprise_005fapp/default_/widget/WidgetPlaceholder_jsp.java
aef24d4dbeae719d28f3d04adfeae0c563397641
[]
no_license
arthurAddamsSiebert/cartridges
7808f484de6b06c98c59be49f816164dba21366e
cc1141019a601f76ad15727af442718f1f6bb6cb
refs/heads/master
2020-06-11T08:58:02.419907
2019-06-26T12:16:31
2019-06-26T12:16:31
193,898,014
0
1
null
2019-11-02T23:33:49
2019-06-26T12:15:29
Java
UTF-8
Java
false
false
4,270
java
/* * Generated by the Jasper component of Apache Tomcat * Version: JspCServletContext/1.0 * Generated at: 2019-02-13 15:29:26 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package ish.cartridges.sld_005fenterprise_005fapp.default_.widget; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.util.*; import java.io.*; import com.intershop.beehive.core.internal.template.*; import com.intershop.beehive.core.internal.template.isml.*; import com.intershop.beehive.core.capi.log.*; import com.intershop.beehive.core.capi.resource.*; import com.intershop.beehive.core.capi.util.UUIDMgr; import com.intershop.beehive.core.capi.util.XMLHelper; import com.intershop.beehive.foundation.util.*; import com.intershop.beehive.core.internal.url.*; import com.intershop.beehive.core.internal.resource.*; import com.intershop.beehive.core.internal.wsrp.*; import com.intershop.beehive.core.capi.pipeline.PipelineDictionary; import com.intershop.beehive.core.capi.naming.NamingMgr; import com.intershop.beehive.core.capi.pagecache.PageCacheMgr; import com.intershop.beehive.core.capi.request.SessionMgr; import com.intershop.beehive.core.internal.request.SessionMgrImpl; import com.intershop.beehive.core.pipelet.PipelineConstants; public final class WidgetPlaceholder_jsp extends com.intershop.beehive.core.internal.template.AbstractTemplate implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=utf-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 0, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; boolean _boolean_result=false; TemplateExecutionConfig context = getTemplateExecutionConfig(); createTemplatePageConfig(context.getServletRequest()); printHeader(out); setEncodingType("text/html"); out.write("<div class=\"content\">"); {out.write(localizeISText("widgettype.placeholder.ThisWidgetTypeIsNotAvailableAnymore.content","",null,null,null,null,null,null,null,null,null,null,null));} out.write("</div>"); printFooter(out); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
[ "root@Inteshoppa1v11.yyrtatjsacuefh5ihlz5gkzqpd.ax.internal.cloudapp.net" ]
root@Inteshoppa1v11.yyrtatjsacuefh5ihlz5gkzqpd.ax.internal.cloudapp.net
321e3cdfd5c4f185b484c6b655579baab5f7f164
fe2a92fb961cd9a185f5e675cbbec7d9ee1b5930
/frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java
eabe9a464dc3e8492324b40dc90524b942db1096
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
redstorm82/Framwork
e5bfe51a490d1a29d94bcb7d6dfce2869f70b34d
b48c6ac58cfd4355512df4dbd48b56f2d9342091
refs/heads/master
2021-05-30T10:01:51.835572
2015-08-04T06:42:49
2015-08-04T06:42:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
624,123
java
/* * Copyright (C) 2006 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.server.pm; import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; import static android.content.pm.PackageManager.INSTALL_EXTERNAL; import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; import static android.content.pm.PackageParser.isApkFile; import static android.os.Process.PACKAGE_INFO_GID; import static android.os.Process.SYSTEM_UID; import static android.system.OsConstants.O_CREAT; import static android.system.OsConstants.O_RDWR; import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; import static com.android.internal.util.ArrayUtils.appendInt; import static com.android.internal.util.ArrayUtils.removeInt; import android.util.ArrayMap; import com.android.internal.R; import com.android.internal.app.IMediaContainerService; import com.android.internal.app.ResolverActivity; import com.android.internal.content.NativeLibraryHelper; import com.android.internal.content.PackageHelper; import com.android.internal.os.IParcelFileDescriptorFactory; import com.android.internal.util.ArrayUtils; import com.android.internal.util.FastPrintWriter; import com.android.internal.util.FastXmlSerializer; import com.android.internal.util.IndentingPrintWriter; import com.android.server.EventLogTags; import com.android.server.IntentResolver; import com.android.server.LocalServices; import com.android.server.ServiceThread; import com.android.server.SystemConfig; import com.android.server.Watchdog; import com.android.server.pm.Settings.DatabaseVersion; import com.android.server.storage.DeviceStorageMonitorInternal; import org.xmlpull.v1.XmlSerializer; import android.app.ActivityManager; import android.app.ActivityManagerNative; import android.app.AppGlobals; import android.app.IActivityManager; import android.app.admin.IDevicePolicyManager; import android.app.backup.IBackupManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.IIntentReceiver; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.FeatureInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.IPackageDeleteObserver; import android.content.pm.IPackageDeleteObserver2; import android.content.pm.IPackageInstallObserver2; import android.content.pm.IPackageInstaller; import android.content.pm.IPackageManager; import android.content.pm.IPackageMoveObserver; import android.content.pm.IPackageStatsObserver; import android.content.pm.InstrumentationInfo; import android.content.pm.KeySet; import android.content.pm.ManifestDigest; import android.content.pm.PackageCleanItem; import android.content.pm.PackageInfo; import android.content.pm.PackageInfoLite; import android.content.pm.PackageInstaller; import android.content.pm.PackageManager; import android.content.pm.PackageManager.LegacyPackageDeleteObserver; import android.content.pm.PackageParser.ActivityIntentInfo; import android.content.pm.PackageParser.PackageLite; import android.content.pm.PackageParser.PackageParserException; import android.content.pm.PackageParser; import android.content.pm.PackageStats; import android.content.pm.PackageUserState; import android.content.pm.ParceledListSlice; import android.content.pm.PermissionGroupInfo; import android.content.pm.PermissionInfo; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.pm.Signature; import android.content.pm.UserInfo; import android.content.pm.VerificationParams; import android.content.pm.VerifierDeviceIdentity; import android.content.pm.VerifierInfo; import android.content.res.Resources; import android.hardware.display.DisplayManager; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Environment.UserEnvironment; import android.os.storage.StorageManager; import android.os.Debug; import android.os.FileUtils; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Parcel; import android.os.ParcelFileDescriptor; import android.os.Process; import android.os.RemoteException; import android.os.SELinux; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.os.UserHandle; import android.os.UserManager; import android.security.KeyStore; import android.security.SystemKeyStore; import android.system.ErrnoException; import android.system.Os; import android.system.StructStat; import android.text.TextUtils; import android.util.ArraySet; import android.util.AtomicFile; import android.util.DisplayMetrics; import android.util.EventLog; import android.util.ExceptionUtils; import android.util.Log; import android.util.LogPrinter; import android.util.PrintStreamPrinter; import android.util.Slog; import android.util.SparseArray; import android.util.SparseBooleanArray; import android.view.Display; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import dalvik.system.DexFile; import dalvik.system.StaleDexCacheError; import dalvik.system.VMRuntime; import libcore.io.IoUtils; import libcore.util.EmptyArray; /** * Keep track of all those .apks everywhere. * * This is very central to the platform's security; please run the unit * tests whenever making modifications here: * mmm frameworks/base/tests/AndroidTests adb install -r -f out/target/product/passion/data/app/AndroidTests.apk adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner * * {@hide} */ public class PackageManagerService extends IPackageManager.Stub { static final String TAG = "PackageManager"; static boolean DEBUG_SETTINGS = false; static boolean DEBUG_PREFERRED = false; static boolean DEBUG_UPGRADE = true; private static boolean DEBUG_INSTALL = true; private static boolean DEBUG_REMOVE = true; private static boolean DEBUG_BROADCASTS = false; private static boolean DEBUG_SHOW_INFO = false; private static boolean DEBUG_PACKAGE_INFO = false; private static boolean DEBUG_INTENT_MATCHING = false; private static boolean DEBUG_PACKAGE_SCANNING = false; private static boolean DEBUG_VERIFY = false; private static boolean DEBUG_DEXOPT = false; private static boolean DEBUG_ABI_SELECTION = false; private static boolean DEBUG_PERMISSION = false; private static final int RADIO_UID = Process.PHONE_UID; private static final int LOG_UID = Process.LOG_UID; private static final int NFC_UID = Process.NFC_UID; private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; private static final int SHELL_UID = Process.SHELL_UID; // Cap the size of permission trees that 3rd party apps can define private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text // Suffix used during package installation when copying/moving // package apks to install directory. private static final String INSTALL_PACKAGE_SUFFIX = "-"; static final int SCAN_NO_DEX = 1<<1; static final int SCAN_FORCE_DEX = 1<<2; static final int SCAN_UPDATE_SIGNATURE = 1<<3; static final int SCAN_NEW_INSTALL = 1<<4; static final int SCAN_NO_PATHS = 1<<5; static final int SCAN_UPDATE_TIME = 1<<6; static final int SCAN_DEFER_DEX = 1<<7; static final int SCAN_BOOTING = 1<<8; static final int SCAN_TRUSTED_OVERLAY = 1<<9; static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; static final int SCAN_REPLACING = 1<<11; static final int REMOVE_CHATTY = 1<<16; /** * Timeout (in milliseconds) after which the watchdog should declare that * our handler thread is wedged. The usual default for such things is one * minute but we sometimes do very lengthy I/O operations on this thread, * such as installing multi-gigabyte applications, so ours needs to be longer. */ private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes /** * Whether verification is enabled by default. */ private static final boolean DEFAULT_VERIFY_ENABLE = true; /** * The default maximum time to wait for the verification agent to return in * milliseconds. */ private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; /** * The default response for package verification timeout. * * This can be either PackageManager.VERIFICATION_ALLOW or * PackageManager.VERIFICATION_REJECT. */ private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( DEFAULT_CONTAINER_PACKAGE, "com.android.defcontainer.DefaultContainerService"); private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; private static String sPreferredInstructionSet; final ServiceThread mHandlerThread; private static final String IDMAP_PREFIX = "/data/resource-cache/"; private static final String IDMAP_SUFFIX = "@idmap"; final PackageHandler mHandler; /** * Messages for {@link #mHandler} that need to wait for system ready before * being dispatched. */ private ArrayList<Message> mPostSystemReadyMessages; final int mSdkVersion = Build.VERSION.SDK_INT; final Context mContext; final boolean mFactoryTest; final boolean mOnlyCore; final boolean mLazyDexOpt; final DisplayMetrics mMetrics; final int mDefParseFlags; final String[] mSeparateProcesses; /// M: Mtprof tool boolean mMTPROFDisable; // This is where all application persistent data goes. final File mAppDataDir; // This is where all application persistent data goes for secondary users. final File mUserAppDataDir; /** The location for ASEC container files on internal storage. */ final String mAsecInternalPath; // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages // LOCK HELD. Can be called with mInstallLock held. final Installer mInstaller; /** Directory where installed third-party apps stored */ final File mAppInstallDir; /// M: [CIP] Add CIP scanning path variable final File mCustomAppInstallDir; /// M: [ALPS00104673][Need Patch][Volunteer Patch]Mechanism for uninstall app from system partition final File mOperatorAppInstallDir; /// M: for plugin app // for cucstom plugin final File mCustomPluginInstallDir; // for system plugin final File mPluginAppInstallDir; /** * Directory to which applications installed internally have their * 32 bit native libraries copied. */ private File mAppLib32InstallDir; // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked // apps. final File mDrmAppPrivateInstallDir; // ---------------------------------------------------------------- // Lock for state used when installing and doing other long running // operations. Methods that must be called with this lock held have // the suffix "LI". final Object mInstallLock = new Object(); // ---------------------------------------------------------------- // Keys are String (package name), values are Package. This also serves // as the lock for the global state. Methods that must be called with // this lock held have the prefix "LP". final HashMap<String, PackageParser.Package> mPackages = new HashMap<String, PackageParser.Package>(); // Tracks available target package names -> overlay package paths. final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = new HashMap<String, HashMap<String, PackageParser.Package>>(); final Settings mSettings; boolean mRestoredSettings; // System configuration read by SystemConfig. final int[] mGlobalGids; final SparseArray<HashSet<String>> mSystemPermissions; final HashMap<String, FeatureInfo> mAvailableFeatures; // If mac_permissions.xml was found for seinfo labeling. boolean mFoundPolicyFile; // If a recursive restorecon of /data/data/<pkg> is needed. private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); public static final class SharedLibraryEntry { public final String path; public final String apk; SharedLibraryEntry(String _path, String _apk) { path = _path; apk = _apk; } } // Currently known shared libraries. final HashMap<String, SharedLibraryEntry> mSharedLibraries = new HashMap<String, SharedLibraryEntry>(); // All available activities, for your resolving pleasure. final ActivityIntentResolver mActivities = new ActivityIntentResolver(); // All available receivers, for your resolving pleasure. final ActivityIntentResolver mReceivers = new ActivityIntentResolver(); // All available services, for your resolving pleasure. final ServiceIntentResolver mServices = new ServiceIntentResolver(); // All available providers, for your resolving pleasure. final ProviderIntentResolver mProviders = new ProviderIntentResolver(); // Mapping from provider base names (first directory in content URI codePath) // to the provider information. final HashMap<String, PackageParser.Provider> mProvidersByAuthority = new HashMap<String, PackageParser.Provider>(); // Mapping from instrumentation class names to info about them. final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = new HashMap<ComponentName, PackageParser.Instrumentation>(); // Mapping from permission names to info about them. final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = new HashMap<String, PackageParser.PermissionGroup>(); // Packages whose data we have transfered into another package, thus // should no longer exist. final HashSet<String> mTransferedPackages = new HashSet<String>(); // Broadcast actions that are only available to the system. final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); /** List of packages waiting for verification. */ final SparseArray<PackageVerificationState> mPendingVerification = new SparseArray<PackageVerificationState>(); /** Set of packages associated with each app op permission. */ final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); final PackageInstallerService mInstallerService; HashSet<PackageParser.Package> mDeferredDexOpt = null; // Cache of users who need badging. SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); /** Token for keys in mPendingVerification. */ private int mPendingVerificationToken = 0; volatile boolean mSystemReady; volatile boolean mSafeMode; volatile boolean mHasSystemUidErrors; ApplicationInfo mAndroidApplication; /// M: [CIP] Add application info for mediatek-res.apk ApplicationInfo mMediatekApplication; final ActivityInfo mResolveActivity = new ActivityInfo(); final ResolveInfo mResolveInfo = new ResolveInfo(); ComponentName mResolveComponentName; PackageParser.Package mPlatformPackage; ComponentName mCustomResolverComponentName; boolean mResolverReplaced = false; // Set of pending broadcasts for aggregating enable/disable of components. static class PendingPackageBroadcasts { // for each user id, a map of <package name -> components within that package> final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; public PendingPackageBroadcasts() { mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); } public ArrayList<String> get(int userId, String packageName) { HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); return packages.get(packageName); } public void put(int userId, String packageName, ArrayList<String> components) { HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); packages.put(packageName, components); } public void remove(int userId, String packageName) { HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); if (packages != null) { packages.remove(packageName); } } public void remove(int userId) { mUidMap.remove(userId); } public int userIdCount() { return mUidMap.size(); } public int userIdAt(int n) { return mUidMap.keyAt(n); } public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { return mUidMap.get(userId); } public int size() { // total number of pending broadcast entries across all userIds int num = 0; for (int i = 0; i< mUidMap.size(); i++) { num += mUidMap.valueAt(i).size(); } return num; } public void clear() { mUidMap.clear(); } private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { HashMap<String, ArrayList<String>> map = mUidMap.get(userId); if (map == null) { map = new HashMap<String, ArrayList<String>>(); mUidMap.put(userId, map); } return map; } } final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); // Service Connection to remote media container service to copy // package uri's from external media onto secure containers // or internal storage. private IMediaContainerService mContainerService = null; static final int SEND_PENDING_BROADCAST = 1; static final int MCS_BOUND = 3; static final int END_COPY = 4; static final int INIT_COPY = 5; static final int MCS_UNBIND = 6; static final int START_CLEANING_PACKAGE = 7; static final int FIND_INSTALL_LOC = 8; static final int POST_INSTALL = 9; static final int MCS_RECONNECT = 10; static final int MCS_GIVE_UP = 11; static final int UPDATED_MEDIA_STATUS = 12; static final int WRITE_SETTINGS = 13; static final int WRITE_PACKAGE_RESTRICTIONS = 14; static final int PACKAGE_VERIFIED = 15; static final int CHECK_PENDING_VERIFICATION = 16; /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ static final int MCS_CHECK = 17; /// @} static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds // Delay time in millisecs static final int BROADCAST_DELAY = 10 * 1000; /// M : For RMS reference public static UserManagerService sUserManager; // Stores a list of users whose package restrictions file needs to be updated private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ private boolean mServiceConnected = false; private int mServiceCheck = 0; /// @} final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection(); class DefaultContainerConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder service) { if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ mServiceConnected = true; mServiceCheck = 0; if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected: " + mServiceConnected + ", " + mServiceCheck); /// @} IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service); mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); } public void onServiceDisconnected(ComponentName name) { if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ mServiceConnected = false; if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected: " + mServiceConnected); /// @} } }; // Recordkeeping of restore-after-install operations that are currently in flight // between the Package Manager and the Backup Manager class PostInstallData { public InstallArgs args; public PackageInstalledInfo res; PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { args = _a; res = _r; } }; final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows private final String mRequiredVerifierPackage; private final PackageUsage mPackageUsage = new PackageUsage(); private class PackageUsage { private final int WRITE_INTERVAL = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms private final Object mFileLock = new Object(); private final AtomicLong mLastWritten = new AtomicLong(0); private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); private boolean mIsHistoricalPackageUsageAvailable = true; boolean isHistoricalPackageUsageAvailable() { return mIsHistoricalPackageUsageAvailable; } void write(boolean force) { if (force) { writeInternal(); return; } if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL && !DEBUG_DEXOPT) { return; } if (mBackgroundWriteRunning.compareAndSet(false, true)) { new Thread("PackageUsage_DiskWriter") { @Override public void run() { try { writeInternal(); } finally { mBackgroundWriteRunning.set(false); } } }.start(); } } private void writeInternal() { synchronized (mPackages) { synchronized (mFileLock) { AtomicFile file = getFile(); FileOutputStream f = null; try { f = file.startWrite(); BufferedOutputStream out = new BufferedOutputStream(f); FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); StringBuilder sb = new StringBuilder(); for (PackageParser.Package pkg : mPackages.values()) { if (pkg.mLastPackageUsageTimeInMills == 0) { continue; } sb.setLength(0); sb.append(pkg.packageName); sb.append(' '); sb.append((long)pkg.mLastPackageUsageTimeInMills); sb.append('\n'); out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); } out.flush(); file.finishWrite(f); } catch (IOException e) { if (f != null) { file.failWrite(f); } Log.e(TAG, "Failed to write package usage times", e); } } } mLastWritten.set(SystemClock.elapsedRealtime()); } void readLP() { synchronized (mFileLock) { AtomicFile file = getFile(); BufferedInputStream in = null; try { in = new BufferedInputStream(file.openRead()); StringBuffer sb = new StringBuffer(); while (true) { String packageName = readToken(in, sb, ' '); if (packageName == null) { break; } String timeInMillisString = readToken(in, sb, '\n'); if (timeInMillisString == null) { throw new IOException("Failed to find last usage time for package " + packageName); } PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { continue; } long timeInMillis; try { timeInMillis = Long.parseLong(timeInMillisString.toString()); } catch (NumberFormatException e) { throw new IOException("Failed to parse " + timeInMillisString + " as a long.", e); } pkg.mLastPackageUsageTimeInMills = timeInMillis; } } catch (FileNotFoundException expected) { mIsHistoricalPackageUsageAvailable = false; } catch (IOException e) { Log.w(TAG, "Failed to read package usage times", e); } finally { IoUtils.closeQuietly(in); } } mLastWritten.set(SystemClock.elapsedRealtime()); } private String readToken(InputStream in, StringBuffer sb, char endOfToken) throws IOException { sb.setLength(0); while (true) { int ch = in.read(); if (ch == -1) { if (sb.length() == 0) { return null; } throw new IOException("Unexpected EOF"); } if (ch == endOfToken) { return sb.toString(); } sb.append((char)ch); } } private AtomicFile getFile() { File dataDir = Environment.getDataDirectory(); File systemDir = new File(dataDir, "system"); File fname = new File(systemDir, "package-usage.list"); return new AtomicFile(fname); } } class PackageHandler extends Handler { private boolean mBound = false; final ArrayList<HandlerParams> mPendingInstalls = new ArrayList<HandlerParams>(); private boolean connectToService() { if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + " DefaultContainerService"); Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); if (mContext.bindServiceAsUser(service, mDefContainerConn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); mBound = true; /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ final long DEFCONTAINER_CHECK = 1 * 1000; final Message msg = mHandler.obtainMessage(MCS_CHECK); mHandler.sendMessageDelayed(msg, DEFCONTAINER_CHECK); /// @} return true; } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return false; } private void disconnectService() { mContainerService = null; mBound = false; /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ mServiceConnected = false; if (DEBUG_SD_INSTALL) Log.i(TAG, "disconnectService: " + mServiceConnected); /// @} Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); mContext.unbindService(mDefContainerConn); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } PackageHandler(Looper looper) { super(looper); } public void handleMessage(Message msg) { try { doHandleMessage(msg); } finally { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } void doHandleMessage(Message msg) { switch (msg.what) { case INIT_COPY: { HandlerParams params = (HandlerParams) msg.obj; int idx = mPendingInstalls.size(); if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); // If a bind was already initiated we dont really // need to do anything. The pending install // will be processed later on. if (!mBound) { // If this is the only one pending we might // have to bind to the service again. if (!connectToService()) { Slog.e(TAG, "Failed to bind to media container service"); params.serviceError(); return; } else { // Once we bind to the service, the first // pending request will be processed. mPendingInstalls.add(idx, params); } } else { mPendingInstalls.add(idx, params); // Already bound to the service. Just make // sure we trigger off processing the first request. if (idx == 0) { mHandler.sendEmptyMessage(MCS_BOUND); } } break; } case MCS_BOUND: { if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); if (msg.obj != null) { mContainerService = (IMediaContainerService) msg.obj; } if (mContainerService == null) { // Something seriously wrong. Bail out Slog.e(TAG, "Cannot bind to media container service"); for (HandlerParams params : mPendingInstalls) { // Indicate service bind error params.serviceError(); } mPendingInstalls.clear(); } else if (mPendingInstalls.size() > 0) { HandlerParams params = mPendingInstalls.get(0); if (params != null) { if (params.startCopy()) { // We are done... look for more work or to // go idle. if (DEBUG_SD_INSTALL) Log.i(TAG, "Checking for more work or unbind..."); // Delete pending install if (mPendingInstalls.size() > 0) { mPendingInstalls.remove(0); } if (mPendingInstalls.size() == 0) { if (mBound) { if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting delayed MCS_UNBIND"); removeMessages(MCS_UNBIND); Message ubmsg = obtainMessage(MCS_UNBIND); // Unbind after a little delay, to avoid // continual thrashing. sendMessageDelayed(ubmsg, 10000); } } else { // There are more pending requests in queue. // Just post MCS_BOUND message to trigger processing // of next pending install. if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting MCS_BOUND for next work"); mHandler.sendEmptyMessage(MCS_BOUND); } } } } else { // Should never happen ideally. Slog.w(TAG, "Empty queue"); } break; } /// M: [ALPS01414464][Blocking][MTK-MTBF][MT6572][KK]adb install cannot response after run MTK-MTBF for a period of time @{ case MCS_CHECK: { if (DEBUG_INSTALL) Slog.i(TAG, "mcs_check"); mServiceCheck ++; Slog.i(TAG, "mcs_check(" + mServiceConnected + ", " + mServiceCheck + ")"); if (!mServiceConnected && mServiceCheck <= 3) { connectToService(); } break; } /// @} case MCS_RECONNECT: { if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); if (mPendingInstalls.size() > 0) { if (mBound) { disconnectService(); } if (!connectToService()) { Slog.e(TAG, "Failed to bind to media container service"); for (HandlerParams params : mPendingInstalls) { // Indicate service bind error params.serviceError(); } mPendingInstalls.clear(); } } break; } case MCS_UNBIND: { // If there is no actual work left, then time to unbind. if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { if (mBound) { if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); disconnectService(); } } else if (mPendingInstalls.size() > 0) { // There are more pending requests in queue. // Just post MCS_BOUND message to trigger processing // of next pending install. mHandler.sendEmptyMessage(MCS_BOUND); } break; } case MCS_GIVE_UP: { if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); mPendingInstalls.remove(0); break; } case SEND_PENDING_BROADCAST: { String packages[]; ArrayList<String> components[]; int size = 0; int uids[]; Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); synchronized (mPackages) { if (mPendingBroadcasts == null) { return; } size = mPendingBroadcasts.size(); if (size <= 0) { // Nothing to be done. Just return return; } packages = new String[size]; components = new ArrayList[size]; uids = new int[size]; int i = 0; // filling out the above arrays for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { int packageUserId = mPendingBroadcasts.userIdAt(n); Iterator<Map.Entry<String, ArrayList<String>>> it = mPendingBroadcasts.packagesForUserId(packageUserId) .entrySet().iterator(); while (it.hasNext() && i < size) { Map.Entry<String, ArrayList<String>> ent = it.next(); packages[i] = ent.getKey(); components[i] = ent.getValue(); PackageSetting ps = mSettings.mPackages.get(ent.getKey()); uids[i] = (ps != null) ? UserHandle.getUid(packageUserId, ps.appId) : -1; i++; } } size = i; mPendingBroadcasts.clear(); } // Send broadcasts for (int i = 0; i < size; i++) { sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); break; } case START_CLEANING_PACKAGE: { Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); final String packageName = (String)msg.obj; final int userId = msg.arg1; final boolean andCode = msg.arg2 != 0; synchronized (mPackages) { if (userId == UserHandle.USER_ALL) { int[] users = sUserManager.getUserIds(); for (int user : users) { mSettings.addPackageToCleanLPw( new PackageCleanItem(user, packageName, andCode)); } } else { mSettings.addPackageToCleanLPw( new PackageCleanItem(userId, packageName, andCode)); } } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); startCleaningPackages(); } break; case POST_INSTALL: { if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); PostInstallData data = mRunningInstalls.get(msg.arg1); mRunningInstalls.delete(msg.arg1); boolean deleteOld = false; if (data != null) { InstallArgs args = data.args; PackageInstalledInfo res = data.res; if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { res.removedInfo.sendBroadcast(false, true, false); Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, res.uid); // Determine the set of users who are adding this // package for the first time vs. those who are seeing // an update. int[] firstUsers; int[] updateUsers = new int[0]; if (res.origUsers == null || res.origUsers.length == 0) { firstUsers = res.newUsers; } else { firstUsers = new int[0]; for (int i=0; i<res.newUsers.length; i++) { int user = res.newUsers[i]; boolean isNew = true; for (int j=0; j<res.origUsers.length; j++) { if (res.origUsers[j] == user) { isNew = false; break; } } if (isNew) { int[] newFirst = new int[firstUsers.length+1]; System.arraycopy(firstUsers, 0, newFirst, 0, firstUsers.length); newFirst[firstUsers.length] = user; firstUsers = newFirst; } else { int[] newUpdate = new int[updateUsers.length+1]; System.arraycopy(updateUsers, 0, newUpdate, 0, updateUsers.length); newUpdate[updateUsers.length] = user; updateUsers = newUpdate; } } } sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, res.pkg.applicationInfo.packageName, extras, null, null, firstUsers); final boolean update = res.removedInfo.removedPackage != null; if (update) { extras.putBoolean(Intent.EXTRA_REPLACING, true); } sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, res.pkg.applicationInfo.packageName, extras, null, null, updateUsers); if (update) { sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, res.pkg.applicationInfo.packageName, extras, null, null, updateUsers); sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, null, res.pkg.applicationInfo.packageName, null, updateUsers); // treat asec-hosted packages like removable media on upgrade if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { if (DEBUG_INSTALL) { Slog.i(TAG, "upgrading pkg " + res.pkg + " is ASEC-hosted -> AVAILABLE"); } int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; ArrayList<String> pkgList = new ArrayList<String>(1); pkgList.add(res.pkg.applicationInfo.packageName); sendResourcesChangedBroadcast(true, true, pkgList,uidArray, null); } } if (res.removedInfo.args != null) { // Remove the replaced package's older resources safely now deleteOld = true; } // Log current value of "unknown sources" setting EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, getUnknownSourcesSettings()); } // Force a gc to clear up things Runtime.getRuntime().gc(); // We delete after a gc for applications on sdcard. if (deleteOld) { synchronized (mInstallLock) { res.removedInfo.args.doPostDeleteLI(true); } } if (args.observer != null) { try { Bundle extras = extrasForInstallResult(res); args.observer.onPackageInstalled(res.name, res.returnCode, res.returnMsg, extras); } catch (RemoteException e) { Slog.i(TAG, "Observer no longer exists."); } } } else { Slog.e(TAG, "Bogus post-install token " + msg.arg1); } } break; case UPDATED_MEDIA_STATUS: { if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); boolean reportStatus = msg.arg1 == 1; boolean doGc = msg.arg2 == 1; if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); if (doGc) { // Force a gc to clear up stale containers. Runtime.getRuntime().gc(); } if (msg.obj != null) { @SuppressWarnings("unchecked") Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); // Unload containers unloadAllContainers(args); } if (reportStatus) { try { if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); PackageHelper.getMountService().finishMediaUpdate(); } catch (RemoteException e) { Log.e(TAG, "MountService not running?"); } } } break; case WRITE_SETTINGS: { Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); synchronized (mPackages) { removeMessages(WRITE_SETTINGS); removeMessages(WRITE_PACKAGE_RESTRICTIONS); mSettings.writeLPr(); mDirtyUsers.clear(); } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } break; case WRITE_PACKAGE_RESTRICTIONS: { Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); synchronized (mPackages) { removeMessages(WRITE_PACKAGE_RESTRICTIONS); for (int userId : mDirtyUsers) { mSettings.writePackageRestrictionsLPr(userId); } mDirtyUsers.clear(); } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } break; case CHECK_PENDING_VERIFICATION: { final int verificationId = msg.arg1; final PackageVerificationState state = mPendingVerification.get(verificationId); if ((state != null) && !state.timeoutExtended()) { final InstallArgs args = state.getInstallArgs(); final Uri originUri = Uri.fromFile(args.origin.resolvedFile); Slog.i(TAG, "Verification timed out for " + originUri); mPendingVerification.remove(verificationId); int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { Slog.i(TAG, "Continuing with installation of " + originUri); state.setVerifierResponse(Binder.getCallingUid(), PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); broadcastPackageVerified(verificationId, originUri, PackageManager.VERIFICATION_ALLOW, state.getInstallArgs().getUser()); try { ret = args.copyApk(mContainerService, true); } catch (RemoteException e) { Slog.e(TAG, "Could not contact the ContainerService"); } } else { broadcastPackageVerified(verificationId, originUri, PackageManager.VERIFICATION_REJECT, state.getInstallArgs().getUser()); } processPendingInstall(args, ret); mHandler.sendEmptyMessage(MCS_UNBIND); } break; } case PACKAGE_VERIFIED: { final int verificationId = msg.arg1; final PackageVerificationState state = mPendingVerification.get(verificationId); if (state == null) { Slog.w(TAG, "Invalid verification token " + verificationId + " received"); break; } final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; state.setVerifierResponse(response.callerUid, response.code); if (state.isVerificationComplete()) { mPendingVerification.remove(verificationId); final InstallArgs args = state.getInstallArgs(); final Uri originUri = Uri.fromFile(args.origin.resolvedFile); int ret; if (state.isInstallAllowed()) { ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; broadcastPackageVerified(verificationId, originUri, response.code, state.getInstallArgs().getUser()); try { ret = args.copyApk(mContainerService, true); } catch (RemoteException e) { Slog.e(TAG, "Could not contact the ContainerService"); } } else { ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; } processPendingInstall(args, ret); mHandler.sendEmptyMessage(MCS_UNBIND); } break; } } } } Bundle extrasForInstallResult(PackageInstalledInfo res) { Bundle extras = null; switch (res.returnCode) { case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { extras = new Bundle(); extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, res.origPermission); extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, res.origPackage); break; } } return extras; } void scheduleWriteSettingsLocked() { if (!mHandler.hasMessages(WRITE_SETTINGS)) { mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); } } void scheduleWritePackageRestrictionsLocked(int userId) { if (!sUserManager.exists(userId)) return; mDirtyUsers.add(userId); if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); } } public static final PackageManagerService main(Context context, Installer installer, boolean factoryTest, boolean onlyCore) { PackageManagerService m = new PackageManagerService(context, installer, factoryTest, onlyCore); ServiceManager.addService("package", m); return m; } static String[] splitString(String str, char sep) { int count = 1; int i = 0; while ((i=str.indexOf(sep, i)) >= 0) { count++; i++; } String[] res = new String[count]; i=0; count = 0; int lastI=0; while ((i=str.indexOf(sep, i)) >= 0) { res[count] = str.substring(lastI, i); count++; i++; lastI = i; } res[count] = str.substring(lastI, str.length()); return res; } /** M: Mtprof tool @{ */ public void addBootEvent(String bootevent) { try { if (!mMTPROFDisable) { FileOutputStream fbp = new FileOutputStream("/proc/bootprof"); fbp.write(bootevent.getBytes()); fbp.flush(); fbp.close(); } } catch (FileNotFoundException e) { Slog.e("BOOTPROF", "Failure open /proc/bootprof, not found!", e); mMTPROFDisable = true; } catch (java.io.IOException e) { Slog.e("BOOTPROF", "Failure open /proc/bootprof entry", e); mMTPROFDisable = true; } } /** @} */ private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { DisplayManager displayManager = (DisplayManager) context.getSystemService( Context.DISPLAY_SERVICE); displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); } public PackageManagerService(Context context, Installer installer, boolean factoryTest, boolean onlyCore) { EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, SystemClock.uptimeMillis()); /** M: Mtprof tool @{ */ //mMTPROFDisable = "1".equals(SystemProperties.get("ro.mtprof.disable")); mMTPROFDisable = false; addBootEvent(new String("Android:PackageManagerService_Start")); /** @} */ if (mSdkVersion <= 0) { Slog.w(TAG, "**** ro.build.version.sdk not set!"); } mContext = context; mFactoryTest = factoryTest; mOnlyCore = onlyCore; mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); mMetrics = new DisplayMetrics(); mSettings = new Settings(context); mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); String separateProcesses = SystemProperties.get("debug.separate_processes"); if (separateProcesses != null && separateProcesses.length() > 0) { if ("*".equals(separateProcesses)) { mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; mSeparateProcesses = null; Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); } else { mDefParseFlags = 0; mSeparateProcesses = separateProcesses.split(","); Slog.w(TAG, "Running with debug.separate_processes: " + separateProcesses); } } else { mDefParseFlags = 0; mSeparateProcesses = null; } mInstaller = installer; getDefaultDisplayMetrics(context, mMetrics); SystemConfig systemConfig = SystemConfig.getInstance(); mGlobalGids = systemConfig.getGlobalGids(); mSystemPermissions = systemConfig.getSystemPermissions(); mAvailableFeatures = systemConfig.getAvailableFeatures(); synchronized (mInstallLock) { // writer synchronized (mPackages) { mHandlerThread = new ServiceThread(TAG, Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); mHandlerThread.start(); mHandler = new PackageHandler(mHandlerThread.getLooper()); Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); File dataDir = Environment.getDataDirectory(); mAppDataDir = new File(dataDir, "data"); mAppInstallDir = new File(dataDir, "app"); mAppLib32InstallDir = new File(dataDir, "app-lib"); mAsecInternalPath = new File(dataDir, "app-asec").getPath(); mUserAppDataDir = new File(dataDir, "user"); mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); sUserManager = new UserManagerService(context, this, mInstallLock, mPackages); // Propagate permission configuration in to package manager. ArrayMap<String, SystemConfig.PermissionEntry> permConfig = systemConfig.getPermissions(); for (int i=0; i<permConfig.size(); i++) { SystemConfig.PermissionEntry perm = permConfig.valueAt(i); BasePermission bp = mSettings.mPermissions.get(perm.name); if (bp == null) { bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); mSettings.mPermissions.put(perm.name, bp); } if (perm.gids != null) { bp.gids = appendInts(bp.gids, perm.gids); } } ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); for (int i=0; i<libConfig.size(); i++) { mSharedLibraries.put(libConfig.keyAt(i), new SharedLibraryEntry(libConfig.valueAt(i), null)); } mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), mSdkVersion, mOnlyCore); String customResolverActivity = Resources.getSystem().getString( R.string.config_customResolverActivity); if (TextUtils.isEmpty(customResolverActivity)) { customResolverActivity = null; } else { mCustomResolverComponentName = ComponentName.unflattenFromString( customResolverActivity); } long startTime = SystemClock.uptimeMillis(); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, startTime); /// M: Mtprof tool addBootEvent(new String("Android:PMS_scan_START")); // Set flag to monitor and not change apk file paths when // scanning install directories. final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; final HashSet<String> alreadyDexOpted = new HashSet<String>(); /** * Add everything in the in the boot class path to the * list of process files because dexopt will have been run * if necessary during zygote startup. */ final String bootClassPath = System.getenv("BOOTCLASSPATH"); final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); if (bootClassPath != null) { String[] bootClassPathElements = splitString(bootClassPath, ':'); for (String element : bootClassPathElements) { alreadyDexOpted.add(element); } } else { Slog.w(TAG, "No BOOTCLASSPATH found!"); } if (systemServerClassPath != null) { String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); for (String element : systemServerClassPathElements) { alreadyDexOpted.add(element); } } else { Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); } boolean didDexOptLibraryOrTool = false; final List<String> allInstructionSets = getAllInstructionSets(); final String[] dexCodeInstructionSets = getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); /** * Ensure all external libraries have had dexopt run on them. */ if (mSharedLibraries.size() > 0) { // NOTE: For now, we're compiling these system "shared libraries" // (and framework jars) into all available architectures. It's possible // to compile them only when we come across an app that uses them (there's // already logic for that in scanPackageLI) but that adds some complexity. for (String dexCodeInstructionSet : dexCodeInstructionSets) { for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { final String lib = libEntry.path; if (lib == null) { continue; } try { byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, dexCodeInstructionSet, false); if (dexoptRequired != DexFile.UP_TO_DATE) { alreadyDexOpted.add(lib); // The list of "shared libraries" we have at this point is if (dexoptRequired == DexFile.DEXOPT_NEEDED) { mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); } else { mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); } didDexOptLibraryOrTool = true; } } catch (FileNotFoundException e) { Slog.w(TAG, "Library not found: " + lib); } catch (IOException e) { Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " + e.getMessage()); } } } } File frameworkDir = new File(Environment.getRootDirectory(), "framework"); // Gross hack for now: we know this file doesn't contain any // code, so don't dexopt it to avoid the resulting log spew. alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); /// M: This file doesn't contain any code,just like framework-res,so don't dexopt it alreadyDexOpted.add(frameworkDir.getPath() + "/mediatek-res/mediatek-res.apk"); /** M: [CIP] Add CIP scanning path variable @{ */ File customFrameworkDir = new File("/custom/framework"); /// M: [CIP] Add custom resources to libFiles to avoid dex opt. alreadyDexOpted.add(customFrameworkDir.getPath() + "/framework-res.apk"); alreadyDexOpted.add(customFrameworkDir.getPath() + "/mediatek-res.apk"); /** @} */ // Gross hack for now: we know this file is only part of // the boot class path for art, so don't dexopt it to // avoid the resulting log spew. alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); /** * And there are a number of commands implemented in Java, which * we currently need to do the dexopt on so that they can be * run from a non-root shell. */ /** M: [CIP] Perform dex opt on custom frameworks. @{ */ String[] customFrameworkFiles = customFrameworkDir.list(); if (customFrameworkFiles != null) { for (String instructionSet : dexCodeInstructionSets) { for (int i = 0; i < customFrameworkFiles.length; i++) { File libPath = new File(customFrameworkDir, customFrameworkFiles[i]); String path = libPath.getPath(); // Skip the file if we alrady did it. if (alreadyDexOpted.contains(path)) { continue; } // Skip the file if it is not a type we want to dexopt. if (!path.endsWith(".apk") && !path.endsWith(".jar")) { continue; } try { byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, instructionSet, false); if (dexoptRequired == DexFile.DEXOPT_NEEDED) { mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); didDexOptLibraryOrTool = true; } } catch (FileNotFoundException e) { Slog.w(TAG, "Jar not found: " + path); } catch (IOException e) { Slog.w(TAG, "Exception reading jar: " + path, e); } } } } /** @} */ String[] frameworkFiles = frameworkDir.list(); if (frameworkFiles != null) { // TODO: We could compile these only for the most preferred ABI. We should // first double check that the dex files for these commands are not referenced // by other system apps. for (String dexCodeInstructionSet : dexCodeInstructionSets) { for (int i=0; i<frameworkFiles.length; i++) { File libPath = new File(frameworkDir, frameworkFiles[i]); String path = libPath.getPath(); // Skip the file if we already did it. if (alreadyDexOpted.contains(path)) { continue; } // Skip the file if it is not a type we want to dexopt. if (!path.endsWith(".apk") && !path.endsWith(".jar")) { continue; } try { byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, dexCodeInstructionSet, false); if (dexoptRequired == DexFile.DEXOPT_NEEDED) { mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); didDexOptLibraryOrTool = true; } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); didDexOptLibraryOrTool = true; } } catch (FileNotFoundException e) { Slog.w(TAG, "Jar not found: " + path); } catch (IOException e) { Slog.w(TAG, "Exception reading jar: " + path, e); } } } } /** M: for plugin app @{ */ // for system plugin File pluginDir = new File(Environment.getRootDirectory(), "plugin"); String[] pluginFiles = pluginDir.list(); if (pluginFiles != null) { for (String dexCodeInstructionSet : dexCodeInstructionSets) { for (int i = 0; i < pluginFiles.length; i++) { File libPath = new File(pluginDir, pluginFiles[i]); String path = libPath.getPath(); // Skip the file if we alrady did it. if (alreadyDexOpted.contains(path)) { continue; } // Skip the file if it is not a type we want to dexopt. if (!path.endsWith(".apk") && !path.endsWith(".jar")) { continue; } try { byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, dexCodeInstructionSet, false); if (dexoptRequired == DexFile.DEXOPT_NEEDED) { mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); didDexOptLibraryOrTool = true; } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); didDexOptLibraryOrTool = true; } } catch (FileNotFoundException e) { Slog.w(TAG, "Jar not found: " + path); } catch (IOException e) { Slog.w(TAG, "Exception reading jar: " + path, e); } } } } // for custom plugin File customPluginDir = new File("/custom/plugin"); String[] customPluginFiles = customPluginDir.list(); if (customPluginFiles != null) { for (String dexCodeInstructionSet : dexCodeInstructionSets) { for (int i = 0; i < customPluginFiles.length; i++) { File libPath = new File(customPluginDir, customPluginFiles[i]); String path = libPath.getPath(); // Skip the file if we alrady did it. if (alreadyDexOpted.contains(path)) { continue; } // Skip the file if it is not a type we want to dexopt. if (!path.endsWith(".apk") && !path.endsWith(".jar")) { continue; } try { byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, dexCodeInstructionSet, false); if (dexoptRequired == DexFile.DEXOPT_NEEDED) { mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); didDexOptLibraryOrTool = true; } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); didDexOptLibraryOrTool = true; } } catch (FileNotFoundException e) { Slog.w(TAG, "Jar not found: " + path); } catch (IOException e) { Slog.w(TAG, "Exception reading jar: " + path, e); } } } } /** @} */ // Collect vendor overlay packages. // (Do this before scanning any apps.) // For security and version matching reason, only consider // overlay packages if they reside in VENDOR_OVERLAY_DIR. File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); /** M: [CIP] Find base frameworks (resource packages without code). @{ */ /// The scan order for CIP frameworks must appear ahead of /// the original system folder. Because CIP resources must /// replace the original resource if they exist. scanDirLI(customFrameworkDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_NO_DEX, 0); /** @} */ // Find base frameworks (resource packages without code). scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR | PackageParser.PARSE_IS_PRIVILEGED, scanFlags | SCAN_NO_DEX, 0); // Collected privileged system packages. final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); // Collect ordinary system packages. final File systemAppDir = new File(Environment.getRootDirectory(), "app"); scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); /** M: [Resmon] Enhancement of resmon filter @{ */ ResmonFilter rf = new ResmonFilter(); rf.filt(mSettings, mPackages); /** @} */ // Collect all vendor packages. File vendorAppDir = new File("/vendor/app"); try { vendorAppDir = vendorAppDir.getCanonicalFile(); } catch (IOException e) { // failed to look up canonical path, continue with original one } scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); /** M: [ALPS00104673][Need Patch][Volunteer Patch]Mechanism for uninstall app from system partition @{ */ /// M: [ALPS01210636] Unify path from /vendor to /system/vendor/ /// So that DVM can find the correct odex mOperatorAppInstallDir = new File(Environment.getRootDirectory(), "/vendor/operator/app"); /// M: [ALPS00270065][Urgent] User mode, cannot move applications to SD /// M: [ALPS00338366] Add PARSE_IS_OPERATOR for operator apps scanDirLI(mOperatorAppInstallDir, PackageParser.PARSE_IS_OPERATOR, scanFlags, 0); /** @} */ /** M: [CIP] Scan CIP app folder @{ */ mCustomAppInstallDir = new File("/custom/app"); /// M: App under CIP folder can be uninstalled scanDirLI(mCustomAppInstallDir, PackageParser.PARSE_IS_OPERATOR | PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); /** @} */ /** M: for plugin app @{ */ /// APP plugin mPluginAppInstallDir = new File(Environment.getRootDirectory(), "plugin"); scanDirLI(mPluginAppInstallDir, PackageParser.PARSE_IS_OPERATOR | PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); /// CIP plugin mCustomPluginInstallDir = new File("/custom/plugin"); /// M: App under CIP folder can be uninstalled scanDirLI(mCustomPluginInstallDir, PackageParser.PARSE_IS_OPERATOR | PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); /** @} */ // Collect all OEM packages. final File oemAppDir = new File(Environment.getOemDirectory(), "app"); scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); mInstaller.moveFiles(); // Prune any system packages that no longer exist. final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); if (!mOnlyCore) { Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); while (psit.hasNext()) { PackageSetting ps = psit.next(); /* * If this is not a system app, it can't be a * disable system app. */ if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { /// M: [Operator] Operator apps are belong to system domain, therefore, need prune. /// M: [Operator] We should also consider OTA from old version without mtkFlag if (!isVendorApp(ps) && !locationIsOperator(ps.codePath)) { continue; } } /* * If the package is scanned, it's not erased. */ final PackageParser.Package scannedPkg = mPackages.get(ps.name); if (scannedPkg != null) { /* * If the system app is both scanned and in the * disabled packages list, then it must have been * added via OTA. Remove it from the currently * scanned package so the previously user-installed * application can be scanned. */ if (mSettings.isDisabledSystemPackageLPr(ps.name)) { logCriticalInfo(Log.WARN, "Expecting better updated system app for " + ps.name + "; removing system app. Last known codePath=" + ps.codePathString + ", installStatus=" + ps.installStatus + ", versionCode=" + ps.versionCode + "; scanned versionCode=" + scannedPkg.mVersionCode); removePackageLI(ps, true); expectingBetter.put(ps.name, ps.codePath); } continue; } if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { psit.remove(); logCriticalInfo(Log.WARN, "System package " + ps.name + " no longer exists; wiping its data"); removeDataDirsLI(ps.name); } else { final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { possiblyDeletedUpdatedSystemApps.add(ps.name); } } } } //look for any incomplete package installations ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); //clean up list for(int i = 0; i < deletePkgsList.size(); i++) { //clean up here cleanupInstallFailedPackage(deletePkgsList.get(i)); } //delete tmp files deleteTempPackageFiles(); // Remove any shared userIDs that have no associated packages mSettings.pruneSharedUsersLPw(); if (!mOnlyCore) { EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, SystemClock.uptimeMillis()); scanDirLI(mAppInstallDir, 0, scanFlags, 0); scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanFlags, 0); /** * Remove disable package settings for any updated system * apps that were removed via an OTA. If they're not a * previously-updated app, remove them completely. * Otherwise, just revoke their system-level permissions. */ for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { PackageParser.Package deletedPkg = mPackages.get(deletedAppName); mSettings.removeDisabledSystemPackageLPw(deletedAppName); String msg; if (deletedPkg == null) { msg = "Updated system package " + deletedAppName + " no longer exists; wiping its data"; removeDataDirsLI(deletedAppName); } else { msg = "Updated system app + " + deletedAppName + " no longer present; removing system privileges for " + deletedAppName; deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; /// M: [Operator] Revoke operator permissions for the original operator package /// under operator folder was gone due to OTA deletedPkg.applicationInfo.flagsEx &= ~ApplicationInfo.FLAG_EX_OPERATOR; PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; /// M: [Operator] Revoke vendor permissions deletedPs.pkgFlagsEx &= ~ApplicationInfo.FLAG_EX_OPERATOR; } logCriticalInfo(Log.WARN, msg); } /** * Make sure all system apps that we expected to appear on * the userdata partition actually showed up. If they never * appeared, crawl back and revive the system version. */ for (int i = 0; i < expectingBetter.size(); i++) { final String packageName = expectingBetter.keyAt(i); if (!mPackages.containsKey(packageName)) { final File scanFile = expectingBetter.valueAt(i); logCriticalInfo(Log.WARN, "Expected better " + packageName + " but never showed up; reverting to system"); final int reparseFlags; if (FileUtils.contains(privilegedAppDir, scanFile)) { reparseFlags = PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR | PackageParser.PARSE_IS_PRIVILEGED; } else if (FileUtils.contains(systemAppDir, scanFile)) { reparseFlags = PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR; } else if (FileUtils.contains(vendorAppDir, scanFile)) { reparseFlags = PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR; } else if (FileUtils.contains(oemAppDir, scanFile)) { reparseFlags = PackageParser.PARSE_IS_SYSTEM | PackageParser.PARSE_IS_SYSTEM_DIR; } else { Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); continue; } mSettings.enableSystemPackageLPw(packageName); try { scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); } catch (PackageManagerException e) { Slog.e(TAG, "Failed to parse original system package: " + e.getMessage()); } } } } // Now that we know all of the shared libraries, update all clients to have // the correct library paths. updateAllSharedLibrariesLPw(); for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { // NOTE: We ignore potential failures here during a system scan (like // the rest of the commands above) because there's precious little we // can do about it. A settings error is reported, though. adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, false /* force dexopt */, false /* defer dexopt */); } // Now that we know all the packages we are keeping, // read and update their last usage times. mPackageUsage.readLP(); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, SystemClock.uptimeMillis()); /// M: [ALPS00098646] Mtprof tool addBootEvent(new String("Android:PMS_scan_END")); Slog.i(TAG, "Time to scan packages: " + ((SystemClock.uptimeMillis()-startTime)/1000f) + " seconds"); // If the platform SDK has changed since the last time we booted, // we need to re-grant app permission to catch any new ones that // appear. This is really a hack, and means that apps can in some // cases get permissions that the user didn't initially explicitly // allow... it would be nice to have some better way to handle // this situation. final boolean regrantPermissions = mSettings.mInternalSdkPlatform != mSdkVersion; if (regrantPermissions) Slog.i(TAG, "Platform changed from " + mSettings.mInternalSdkPlatform + " to " + mSdkVersion + "; regranting permissions for internal storage"); mSettings.mInternalSdkPlatform = mSdkVersion; updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL | (regrantPermissions ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) : 0)); // If this is the first boot, and it is a normal boot, then // we need to initialize the default preferred apps. if (!mRestoredSettings && !onlyCore) { mSettings.readDefaultPreferredAppsLPw(this, 0); } // If this is first boot after an OTA, and a normal boot, then // we need to clear code cache directories. if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { Slog.i(TAG, "Build fingerprint changed; clearing code caches"); for (String pkgName : mSettings.mPackages.keySet()) { deleteCodeCacheDirsLI(pkgName); } mSettings.mFingerprint = Build.FINGERPRINT; } // All the changes are done during package scanning. mSettings.updateInternalDatabaseVersion(); // can downgrade to reader mSettings.writeLPr(); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, SystemClock.uptimeMillis()); /// M: Mtprof tool addBootEvent(new String("Android:PMS_READY")); mRequiredVerifierPackage = getRequiredVerifierLPr(); } // synchronized (mPackages) } // synchronized (mInstallLock) mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); // Now after opening every single application zip, make sure they // are all flushed. Not really needed, but keeps things nice and // tidy. Runtime.getRuntime().gc(); } @Override public boolean isFirstBoot() { return !mRestoredSettings; } @Override public boolean isOnlyCoreApps() { return mOnlyCore; } private String getRequiredVerifierLPr() { final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); String requiredVerifier = null; final int N = receivers.size(); for (int i = 0; i < N; i++) { final ResolveInfo info = receivers.get(i); if (info.activityInfo == null) { continue; } final String packageName = info.activityInfo.packageName; final PackageSetting ps = mSettings.mPackages.get(packageName); if (ps == null) { continue; } final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; if (!gp.grantedPermissions .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { continue; } if (requiredVerifier != null) { throw new RuntimeException("There can be only one required verifier"); } requiredVerifier = packageName; } return requiredVerifier; } @Override public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { try { return super.onTransact(code, data, reply, flags); } catch (RuntimeException e) { if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { Slog.wtf(TAG, "Package Manager Crash", e); } throw e; } } void cleanupInstallFailedPackage(PackageSetting ps) { logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); removeDataDirsLI(ps.name); if (ps.codePath != null) { if (ps.codePath.isDirectory()) { FileUtils.deleteContents(ps.codePath); } ps.codePath.delete(); } if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { if (ps.resourcePath.isDirectory()) { FileUtils.deleteContents(ps.resourcePath); } ps.resourcePath.delete(); } mSettings.removePackageLPw(ps.name); } static int[] appendInts(int[] cur, int[] add) { if (add == null) return cur; if (cur == null) return add; final int N = add.length; for (int i=0; i<N; i++) { cur = appendInt(cur, add[i]); } return cur; } static int[] removeInts(int[] cur, int[] rem) { if (rem == null) return cur; if (cur == null) return cur; final int N = rem.length; for (int i=0; i<N; i++) { cur = removeInt(cur, rem[i]); } return cur; } PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { if (!sUserManager.exists(userId)) return null; final PackageSetting ps = (PackageSetting) p.mExtras; if (ps == null) { return null; } final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; final PackageUserState state = ps.readUserState(userId); return PackageParser.generatePackageInfo(p, gp.gids, flags, ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, state, userId); } @Override public boolean isPackageAvailable(String packageName, int userId) { if (!sUserManager.exists(userId)) return false; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); synchronized (mPackages) { PackageParser.Package p = mPackages.get(packageName); if (p != null) { final PackageSetting ps = (PackageSetting) p.mExtras; if (ps != null) { final PackageUserState state = ps.readUserState(userId); if (state != null) { return PackageParser.isAvailable(state); } } } } return false; } @Override public PackageInfo getPackageInfo(String packageName, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); // reader synchronized (mPackages) { PackageParser.Package p = mPackages.get(packageName); if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getPackageInfo " + packageName + ": " + p); if (p != null) { return generatePackageInfo(p, flags, userId); } if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { return generatePackageInfoFromSettingsLPw(packageName, flags, userId); } } return null; } @Override public String[] currentToCanonicalPackageNames(String[] names) { String[] out = new String[names.length]; // reader synchronized (mPackages) { for (int i=names.length-1; i>=0; i--) { PackageSetting ps = mSettings.mPackages.get(names[i]); out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; } } return out; } @Override public String[] canonicalToCurrentPackageNames(String[] names) { String[] out = new String[names.length]; // reader synchronized (mPackages) { for (int i=names.length-1; i>=0; i--) { String cur = mSettings.mRenamedPackages.get(names[i]); out[i] = cur != null ? cur : names[i]; } } return out; } @Override public int getPackageUid(String packageName, int userId) { if (!sUserManager.exists(userId)) return -1; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); // reader synchronized (mPackages) { PackageParser.Package p = mPackages.get(packageName); if(p != null) { return UserHandle.getUid(userId, p.applicationInfo.uid); } PackageSetting ps = mSettings.mPackages.get(packageName); if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { return -1; } p = ps.pkg; return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; } } @Override public int[] getPackageGids(String packageName) { // reader synchronized (mPackages) { PackageParser.Package p = mPackages.get(packageName); if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getPackageGids" + packageName + ": " + p); if (p != null) { final PackageSetting ps = (PackageSetting)p.mExtras; return ps.getGids(); } } // stupid thing to indicate an error. return new int[0]; } static final PermissionInfo generatePermissionInfo( BasePermission bp, int flags) { if (bp.perm != null) { return PackageParser.generatePermissionInfo(bp.perm, flags); } PermissionInfo pi = new PermissionInfo(); pi.name = bp.name; pi.packageName = bp.sourcePackage; pi.nonLocalizedLabel = bp.name; pi.protectionLevel = bp.protectionLevel; return pi; } @Override public PermissionInfo getPermissionInfo(String name, int flags) { // reader synchronized (mPackages) { final BasePermission p = mSettings.mPermissions.get(name); if (p != null) { return generatePermissionInfo(p, flags); } return null; } } @Override public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { // reader synchronized (mPackages) { ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); for (BasePermission p : mSettings.mPermissions.values()) { if (group == null) { if (p.perm == null || p.perm.info.group == null) { out.add(generatePermissionInfo(p, flags)); } } else { if (p.perm != null && group.equals(p.perm.info.group)) { out.add(PackageParser.generatePermissionInfo(p.perm, flags)); } } } if (out.size() > 0) { return out; } return mPermissionGroups.containsKey(group) ? out : null; } } @Override public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { // reader synchronized (mPackages) { return PackageParser.generatePermissionGroupInfo( mPermissionGroups.get(name), flags); } } @Override public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { // reader synchronized (mPackages) { final int N = mPermissionGroups.size(); ArrayList<PermissionGroupInfo> out = new ArrayList<PermissionGroupInfo>(N); for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); } return out; } } private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, int userId) { if (!sUserManager.exists(userId)) return null; PackageSetting ps = mSettings.mPackages.get(packageName); if (ps != null) { if (ps.pkg == null) { PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, flags, userId); if (pInfo != null) { return pInfo.applicationInfo; } return null; } return PackageParser.generateApplicationInfo(ps.pkg, flags, ps.readUserState(userId), userId); } return null; } private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, int userId) { if (!sUserManager.exists(userId)) return null; PackageSetting ps = mSettings.mPackages.get(packageName); if (ps != null) { PackageParser.Package pkg = ps.pkg; if (pkg == null) { if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { return null; } // Only data remains, so we aren't worried about code paths pkg = new PackageParser.Package(packageName); pkg.applicationInfo.packageName = packageName; pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; pkg.applicationInfo.dataDir = getDataPathForPackage(packageName, 0).getPath(); pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; } return generatePackageInfo(pkg, flags, userId); } return null; } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); // writer synchronized (mPackages) { PackageParser.Package p = mPackages.get(packageName); if (DEBUG_PACKAGE_INFO) Log.v( TAG, "getApplicationInfo " + packageName + ": " + p); if (p != null) { PackageSetting ps = mSettings.mPackages.get(packageName); if (ps == null) return null; // Note: isEnabledLP() does not apply here - always return info return PackageParser.generateApplicationInfo( p, flags, ps.readUserState(userId), userId); } if ("android".equals(packageName)||"system".equals(packageName)) { return mAndroidApplication; } if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); } } return null; } @Override public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.CLEAR_APP_CACHE, null); // Queue up an async operation since clearing cache may take a little while. mHandler.post(new Runnable() { public void run() { mHandler.removeCallbacks(this); int retCode = -1; synchronized (mInstallLock) { retCode = mInstaller.freeCache(freeStorageSize); if (retCode < 0) { Slog.w(TAG, "Couldn't clear application caches"); } } if (observer != null) { try { observer.onRemoveCompleted(null, (retCode >= 0)); } catch (RemoteException e) { Slog.w(TAG, "RemoveException when invoking call back"); } } } }); } @Override public void freeStorage(final long freeStorageSize, final IntentSender pi) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.CLEAR_APP_CACHE, null); // Queue up an async operation since clearing cache may take a little while. mHandler.post(new Runnable() { public void run() { mHandler.removeCallbacks(this); int retCode = -1; synchronized (mInstallLock) { retCode = mInstaller.freeCache(freeStorageSize); if (retCode < 0) { Slog.w(TAG, "Couldn't clear application caches"); } } if(pi != null) { try { // Callback via pending intent int code = (retCode >= 0) ? 1 : 0; pi.sendIntent(null, code, null, null, null); } catch (SendIntentException e1) { Slog.i(TAG, "Failed to send pending intent"); } } } }); } void freeStorage(long freeStorageSize) throws IOException { synchronized (mInstallLock) { if (mInstaller.freeCache(freeStorageSize) < 0) { throw new IOException("Failed to free enough space"); } } } @Override public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); synchronized (mPackages) { PackageParser.Activity a = mActivities.mActivities.get(component); if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); if (ps == null) return null; return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), userId); } if (mResolveComponentName.equals(component)) { return PackageParser.generateActivityInfo(mResolveActivity, flags, new PackageUserState(), userId); } } return null; } @Override public boolean activitySupportsIntent(ComponentName component, Intent intent, String resolvedType) { synchronized (mPackages) { PackageParser.Activity a = mActivities.mActivities.get(component); if (a == null) { return false; } for (int i=0; i<a.intents.size(); i++) { if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), intent.getData(), intent.getCategories(), TAG) >= 0) { return true; } } return false; } } @Override public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); synchronized (mPackages) { PackageParser.Activity a = mReceivers.mActivities.get(component); if (DEBUG_PACKAGE_INFO) Log.v( TAG, "getReceiverInfo " + component + ": " + a); if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); if (ps == null) return null; return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), userId); } } return null; } @Override public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); synchronized (mPackages) { PackageParser.Service s = mServices.mServices.get(component); if (DEBUG_PACKAGE_INFO) Log.v( TAG, "getServiceInfo " + component + ": " + s); if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); if (ps == null) return null; return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), userId); } } return null; } @Override public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); synchronized (mPackages) { PackageParser.Provider p = mProviders.mProviders.get(component); if (DEBUG_PACKAGE_INFO) Log.v( TAG, "getProviderInfo " + component + ": " + p); if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); if (ps == null) return null; return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), userId); } } return null; } @Override public String[] getSystemSharedLibraryNames() { Set<String> libSet; synchronized (mPackages) { libSet = mSharedLibraries.keySet(); int size = libSet.size(); if (size > 0) { String[] libs = new String[size]; libSet.toArray(libs); return libs; } } return null; } @Override public FeatureInfo[] getSystemAvailableFeatures() { Collection<FeatureInfo> featSet; synchronized (mPackages) { featSet = mAvailableFeatures.values(); int size = featSet.size(); if (size > 0) { FeatureInfo[] features = new FeatureInfo[size+1]; featSet.toArray(features); FeatureInfo fi = new FeatureInfo(); fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", FeatureInfo.GL_ES_VERSION_UNDEFINED); features[size] = fi; return features; } } return null; } @Override public boolean hasSystemFeature(String name) { synchronized (mPackages) { return mAvailableFeatures.containsKey(name); } } private void checkValidCaller(int uid, int userId) { if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return; throw new SecurityException("Caller uid=" + uid + " is not privileged to communicate with user=" + userId); } @Override public int checkPermission(String permName, String pkgName) { synchronized (mPackages) { PackageParser.Package p = mPackages.get(pkgName); if (p != null && p.mExtras != null) { PackageSetting ps = (PackageSetting)p.mExtras; if (ps.sharedUser != null) { if (ps.sharedUser.grantedPermissions.contains(permName)) { return PackageManager.PERMISSION_GRANTED; } } else if (ps.grantedPermissions.contains(permName)) { return PackageManager.PERMISSION_GRANTED; } } } return PackageManager.PERMISSION_DENIED; } @Override public int checkUidPermission(String permName, int uid) { synchronized (mPackages) { Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); if (obj != null) { GrantedPermissions gp = (GrantedPermissions)obj; if (gp.grantedPermissions.contains(permName)) { return PackageManager.PERMISSION_GRANTED; } } else { HashSet<String> perms = mSystemPermissions.get(uid); if (perms != null && perms.contains(permName)) { return PackageManager.PERMISSION_GRANTED; } } } return PackageManager.PERMISSION_DENIED; } /** * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. * @param checkShell TODO(yamasani): * @param message the message to log on security exception */ void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, boolean checkShell, String message) { if (userId < 0) { throw new IllegalArgumentException("Invalid userId " + userId); } if (checkShell) { enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); } if (userId == UserHandle.getUserId(callingUid)) return; if (callingUid != Process.SYSTEM_UID && callingUid != 0) { if (requireFullPermission) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); } else { try { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); } catch (SecurityException se) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS, message); } } } } void enforceShellRestriction(String restriction, int callingUid, int userHandle) { if (callingUid == Process.SHELL_UID) { if (userHandle >= 0 && sUserManager.hasUserRestriction(restriction, userHandle)) { throw new SecurityException("Shell does not have permission to access user " + userHandle); } else if (userHandle < 0) { Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" + Debug.getCallers(3)); } } } private BasePermission findPermissionTreeLP(String permName) { for(BasePermission bp : mSettings.mPermissionTrees.values()) { if (permName.startsWith(bp.name) && permName.length() > bp.name.length() && permName.charAt(bp.name.length()) == '.') { return bp; } } return null; } private BasePermission checkPermissionTreeLP(String permName) { if (permName != null) { BasePermission bp = findPermissionTreeLP(permName); if (bp != null) { if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { return bp; } throw new SecurityException("Calling uid " + Binder.getCallingUid() + " is not allowed to add to permission tree " + bp.name + " owned by uid " + bp.uid); } } throw new SecurityException("No permission tree found for " + permName); } static boolean compareStrings(CharSequence s1, CharSequence s2) { if (s1 == null) { return s2 == null; } if (s2 == null) { return false; } if (s1.getClass() != s2.getClass()) { return false; } return s1.equals(s2); } static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { if (pi1.icon != pi2.icon) return false; if (pi1.logo != pi2.logo) return false; if (pi1.protectionLevel != pi2.protectionLevel) return false; if (!compareStrings(pi1.name, pi2.name)) return false; if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; // We'll take care of setting this one. if (!compareStrings(pi1.packageName, pi2.packageName)) return false; // These are not currently stored in settings. //if (!compareStrings(pi1.group, pi2.group)) return false; //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; //if (pi1.labelRes != pi2.labelRes) return false; //if (pi1.descriptionRes != pi2.descriptionRes) return false; return true; } int permissionInfoFootprint(PermissionInfo info) { int size = info.name.length(); if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); return size; } int calculateCurrentPermissionFootprintLocked(BasePermission tree) { int size = 0; for (BasePermission perm : mSettings.mPermissions.values()) { if (perm.uid == tree.uid) { size += perm.name.length() + permissionInfoFootprint(perm.perm.info); } } return size; } void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { // We calculate the max size of permissions defined by this uid and throw // if that plus the size of 'info' would exceed our stated maximum. if (tree.uid != Process.SYSTEM_UID) { final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { throw new SecurityException("Permission tree size cap exceeded"); } } } boolean addPermissionLocked(PermissionInfo info, boolean async) { if (info.labelRes == 0 && info.nonLocalizedLabel == null) { throw new SecurityException("Label must be specified in permission"); } BasePermission tree = checkPermissionTreeLP(info.name); BasePermission bp = mSettings.mPermissions.get(info.name); boolean added = bp == null; boolean changed = true; int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); if (added) { enforcePermissionCapLocked(info, tree); bp = new BasePermission(info.name, tree.sourcePackage, BasePermission.TYPE_DYNAMIC); } else if (bp.type != BasePermission.TYPE_DYNAMIC) { throw new SecurityException( "Not allowed to modify non-dynamic permission " + info.name); } else { if (bp.protectionLevel == fixedLevel && bp.perm.owner.equals(tree.perm.owner) && bp.uid == tree.uid && comparePermissionInfos(bp.perm.info, info)) { changed = false; } } bp.protectionLevel = fixedLevel; info = new PermissionInfo(info); info.protectionLevel = fixedLevel; bp.perm = new PackageParser.Permission(tree.perm.owner, info); bp.perm.info.packageName = tree.perm.info.packageName; bp.uid = tree.uid; if (added) { mSettings.mPermissions.put(info.name, bp); } if (changed) { if (!async) { mSettings.writeLPr(); } else { scheduleWriteSettingsLocked(); } } return added; } @Override public boolean addPermission(PermissionInfo info) { synchronized (mPackages) { return addPermissionLocked(info, false); } } @Override public boolean addPermissionAsync(PermissionInfo info) { synchronized (mPackages) { return addPermissionLocked(info, true); } } @Override public void removePermission(String name) { synchronized (mPackages) { checkPermissionTreeLP(name); BasePermission bp = mSettings.mPermissions.get(name); if (bp != null) { if (bp.type != BasePermission.TYPE_DYNAMIC) { throw new SecurityException( "Not allowed to modify non-dynamic permission " + name); } mSettings.mPermissions.remove(name); mSettings.writeLPr(); } } } private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { int index = pkg.requestedPermissions.indexOf(bp.name); if (index == -1) { throw new SecurityException("Package " + pkg.packageName + " has not requested permission " + bp.name); } boolean isNormal = ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) == PermissionInfo.PROTECTION_NORMAL); boolean isDangerous = ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) == PermissionInfo.PROTECTION_DANGEROUS); boolean isDevelopment = ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); if (!isNormal && !isDangerous && !isDevelopment) { throw new SecurityException("Permission " + bp.name + " is not a changeable permission type"); } if (isNormal || isDangerous) { if (pkg.requestedPermissionsRequired.get(index)) { throw new SecurityException("Can't change " + bp.name + ". It is required by the application"); } } } @Override public void grantPermission(String packageName, String permissionName) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); synchronized (mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { throw new IllegalArgumentException("Unknown package: " + packageName); } final BasePermission bp = mSettings.mPermissions.get(permissionName); if (bp == null) { throw new IllegalArgumentException("Unknown permission: " + permissionName); } checkGrantRevokePermissions(pkg, bp); final PackageSetting ps = (PackageSetting) pkg.mExtras; if (ps == null) { return; } final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; if (gp.grantedPermissions.add(permissionName)) { if (ps.haveGids) { gp.gids = appendInts(gp.gids, bp.gids); } mSettings.writeLPr(); } } } @Override public void revokePermission(String packageName, String permissionName) { int changedAppId = -1; synchronized (mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { throw new IllegalArgumentException("Unknown package: " + packageName); } if (pkg.applicationInfo.uid != Binder.getCallingUid()) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); } final BasePermission bp = mSettings.mPermissions.get(permissionName); if (bp == null) { throw new IllegalArgumentException("Unknown permission: " + permissionName); } checkGrantRevokePermissions(pkg, bp); final PackageSetting ps = (PackageSetting) pkg.mExtras; if (ps == null) { return; } final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; if (gp.grantedPermissions.remove(permissionName)) { gp.grantedPermissions.remove(permissionName); if (ps.haveGids) { gp.gids = removeInts(gp.gids, bp.gids); } mSettings.writeLPr(); changedAppId = ps.appId; } } if (changedAppId >= 0) { // We changed the perm on someone, kill its processes. IActivityManager am = ActivityManagerNative.getDefault(); if (am != null) { final int callingUserId = UserHandle.getCallingUserId(); final long ident = Binder.clearCallingIdentity(); try { //XXX we should only revoke for the calling user's app permissions, // but for now we impact all users. //am.killUid(UserHandle.getUid(callingUserId, changedAppId), // "revoke " + permissionName); int[] users = sUserManager.getUserIds(); for (int user : users) { am.killUid(UserHandle.getUid(user, changedAppId), "revoke " + permissionName); } } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(ident); } } } } @Override public boolean isProtectedBroadcast(String actionName) { synchronized (mPackages) { return mProtectedBroadcasts.contains(actionName); } } @Override public int checkSignatures(String pkg1, String pkg2) { synchronized (mPackages) { final PackageParser.Package p1 = mPackages.get(pkg1); final PackageParser.Package p2 = mPackages.get(pkg2); if (p1 == null || p1.mExtras == null || p2 == null || p2.mExtras == null) { return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; } return compareSignatures(p1.mSignatures, p2.mSignatures); } } @Override public int checkUidSignatures(int uid1, int uid2) { // Map to base uids. uid1 = UserHandle.getAppId(uid1); uid2 = UserHandle.getAppId(uid2); // reader synchronized (mPackages) { Signature[] s1; Signature[] s2; Object obj = mSettings.getUserIdLPr(uid1); if (obj != null) { if (obj instanceof SharedUserSetting) { s1 = ((SharedUserSetting)obj).signatures.mSignatures; } else if (obj instanceof PackageSetting) { s1 = ((PackageSetting)obj).signatures.mSignatures; } else { return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; } } else { return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; } obj = mSettings.getUserIdLPr(uid2); if (obj != null) { if (obj instanceof SharedUserSetting) { s2 = ((SharedUserSetting)obj).signatures.mSignatures; } else if (obj instanceof PackageSetting) { s2 = ((PackageSetting)obj).signatures.mSignatures; } else { return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; } } else { return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; } return compareSignatures(s1, s2); } } /** * Compares two sets of signatures. Returns: * <br /> * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, * <br /> * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, * <br /> * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, * <br /> * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, * <br /> * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. */ static int compareSignatures(Signature[] s1, Signature[] s2) { if (s1 == null) { return s2 == null ? PackageManager.SIGNATURE_NEITHER_SIGNED : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; } if (s2 == null) { return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; } if (s1.length != s2.length) { return PackageManager.SIGNATURE_NO_MATCH; } // Since both signature sets are of size 1, we can compare without HashSets. if (s1.length == 1) { return s1[0].equals(s2[0]) ? PackageManager.SIGNATURE_MATCH : PackageManager.SIGNATURE_NO_MATCH; } HashSet<Signature> set1 = new HashSet<Signature>(); for (Signature sig : s1) { set1.add(sig); } HashSet<Signature> set2 = new HashSet<Signature>(); for (Signature sig : s2) { set2.add(sig); } // Make sure s2 contains all signatures in s1. if (set1.equals(set2)) { return PackageManager.SIGNATURE_MATCH; } return PackageManager.SIGNATURE_NO_MATCH; } /** * If the database version for this type of package (internal storage or * external storage) is less than the version where package signatures * were updated, return true. */ private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( DatabaseVersion.SIGNATURE_END_ENTITY)) || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( DatabaseVersion.SIGNATURE_END_ENTITY)); } /** * Used for backward compatibility to make sure any packages with * certificate chains get upgraded to the new style. {@code existingSigs} * will be in the old format (since they were stored on disk from before the * system upgrade) and {@code scannedSigs} will be in the newer format. */ private int compareSignaturesCompat(PackageSignatures existingSigs, PackageParser.Package scannedPkg) { if (!isCompatSignatureUpdateNeeded(scannedPkg)) { return PackageManager.SIGNATURE_NO_MATCH; } HashSet<Signature> existingSet = new HashSet<Signature>(); for (Signature sig : existingSigs.mSignatures) { existingSet.add(sig); } HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); for (Signature sig : scannedPkg.mSignatures) { try { Signature[] chainSignatures = sig.getChainSignatures(); for (Signature chainSig : chainSignatures) { scannedCompatSet.add(chainSig); } } catch (CertificateEncodingException e) { scannedCompatSet.add(sig); } } /* * Make sure the expanded scanned set contains all signatures in the * existing one. */ if (scannedCompatSet.equals(existingSet)) { // Migrate the old signatures to the new scheme. existingSigs.assignSignatures(scannedPkg.mSignatures); // The new KeySets will be re-added later in the scanning process. synchronized (mPackages) { mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); } return PackageManager.SIGNATURE_MATCH; } return PackageManager.SIGNATURE_NO_MATCH; } @Override public String[] getPackagesForUid(int uid) { uid = UserHandle.getAppId(uid); // reader synchronized (mPackages) { Object obj = mSettings.getUserIdLPr(uid); if (obj instanceof SharedUserSetting) { final SharedUserSetting sus = (SharedUserSetting) obj; final int N = sus.packages.size(); final String[] res = new String[N]; final Iterator<PackageSetting> it = sus.packages.iterator(); int i = 0; while (it.hasNext()) { res[i++] = it.next().name; } return res; } else if (obj instanceof PackageSetting) { final PackageSetting ps = (PackageSetting) obj; return new String[] { ps.name }; } } return null; } @Override public String getNameForUid(int uid) { // reader synchronized (mPackages) { Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); if (obj instanceof SharedUserSetting) { final SharedUserSetting sus = (SharedUserSetting) obj; return sus.name + ":" + sus.userId; } else if (obj instanceof PackageSetting) { final PackageSetting ps = (PackageSetting) obj; return ps.name; } } return null; } @Override public int getUidForSharedUser(String sharedUserName) { if(sharedUserName == null) { return -1; } // reader synchronized (mPackages) { final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); if (suid == null) { return -1; } return suid.userId; } } @Override public int getFlagsForUid(int uid) { synchronized (mPackages) { Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); if (obj instanceof SharedUserSetting) { final SharedUserSetting sus = (SharedUserSetting) obj; return sus.pkgFlags; } else if (obj instanceof PackageSetting) { final PackageSetting ps = (PackageSetting) obj; return ps.pkgFlags; } } return 0; } //@Override public boolean isUidPrivileged(int uid) { uid = UserHandle.getAppId(uid); // reader synchronized (mPackages) { Object obj = mSettings.getUserIdLPr(uid); if (obj instanceof SharedUserSetting) { final SharedUserSetting sus = (SharedUserSetting) obj; final Iterator<PackageSetting> it = sus.packages.iterator(); while (it.hasNext()) { if (it.next().isPrivileged()) { return true; } } } else if (obj instanceof PackageSetting) { final PackageSetting ps = (PackageSetting) obj; return ps.isPrivileged(); } } return false; } @Override public String[] getAppOpPermissionPackages(String permissionName) { synchronized (mPackages) { ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); if (pkgs == null) { return null; } return pkgs.toArray(new String[pkgs.size()]); } } @Override public ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); return chooseBestActivity(intent, resolvedType, flags, query, userId); } @Override public void setLastChosenActivity(Intent intent, String resolvedType, int flags, IntentFilter filter, int match, ComponentName activity) { final int userId = UserHandle.getCallingUserId(); if (DEBUG_PREFERRED) { Log.v(TAG, "setLastChosenActivity intent=" + intent + " resolvedType=" + resolvedType + " flags=" + flags + " filter=" + filter + " match=" + match + " activity=" + activity); filter.dump(new PrintStreamPrinter(System.out), " "); } intent.setComponent(null); List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); // Find any earlier preferred or last chosen entries and nuke them findPreferredActivity(intent, resolvedType, flags, query, 0, false, true, false, userId); // Add the new activity as the last chosen for this filter addPreferredActivityInternal(filter, match, null, activity, false, userId, "Setting last chosen"); } @Override public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { final int userId = UserHandle.getCallingUserId(); if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); return findPreferredActivity(intent, resolvedType, flags, query, 0, false, false, false, userId); } private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, int flags, List<ResolveInfo> query, int userId) { if (query != null) { final int N = query.size(); if (N == 1) { return query.get(0); } else if (N > 1) { final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); // If there is more than one activity with the same priority, // then let the user decide between them. ResolveInfo r0 = query.get(0); ResolveInfo r1 = query.get(1); if (DEBUG_INTENT_MATCHING || debug) { Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " + r1.activityInfo.name + "=" + r1.priority); } // If the first activity has a higher priority, or a different // default, then it is always desireable to pick it. if (r0.priority != r1.priority || r0.preferredOrder != r1.preferredOrder || r0.isDefault != r1.isDefault) { return query.get(0); } // If we have saved a preference for a preferred activity for // this Intent, use that. ResolveInfo ri = findPreferredActivity(intent, resolvedType, flags, query, r0.priority, true, false, debug, userId); if (ri != null) { return ri; } if (userId != 0) { ri = new ResolveInfo(mResolveInfo); ri.activityInfo = new ActivityInfo(ri.activityInfo); ri.activityInfo.applicationInfo = new ApplicationInfo( ri.activityInfo.applicationInfo); ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); return ri; } return mResolveInfo; } } return null; } private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, int flags, List<ResolveInfo> query, boolean debug, int userId) { final int N = query.size(); PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities .get(userId); // Get the list of persistent preferred activities that handle the intent if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); List<PersistentPreferredActivity> pprefs = ppir != null ? ppir.queryIntent(intent, resolvedType, (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) : null; if (pprefs != null && pprefs.size() > 0) { final int M = pprefs.size(); for (int i=0; i<M; i++) { final PersistentPreferredActivity ppa = pprefs.get(i); if (DEBUG_PREFERRED || debug) { Slog.v(TAG, "Checking PersistentPreferredActivity ds=" + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") + "\n component=" + ppa.mComponent); ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); } final ActivityInfo ai = getActivityInfo(ppa.mComponent, flags | PackageManager.GET_DISABLED_COMPONENTS, userId); if (DEBUG_PREFERRED || debug) { Slog.v(TAG, "Found persistent preferred activity:"); if (ai != null) { ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); } else { Slog.v(TAG, " null"); } } if (ai == null) { // This previously registered persistent preferred activity // component is no longer known. Ignore it and do NOT remove it. continue; } for (int j=0; j<N; j++) { final ResolveInfo ri = query.get(j); if (!ri.activityInfo.applicationInfo.packageName .equals(ai.applicationInfo.packageName)) { continue; } if (!ri.activityInfo.name.equals(ai.name)) { continue; } // Found a persistent preference that can handle the intent. if (DEBUG_PREFERRED || debug) { Slog.v(TAG, "Returning persistent preferred activity: " + ri.activityInfo.packageName + "/" + ri.activityInfo.name); } return ri; } } } return null; } ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, List<ResolveInfo> query, int priority, boolean always, boolean removeMatches, boolean debug, int userId) { if (!sUserManager.exists(userId)) return null; // writer synchronized (mPackages) { if (intent.getSelector() != null) { intent = intent.getSelector(); } if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); // Try to find a matching persistent preferred activity. ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, debug, userId); // If a persistent preferred activity matched, use it. if (pri != null) { return pri; } PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); // Get the list of preferred activities that handle the intent if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); List<PreferredActivity> prefs = pir != null ? pir.queryIntent(intent, resolvedType, (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) : null; if (prefs != null && prefs.size() > 0) { boolean changed = false; try { // First figure out how good the original match set is. // We will only allow preferred activities that came // from the same match quality. int match = 0; if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); final int N = query.size(); for (int j=0; j<N; j++) { final ResolveInfo ri = query.get(j); if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo + ": 0x" + Integer.toHexString(match)); if (ri.match > match) { match = ri.match; } } if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" + Integer.toHexString(match)); match &= IntentFilter.MATCH_CATEGORY_MASK; final int M = prefs.size(); for (int i=0; i<M; i++) { final PreferredActivity pa = prefs.get(i); if (DEBUG_PREFERRED || debug) { Slog.v(TAG, "Checking PreferredActivity ds=" + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") + "\n component=" + pa.mPref.mComponent); pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); } if (pa.mPref.mMatch != match) { if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " + Integer.toHexString(pa.mPref.mMatch)); continue; } // If it's not an "always" type preferred activity and that's what we're // looking for, skip it. if (always && !pa.mPref.mAlways) { if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); continue; } final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags | PackageManager.GET_DISABLED_COMPONENTS, userId); if (DEBUG_PREFERRED || debug) { Slog.v(TAG, "Found preferred activity:"); if (ai != null) { ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); } else { Slog.v(TAG, " null"); } } if (ai == null) { // This previously registered preferred activity // component is no longer known. Most likely an update // to the app was installed and in the new version this // component no longer exists. Clean it up by removing // it from the preferred activities list, and skip it. Slog.w(TAG, "Removing dangling preferred activity: " + pa.mPref.mComponent); pir.removeFilter(pa); changed = true; continue; } for (int j=0; j<N; j++) { final ResolveInfo ri = query.get(j); if (!ri.activityInfo.applicationInfo.packageName .equals(ai.applicationInfo.packageName)) { continue; } if (!ri.activityInfo.name.equals(ai.name)) { continue; } if (removeMatches) { pir.removeFilter(pa); changed = true; if (DEBUG_PREFERRED) { Slog.v(TAG, "Removing match " + pa.mPref.mComponent); } break; } // Okay we found a previously set preferred or last chosen app. // If the result set is different from when this // was created, we need to clear it and re-ask the // user their preference, if we're looking for an "always" type entry. if (always && !pa.mPref.sameSet(query, priority)) { Slog.i(TAG, "Result set changed, dropping preferred activity for " + intent + " type " + resolvedType); if (DEBUG_PREFERRED) { Slog.v(TAG, "Removing preferred activity since set changed " + pa.mPref.mComponent); } pir.removeFilter(pa); // Re-add the filter as a "last chosen" entry (!always) PreferredActivity lastChosen = new PreferredActivity( pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); pir.addFilter(lastChosen); changed = true; return null; } // Yay! Either the set matched or we're looking for the last chosen if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " + ri.activityInfo.packageName + "/" + ri.activityInfo.name); return ri; } } } finally { if (changed) { if (DEBUG_PREFERRED) { Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); } mSettings.writePackageRestrictionsLPr(userId); } } } } if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); return null; } /* * Returns if intent can be forwarded from the sourceUserId to the targetUserId */ @Override public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, int targetUserId) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); List<CrossProfileIntentFilter> matches = getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); if (matches != null) { int size = matches.size(); for (int i = 0; i < size; i++) { if (matches.get(i).getTargetUserId() == targetUserId) return true; } } return false; } private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, String resolvedType, int userId) { CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); if (resolver != null) { return resolver.queryIntent(intent, resolvedType, false, userId); } return null; } @Override public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return Collections.emptyList(); enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); ComponentName comp = intent.getComponent(); if (comp == null) { if (intent.getSelector() != null) { intent = intent.getSelector(); comp = intent.getComponent(); } } if (comp != null) { final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); final ActivityInfo ai = getActivityInfo(comp, flags, userId); if (ai != null) { final ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; list.add(ri); } return list; } // reader synchronized (mPackages) { final String pkgName = intent.getPackage(); if (pkgName == null) { List<CrossProfileIntentFilter> matchingFilters = getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); // Check for results that need to skip the current profile. ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, resolvedType, flags, userId); if (resolveInfo != null) { List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); result.add(resolveInfo); return result; } // Check for cross profile results. resolveInfo = queryCrossProfileIntents( matchingFilters, intent, resolvedType, flags, userId); // Check for results in the current profile. List<ResolveInfo> result = mActivities.queryIntent( intent, resolvedType, flags, userId); if (resolveInfo != null) { result.add(resolveInfo); Collections.sort(result, mResolvePrioritySorter); } return result; } final PackageParser.Package pkg = mPackages.get(pkgName); if (pkg != null) { return mActivities.queryIntentForPackage(intent, resolvedType, flags, pkg.activities, userId); } return new ArrayList<ResolveInfo>(); } } private ResolveInfo querySkipCurrentProfileIntents( List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, int flags, int sourceUserId) { if (matchingFilters != null) { int size = matchingFilters.size(); for (int i = 0; i < size; i ++) { CrossProfileIntentFilter filter = matchingFilters.get(i); if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { // Checking if there are activities in the target user that can handle the // intent. ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, flags, sourceUserId); if (resolveInfo != null) { return resolveInfo; } } } } return null; } // Return matching ResolveInfo if any for skip current profile intent filters. private ResolveInfo queryCrossProfileIntents( List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, int flags, int sourceUserId) { if (matchingFilters != null) { // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and // match the same intent. For performance reasons, it is better not to // run queryIntent twice for the same userId SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); int size = matchingFilters.size(); for (int i = 0; i < size; i++) { CrossProfileIntentFilter filter = matchingFilters.get(i); int targetUserId = filter.getTargetUserId(); if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 && !alreadyTriedUserIds.get(targetUserId)) { // Checking if there are activities in the target user that can handle the // intent. ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, flags, sourceUserId); if (resolveInfo != null) return resolveInfo; alreadyTriedUserIds.put(targetUserId, true); } } } return null; } private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, String resolvedType, int flags, int sourceUserId) { List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, resolvedType, flags, filter.getTargetUserId()); if (resultTargetUser != null && !resultTargetUser.isEmpty()) { return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); } return null; } private ResolveInfo createForwardingResolveInfo(IntentFilter filter, int sourceUserId, int targetUserId) { ResolveInfo forwardingResolveInfo = new ResolveInfo(); String className; if (targetUserId == UserHandle.USER_OWNER) { className = FORWARD_INTENT_TO_USER_OWNER; } else { className = FORWARD_INTENT_TO_MANAGED_PROFILE; } ComponentName forwardingActivityComponentName = new ComponentName( mAndroidApplication.packageName, className); ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, sourceUserId); if (targetUserId == UserHandle.USER_OWNER) { forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; forwardingResolveInfo.noResourceId = true; } forwardingResolveInfo.activityInfo = forwardingActivityInfo; forwardingResolveInfo.priority = 0; forwardingResolveInfo.preferredOrder = 0; forwardingResolveInfo.match = 0; forwardingResolveInfo.isDefault = true; forwardingResolveInfo.filter = filter; forwardingResolveInfo.targetUserId = targetUserId; return forwardingResolveInfo; } @Override public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics, String[] specificTypes, Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return Collections.emptyList(); enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activity options"); final String resultsAction = intent.getAction(); List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags | PackageManager.GET_RESOLVED_FILTER, userId); if (DEBUG_INTENT_MATCHING) { Log.v(TAG, "Query " + intent + ": " + results); } int specificsPos = 0; int N; // todo: note that the algorithm used here is O(N^2). This // isn't a problem in our current environment, but if we start running // into situations where we have more than 5 or 10 matches then this // should probably be changed to something smarter... // First we go through and resolve each of the specific items // that were supplied, taking care of removing any corresponding // duplicate items in the generic resolve list. if (specifics != null) { for (int i=0; i<specifics.length; i++) { final Intent sintent = specifics[i]; if (sintent == null) { continue; } if (DEBUG_INTENT_MATCHING) { Log.v(TAG, "Specific #" + i + ": " + sintent); } String action = sintent.getAction(); if (resultsAction != null && resultsAction.equals(action)) { // If this action was explicitly requested, then don't // remove things that have it. action = null; } ResolveInfo ri = null; ActivityInfo ai = null; ComponentName comp = sintent.getComponent(); if (comp == null) { ri = resolveIntent( sintent, specificTypes != null ? specificTypes[i] : null, flags, userId); if (ri == null) { continue; } if (ri == mResolveInfo) { // ACK! Must do something better with this. } ai = ri.activityInfo; comp = new ComponentName(ai.applicationInfo.packageName, ai.name); } else { ai = getActivityInfo(comp, flags, userId); if (ai == null) { continue; } } // Look for any generic query activities that are duplicates // of this specific one, and remove them from the results. if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); N = results.size(); int j; for (j=specificsPos; j<N; j++) { ResolveInfo sri = results.get(j); if ((sri.activityInfo.name.equals(comp.getClassName()) && sri.activityInfo.applicationInfo.packageName.equals( comp.getPackageName())) || (action != null && sri.filter.matchAction(action))) { results.remove(j); if (DEBUG_INTENT_MATCHING) Log.v( TAG, "Removing duplicate item from " + j + " due to specific " + specificsPos); if (ri == null) { ri = sri; } j--; N--; } } // Add this specific item to its proper place. if (ri == null) { ri = new ResolveInfo(); ri.activityInfo = ai; } results.add(specificsPos, ri); ri.specificIndex = i; specificsPos++; } } // Now we go through the remaining generic results and remove any // duplicate actions that are found here. N = results.size(); for (int i=specificsPos; i<N-1; i++) { final ResolveInfo rii = results.get(i); if (rii.filter == null) { continue; } // Iterate over all of the actions of this result's intent // filter... typically this should be just one. final Iterator<String> it = rii.filter.actionsIterator(); if (it == null) { continue; } while (it.hasNext()) { final String action = it.next(); if (resultsAction != null && resultsAction.equals(action)) { // If this action was explicitly requested, then don't // remove things that have it. continue; } for (int j=i+1; j<N; j++) { final ResolveInfo rij = results.get(j); if (rij.filter != null && rij.filter.hasAction(action)) { results.remove(j); if (DEBUG_INTENT_MATCHING) Log.v( TAG, "Removing duplicate item from " + j + " due to action " + action + " at " + i); j--; N--; } } } // If the caller didn't request filter information, drop it now // so we don't have to marshall/unmarshall it. if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { rii.filter = null; } } // Filter out the caller activity if so requested. if (caller != null) { N = results.size(); for (int i=0; i<N; i++) { ActivityInfo ainfo = results.get(i).activityInfo; if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) && caller.getClassName().equals(ainfo.name)) { results.remove(i); break; } } } // If the caller didn't request filter information, // drop them now so we don't have to // marshall/unmarshall it. if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { N = results.size(); for (int i=0; i<N; i++) { results.get(i).filter = null; } } if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); return results; } @Override public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return Collections.emptyList(); ComponentName comp = intent.getComponent(); if (comp == null) { if (intent.getSelector() != null) { intent = intent.getSelector(); comp = intent.getComponent(); } } if (comp != null) { List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); ActivityInfo ai = getReceiverInfo(comp, flags, userId); if (ai != null) { ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; list.add(ri); } return list; } // reader synchronized (mPackages) { String pkgName = intent.getPackage(); if (pkgName == null) { return mReceivers.queryIntent(intent, resolvedType, flags, userId); } final PackageParser.Package pkg = mPackages.get(pkgName); if (pkg != null) { return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, userId); } return null; } } @Override public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); if (!sUserManager.exists(userId)) return null; if (query != null) { if (query.size() >= 1) { // If there is more than one service with the same priority, // just arbitrarily pick the first one. return query.get(0); } } return null; } @Override public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return Collections.emptyList(); ComponentName comp = intent.getComponent(); if (comp == null) { if (intent.getSelector() != null) { intent = intent.getSelector(); comp = intent.getComponent(); } } if (comp != null) { final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); final ServiceInfo si = getServiceInfo(comp, flags, userId); if (si != null) { final ResolveInfo ri = new ResolveInfo(); ri.serviceInfo = si; list.add(ri); } return list; } // reader synchronized (mPackages) { String pkgName = intent.getPackage(); if (pkgName == null) { return mServices.queryIntent(intent, resolvedType, flags, userId); } final PackageParser.Package pkg = mPackages.get(pkgName); if (pkg != null) { return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, userId); } return null; } } @Override public List<ResolveInfo> queryIntentContentProviders( Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return Collections.emptyList(); ComponentName comp = intent.getComponent(); if (comp == null) { if (intent.getSelector() != null) { intent = intent.getSelector(); comp = intent.getComponent(); } } if (comp != null) { final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); final ProviderInfo pi = getProviderInfo(comp, flags, userId); if (pi != null) { final ResolveInfo ri = new ResolveInfo(); ri.providerInfo = pi; list.add(ri); } return list; } // reader synchronized (mPackages) { String pkgName = intent.getPackage(); if (pkgName == null) { return mProviders.queryIntent(intent, resolvedType, flags, userId); } final PackageParser.Package pkg = mPackages.get(pkgName); if (pkg != null) { return mProviders.queryIntentForPackage( intent, resolvedType, flags, pkg.providers, userId); } return null; } } @Override public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); // writer synchronized (mPackages) { ArrayList<PackageInfo> list; if (listUninstalled) { list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); for (PackageSetting ps : mSettings.mPackages.values()) { PackageInfo pi; if (ps.pkg != null) { pi = generatePackageInfo(ps.pkg, flags, userId); } else { pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); } if (pi != null) { list.add(pi); } } } else { list = new ArrayList<PackageInfo>(mPackages.size()); for (PackageParser.Package p : mPackages.values()) { PackageInfo pi = generatePackageInfo(p, flags, userId); if (pi != null) { list.add(pi); } } } return new ParceledListSlice<PackageInfo>(list); } } private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, String[] permissions, boolean[] tmp, int flags, int userId) { int numMatch = 0; final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; for (int i=0; i<permissions.length; i++) { if (gp.grantedPermissions.contains(permissions[i])) { tmp[i] = true; numMatch++; } else { tmp[i] = false; } } if (numMatch == 0) { return; } PackageInfo pi; if (ps.pkg != null) { pi = generatePackageInfo(ps.pkg, flags, userId); } else { pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); } // The above might return null in cases of uninstalled apps or install-state // skew across users/profiles. if (pi != null) { if ((flags&PackageManager.GET_PERMISSIONS) == 0) { if (numMatch == permissions.length) { pi.requestedPermissions = permissions; } else { pi.requestedPermissions = new String[numMatch]; numMatch = 0; for (int i=0; i<permissions.length; i++) { if (tmp[i]) { pi.requestedPermissions[numMatch] = permissions[i]; numMatch++; } } } } list.add(pi); } } @Override public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( String[] permissions, int flags, int userId) { if (!sUserManager.exists(userId)) return null; final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; // writer synchronized (mPackages) { ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); boolean[] tmpBools = new boolean[permissions.length]; if (listUninstalled) { for (PackageSetting ps : mSettings.mPackages.values()) { addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); } } else { for (PackageParser.Package pkg : mPackages.values()) { PackageSetting ps = (PackageSetting)pkg.mExtras; if (ps != null) { addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); } } } return new ParceledListSlice<PackageInfo>(list); } } @Override public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { if (!sUserManager.exists(userId)) return null; final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; // writer synchronized (mPackages) { ArrayList<ApplicationInfo> list; if (listUninstalled) { list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); for (PackageSetting ps : mSettings.mPackages.values()) { ApplicationInfo ai; if (ps.pkg != null) { ai = PackageParser.generateApplicationInfo(ps.pkg, flags, ps.readUserState(userId), userId); } else { ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); } if (ai != null) { /** M: [ALPS00552304][JB][CU][Case Fail][Settings]Wo.3g App cannot be uninstall successful(5/5). @{ */ if (isVendorApp(ai) && !ps.getInstalled(userId)) { continue; } /** @} 2013-05-06 */ list.add(ai); } } } else { list = new ArrayList<ApplicationInfo>(mPackages.size()); for (PackageParser.Package p : mPackages.values()) { if (p.mExtras != null) { ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, ((PackageSetting)p.mExtras).readUserState(userId), userId); if (ai != null) { list.add(ai); } } } } return new ParceledListSlice<ApplicationInfo>(list); } } public List<ApplicationInfo> getPersistentApplications(int flags) { final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); // reader synchronized (mPackages) { final Iterator<PackageParser.Package> i = mPackages.values().iterator(); final int userId = UserHandle.getCallingUserId(); while (i.hasNext()) { final PackageParser.Package p = i.next(); if (p.applicationInfo != null && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 && (!mSafeMode || isSystemApp(p))) { PackageSetting ps = mSettings.mPackages.get(p.packageName); if (ps != null) { ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, ps.readUserState(userId), userId); if (ai != null) { finalList.add(ai); } } } } } return finalList; } @Override public ProviderInfo resolveContentProvider(String name, int flags, int userId) { if (!sUserManager.exists(userId)) return null; // reader synchronized (mPackages) { final PackageParser.Provider provider = mProvidersByAuthority.get(name); PackageSetting ps = provider != null ? mSettings.mPackages.get(provider.owner.packageName) : null; return ps != null && mSettings.isEnabledLPr(provider.info, flags, userId) && (!mSafeMode || (provider.info.applicationInfo.flags &ApplicationInfo.FLAG_SYSTEM) != 0) ? PackageParser.generateProviderInfo(provider, flags, ps.readUserState(userId), userId) : null; } } /** * @deprecated */ @Deprecated public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { // reader synchronized (mPackages) { final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority .entrySet().iterator(); final int userId = UserHandle.getCallingUserId(); while (i.hasNext()) { Map.Entry<String, PackageParser.Provider> entry = i.next(); PackageParser.Provider p = entry.getValue(); PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); if (ps != null && p.syncable && (!mSafeMode || (p.info.applicationInfo.flags &ApplicationInfo.FLAG_SYSTEM) != 0)) { ProviderInfo info = PackageParser.generateProviderInfo(p, 0, ps.readUserState(userId), userId); if (info != null) { outNames.add(entry.getKey()); outInfo.add(info); } } } } } @Override public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) { ArrayList<ProviderInfo> finalList = null; // reader synchronized (mPackages) { final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); final int userId = processName != null ? UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); while (i.hasNext()) { final PackageParser.Provider p = i.next(); PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); if (ps != null && p.info.authority != null && (processName == null || (p.info.processName.equals(processName) && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) && mSettings.isEnabledLPr(p.info, flags, userId) && (!mSafeMode || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { if (finalList == null) { finalList = new ArrayList<ProviderInfo>(3); } ProviderInfo info = PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), userId); if (info != null) { finalList.add(info); } } } } if (finalList != null) { Collections.sort(finalList, mProviderInitOrderSorter); } return finalList; } @Override public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { // reader synchronized (mPackages) { final PackageParser.Instrumentation i = mInstrumentation.get(name); return PackageParser.generateInstrumentationInfo(i, flags); } } @Override public List<InstrumentationInfo> queryInstrumentation(String targetPackage, int flags) { ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); // reader synchronized (mPackages) { final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); while (i.hasNext()) { final PackageParser.Instrumentation p = i.next(); if (targetPackage == null || targetPackage.equals(p.info.targetPackage)) { InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, flags); if (ii != null) { finalList.add(ii); } } } } return finalList; } private void createIdmapsForPackageLI(PackageParser.Package pkg) { HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); if (overlays == null) { Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); return; } for (PackageParser.Package opkg : overlays.values()) { // Not much to do if idmap fails: we already logged the error // and we certainly don't want to abort installation of pkg simply // because an overlay didn't fit properly. For these reasons, // ignore the return value of createIdmapForPackagePairLI. createIdmapForPackagePairLI(pkg, opkg); } } private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, PackageParser.Package opkg) { if (!opkg.mTrustedOverlay) { Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + opkg.baseCodePath + ": overlay not trusted"); return false; } HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); if (overlaySet == null) { Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + opkg.baseCodePath + " but target package has no known overlays"); return false; } final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); // TODO: generate idmap for split APKs if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " + opkg.baseCodePath); return false; } PackageParser.Package[] overlayArray = overlaySet.values().toArray(new PackageParser.Package[0]); Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { public int compare(PackageParser.Package p1, PackageParser.Package p2) { return p1.mOverlayPriority - p2.mOverlayPriority; } }; Arrays.sort(overlayArray, cmp); pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; int i = 0; for (PackageParser.Package p : overlayArray) { pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; } return true; } private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { final File[] files = dir.listFiles(); if (ArrayUtils.isEmpty(files)) { Log.d(TAG, "No files in app dir " + dir); return; } if (DEBUG_PACKAGE_SCANNING) { Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags + " flags=0x" + Integer.toHexString(parseFlags)); } /** M: Add PMS scan package time log @{ */ long startScanTime, endScanTime; /** @} */ for (File file : files) { final boolean isPackage = (isApkFile(file) || file.isDirectory()) && !PackageInstallerService.isStageName(file.getName()); if (!isPackage) { // Ignore entries which are not packages continue; } /** M: Add PMS scan package time log @{ */ startScanTime = SystemClock.uptimeMillis(); Slog.d(TAG, "scan package: " + file.toString() + " , start at: " + startScanTime + "ms."); /** @} */ try { scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, scanFlags, currentTime, null); } catch (PackageManagerException e) { Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); // Delete invalid userdata apps if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); if (file.isDirectory()) { FileUtils.deleteContents(file); } file.delete(); } } /** M: Add PMS scan package time log @{ */ endScanTime = SystemClock.uptimeMillis(); Slog.d(TAG, "scan package: " + file.toString() + " , end at: " + endScanTime + "ms. elapsed time = " + (endScanTime - startScanTime) + "ms."); /** @} */ } /// M: Mtprof tool addBootEvent(new String("Android:PMS_scan_data_done:" + dir.getPath().toString())); } private static File getSettingsProblemFile() { File dataDir = Environment.getDataDirectory(); File systemDir = new File(dataDir, "system"); File fname = new File(systemDir, "uiderrors.txt"); return fname; } static void reportSettingsProblem(int priority, String msg) { logCriticalInfo(priority, msg); } static void logCriticalInfo(int priority, String msg) { Slog.println(priority, TAG, msg); EventLogTags.writePmCriticalInfo(msg); try { File fname = getSettingsProblemFile(); FileOutputStream out = new FileOutputStream(fname, true); PrintWriter pw = new FastPrintWriter(out); SimpleDateFormat formatter = new SimpleDateFormat(); String dateString = formatter.format(new Date(System.currentTimeMillis())); pw.println(dateString + ": " + msg); pw.close(); FileUtils.setPermissions( fname.toString(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, -1, -1); } catch (java.io.IOException e) { } } private void collectCertificatesLI(PackageParser pp, PackageSetting ps, PackageParser.Package pkg, File srcFile, int parseFlags) throws PackageManagerException { if (ps != null && ps.codePath.equals(srcFile) && ps.timeStamp == srcFile.lastModified() && !isCompatSignatureUpdateNeeded(pkg)) { long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); if (ps.signatures.mSignatures != null && ps.signatures.mSignatures.length != 0 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { // Optimization: reuse the existing cached certificates // if the package appears to be unchanged. pkg.mSignatures = ps.signatures.mSignatures; KeySetManagerService ksms = mSettings.mKeySetManagerService; synchronized (mPackages) { pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); } return; } Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); } else { Log.i(TAG, srcFile.toString() + " changed; collecting certs"); } try { pp.collectCertificates(pkg, parseFlags); pp.collectManifestDigest(pkg); } catch (PackageParserException e) { throw PackageManagerException.from(e); } } /* * Scan a package and return the newly parsed package. * Returns null in case of errors and the error code is stored in mLastScanError */ private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); parseFlags |= mDefParseFlags; PackageParser pp = new PackageParser(); pp.setSeparateProcesses(mSeparateProcesses); pp.setOnlyCoreApps(mOnlyCore); pp.setDisplayMetrics(mMetrics); if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; } final PackageParser.Package pkg; try { pkg = pp.parsePackage(scanFile, parseFlags); } catch (PackageParserException e) { throw PackageManagerException.from(e); } PackageSetting ps = null; PackageSetting updatedPkg; // reader synchronized (mPackages) { // Look to see if we already know about this package. String oldName = mSettings.mRenamedPackages.get(pkg.packageName); if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { // This package has been renamed to its original name. Let's // use that. ps = mSettings.peekPackageLPr(oldName); } // If there was no original package, see one for the real package name. if (ps == null) { ps = mSettings.peekPackageLPr(pkg.packageName); } // Check to see if this package could be hiding/updating a system // package. Must look for it either under the original or real // package name depending on our state. updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); } boolean updatedPkgBetter = false; // First check if this is a system package that may involve an update /** M: [Operator] Package in vendor folder should also be checked @{ */ if (updatedPkg != null && (((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) || ((parseFlags & PackageParser.PARSE_IS_OPERATOR) != 0))) { /** @} */ if (ps != null && !ps.codePath.equals(scanFile)) { // The path has changed from what was last scanned... check the // version of the new path against what we have stored to determine // what to do. if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); /** M: [Operator] Allow vendor package downgrade. @{ */ /// Always install the updated one on data partition if (pkg.mVersionCode < ps.versionCode || ((parseFlags & PackageParser.PARSE_IS_OPERATOR) != 0)) { /** @} */ // The system package has been updated and the code path does not match // Ignore entry. Skip it. logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile + " ignored: updated version " + ps.versionCode + " better than this " + pkg.mVersionCode); if (!updatedPkg.codePath.equals(scanFile)) { Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " + ps.name + " changing from " + updatedPkg.codePathString + " to " + scanFile); updatedPkg.codePath = scanFile; updatedPkg.codePathString = scanFile.toString(); // This is the point at which we know that the system-disk APK // for this package has moved during a reboot (e.g. due to an OTA), // so we need to reevaluate it for privilege policy. if (locationIsPrivileged(scanFile)) { updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; } } updatedPkg.pkg = pkg; throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); } else { // The current app on the system partition is better than // what we have updated to on the data partition; switch // back to the system partition version. // At this point, its safely assumed that package installation for // apps in system partition will go through. If not there won't be a working // version of the app // writer synchronized (mPackages) { // Just remove the loaded entries from package lists. mPackages.remove(ps.name); } logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile + " reverting from " + ps.codePathString + ": new version " + pkg.mVersionCode + " better than installed " + ps.versionCode); InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, getAppDexInstructionSets(ps)); synchronized (mInstallLock) { args.cleanUpResourcesLI(); } synchronized (mPackages) { mSettings.enableSystemPackageLPw(ps.name); } updatedPkgBetter = true; } } } if (updatedPkg != null) { // An updated system app will not have the PARSE_IS_SYSTEM flag set // initially /** M: [Operator] Only system app have system flag @{ */ if (isSystemApp(updatedPkg)) { parseFlags |= PackageParser.PARSE_IS_SYSTEM; } /// M: [Operator] Add operator flags for updated vendor package /// We should consider an operator app with flag changed after OTA if (isVendorApp(updatedPkg) || locationIsOperator(updatedPkg.codePath)) { parseFlags |= PackageParser.PARSE_IS_OPERATOR; } /** @} */ // An updated privileged app will not have the PARSE_IS_PRIVILEGED // flag set initially if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; } } // Verify certificates against what was last scanned collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); /* * A new system app appeared, but we already had a non-system one of the * same name installed earlier. */ boolean shouldHideSystemApp = false; if (updatedPkg == null && ps != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { /* * Check to make sure the signatures match first. If they don't, * wipe the installed application and its data. */ if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" + " signatures don't match existing userdata copy; removing"); deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); ps = null; } else { /* * If the newly-added system app is an older version than the * already installed version, hide it. It will be scanned later * and re-added like an update. */ if (pkg.mVersionCode < ps.versionCode) { shouldHideSystemApp = true; logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile + " but new version " + pkg.mVersionCode + " better than installed " + ps.versionCode + "; hiding system"); } else { /* * The newly found system app is a newer version that the * one previously installed. Simply remove the * already-installed application and replace it with our own * while keeping the application data. */ logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile + " reverting from " + ps.codePathString + ": new version " + pkg.mVersionCode + " better than installed " + ps.versionCode); InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, getAppDexInstructionSets(ps)); synchronized (mInstallLock) { args.cleanUpResourcesLI(); } } } } // The apk is forward locked (not public) if its code and resources // are kept in different files. (except for app in either system or // vendor path). // TODO grab this value from PackageSettings if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { if (ps != null && !ps.codePath.equals(ps.resourcePath)) { parseFlags |= PackageParser.PARSE_FORWARD_LOCK; } } // TODO: extend to support forward-locked splits String resourcePath = null; String baseResourcePath = null; if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { if (ps != null && ps.resourcePathString != null) { resourcePath = ps.resourcePathString; baseResourcePath = ps.resourcePathString; } else { // Should not happen at all. Just log an error. Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); } } else { resourcePath = pkg.codePath; baseResourcePath = pkg.baseCodePath; } // Set application objects path explicitly. pkg.applicationInfo.setCodePath(pkg.codePath); pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); pkg.applicationInfo.setResourcePath(resourcePath); pkg.applicationInfo.setBaseResourcePath(baseResourcePath); pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); // Note that we invoke the following method only if we are about to unpack an application PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags | SCAN_UPDATE_SIGNATURE, currentTime, user); /* * If the system app should be overridden by a previously installed * data, hide the system app now and let the /data/app scan pick it up * again. */ if (shouldHideSystemApp) { synchronized (mPackages) { /* * We have to grant systems permissions before we hide, because * grantPermissions will assume the package update is trying to * expand its permissions. */ grantPermissionsLPw(pkg, true, pkg.packageName); mSettings.disableSystemPackageLPw(pkg.packageName); } } return scannedPkg; } private static String fixProcessName(String defProcessName, String processName, int uid) { if (processName == null) { return defProcessName; } return processName; } private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) throws PackageManagerException { if (pkgSetting.signatures.mSignatures != null) { // Already existing package. Make sure signatures match boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; if (!match) { match = compareSignaturesCompat(pkgSetting.signatures, pkg) == PackageManager.SIGNATURE_MATCH; /** M: Add dynamic enable PMS log @{ */ if (DEBUG_PERMISSION) Log.i(TAG, "pkgSetting.sig = " + pkgSetting.sharedUser.signatures.mSignatures[0].toCharsString()); if (DEBUG_PERMISSION) Log.i(TAG, "pkg.mSignatures = " + pkg.mSignatures[0].toCharsString()); /** @} */ } if (!match) { throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " + pkg.packageName + " signatures do not match the " + "previously installed version; ignoring!"); } } // Check for shared user signatures if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { // Already existing package. Make sure signatures match boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; if (!match) { match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) == PackageManager.SIGNATURE_MATCH; /** M: Add dynamic enable PMS log @{ */ if (DEBUG_PERMISSION) Log.i(TAG, "pkgSetting.sig = " + pkgSetting.sharedUser.signatures.mSignatures[0].toCharsString()); if (DEBUG_PERMISSION) Log.i(TAG, "pkg.mSignatures = " + pkg.mSignatures[0].toCharsString()); /** @} */ } if (!match) { throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, "Package " + pkg.packageName + " has no signatures that match those in shared user " + pkgSetting.sharedUser.name + "; ignoring!"); } } } /** * Enforces that only the system UID or root's UID can call a method exposed * via Binder. * * @param message used as message if SecurityException is thrown * @throws SecurityException if the caller is not system or root */ private static final void enforceSystemOrRoot(String message) { final int uid = Binder.getCallingUid(); if (uid != Process.SYSTEM_UID && uid != 0) { throw new SecurityException(message); } } @Override public void performBootDexOpt() { enforceSystemOrRoot("Only the system can request dexopt be performed"); final HashSet<PackageParser.Package> pkgs; synchronized (mPackages) { pkgs = mDeferredDexOpt; mDeferredDexOpt = null; } if (pkgs != null) { // Sort apps by importance for dexopt ordering. Important apps are given more priority // in case the device runs out of space. ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); // Give priority to core apps. for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { PackageParser.Package pkg = it.next(); if (pkg.coreApp) { if (DEBUG_DEXOPT) { Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); } sortedPkgs.add(pkg); it.remove(); } } // Give priority to system apps that listen for pre boot complete. Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); HashSet<String> pkgNames = getPackageNamesForIntent(intent); for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { PackageParser.Package pkg = it.next(); if (pkgNames.contains(pkg.packageName)) { if (DEBUG_DEXOPT) { Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); } sortedPkgs.add(pkg); it.remove(); } } // Give priority to system apps. for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { PackageParser.Package pkg = it.next(); if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { if (DEBUG_DEXOPT) { Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); } sortedPkgs.add(pkg); it.remove(); } } // Give priority to updated system apps. for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { PackageParser.Package pkg = it.next(); if (isUpdatedSystemApp(pkg)) { if (DEBUG_DEXOPT) { Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); } sortedPkgs.add(pkg); it.remove(); } } // Give priority to apps that listen for boot complete. intent = new Intent(Intent.ACTION_BOOT_COMPLETED); pkgNames = getPackageNamesForIntent(intent); for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { PackageParser.Package pkg = it.next(); if (pkgNames.contains(pkg.packageName)) { if (DEBUG_DEXOPT) { Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); } sortedPkgs.add(pkg); it.remove(); } } // Filter out packages that aren't recently used. filterRecentlyUsedApps(pkgs); // Add all remaining apps. for (PackageParser.Package pkg : pkgs) { if (DEBUG_DEXOPT) { Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); } sortedPkgs.add(pkg); } int i = 0; int total = sortedPkgs.size(); File dataDir = Environment.getDataDirectory(); long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); if (lowThreshold == 0) { throw new IllegalStateException("Invalid low memory threshold"); } for (PackageParser.Package pkg : sortedPkgs) { long usableSpace = dataDir.getUsableSpace(); if (usableSpace < lowThreshold) { Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); break; } performBootDexOpt(pkg, ++i, total); } } } private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) { // Filter out packages that aren't recently used. // // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which // should do a full dexopt. if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { // TODO: add a property to control this? long dexOptLRUThresholdInMinutes; if (mLazyDexOpt) { dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. } else { dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. } long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; int total = pkgs.size(); int skipped = 0; long now = System.currentTimeMillis(); for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { PackageParser.Package pkg = i.next(); long then = pkg.mLastPackageUsageTimeInMills; if (then + dexOptLRUThresholdInMills < now) { if (DEBUG_DEXOPT) { Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + ((then == 0) ? "never" : new Date(then))); } i.remove(); skipped++; } } if (DEBUG_DEXOPT) { Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); } } } private HashSet<String> getPackageNamesForIntent(Intent intent) { List<ResolveInfo> ris = null; try { ris = AppGlobals.getPackageManager().queryIntentReceivers( intent, null, 0, UserHandle.USER_OWNER); } catch (RemoteException e) { } HashSet<String> pkgNames = new HashSet<String>(); if (ris != null) { for (ResolveInfo ri : ris) { pkgNames.add(ri.activityInfo.packageName); } } return pkgNames; } private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { if (DEBUG_DEXOPT) { Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); } if (!isFirstBoot()) { try { ActivityManagerNative.getDefault().showBootMessage( mContext.getResources().getString(R.string.android_upgrading_apk, curr, total), true); } catch (RemoteException e) { } } PackageParser.Package p = pkg; synchronized (mInstallLock) { performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, true /* include dependencies */); } } @Override public boolean performDexOptIfNeeded(String packageName, String instructionSet) { return performDexOpt(packageName, instructionSet, false); } private static String getPrimaryInstructionSet(ApplicationInfo info) { if (info.primaryCpuAbi == null) { return getPreferredInstructionSet(); } return VMRuntime.getInstructionSet(info.primaryCpuAbi); } public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { boolean dexopt = mLazyDexOpt || backgroundDexopt; boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt if (!dexopt && !updateUsage) { // We aren't going to dexopt or update usage, so bail early. return false; } PackageParser.Package p; final String targetInstructionSet; synchronized (mPackages) { p = mPackages.get(packageName); if (p == null) { return false; } if (updateUsage) { p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); } mPackageUsage.write(false); if (!dexopt) { // We aren't going to dexopt, so bail early. return false; } targetInstructionSet = instructionSet != null ? instructionSet : getPrimaryInstructionSet(p.applicationInfo); if (p.mDexOptPerformed.contains(targetInstructionSet)) { return false; } } synchronized (mInstallLock) { final String[] instructionSets = new String[] { targetInstructionSet }; return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, true /* include dependencies */) == DEX_OPT_PERFORMED; } } public HashSet<String> getPackagesThatNeedDexOpt() { HashSet<String> pkgs = null; synchronized (mPackages) { for (PackageParser.Package p : mPackages.values()) { if (DEBUG_DEXOPT) { Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); } if (!p.mDexOptPerformed.isEmpty()) { continue; } if (pkgs == null) { pkgs = new HashSet<String>(); } pkgs.add(p.packageName); } } return pkgs; } public void shutdown() { mPackageUsage.write(true); } private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, boolean forceDex, boolean defer, HashSet<String> done) { for (int i=0; i<libs.size(); i++) { PackageParser.Package libPkg; String libName; synchronized (mPackages) { libName = libs.get(i); SharedLibraryEntry lib = mSharedLibraries.get(libName); if (lib != null && lib.apk != null) { libPkg = mPackages.get(lib.apk); } else { libPkg = null; } } if (libPkg != null && !done.contains(libName)) { performDexOptLI(libPkg, instructionSets, forceDex, defer, done); } } } static final int DEX_OPT_SKIPPED = 0; static final int DEX_OPT_PERFORMED = 1; static final int DEX_OPT_DEFERRED = 2; static final int DEX_OPT_FAILED = -1; private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, boolean forceDex, boolean defer, HashSet<String> done) { final String[] instructionSets = targetInstructionSets != null ? targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); if (done != null) { done.add(pkg.packageName); if (pkg.usesLibraries != null) { performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); } if (pkg.usesOptionalLibraries != null) { performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); } } if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { return DEX_OPT_SKIPPED; } final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); boolean performedDexOpt = false; // There are three basic cases here: // 1.) we need to dexopt, either because we are forced or it is needed // 2.) we are defering a needed dexopt // 3.) we are skipping an unneeded dexopt final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); for (String dexCodeInstructionSet : dexCodeInstructionSets) { if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { continue; } for (String path : paths) { try { // This will return DEXOPT_NEEDED if we either cannot find any odex file for this // patckage or the one we find does not match the image checksum (i.e. it was // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a // odex file and it matches the checksum of the image but not its base address, // meaning we need to move it. final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, pkg.packageName, dexCodeInstructionSet, defer); if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { Slog.i(TAG, "Running dexopt on: " + path + " pkg=" + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet + " vmSafeMode=" + vmSafeMode); final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); final int ret = mInstaller.dexopt(new File(path).getCanonicalPath(), sharedGid, !isForwardLocked(pkg), pkg.packageName, dexCodeInstructionSet, vmSafeMode); /// M: Enchane the log for dexopt operation Slog.i(TAG, "Dexopt done on: " + pkg.applicationInfo.packageName); if (ret < 0) { // Don't bother running dexopt again if we failed, it will probably // just result in an error again. Also, don't bother dexopting for other // paths & ISAs. return DEX_OPT_FAILED; } performedDexOpt = true; } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), pkg.packageName, dexCodeInstructionSet); if (ret < 0) { // Don't bother running patchoat again if we failed, it will probably // just result in an error again. Also, don't bother dexopting for other // paths & ISAs. return DEX_OPT_FAILED; } performedDexOpt = true; } // We're deciding to defer a needed dexopt. Don't bother dexopting for other // paths and instruction sets. We'll deal with them all together when we process // our list of deferred dexopts. if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { if (mDeferredDexOpt == null) { mDeferredDexOpt = new HashSet<PackageParser.Package>(); } mDeferredDexOpt.add(pkg); return DEX_OPT_DEFERRED; } } catch (FileNotFoundException e) { Slog.w(TAG, "Apk not found for dexopt: " + path); return DEX_OPT_FAILED; } catch (IOException e) { Slog.w(TAG, "IOException reading apk: " + path, e); return DEX_OPT_FAILED; } catch (StaleDexCacheError e) { Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); return DEX_OPT_FAILED; } catch (Exception e) { Slog.w(TAG, "Exception when doing dexopt : ", e); return DEX_OPT_FAILED; } } // At this point we haven't failed dexopt and we haven't deferred dexopt. We must // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us // it isn't required. We therefore mark that this package doesn't need dexopt unless // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped // it. pkg.mDexOptPerformed.add(dexCodeInstructionSet); } // If we've gotten here, we're sure that no error occurred and that we haven't // deferred dex-opt. We've either dex-opted one more paths or instruction sets or // we've skipped all of them because they are up to date. In both cases this // package doesn't need dexopt any longer. return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; } private static String[] getAppDexInstructionSets(ApplicationInfo info) { if (info.primaryCpuAbi != null) { if (info.secondaryCpuAbi != null) { return new String[] { VMRuntime.getInstructionSet(info.primaryCpuAbi), VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; } else { return new String[] { VMRuntime.getInstructionSet(info.primaryCpuAbi) }; } } return new String[] { getPreferredInstructionSet() }; } private static String[] getAppDexInstructionSets(PackageSetting ps) { if (ps.primaryCpuAbiString != null) { if (ps.secondaryCpuAbiString != null) { return new String[] { VMRuntime.getInstructionSet(ps.primaryCpuAbiString), VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; } else { return new String[] { VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; } } return new String[] { getPreferredInstructionSet() }; } private static String getPreferredInstructionSet() { if (sPreferredInstructionSet == null) { sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); } return sPreferredInstructionSet; } private static List<String> getAllInstructionSets() { final String[] allAbis = Build.SUPPORTED_ABIS; final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); for (String abi : allAbis) { final String instructionSet = VMRuntime.getInstructionSet(abi); if (!allInstructionSets.contains(instructionSet)) { allInstructionSets.add(instructionSet); } } return allInstructionSets; } /** * Returns the instruction set that should be used to compile dex code. In the presence of * a native bridge this might be different than the one shared libraries use. */ private static String getDexCodeInstructionSet(String sharedLibraryIsa) { String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); } private static String[] getDexCodeInstructionSets(String[] instructionSets) { HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); for (String instructionSet : instructionSets) { dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); } return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); } /** * Returns deduplicated list of supported instructions for dex code. */ public static String[] getAllDexCodeInstructionSets() { String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; for (int i = 0; i < supportedInstructionSets.length; i++) { String abi = Build.SUPPORTED_ABIS[i]; supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); } return getDexCodeInstructionSets(supportedInstructionSets); } @Override public void forceDexOpt(String packageName) { enforceSystemOrRoot("forceDexOpt"); PackageParser.Package pkg; synchronized (mPackages) { pkg = mPackages.get(packageName); if (pkg == null) { throw new IllegalArgumentException("Missing package: " + packageName); } } synchronized (mInstallLock) { final String[] instructionSets = new String[] { getPrimaryInstructionSet(pkg.applicationInfo) }; final int res = performDexOptLI(pkg, instructionSets, true, false, true); if (res != DEX_OPT_PERFORMED) { throw new IllegalStateException("Failed to dexopt: " + res); } } } private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, boolean forceDex, boolean defer, boolean inclDependencies) { HashSet<String> done; if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { done = new HashSet<String>(); done.add(pkg.packageName); } else { done = null; } return performDexOptLI(pkg, instructionSets, forceDex, defer, done); } private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { Slog.w(TAG, "Unable to update from " + oldPkg.name + " to " + newPkg.packageName + ": old package not in system partition"); return false; } else if (mPackages.get(oldPkg.name) != null) { Slog.w(TAG, "Unable to update from " + oldPkg.name + " to " + newPkg.packageName + ": old package still exists"); return false; } return true; } File getDataPathForUser(int userId) { return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); } private File getDataPathForPackage(String packageName, int userId) { /* * Until we fully support multiple users, return the directory we * previously would have. The PackageManagerTests will need to be * revised when this is changed back.. */ if (userId == 0) { return new File(mAppDataDir, packageName); } else { return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId + File.separator + packageName); } } private int createDataDirsLI(String packageName, int uid, String seinfo) { int[] users = sUserManager.getUserIds(); int res = mInstaller.install(packageName, uid, uid, seinfo); if (res < 0) { return res; } for (int user : users) { if (user != 0) { res = mInstaller.createUserData(packageName, UserHandle.getUid(user, uid), user, seinfo); if (res < 0) { return res; } } } return res; } private int removeDataDirsLI(String packageName) { int[] users = sUserManager.getUserIds(); int res = 0; for (int user : users) { int resInner = mInstaller.remove(packageName, user); if (resInner < 0) { res = resInner; } } return res; } private int deleteCodeCacheDirsLI(String packageName) { int[] users = sUserManager.getUserIds(); int res = 0; for (int user : users) { int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); if (resInner < 0) { res = resInner; } } return res; } private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, PackageParser.Package changingLib) { if (file.path != null) { usesLibraryFiles.add(file.path); return; } PackageParser.Package p = mPackages.get(file.apk); if (changingLib != null && changingLib.packageName.equals(file.apk)) { // If we are doing this while in the middle of updating a library apk, // then we need to make sure to use that new apk for determining the // dependencies here. (We haven't yet finished committing the new apk // to the package manager state.) if (p == null || p.packageName.equals(changingLib.packageName)) { p = changingLib; } } if (p != null) { usesLibraryFiles.addAll(p.getAllCodePaths()); } } private void updateSharedLibrariesLPw(PackageParser.Package pkg, PackageParser.Package changingLib) throws PackageManagerException { if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { final ArraySet<String> usesLibraryFiles = new ArraySet<>(); int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; for (int i=0; i<N; i++) { final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); if (file == null) { throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, "Package " + pkg.packageName + " requires unavailable shared library " + pkg.usesLibraries.get(i) + "; failing!"); } addSharedLibraryLPw(usesLibraryFiles, file, changingLib); } N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; for (int i=0; i<N; i++) { final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); if (file == null) { Slog.w(TAG, "Package " + pkg.packageName + " desires unavailable shared library " + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); } else { addSharedLibraryLPw(usesLibraryFiles, file, changingLib); } } N = usesLibraryFiles.size(); if (N > 0) { pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); } else { pkg.usesLibraryFiles = null; } } } private static boolean hasString(List<String> list, List<String> which) { if (list == null) { return false; } for (int i=list.size()-1; i>=0; i--) { for (int j=which.size()-1; j>=0; j--) { if (which.get(j).equals(list.get(i))) { return true; } } } return false; } private void updateAllSharedLibrariesLPw() { for (PackageParser.Package pkg : mPackages.values()) { try { updateSharedLibrariesLPw(pkg, null); } catch (PackageManagerException e) { Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); } } } private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( PackageParser.Package changingPkg) { ArrayList<PackageParser.Package> res = null; for (PackageParser.Package pkg : mPackages.values()) { if (hasString(pkg.usesLibraries, changingPkg.libraryNames) || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { if (res == null) { res = new ArrayList<PackageParser.Package>(); } res.add(pkg); try { updateSharedLibrariesLPw(pkg, changingPkg); } catch (PackageManagerException e) { Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); } } } return res; } /** * Derive the value of the {@code cpuAbiOverride} based on the provided * value and an optional stored value from the package settings. */ private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { String cpuAbiOverride = null; if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { cpuAbiOverride = null; } else if (abiOverride != null) { cpuAbiOverride = abiOverride; } else if (settings != null) { cpuAbiOverride = settings.cpuAbiOverrideString; } return cpuAbiOverride; } private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { boolean success = false; try { final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, currentTime, user); success = true; return res; } finally { if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { removeDataDirsLI(pkg.packageName); } } } private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { final File scanFile = new File(pkg.codePath); if (pkg.applicationInfo.getCodePath() == null || pkg.applicationInfo.getResourcePath() == null) { // Bail out. The resource and code paths haven't been set. throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, "Code and resource paths haven't been set correctly"); } if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; } else { // Only allow system apps to be flagged as core apps. pkg.coreApp = false; } if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; } /** M: [Operator] Add operator flags @{ */ if ((parseFlags & PackageParser.PARSE_IS_OPERATOR) != 0) { pkg.applicationInfo.flagsEx |= ApplicationInfo.FLAG_EX_OPERATOR; } /** @} */ if (mCustomResolverComponentName != null && mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { setUpCustomResolverActivity(pkg); } if (pkg.packageName.equals("android")) { synchronized (mPackages) { if (mAndroidApplication != null) { Slog.w(TAG, "*************************************************"); Slog.w(TAG, "Core android package being redefined. Skipping."); Slog.w(TAG, " file=" + scanFile); Slog.w(TAG, "*************************************************"); throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, "Core android package being redefined. Skipping."); } // Set up information for our fall-back user intent resolution activity. mPlatformPackage = pkg; pkg.mVersionCode = mSdkVersion; mAndroidApplication = pkg.applicationInfo; if (!mResolverReplaced) { mResolveActivity.applicationInfo = mAndroidApplication; mResolveActivity.name = ResolverActivity.class.getName(); mResolveActivity.packageName = mAndroidApplication.packageName; mResolveActivity.processName = "system:ui"; mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; mResolveActivity.exported = true; mResolveActivity.enabled = true; mResolveInfo.activityInfo = mResolveActivity; mResolveInfo.priority = 0; mResolveInfo.preferredOrder = 0; mResolveInfo.match = 0; mResolveComponentName = new ComponentName( mAndroidApplication.packageName, mResolveActivity.name); } } } /** M: [CIP] skip duplicated mediatek-res.apk @{ */ /// This will replace original resources with CIP resources if (pkg.packageName.equals("com.mediatek")) { synchronized (mPackages) { if (mMediatekApplication != null) { Slog.w(TAG, "*************************************************"); Slog.w(TAG, "Core mediatek package being redefined. Skipping."); Slog.w(TAG, " file=" + scanFile); Slog.w(TAG, "*************************************************"); throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, "Core android package being redefined. Skipping."); } mMediatekApplication = pkg.applicationInfo; } } /** @} */ if (DEBUG_PACKAGE_SCANNING) { if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) Log.d(TAG, "Scanning package " + pkg.packageName); } if (mPackages.containsKey(pkg.packageName) || mSharedLibraries.containsKey(pkg.packageName)) { throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, "Application package " + pkg.packageName + " already installed. Skipping duplicate."); } // Initialize package source and resource directories File destCodeFile = new File(pkg.applicationInfo.getCodePath()); File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); SharedUserSetting suid = null; PackageSetting pkgSetting = null; if (!isSystemApp(pkg)) { // Only system apps can use these features. pkg.mOriginalPackages = null; pkg.mRealPackage = null; pkg.mAdoptPermissions = null; } // writer synchronized (mPackages) { if (pkg.mSharedUserId != null) { suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); if (suid == null) { throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Creating application package " + pkg.packageName + " for shared user failed"); } if (DEBUG_PACKAGE_SCANNING) { if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId + "): packages=" + suid.packages); } } // Check if we are renaming from an original package name. PackageSetting origPackage = null; String realName = null; if (pkg.mOriginalPackages != null) { // This package may need to be renamed to a previously // installed name. Let's check on that... final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); if (pkg.mOriginalPackages.contains(renamed)) { // This package had originally been installed as the // original name, and we have already taken care of // transitioning to the new one. Just update the new // one to continue using the old name. realName = pkg.mRealPackage; if (!pkg.packageName.equals(renamed)) { // Callers into this function may have already taken // care of renaming the package; only do it here if // it is not already done. pkg.setPackageName(renamed); } } else { for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { if ((origPackage = mSettings.peekPackageLPr( pkg.mOriginalPackages.get(i))) != null) { // We do have the package already installed under its // original name... should we use it? if (!verifyPackageUpdateLPr(origPackage, pkg)) { // New package is not compatible with original. origPackage = null; continue; } else if (origPackage.sharedUser != null) { // Make sure uid is compatible between packages. if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { Slog.w(TAG, "Unable to migrate data from " + origPackage.name + " to " + pkg.packageName + ": old uid " + origPackage.sharedUser.name + " differs from " + pkg.mSharedUserId); origPackage = null; continue; } } else { if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " + pkg.packageName + " to old name " + origPackage.name); } break; } } } } if (mTransferedPackages.contains(pkg.packageName)) { Slog.w(TAG, "Package " + pkg.packageName + " was transferred to another, but its .apk remains"); } // Just create the setting, don't add it yet. For already existing packages // the PkgSetting exists already and doesn't have to be created. pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, pkg.applicationInfo.flagsEx, user, false); if (pkgSetting == null) { throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Creating application package " + pkg.packageName + " failed"); } if (pkgSetting.origPackage != null) { // If we are first transitioning from an original package, // fix up the new package's name now. We need to do this after // looking up the package under its new name, so getPackageLP // can take care of fiddling things correctly. pkg.setPackageName(origPackage.name); // File a report about this. String msg = "New package " + pkgSetting.realName + " renamed to replace old package " + pkgSetting.name; reportSettingsProblem(Log.WARN, msg); // Make a note of it. mTransferedPackages.add(origPackage.name); // No longer need to retain this. pkgSetting.origPackage = null; } if (realName != null) { // Make a note of it. mTransferedPackages.add(pkg.packageName); } if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { /** M: [Operator] Operator package should not have FLAG_UPDATED_SYSTEM_APP @{ */ if ((parseFlags & PackageParser.PARSE_IS_OPERATOR) == 0) { pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; } /** @} */ } if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { // Check all shared libraries and map to their actual file path. // We only do this here for apps not on a system dir, because those // are the only ones that can fail an install due to this. We // will take care of the system apps by updating all of their // library paths after the scan is done. updateSharedLibrariesLPw(pkg, null); } if (mFoundPolicyFile) { SELinuxMMAC.assignSeinfoValue(pkg); } pkg.applicationInfo.uid = pkgSetting.appId; pkg.mExtras = pkgSetting; if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { try { verifySignaturesLP(pkgSetting, pkg); } catch (PackageManagerException e) { if (((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) | (parseFlags & PackageParser.PARSE_IS_OPERATOR)) == 0) { throw e; } // The signature has changed, but this package is in the system // image... let's recover! pkgSetting.signatures.mSignatures = pkg.mSignatures; // However... if this package is part of a shared user, but it // doesn't match the signature of the shared user, let's fail. // What this means is that you can't change the signatures // associated with an overall shared user, which doesn't seem all // that unreasonable. if (pkgSetting.sharedUser != null) { if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { throw new PackageManagerException( INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, "Signature mismatch for shared user : " + pkgSetting.sharedUser); } } // File a report about this. String msg = "System package " + pkg.packageName + " signature changed; retaining data."; reportSettingsProblem(Log.WARN, msg); } } else { if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " + pkg.packageName + " upgrade keys do not match the " + "previously installed version"); } else { // signatures may have changed as result of upgrade pkgSetting.signatures.mSignatures = pkg.mSignatures; } } // Verify that this new package doesn't have any content providers // that conflict with existing packages. Only do this if the // package isn't already installed, since we don't want to break // things that are installed. if ((scanFlags & SCAN_NEW_INSTALL) != 0) { final int N = pkg.providers.size(); int i; for (i=0; i<N; i++) { PackageParser.Provider p = pkg.providers.get(i); if (p.info.authority != null) { String names[] = p.info.authority.split(";"); for (int j = 0; j < names.length; j++) { if (mProvidersByAuthority.containsKey(names[j])) { PackageParser.Provider other = mProvidersByAuthority.get(names[j]); final String otherPackageName = ((other != null && other.getComponentName() != null) ? other.getComponentName().getPackageName() : "?"); throw new PackageManagerException( INSTALL_FAILED_CONFLICTING_PROVIDER, "Can't install because provider name " + names[j] + " (in package " + pkg.applicationInfo.packageName + ") is already used by " + otherPackageName); } } } } } if (pkg.mAdoptPermissions != null) { // This package wants to adopt ownership of permissions from // another package. for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { final String origName = pkg.mAdoptPermissions.get(i); final PackageSetting orig = mSettings.peekPackageLPr(origName); if (orig != null) { if (verifyPackageUpdateLPr(orig, pkg)) { Slog.i(TAG, "Adopting permissions from " + origName + " to " + pkg.packageName); mSettings.transferPermissionsLPw(origName, pkg.packageName); } } } } } final String pkgName = pkg.packageName; final long scanFileTime = scanFile.lastModified(); final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; pkg.applicationInfo.processName = fixProcessName( pkg.applicationInfo.packageName, pkg.applicationInfo.processName, pkg.applicationInfo.uid); File dataPath; if (mPlatformPackage == pkg) { // The system package is special. dataPath = new File(Environment.getDataDirectory(), "system"); pkg.applicationInfo.dataDir = dataPath.getPath(); } else { // This is a normal package, need to make its data directory. dataPath = getDataPathForPackage(pkg.packageName, 0); boolean uidError = false; if (dataPath.exists()) { int currentUid = 0; try { StructStat stat = Os.stat(dataPath.getPath()); currentUid = stat.st_uid; } catch (ErrnoException e) { Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); } // If we have mismatched owners for the data path, we have a problem. if (currentUid != pkg.applicationInfo.uid) { boolean recovered = false; if (currentUid == 0) { // The directory somehow became owned by root. Wow. // This is probably because the system was stopped while // installd was in the middle of messing with its libs // directory. Ask installd to fix that. int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, pkg.applicationInfo.uid); if (ret >= 0) { recovered = true; String msg = "Package " + pkg.packageName + " unexpectedly changed to uid 0; recovered to " + + pkg.applicationInfo.uid; reportSettingsProblem(Log.WARN, msg); } } if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 || (scanFlags&SCAN_BOOTING) != 0)) { // If this is a system app, we can at least delete its // current data so the application will still work. int ret = removeDataDirsLI(pkgName); if (ret >= 0) { // TODO: Kill the processes first // Old data gone! String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 ? "System package " : "Third party package "; String msg = prefix + pkg.packageName + " has changed from uid: " + currentUid + " to " + pkg.applicationInfo.uid + "; old data erased"; reportSettingsProblem(Log.WARN, msg); recovered = true; // And now re-install the app. ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, pkg.applicationInfo.seinfo); if (ret == -1) { // Ack should not happen! msg = prefix + pkg.packageName + " could not have data directory re-created after delete."; reportSettingsProblem(Log.WARN, msg); throw new PackageManagerException( INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); } } if (!recovered) { mHasSystemUidErrors = true; } } else if (!recovered) { // If we allow this install to proceed, we will be broken. // Abort, abort! throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, "scanPackageLI"); } if (!recovered) { pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" + pkg.applicationInfo.uid + "/fs_" + currentUid; pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; String msg = "Package " + pkg.packageName + " has mismatched uid: " + currentUid + " on disk, " + pkg.applicationInfo.uid + " in settings"; // writer synchronized (mPackages) { mSettings.mReadMessages.append(msg); mSettings.mReadMessages.append('\n'); uidError = true; if (!pkgSetting.uidError) { reportSettingsProblem(Log.ERROR, msg); } } } } pkg.applicationInfo.dataDir = dataPath.getPath(); if (mShouldRestoreconData) { Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); } } else { if (DEBUG_PACKAGE_SCANNING) { if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) Log.v(TAG, "Want this data dir: " + dataPath); } //invoke installer to do the actual installation int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, pkg.applicationInfo.seinfo); if (ret < 0) { // Error from installer throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Unable to create data dirs [errorCode=" + ret + "]"); } if (dataPath.exists()) { pkg.applicationInfo.dataDir = dataPath.getPath(); } else { Slog.w(TAG, "Unable to create data directory: " + dataPath); pkg.applicationInfo.dataDir = null; } } pkgSetting.uidError = uidError; } final String path = scanFile.getPath(); final String codePath = pkg.applicationInfo.getCodePath(); final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { setBundledAppAbisAndRoots(pkg, pkgSetting); // If we haven't found any native libraries for the app, check if it has // renderscript code. We'll need to force the app to 32 bit if it has // renderscript bitcode. if (pkg.applicationInfo.primaryCpuAbi == null && pkg.applicationInfo.secondaryCpuAbi == null && Build.SUPPORTED_64_BIT_ABIS.length > 0) { NativeLibraryHelper.Handle handle = null; try { handle = NativeLibraryHelper.Handle.create(scanFile); if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; } } catch (IOException ioe) { Slog.w(TAG, "Error scanning system app : " + ioe); } finally { IoUtils.closeQuietly(handle); } } setNativeLibraryPaths(pkg); } else { // TODO: We can probably be smarter about this stuff. For installed apps, // we can calculate this information at install time once and for all. For // system apps, we can probably assume that this information doesn't change // after the first boot scan. As things stand, we do lots of unnecessary work. // Give ourselves some initial paths; we'll come back for another // pass once we've determined ABI below. setNativeLibraryPaths(pkg); final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; NativeLibraryHelper.Handle handle = null; try { handle = NativeLibraryHelper.Handle.create(scanFile); // TODO(multiArch): This can be null for apps that didn't go through the // usual installation process. We can calculate it again, like we // do during install time. // // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally // unnecessary. final File nativeLibraryRoot = new File(nativeLibraryRootStr); // Null out the abis so that they can be recalculated. pkg.applicationInfo.primaryCpuAbi = null; pkg.applicationInfo.secondaryCpuAbi = null; if (isMultiArch(pkg.applicationInfo)) { // Warn if we've set an abiOverride for multi-lib packages.. // By definition, we need to copy both 32 and 64 bit libraries for // such packages. if (pkg.cpuAbiOverride != null && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { Slog.w(TAG, "Ignoring abiOverride for multi arch application."); } int abi32 = PackageManager.NO_NATIVE_LIBRARIES; int abi64 = PackageManager.NO_NATIVE_LIBRARIES; if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { if (isAsec) { abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); } else { abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); } } maybeThrowExceptionForMultiArchCopy( "Error unpackaging 32 bit native libs for multiarch app.", abi32); if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { if (isAsec) { abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); } else { abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); } } maybeThrowExceptionForMultiArchCopy( "Error unpackaging 64 bit native libs for multiarch app.", abi64); if (abi64 >= 0) { pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; } if (abi32 >= 0) { final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; if (abi64 >= 0) { pkg.applicationInfo.secondaryCpuAbi = abi; } else { pkg.applicationInfo.primaryCpuAbi = abi; } } } else { String[] abiList = (cpuAbiOverride != null) ? new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; // Enable gross and lame hacks for apps that are built with old // SDK tools. We must scan their APKs for renderscript bitcode and // not launch them if it's present. Don't bother checking on devices // that don't have 64 bit support. boolean needsRenderScriptOverride = false; if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && NativeLibraryHelper.hasRenderscriptBitcode(handle)) { abiList = Build.SUPPORTED_32_BIT_ABIS; needsRenderScriptOverride = true; } final int copyRet; if (isAsec) { copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); } else { copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, nativeLibraryRoot, abiList, useIsaSpecificSubdirs); } if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, "Error unpackaging native libs for app, errorCode=" + copyRet); } if (copyRet >= 0) { pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; } else if (needsRenderScriptOverride) { pkg.applicationInfo.primaryCpuAbi = abiList[0]; } } } catch (IOException ioe) { Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); } finally { IoUtils.closeQuietly(handle); } // Now that we've calculated the ABIs and determined if it's an internal app, // we will go ahead and populate the nativeLibraryPath. setNativeLibraryPaths(pkg); if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); final int[] userIds = sUserManager.getUserIds(); synchronized (mInstallLock) { // Create a native library symlink only if we have native libraries // and if the native libraries are 32 bit libraries. We do not provide // this symlink for 64 bit libraries. if (pkg.applicationInfo.primaryCpuAbi != null && !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; for (int userId : userIds) { if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, "Failed linking native library dir (user=" + userId + ")"); } } } } } // This is a special case for the "system" package, where the ABI is // dictated by the zygote configuration (and init.rc). We should keep track // of this ABI so that we can deal with "normal" applications that run under // the same UID correctly. if (mPlatformPackage == pkg) { pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; } pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; pkgSetting.cpuAbiOverrideString = cpuAbiOverride; // Copy the derived override back to the parsed package, so that we can // update the package settings accordingly. pkg.cpuAbiOverride = cpuAbiOverride; if (DEBUG_ABI_SELECTION) { Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" + pkg.applicationInfo.nativeLibraryRootRequiresIsa); } // Push the derived path down into PackageSettings so we know what to // clean up at uninstall time. pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; if (DEBUG_ABI_SELECTION) { Slog.d(TAG, "Abis for package[" + pkg.packageName + "] are" + " primary=" + pkg.applicationInfo.primaryCpuAbi + " secondary=" + pkg.applicationInfo.secondaryCpuAbi); } if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { // We don't do this here during boot because we can do it all // at once after scanning all existing packages. // // We also do this *before* we perform dexopt on this package, so that // we can avoid redundant dexopts, and also to make sure we've got the // code and package path correct. adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); } if ((scanFlags & SCAN_NO_DEX) == 0) { Slog.i(TAG, "Perform pre-dex opt for package: " + pkg.packageName); if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); } } if (mFactoryTest && pkg.requestedPermissions.contains( android.Manifest.permission.FACTORY_TEST)) { pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; } ArrayList<PackageParser.Package> clientLibPkgs = null; // writer synchronized (mPackages) { if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { // Only system apps can add new shared libraries. if (pkg.libraryNames != null) { for (int i=0; i<pkg.libraryNames.size(); i++) { String name = pkg.libraryNames.get(i); boolean allowed = false; if (isUpdatedSystemApp(pkg)) { // New library entries can only be added through the // system image. This is important to get rid of a lot // of nasty edge cases: for example if we allowed a non- // system update of the app to add a library, then uninstalling // the update would make the library go away, and assumptions // we made such as through app install filtering would now // have allowed apps on the device which aren't compatible // with it. Better to just have the restriction here, be // conservative, and create many fewer cases that can negatively // impact the user experience. final PackageSetting sysPs = mSettings .getDisabledSystemPkgLPr(pkg.packageName); if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { if (name.equals(sysPs.pkg.libraryNames.get(j))) { allowed = true; allowed = true; break; } } } } else { allowed = true; } if (allowed) { if (!mSharedLibraries.containsKey(name)) { mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); } else if (!name.equals(pkg.packageName)) { Slog.w(TAG, "Package " + pkg.packageName + " library " + name + " already exists; skipping"); } } else { Slog.w(TAG, "Package " + pkg.packageName + " declares lib " + name + " that is not declared on system image; skipping"); } } if ((scanFlags&SCAN_BOOTING) == 0) { // If we are not booting, we need to update any applications // that are clients of our shared library. If we are booting, // this will all be done once the scan is complete. clientLibPkgs = updateAllSharedLibrariesLPw(pkg); } } } } // We also need to dexopt any apps that are dependent on this library. Note that // if these fail, we should abort the install since installing the library will // result in some apps being broken. if (clientLibPkgs != null) { if ((scanFlags & SCAN_NO_DEX) == 0) { for (int i = 0; i < clientLibPkgs.size(); i++) { PackageParser.Package clientPkg = clientLibPkgs.get(i); if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI failed to dexopt clientLibPkgs"); } } } } // Request the ActivityManager to kill the process(only for existing packages) // so that we do not end up in a confused state while the user is still using the older // version of the application while the new one gets installed. if ((scanFlags & SCAN_REPLACING) != 0) { killApplication(pkg.applicationInfo.packageName, pkg.applicationInfo.uid, "update pkg"); } // Also need to kill any apps that are dependent on the library. if (clientLibPkgs != null) { for (int i=0; i<clientLibPkgs.size(); i++) { PackageParser.Package clientPkg = clientLibPkgs.get(i); killApplication(clientPkg.applicationInfo.packageName, clientPkg.applicationInfo.uid, "update lib"); } } // writer synchronized (mPackages) { // We don't expect installation to fail beyond this point // Add the new setting to mSettings mSettings.insertPackageSettingLPw(pkgSetting, pkg); // Add the new setting to mPackages mPackages.put(pkg.applicationInfo.packageName, pkg); // Make sure we don't accidentally delete its data. final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); while (iter.hasNext()) { PackageCleanItem item = iter.next(); if (pkgName.equals(item.packageName)) { iter.remove(); } } // Take care of first install / last update times. if (currentTime != 0) { if (pkgSetting.firstInstallTime == 0) { pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { pkgSetting.lastUpdateTime = currentTime; } } else if (pkgSetting.firstInstallTime == 0) { // We need *something*. Take time time stamp of the file. pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { if (scanFileTime != pkgSetting.timeStamp) { // A package on the system image has changed; consider this // to be an update. pkgSetting.lastUpdateTime = scanFileTime; } } // Add the package's KeySets to the global KeySetManagerService KeySetManagerService ksms = mSettings.mKeySetManagerService; try { // Old KeySetData no longer valid. ksms.removeAppKeySetDataLPw(pkg.packageName); ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); if (pkg.mKeySetMapping != null) { for (Map.Entry<String, ArraySet<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { if (entry.getValue() != null) { ksms.addDefinedKeySetToPackageLPw(pkg.packageName, entry.getValue(), entry.getKey()); } } if (pkg.mUpgradeKeySets != null) { for (String upgradeAlias : pkg.mUpgradeKeySets) { ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); } } } } catch (NullPointerException e) { Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); } catch (IllegalArgumentException e) { Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); } int N = pkg.providers.size(); StringBuilder r = null; int i; for (i=0; i<N; i++) { PackageParser.Provider p = pkg.providers.get(i); p.info.processName = fixProcessName(pkg.applicationInfo.processName, p.info.processName, pkg.applicationInfo.uid); mProviders.addProvider(p); p.syncable = p.info.isSyncable; if (p.info.authority != null) { String names[] = p.info.authority.split(";"); p.info.authority = null; for (int j = 0; j < names.length; j++) { if (j == 1 && p.syncable) { // We only want the first authority for a provider to possibly be // syncable, so if we already added this provider using a different // authority clear the syncable flag. We copy the provider before // changing it because the mProviders object contains a reference // to a provider that we don't want to change. // Only do this for the second authority since the resulting provider // object can be the same for all future authorities for this provider. p = new PackageParser.Provider(p); p.syncable = false; } if (!mProvidersByAuthority.containsKey(names[j])) { mProvidersByAuthority.put(names[j], p); if (p.info.authority == null) { p.info.authority = names[j]; } else { p.info.authority = p.info.authority + ";" + names[j]; } if (DEBUG_PACKAGE_SCANNING) { if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) Log.d(TAG, "Registered content provider: " + names[j] + ", className = " + p.info.name + ", isSyncable = " + p.info.isSyncable); } } else { PackageParser.Provider other = mProvidersByAuthority.get(names[j]); Slog.w(TAG, "Skipping provider name " + names[j] + " (in package " + pkg.applicationInfo.packageName + "): name already used by " + ((other != null && other.getComponentName() != null) ? other.getComponentName().getPackageName() : "?")); } } } if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(p.info.name); } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); } N = pkg.services.size(); r = null; for (i=0; i<N; i++) { PackageParser.Service s = pkg.services.get(i); s.info.processName = fixProcessName(pkg.applicationInfo.processName, s.info.processName, pkg.applicationInfo.uid); mServices.addService(s); if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(s.info.name); } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); } N = pkg.receivers.size(); r = null; for (i=0; i<N; i++) { PackageParser.Activity a = pkg.receivers.get(i); a.info.processName = fixProcessName(pkg.applicationInfo.processName, a.info.processName, pkg.applicationInfo.uid); mReceivers.addActivity(a, "receiver"); if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(a.info.name); } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); } N = pkg.activities.size(); r = null; for (i=0; i<N; i++) { PackageParser.Activity a = pkg.activities.get(i); a.info.processName = fixProcessName(pkg.applicationInfo.processName, a.info.processName, pkg.applicationInfo.uid); mActivities.addActivity(a, "activity"); if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(a.info.name); } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); } N = pkg.permissionGroups.size(); r = null; for (i=0; i<N; i++) { PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); if (cur == null) { mPermissionGroups.put(pg.info.name, pg); if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(pg.info.name); } } else { Slog.w(TAG, "Permission group " + pg.info.name + " from package " + pg.info.packageName + " ignored: original from " + cur.info.packageName); if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append("DUP:"); r.append(pg.info.name); } } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); } N = pkg.permissions.size(); r = null; for (i=0; i<N; i++) { PackageParser.Permission p = pkg.permissions.get(i); HashMap<String, BasePermission> permissionMap = p.tree ? mSettings.mPermissionTrees : mSettings.mPermissions; p.group = mPermissionGroups.get(p.info.group); if (p.info.group == null || p.group != null) { BasePermission bp = permissionMap.get(p.info.name); // Allow system apps to redefine non-system permissions if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { final boolean currentOwnerIsSystem = (bp.perm != null && isSystemApp(bp.perm.owner)); if (isSystemApp(p.owner)) { if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { // It's a built-in permission and no owner, take ownership now bp.packageSetting = pkgSetting; bp.perm = p; bp.uid = pkg.applicationInfo.uid; bp.sourcePackage = p.info.packageName; } else if (!currentOwnerIsSystem) { String msg = "New decl " + p.owner + " of permission " + p.info.name + " is system; overriding " + bp.sourcePackage; reportSettingsProblem(Log.WARN, msg); bp = null; } } } if (bp == null) { bp = new BasePermission(p.info.name, p.info.packageName, BasePermission.TYPE_NORMAL); permissionMap.put(p.info.name, bp); } if (bp.perm == null) { if (bp.sourcePackage == null || bp.sourcePackage.equals(p.info.packageName)) { BasePermission tree = findPermissionTreeLP(p.info.name); if (tree == null || tree.sourcePackage.equals(p.info.packageName)) { bp.packageSetting = pkgSetting; bp.perm = p; bp.uid = pkg.applicationInfo.uid; bp.sourcePackage = p.info.packageName; if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(p.info.name); } } else { Slog.w(TAG, "Permission " + p.info.name + " from package " + p.info.packageName + " ignored: base tree " + tree.name + " is from package " + tree.sourcePackage); } } else { Slog.w(TAG, "Permission " + p.info.name + " from package " + p.info.packageName + " ignored: original from " + bp.sourcePackage); } } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append("DUP:"); r.append(p.info.name); } if (bp.perm == p) { bp.protectionLevel = p.info.protectionLevel; } } else { Slog.w(TAG, "Permission " + p.info.name + " from package " + p.info.packageName + " ignored: no group " + p.group); } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); } N = pkg.instrumentation.size(); r = null; for (i=0; i<N; i++) { PackageParser.Instrumentation a = pkg.instrumentation.get(i); a.info.packageName = pkg.applicationInfo.packageName; a.info.sourceDir = pkg.applicationInfo.sourceDir; a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; a.info.dataDir = pkg.applicationInfo.dataDir; // TODO: Update instrumentation.nativeLibraryDir as well ? Does it // need other information about the application, like the ABI and what not ? a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; mInstrumentation.put(a.getComponentName(), a); if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(a.info.name); } } if (r != null) { if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); } if (pkg.protectedBroadcasts != null) { N = pkg.protectedBroadcasts.size(); for (i=0; i<N; i++) { mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); } } pkgSetting.setTimeStamp(scanFileTime); // Create idmap files for pairs of (packages, overlay packages). // Note: "android", ie framework-res.apk, is handled by native layers. if (pkg.mOverlayTarget != null) { // This is an overlay package. if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { if (!mOverlays.containsKey(pkg.mOverlayTarget)) { mOverlays.put(pkg.mOverlayTarget, new HashMap<String, PackageParser.Package>()); } HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); map.put(pkg.packageName, pkg); PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "scanPackageLI failed to createIdmap"); } } } else if (mOverlays.containsKey(pkg.packageName) && !pkg.packageName.equals("android")) { // This is a regular package, with one or more known overlay packages. createIdmapsForPackageLI(pkg); } } return pkg; } /** * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. * i.e, so that all packages can be run inside a single process if required. * * Optionally, callers can pass in a parsed package via {@code newPackage} in which case * this function will either try and make the ABI for all packages in {@code packagesForUser} * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match * the ABI selected for {@code packagesForUser}. This variant is used when installing or * updating a package that belongs to a shared user. * * NOTE: We currently only match for the primary CPU abi string. Matching the secondary * adds unnecessary complexity. */ private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { String requiredInstructionSet = null; if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { requiredInstructionSet = VMRuntime.getInstructionSet( scannedPackage.applicationInfo.primaryCpuAbi); } PackageSetting requirer = null; for (PackageSetting ps : packagesForUser) { // If packagesForUser contains scannedPackage, we skip it. This will happen // when scannedPackage is an update of an existing package. Without this check, // we will never be able to change the ABI of any package belonging to a shared // user, even if it's compatible with other packages. if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { if (ps.primaryCpuAbiString == null) { continue; } final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { // We have a mismatch between instruction sets (say arm vs arm64) warn about // this but there's not much we can do. String errorMessage = "Instruction set mismatch, " + ((requirer == null) ? "[caller]" : requirer) + " requires " + requiredInstructionSet + " whereas " + ps + " requires " + instructionSet; Slog.w(TAG, errorMessage); } if (requiredInstructionSet == null) { requiredInstructionSet = instructionSet; requirer = ps; } } } if (requiredInstructionSet != null) { String adjustedAbi; if (requirer != null) { // requirer != null implies that either scannedPackage was null or that scannedPackage // did not require an ABI, in which case we have to adjust scannedPackage to match // the ABI of the set (which is the same as requirer's ABI) adjustedAbi = requirer.primaryCpuAbiString; if (scannedPackage != null) { scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; } } else { // requirer == null implies that we're updating all ABIs in the set to // match scannedPackage. adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; } for (PackageSetting ps : packagesForUser) { if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { if (ps.primaryCpuAbiString != null) { continue; } ps.primaryCpuAbiString = adjustedAbi; if (ps.pkg != null && ps.pkg.applicationInfo != null) { ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { ps.primaryCpuAbiString = null; ps.pkg.applicationInfo.primaryCpuAbi = null; return; } else { mInstaller.rmdex(ps.codePathString, getDexCodeInstructionSet(getPreferredInstructionSet())); } } } } } } private void setUpCustomResolverActivity(PackageParser.Package pkg) { synchronized (mPackages) { mResolverReplaced = true; // Set up information for custom user intent resolution activity. mResolveActivity.applicationInfo = pkg.applicationInfo; mResolveActivity.name = mCustomResolverComponentName.getClassName(); mResolveActivity.packageName = pkg.applicationInfo.packageName; mResolveActivity.processName = null; mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; mResolveActivity.theme = 0; mResolveActivity.exported = true; mResolveActivity.enabled = true; mResolveInfo.activityInfo = mResolveActivity; mResolveInfo.priority = 0; mResolveInfo.preferredOrder = 0; mResolveInfo.match = 0; mResolveComponentName = mCustomResolverComponentName; Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + mResolveComponentName); } } private static String calculateBundledApkRoot(final String codePathString) { final File codePath = new File(codePathString); final File codeRoot; if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { codeRoot = Environment.getRootDirectory(); } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { codeRoot = Environment.getOemDirectory(); } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { codeRoot = Environment.getVendorDirectory(); } else { // Unrecognized code path; take its top real segment as the apk root: // e.g. /something/app/blah.apk => /something try { File f = codePath.getCanonicalFile(); File parent = f.getParentFile(); // non-null because codePath is a file File tmp; while ((tmp = parent.getParentFile()) != null) { f = parent; parent = tmp; } codeRoot = f; Slog.w(TAG, "Unrecognized code path " + codePath + " - using " + codeRoot); } catch (IOException e) { // Can't canonicalize the code path -- shenanigans? Slog.w(TAG, "Can't canonicalize code path " + codePath); return Environment.getRootDirectory().getPath(); } } return codeRoot.getPath(); } /** * Derive and set the location of native libraries for the given package, * which varies depending on where and how the package was installed. */ private void setNativeLibraryPaths(PackageParser.Package pkg) { final ApplicationInfo info = pkg.applicationInfo; final String codePath = pkg.codePath; final File codeFile = new File(codePath); final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); final boolean asecApp = isForwardLocked(info) || isExternal(info); info.nativeLibraryRootDir = null; info.nativeLibraryRootRequiresIsa = false; info.nativeLibraryDir = null; info.secondaryNativeLibraryDir = null; if (isApkFile(codeFile)) { // Monolithic install if (bundledApp) { // If "/system/lib64/apkname" exists, assume that is the per-package // native library directory to use; otherwise use "/system/lib/apkname". final String apkRoot = calculateBundledApkRoot(info.sourceDir); final boolean is64Bit = VMRuntime.is64BitInstructionSet( getPrimaryInstructionSet(info)); // This is a bundled system app so choose the path based on the ABI. // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this // is just the default path. final String apkName = deriveCodePathName(codePath); final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, apkName).getAbsolutePath(); if (info.secondaryCpuAbi != null) { final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), secondaryLibDir, apkName).getAbsolutePath(); } } else if (asecApp) { info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) .getAbsolutePath(); } else { final String apkName = deriveCodePathName(codePath); info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) .getAbsolutePath(); } info.nativeLibraryRootRequiresIsa = false; info.nativeLibraryDir = info.nativeLibraryRootDir; } else { // Cluster install /// M: [Operator] Operator package libs go to data/app-lib if (isVendorApp(info)) { final String apkName = deriveCodePathName(codePath); info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) .getAbsolutePath(); info.nativeLibraryRootRequiresIsa = false; info.nativeLibraryDir = info.nativeLibraryRootDir; } else { info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); info.nativeLibraryRootRequiresIsa = true; info.nativeLibraryDir = new File(info.nativeLibraryRootDir, getPrimaryInstructionSet(info)).getAbsolutePath(); if (info.secondaryCpuAbi != null) { info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); } } } } /** * Calculate the abis and roots for a bundled app. These can uniquely * be determined from the contents of the system partition, i.e whether * it contains 64 or 32 bit shared libraries etc. We do not validate any * of this information, and instead assume that the system was built * sensibly. */ private void setBundledAppAbisAndRoots(PackageParser.Package pkg, PackageSetting pkgSetting) { final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); // If "/system/lib64/apkname" exists, assume that is the per-package // native library directory to use; otherwise use "/system/lib/apkname". final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); setBundledAppAbi(pkg, apkRoot, apkName); // pkgSetting might be null during rescan following uninstall of updates // to a bundled app, so accommodate that possibility. The settings in // that case will be established later from the parsed package. // // If the settings aren't null, sync them up with what we've just derived. // note that apkRoot isn't stored in the package settings. if (pkgSetting != null) { pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; } } /** * Deduces the ABI of a bundled app and sets the relevant fields on the * parsed pkg object. * * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} * under which system libraries are installed. * @param apkName the name of the installed package. */ private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { final File codeFile = new File(pkg.codePath); final boolean has64BitLibs; final boolean has32BitLibs; if (isApkFile(codeFile)) { // Monolithic install has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); } else { // Cluster install final File rootDir = new File(codeFile, LIB_DIR_NAME); if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); has64BitLibs = (new File(rootDir, isa)).exists(); } else { has64BitLibs = false; } if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); has32BitLibs = (new File(rootDir, isa)).exists(); } else { has32BitLibs = false; } } if (has64BitLibs && !has32BitLibs) { // The package has 64 bit libs, but not 32 bit libs. Its primary // ABI should be 64 bit. We can safely assume here that the bundled // native libraries correspond to the most preferred ABI in the list. pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; pkg.applicationInfo.secondaryCpuAbi = null; } else if (has32BitLibs && !has64BitLibs) { // The package has 32 bit libs but not 64 bit libs. Its primary // ABI should be 32 bit. pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; pkg.applicationInfo.secondaryCpuAbi = null; } else if (has32BitLibs && has64BitLibs) { // The application has both 64 and 32 bit bundled libraries. We check // here that the app declares multiArch support, and warn if it doesn't. // // We will be lenient here and record both ABIs. The primary will be the // ABI that's higher on the list, i.e, a device that's configured to prefer // 64 bit apps will see a 64 bit primary ABI, if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); } if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; } else { pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; } } else { pkg.applicationInfo.primaryCpuAbi = null; pkg.applicationInfo.secondaryCpuAbi = null; } } private void killApplication(String pkgName, int appId, String reason) { // Request the ActivityManager to kill the process(only for existing packages) // so that we do not end up in a confused state while the user is still using the older // version of the application while the new one gets installed. IActivityManager am = ActivityManagerNative.getDefault(); if (am != null) { try { am.killApplicationWithAppId(pkgName, appId, reason); } catch (RemoteException e) { } } } void removePackageLI(PackageSetting ps, boolean chatty) { if (DEBUG_INSTALL) { if (chatty) Log.d(TAG, "Removing package " + ps.name); } // writer synchronized (mPackages) { mPackages.remove(ps.name); final PackageParser.Package pkg = ps.pkg; if (pkg != null) { cleanPackageDataStructuresLILPw(pkg, chatty); } } } void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { if (DEBUG_INSTALL) { if (chatty) Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); } // writer synchronized (mPackages) { mPackages.remove(pkg.applicationInfo.packageName); cleanPackageDataStructuresLILPw(pkg, chatty); } } void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { int N = pkg.providers.size(); StringBuilder r = null; int i; for (i=0; i<N; i++) { PackageParser.Provider p = pkg.providers.get(i); mProviders.removeProvider(p); if (p.info.authority == null) { /* There was another ContentProvider with this authority when * this app was installed so this authority is null, * Ignore it as we don't have to unregister the provider. */ continue; } String names[] = p.info.authority.split(";"); for (int j = 0; j < names.length; j++) { if (mProvidersByAuthority.get(names[j]) == p) { mProvidersByAuthority.remove(names[j]); if (DEBUG_REMOVE) { if (chatty) Log.d(TAG, "Unregistered content provider: " + names[j] + ", className = " + p.info.name + ", isSyncable = " + p.info.isSyncable); } } } if (DEBUG_REMOVE && chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(p.info.name); } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); } N = pkg.services.size(); r = null; for (i=0; i<N; i++) { PackageParser.Service s = pkg.services.get(i); mServices.removeService(s); if (chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(s.info.name); } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); } N = pkg.receivers.size(); r = null; for (i=0; i<N; i++) { PackageParser.Activity a = pkg.receivers.get(i); mReceivers.removeActivity(a, "receiver"); if (DEBUG_REMOVE && chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(a.info.name); } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); } N = pkg.activities.size(); r = null; for (i=0; i<N; i++) { PackageParser.Activity a = pkg.activities.get(i); mActivities.removeActivity(a, "activity"); if (DEBUG_REMOVE && chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(a.info.name); } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); } N = pkg.permissions.size(); r = null; for (i=0; i<N; i++) { PackageParser.Permission p = pkg.permissions.get(i); BasePermission bp = mSettings.mPermissions.get(p.info.name); if (bp == null) { bp = mSettings.mPermissionTrees.get(p.info.name); } if (bp != null && bp.perm == p) { bp.perm = null; if (DEBUG_REMOVE && chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(p.info.name); } } if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); if (appOpPerms != null) { appOpPerms.remove(pkg.packageName); } } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); } N = pkg.requestedPermissions.size(); r = null; for (i=0; i<N; i++) { String perm = pkg.requestedPermissions.get(i); BasePermission bp = mSettings.mPermissions.get(perm); if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); if (appOpPerms != null) { appOpPerms.remove(pkg.packageName); if (appOpPerms.isEmpty()) { mAppOpPermissionPackages.remove(perm); } } } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); } N = pkg.instrumentation.size(); r = null; for (i=0; i<N; i++) { PackageParser.Instrumentation a = pkg.instrumentation.get(i); mInstrumentation.remove(a.getComponentName()); if (DEBUG_REMOVE && chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(a.info.name); } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); } r = null; if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { // Only system apps can hold shared libraries. if (pkg.libraryNames != null) { for (i=0; i<pkg.libraryNames.size(); i++) { String name = pkg.libraryNames.get(i); SharedLibraryEntry cur = mSharedLibraries.get(name); if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { mSharedLibraries.remove(name); if (DEBUG_REMOVE && chatty) { if (r == null) { r = new StringBuilder(256); } else { r.append(' '); } r.append(name); } } } } } if (r != null) { if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); } } private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { if (pkgInfo.permissions.get(i).info.name.equals(perm)) { return true; } } return false; } static final int UPDATE_PERMISSIONS_ALL = 1<<0; static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, int flags) { // Make sure there are no dangling permission trees. Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); while (it.hasNext()) { final BasePermission bp = it.next(); if (bp.packageSetting == null) { // We may not yet have parsed the package, so just see if // we still know about its settings. bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); } if (bp.packageSetting == null) { Slog.w(TAG, "Removing dangling permission tree: " + bp.name + " from package " + bp.sourcePackage); it.remove(); } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { Slog.i(TAG, "Removing old permission tree: " + bp.name + " from package " + bp.sourcePackage); flags |= UPDATE_PERMISSIONS_ALL; it.remove(); } } } // Make sure all dynamic permissions have been assigned to a package, // and make sure there are no dangling permissions. it = mSettings.mPermissions.values().iterator(); while (it.hasNext()) { final BasePermission bp = it.next(); if (bp.type == BasePermission.TYPE_DYNAMIC) { if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" + bp.name + " pkg=" + bp.sourcePackage + " info=" + bp.pendingInfo); if (bp.packageSetting == null && bp.pendingInfo != null) { final BasePermission tree = findPermissionTreeLP(bp.name); if (tree != null && tree.perm != null) { bp.packageSetting = tree.packageSetting; bp.perm = new PackageParser.Permission(tree.perm.owner, new PermissionInfo(bp.pendingInfo)); bp.perm.info.packageName = tree.perm.info.packageName; bp.perm.info.name = bp.name; bp.uid = tree.uid; } } } if (bp.packageSetting == null) { // We may not yet have parsed the package, so just see if // we still know about its settings. bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); } if (bp.packageSetting == null) { Slog.w(TAG, "Removing dangling permission: " + bp.name + " from package " + bp.sourcePackage); it.remove(); } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { Slog.i(TAG, "Removing old permission: " + bp.name + " from package " + bp.sourcePackage); flags |= UPDATE_PERMISSIONS_ALL; it.remove(); } } } // Now update the permissions for all packages, in particular // replace the granted permissions of the system packages. if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { for (PackageParser.Package pkg : mPackages.values()) { if (pkg != pkgInfo) { grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, changingPkg); } } } if (pkgInfo != null) { grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); } } private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, String packageOfInterest) { final PackageSetting ps = (PackageSetting) pkg.mExtras; if (ps == null) { return; } final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; HashSet<String> origPermissions = gp.grantedPermissions; boolean changedPermission = false; if (replace) { ps.permissionsFixed = false; if (gp == ps) { origPermissions = new HashSet<String>(gp.grantedPermissions); gp.grantedPermissions.clear(); gp.gids = mGlobalGids; } } if (gp.gids == null) { gp.gids = mGlobalGids; } final int N = pkg.requestedPermissions.size(); for (int i=0; i<N; i++) { final String name = pkg.requestedPermissions.get(i); final boolean required = pkg.requestedPermissionsRequired.get(i); final BasePermission bp = mSettings.mPermissions.get(name); if (DEBUG_INSTALL) { if (gp != ps) { Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); } } if (bp == null || bp.packageSetting == null) { if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { Slog.w(TAG, "Unknown permission " + name + " in package " + pkg.packageName); } continue; } final String perm = bp.name; boolean allowed; boolean allowedSig = false; if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { // Keep track of app op permissions. ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); if (pkgs == null) { pkgs = new ArraySet<>(); mAppOpPermissionPackages.put(bp.name, pkgs); } pkgs.add(pkg.packageName); } final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; if (level == PermissionInfo.PROTECTION_NORMAL || level == PermissionInfo.PROTECTION_DANGEROUS) { // We grant a normal or dangerous permission if any of the following // are true: // 1) The permission is required // 2) The permission is optional, but was granted in the past // 3) The permission is optional, but was requested by an // app in /system (not /data) // // Otherwise, reject the permission. allowed = (required || origPermissions.contains(perm) || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); } else if (bp.packageSetting == null) { // This permission is invalid; skip it. allowed = false; } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); if (allowed) { allowedSig = true; } } else { allowed = false; } if (DEBUG_INSTALL) { if (gp != ps) { Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); } } if (allowed) { if (!isSystemApp(ps) && ps.permissionsFixed) { // If this is an existing, non-system package, then // we can't add any new permissions to it. if (!allowedSig && !gp.grantedPermissions.contains(perm)) { // Except... if this is a permission that was added // to the platform (note: need to only do this when // updating the platform). allowed = isNewPlatformPermissionForPackage(perm, pkg); } } if (allowed) { if (!gp.grantedPermissions.contains(perm)) { changedPermission = true; gp.grantedPermissions.add(perm); gp.gids = appendInts(gp.gids, bp.gids); } else if (!ps.haveGids) { gp.gids = appendInts(gp.gids, bp.gids); } } else { if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { Slog.w(TAG, "Not granting permission " + perm + " to package " + pkg.packageName + " because it was previously installed without"); } } } else { if (gp.grantedPermissions.remove(perm)) { changedPermission = true; gp.gids = removeInts(gp.gids, bp.gids); Slog.i(TAG, "Un-granting permission " + perm + " from package " + pkg.packageName + " (protectionLevel=" + bp.protectionLevel + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) + ")"); } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { // Don't print warning for app op permissions, since it is fine for them // not to be granted, there is a UI for the user to decide. if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { Slog.w(TAG, "Not granting permission " + perm + " to package " + pkg.packageName + " (protectionLevel=" + bp.protectionLevel + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) + ")"); } } } } if ((changedPermission || replace) && !ps.permissionsFixed && !isSystemApp(ps) || isUpdatedSystemApp(ps)){ // This is the first that we have heard about this package, so the // permissions we have now selected are fixed until explicitly // changed. ps.permissionsFixed = true; } ps.haveGids = true; } private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { boolean allowed = false; final int NP = PackageParser.NEW_PERMISSIONS.length; for (int ip=0; ip<NP; ip++) { final PackageParser.NewPermissionInfo npi = PackageParser.NEW_PERMISSIONS[ip]; if (npi.name.equals(perm) && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { allowed = true; Log.i(TAG, "Auto-granting " + perm + " to old pkg " + pkg.packageName); break; } } return allowed; } private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, BasePermission bp, HashSet<String> origPermissions) { boolean allowed; allowed = (compareSignatures( bp.packageSetting.signatures.mSignatures, pkg.mSignatures) == PackageManager.SIGNATURE_MATCH) || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) == PackageManager.SIGNATURE_MATCH); if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { if (isSystemApp(pkg)) { // For updated system applications, a system permission // is granted only if it had been defined by the original application. if (isUpdatedSystemApp(pkg)) { final PackageSetting sysPs = mSettings .getDisabledSystemPkgLPr(pkg.packageName); final GrantedPermissions origGp = sysPs.sharedUser != null ? sysPs.sharedUser : sysPs; if (origGp.grantedPermissions.contains(perm)) { // If the original was granted this permission, we take // that grant decision as read and propagate it to the // update. allowed = true; } else { // The system apk may have been updated with an older // version of the one on the data partition, but which // granted a new system permission that it didn't have // before. In this case we do want to allow the app to // now get the new permission if the ancestral apk is // privileged to get it. if (sysPs.pkg != null && sysPs.isPrivileged()) { for (int j=0; j<sysPs.pkg.requestedPermissions.size(); j++) { if (perm.equals( sysPs.pkg.requestedPermissions.get(j))) { allowed = true; break; } } } } } else { allowed = isPrivilegedApp(pkg); } } } if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { // For development permissions, a development permission // is granted only if it was already granted. allowed = origPermissions.contains(perm); } return allowed; } final class ActivityIntentResolver extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, boolean defaultOnly, int userId) { if (!sUserManager.exists(userId)) return null; mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; return super.queryIntent(intent, resolvedType, defaultOnly, userId); } public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return null; mFlags = flags; return super.queryIntent(intent, resolvedType, (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); } public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { if (!sUserManager.exists(userId)) return null; if (packageActivities == null) { return null; } mFlags = flags; final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; final int N = packageActivities.size(); ArrayList<PackageParser.ActivityIntentInfo[]> listCut = new ArrayList<PackageParser.ActivityIntentInfo[]>(N); ArrayList<PackageParser.ActivityIntentInfo> intentFilters; for (int i = 0; i < N; ++i) { intentFilters = packageActivities.get(i).intents; if (intentFilters != null && intentFilters.size() > 0) { PackageParser.ActivityIntentInfo[] array = new PackageParser.ActivityIntentInfo[intentFilters.size()]; intentFilters.toArray(array); listCut.add(array); } } return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); } public final void addActivity(PackageParser.Activity a, String type) { final boolean systemApp = isSystemApp(a.info.applicationInfo); mActivities.put(a.getComponentName(), a); if (DEBUG_SHOW_INFO) Log.v( TAG, " " + type + " " + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); if (DEBUG_SHOW_INFO) Log.v(TAG, " Class=" + a.info.name); final int NI = a.intents.size(); for (int j=0; j<NI; j++) { PackageParser.ActivityIntentInfo intent = a.intents.get(j); if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { intent.setPriority(0); Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " + a.className + " with priority > 0, forcing to 0"); } if (DEBUG_SHOW_INFO) { Log.v(TAG, " IntentFilter:"); intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); } if (!intent.debugCheck()) { Log.w(TAG, "==> For Activity " + a.info.name); } addFilter(intent); } } public final void removeActivity(PackageParser.Activity a, String type) { mActivities.remove(a.getComponentName()); if (DEBUG_SHOW_INFO) { Log.v(TAG, " " + type + " " + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); Log.v(TAG, " Class=" + a.info.name); } final int NI = a.intents.size(); for (int j=0; j<NI; j++) { PackageParser.ActivityIntentInfo intent = a.intents.get(j); if (DEBUG_SHOW_INFO) { Log.v(TAG, " IntentFilter:"); intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); } removeFilter(intent); } } @Override protected boolean allowFilterResult( PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { ActivityInfo filterAi = filter.activity.info; for (int i=dest.size()-1; i>=0; i--) { ActivityInfo destAi = dest.get(i).activityInfo; if (destAi.name == filterAi.name && destAi.packageName == filterAi.packageName) { return false; } } return true; } @Override protected ActivityIntentInfo[] newArray(int size) { return new ActivityIntentInfo[size]; } @Override protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { if (!sUserManager.exists(userId)) return true; PackageParser.Package p = filter.activity.owner; if (p != null) { PackageSetting ps = (PackageSetting)p.mExtras; if (ps != null) { // System apps are never considered stopped for purposes of // filtering, because there may be no way for the user to // actually re-launch them. return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 && ps.getStopped(userId); } } return false; } @Override protected boolean isPackageForFilter(String packageName, PackageParser.ActivityIntentInfo info) { return packageName.equals(info.activity.owner.packageName); } @Override protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, int match, int userId) { if (!sUserManager.exists(userId)) return null; if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { return null; } final PackageParser.Activity activity = info.activity; if (mSafeMode && (activity.info.applicationInfo.flags &ApplicationInfo.FLAG_SYSTEM) == 0) { return null; } PackageSetting ps = (PackageSetting) activity.owner.mExtras; if (ps == null) { return null; } ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, ps.readUserState(userId), userId); if (ai == null) { return null; } final ResolveInfo res = new ResolveInfo(); res.activityInfo = ai; if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { res.filter = info; } res.priority = info.getPriority(); res.preferredOrder = activity.owner.mPreferredOrder; //System.out.println("Result: " + res.activityInfo.className + // " = " + res.priority); res.match = match; res.isDefault = info.hasDefault; res.labelRes = info.labelRes; res.nonLocalizedLabel = info.nonLocalizedLabel; if (userNeedsBadging(userId)) { res.noResourceId = true; } else { res.icon = info.icon; } res.system = isSystemApp(res.activityInfo.applicationInfo); return res; } @Override protected void sortResults(List<ResolveInfo> results) { Collections.sort(results, mResolvePrioritySorter); } @Override protected void dumpFilter(PrintWriter out, String prefix, PackageParser.ActivityIntentInfo filter) { out.print(prefix); out.print( Integer.toHexString(System.identityHashCode(filter.activity))); out.print(' '); filter.activity.printComponentShortName(out); out.print(" filter "); out.println(Integer.toHexString(System.identityHashCode(filter))); } // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { // final Iterator<ResolveInfo> i = resolveInfoList.iterator(); // final List<ResolveInfo> retList = Lists.newArrayList(); // while (i.hasNext()) { // final ResolveInfo resolveInfo = i.next(); // if (isEnabledLP(resolveInfo.activityInfo)) { // retList.add(resolveInfo); // } // } // return retList; // } // Keys are String (activity class name), values are Activity. private final HashMap<ComponentName, PackageParser.Activity> mActivities = new HashMap<ComponentName, PackageParser.Activity>(); private int mFlags; } private final class ServiceIntentResolver extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, boolean defaultOnly, int userId) { mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; return super.queryIntent(intent, resolvedType, defaultOnly, userId); } public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return null; mFlags = flags; return super.queryIntent(intent, resolvedType, (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); } public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, int flags, ArrayList<PackageParser.Service> packageServices, int userId) { if (!sUserManager.exists(userId)) return null; if (packageServices == null) { return null; } mFlags = flags; final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; final int N = packageServices.size(); ArrayList<PackageParser.ServiceIntentInfo[]> listCut = new ArrayList<PackageParser.ServiceIntentInfo[]>(N); ArrayList<PackageParser.ServiceIntentInfo> intentFilters; for (int i = 0; i < N; ++i) { intentFilters = packageServices.get(i).intents; if (intentFilters != null && intentFilters.size() > 0) { PackageParser.ServiceIntentInfo[] array = new PackageParser.ServiceIntentInfo[intentFilters.size()]; intentFilters.toArray(array); listCut.add(array); } } return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); } public final void addService(PackageParser.Service s) { mServices.put(s.getComponentName(), s); if (DEBUG_SHOW_INFO) { Log.v(TAG, " " + (s.info.nonLocalizedLabel != null ? s.info.nonLocalizedLabel : s.info.name) + ":"); Log.v(TAG, " Class=" + s.info.name); } final int NI = s.intents.size(); int j; for (j=0; j<NI; j++) { PackageParser.ServiceIntentInfo intent = s.intents.get(j); if (DEBUG_SHOW_INFO) { Log.v(TAG, " IntentFilter:"); intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); } if (!intent.debugCheck()) { Log.w(TAG, "==> For Service " + s.info.name); } addFilter(intent); } } public final void removeService(PackageParser.Service s) { mServices.remove(s.getComponentName()); if (DEBUG_SHOW_INFO) { Log.v(TAG, " " + (s.info.nonLocalizedLabel != null ? s.info.nonLocalizedLabel : s.info.name) + ":"); Log.v(TAG, " Class=" + s.info.name); } final int NI = s.intents.size(); int j; for (j=0; j<NI; j++) { PackageParser.ServiceIntentInfo intent = s.intents.get(j); if (DEBUG_SHOW_INFO) { Log.v(TAG, " IntentFilter:"); intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); } removeFilter(intent); } } @Override protected boolean allowFilterResult( PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { ServiceInfo filterSi = filter.service.info; for (int i=dest.size()-1; i>=0; i--) { ServiceInfo destAi = dest.get(i).serviceInfo; if (destAi.name == filterSi.name && destAi.packageName == filterSi.packageName) { return false; } } return true; } @Override protected PackageParser.ServiceIntentInfo[] newArray(int size) { return new PackageParser.ServiceIntentInfo[size]; } @Override protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { if (!sUserManager.exists(userId)) return true; PackageParser.Package p = filter.service.owner; if (p != null) { PackageSetting ps = (PackageSetting)p.mExtras; if (ps != null) { // System apps are never considered stopped for purposes of // filtering, because there may be no way for the user to // actually re-launch them. return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 && ps.getStopped(userId); } } return false; } @Override protected boolean isPackageForFilter(String packageName, PackageParser.ServiceIntentInfo info) { return packageName.equals(info.service.owner.packageName); } @Override protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, int match, int userId) { if (!sUserManager.exists(userId)) return null; final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { return null; } final PackageParser.Service service = info.service; if (mSafeMode && (service.info.applicationInfo.flags &ApplicationInfo.FLAG_SYSTEM) == 0) { return null; } PackageSetting ps = (PackageSetting) service.owner.mExtras; if (ps == null) { return null; } ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, ps.readUserState(userId), userId); if (si == null) { return null; } final ResolveInfo res = new ResolveInfo(); res.serviceInfo = si; if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { res.filter = filter; } res.priority = info.getPriority(); res.preferredOrder = service.owner.mPreferredOrder; //System.out.println("Result: " + res.activityInfo.className + // " = " + res.priority); res.match = match; res.isDefault = info.hasDefault; res.labelRes = info.labelRes; res.nonLocalizedLabel = info.nonLocalizedLabel; res.icon = info.icon; res.system = isSystemApp(res.serviceInfo.applicationInfo); return res; } @Override protected void sortResults(List<ResolveInfo> results) { Collections.sort(results, mResolvePrioritySorter); } @Override protected void dumpFilter(PrintWriter out, String prefix, PackageParser.ServiceIntentInfo filter) { out.print(prefix); out.print( Integer.toHexString(System.identityHashCode(filter.service))); out.print(' '); filter.service.printComponentShortName(out); out.print(" filter "); out.println(Integer.toHexString(System.identityHashCode(filter))); } // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { // final Iterator<ResolveInfo> i = resolveInfoList.iterator(); // final List<ResolveInfo> retList = Lists.newArrayList(); // while (i.hasNext()) { // final ResolveInfo resolveInfo = (ResolveInfo) i; // if (isEnabledLP(resolveInfo.serviceInfo)) { // retList.add(resolveInfo); // } // } // return retList; // } // Keys are String (activity class name), values are Activity. private final HashMap<ComponentName, PackageParser.Service> mServices = new HashMap<ComponentName, PackageParser.Service>(); private int mFlags; }; private final class ProviderIntentResolver extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, boolean defaultOnly, int userId) { mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; return super.queryIntent(intent, resolvedType, defaultOnly, userId); } public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return null; mFlags = flags; return super.queryIntent(intent, resolvedType, (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); } public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { if (!sUserManager.exists(userId)) return null; if (packageProviders == null) { return null; } mFlags = flags; final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; final int N = packageProviders.size(); ArrayList<PackageParser.ProviderIntentInfo[]> listCut = new ArrayList<PackageParser.ProviderIntentInfo[]>(N); ArrayList<PackageParser.ProviderIntentInfo> intentFilters; for (int i = 0; i < N; ++i) { intentFilters = packageProviders.get(i).intents; if (intentFilters != null && intentFilters.size() > 0) { PackageParser.ProviderIntentInfo[] array = new PackageParser.ProviderIntentInfo[intentFilters.size()]; intentFilters.toArray(array); listCut.add(array); } } return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); } public final void addProvider(PackageParser.Provider p) { if (mProviders.containsKey(p.getComponentName())) { Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); return; } mProviders.put(p.getComponentName(), p); if (DEBUG_SHOW_INFO) { Log.v(TAG, " " + (p.info.nonLocalizedLabel != null ? p.info.nonLocalizedLabel : p.info.name) + ":"); Log.v(TAG, " Class=" + p.info.name); } final int NI = p.intents.size(); int j; for (j = 0; j < NI; j++) { PackageParser.ProviderIntentInfo intent = p.intents.get(j); if (DEBUG_SHOW_INFO) { Log.v(TAG, " IntentFilter:"); intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); } if (!intent.debugCheck()) { Log.w(TAG, "==> For Provider " + p.info.name); } addFilter(intent); } } public final void removeProvider(PackageParser.Provider p) { mProviders.remove(p.getComponentName()); if (DEBUG_SHOW_INFO) { Log.v(TAG, " " + (p.info.nonLocalizedLabel != null ? p.info.nonLocalizedLabel : p.info.name) + ":"); Log.v(TAG, " Class=" + p.info.name); } final int NI = p.intents.size(); int j; for (j = 0; j < NI; j++) { PackageParser.ProviderIntentInfo intent = p.intents.get(j); if (DEBUG_SHOW_INFO) { Log.v(TAG, " IntentFilter:"); intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); } removeFilter(intent); } } @Override protected boolean allowFilterResult( PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { ProviderInfo filterPi = filter.provider.info; for (int i = dest.size() - 1; i >= 0; i--) { ProviderInfo destPi = dest.get(i).providerInfo; if (destPi.name == filterPi.name && destPi.packageName == filterPi.packageName) { return false; } } return true; } @Override protected PackageParser.ProviderIntentInfo[] newArray(int size) { return new PackageParser.ProviderIntentInfo[size]; } @Override protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { if (!sUserManager.exists(userId)) return true; PackageParser.Package p = filter.provider.owner; if (p != null) { PackageSetting ps = (PackageSetting) p.mExtras; if (ps != null) { // System apps are never considered stopped for purposes of // filtering, because there may be no way for the user to // actually re-launch them. return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 && ps.getStopped(userId); } } return false; } @Override protected boolean isPackageForFilter(String packageName, PackageParser.ProviderIntentInfo info) { return packageName.equals(info.provider.owner.packageName); } @Override protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, int match, int userId) { if (!sUserManager.exists(userId)) return null; final PackageParser.ProviderIntentInfo info = filter; if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { return null; } final PackageParser.Provider provider = info.provider; if (mSafeMode && (provider.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { return null; } PackageSetting ps = (PackageSetting) provider.owner.mExtras; if (ps == null) { return null; } ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, ps.readUserState(userId), userId); if (pi == null) { return null; } final ResolveInfo res = new ResolveInfo(); res.providerInfo = pi; if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { res.filter = filter; } res.priority = info.getPriority(); res.preferredOrder = provider.owner.mPreferredOrder; res.match = match; res.isDefault = info.hasDefault; res.labelRes = info.labelRes; res.nonLocalizedLabel = info.nonLocalizedLabel; res.icon = info.icon; res.system = isSystemApp(res.providerInfo.applicationInfo); return res; } @Override protected void sortResults(List<ResolveInfo> results) { Collections.sort(results, mResolvePrioritySorter); } @Override protected void dumpFilter(PrintWriter out, String prefix, PackageParser.ProviderIntentInfo filter) { out.print(prefix); out.print( Integer.toHexString(System.identityHashCode(filter.provider))); out.print(' '); filter.provider.printComponentShortName(out); out.print(" filter "); out.println(Integer.toHexString(System.identityHashCode(filter))); } private final HashMap<ComponentName, PackageParser.Provider> mProviders = new HashMap<ComponentName, PackageParser.Provider>(); private int mFlags; }; private static final Comparator<ResolveInfo> mResolvePrioritySorter = new Comparator<ResolveInfo>() { public int compare(ResolveInfo r1, ResolveInfo r2) { int v1 = r1.priority; int v2 = r2.priority; //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); if (v1 != v2) { return (v1 > v2) ? -1 : 1; } v1 = r1.preferredOrder; v2 = r2.preferredOrder; if (v1 != v2) { return (v1 > v2) ? -1 : 1; } if (r1.isDefault != r2.isDefault) { return r1.isDefault ? -1 : 1; } v1 = r1.match; v2 = r2.match; //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); if (v1 != v2) { return (v1 > v2) ? -1 : 1; } if (r1.system != r2.system) { return r1.system ? -1 : 1; } return 0; } }; private static final Comparator<ProviderInfo> mProviderInitOrderSorter = new Comparator<ProviderInfo>() { public int compare(ProviderInfo p1, ProviderInfo p2) { final int v1 = p1.initOrder; final int v2 = p2.initOrder; return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); } }; static final void sendPackageBroadcast(String action, String pkg, Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, int[] userIds) { IActivityManager am = ActivityManagerNative.getDefault(); if (am != null) { try { if (userIds == null) { userIds = am.getRunningUserIds(); } for (int id : userIds) { final Intent intent = new Intent(action, pkg != null ? Uri.fromParts("package", pkg, null) : null); if (extras != null) { intent.putExtras(extras); } if (targetPkg != null) { intent.setPackage(targetPkg); } // Modify the UID when posting to other users int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); if (uid > 0 && UserHandle.getUserId(uid) != id) { uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); intent.putExtra(Intent.EXTRA_UID, uid); } intent.putExtra(Intent.EXTRA_USER_HANDLE, id); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); if (DEBUG_BROADCASTS) { RuntimeException here = new RuntimeException("here"); here.fillInStackTrace(); Slog.d(TAG, "Sending to user " + id + ": " + intent.toShortString(false, true, false, false) + " " + intent.getExtras(), here); } am.broadcastIntent(null, intent, null, finishedReceiver, 0, null, null, null, android.app.AppOpsManager.OP_NONE, finishedReceiver != null, false, id); } } catch (RemoteException ex) { } } } /** * Check if the external storage media is available. This is true if there * is a mounted external storage medium or if the external storage is * emulated. */ private boolean isExternalMediaAvailable() { return mMediaMounted || Environment.isExternalStorageEmulated(); } @Override public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { // writer synchronized (mPackages) { if (!isExternalMediaAvailable()) { // If the external storage is no longer mounted at this point, // the caller may not have been able to delete all of this // packages files and can not delete any more. Bail. return null; } final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; if (lastPackage != null) { pkgs.remove(lastPackage); } if (pkgs.size() > 0) { return pkgs.get(0); } } return null; } void schedulePackageCleaning(String packageName, int userId, boolean andCode) { final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, userId, andCode ? 1 : 0, packageName); if (mSystemReady) { msg.sendToTarget(); } else { if (mPostSystemReadyMessages == null) { mPostSystemReadyMessages = new ArrayList<>(); } mPostSystemReadyMessages.add(msg); } } void startCleaningPackages() { // reader synchronized (mPackages) { if (!isExternalMediaAvailable()) { return; } if (mSettings.mPackagesToBeCleaned.isEmpty()) { return; } } Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); intent.setComponent(DEFAULT_CONTAINER_COMPONENT); IActivityManager am = ActivityManagerNative.getDefault(); if (am != null) { try { am.startService(null, intent, null, UserHandle.USER_OWNER); } catch (RemoteException e) { } } } @Override public void installPackage(String originPath, IPackageInstallObserver2 observer, int installFlags, String installerPackageName, VerificationParams verificationParams, String packageAbiOverride) { installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); } @Override public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, int installFlags, String installerPackageName, VerificationParams verificationParams, String packageAbiOverride, int userId) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); final int callingUid = Binder.getCallingUid(); enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { try { if (observer != null) { observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); } } catch (RemoteException re) { } return; } if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { installFlags |= PackageManager.INSTALL_FROM_ADB; } else { // Caller holds INSTALL_PACKAGES permission, so we're less strict // about installerPackageName. installFlags &= ~PackageManager.INSTALL_FROM_ADB; installFlags &= ~PackageManager.INSTALL_ALL_USERS; } UserHandle user; if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { user = UserHandle.ALL; } else { user = new UserHandle(userId); } verificationParams.setInstallerUid(callingUid); final File originFile = new File(originPath); final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); final Message msg = mHandler.obtainMessage(INIT_COPY); msg.obj = new InstallParams(origin, observer, installFlags, installerPackageName, verificationParams, user, packageAbiOverride); mHandler.sendMessage(msg); } void installStage(String packageName, File stagedDir, String stagedCid, IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, String installerPackageName, int installerUid, UserHandle user) { final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, params.referrerUri, installerUid, null); final OriginInfo origin; if (stagedDir != null) { origin = OriginInfo.fromStagedFile(stagedDir); } else { origin = OriginInfo.fromStagedContainer(stagedCid); } final Message msg = mHandler.obtainMessage(INIT_COPY); msg.obj = new InstallParams(origin, observer, params.installFlags, installerPackageName, verifParams, user, params.abiOverride); mHandler.sendMessage(msg); } private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null, null, new int[] {userId}); try { IActivityManager am = ActivityManagerNative.getDefault(); final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); if (isSystem && am.isUserRunning(userId, false)) { // The just-installed/enabled app is bundled on the system, so presumed // to be able to run automatically without needing an explicit launch. // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) .setPackage(packageName); am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, android.app.AppOpsManager.OP_NONE, false, false, userId); } } catch (RemoteException e) { // shouldn't happen Slog.w(TAG, "Unable to bootstrap installed package", e); } } @Override public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, int userId) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); PackageSetting pkgSetting; final int uid = Binder.getCallingUid(); enforceCrossUserPermission(uid, userId, true, true, "setApplicationHiddenSetting for user " + userId); if (hidden && isPackageDeviceAdmin(packageName, userId)) { Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); return false; } long callingId = Binder.clearCallingIdentity(); try { boolean sendAdded = false; boolean sendRemoved = false; // writer synchronized (mPackages) { pkgSetting = mSettings.mPackages.get(packageName); if (pkgSetting == null) { return false; } if (pkgSetting.getHidden(userId) != hidden) { pkgSetting.setHidden(hidden, userId); mSettings.writePackageRestrictionsLPr(userId); if (hidden) { sendRemoved = true; } else { sendAdded = true; } } } if (sendAdded) { sendPackageAddedForUser(packageName, pkgSetting, userId); return true; } if (sendRemoved) { killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), "hiding pkg"); sendApplicationHiddenForUser(packageName, pkgSetting, userId); } } finally { Binder.restoreCallingIdentity(callingId); } return false; } private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, int userId) { final PackageRemovedInfo info = new PackageRemovedInfo(); info.removedPackage = packageName; info.removedUsers = new int[] {userId}; info.uid = UserHandle.getUid(userId, pkgSetting.appId); info.sendBroadcast(false, false, false); } /** * Returns true if application is not found or there was an error. Otherwise it returns * the hidden state of the package for the given user. */ @Override public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "getApplicationHidden for user " + userId); PackageSetting pkgSetting; long callingId = Binder.clearCallingIdentity(); try { // writer synchronized (mPackages) { pkgSetting = mSettings.mPackages.get(packageName); if (pkgSetting == null) { return true; } return pkgSetting.getHidden(userId); } } finally { Binder.restoreCallingIdentity(callingId); } } /** * @hide */ @Override public int installExistingPackageAsUser(String packageName, int userId) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); PackageSetting pkgSetting; final int uid = Binder.getCallingUid(); enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " + userId); if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { return PackageManager.INSTALL_FAILED_USER_RESTRICTED; } long callingId = Binder.clearCallingIdentity(); try { boolean sendAdded = false; Bundle extras = new Bundle(1); // writer synchronized (mPackages) { pkgSetting = mSettings.mPackages.get(packageName); if (pkgSetting == null) { return PackageManager.INSTALL_FAILED_INVALID_URI; } if (!pkgSetting.getInstalled(userId)) { pkgSetting.setInstalled(true, userId); pkgSetting.setHidden(false, userId); mSettings.writePackageRestrictionsLPr(userId); sendAdded = true; } } if (sendAdded) { sendPackageAddedForUser(packageName, pkgSetting, userId); } } finally { Binder.restoreCallingIdentity(callingId); } return PackageManager.INSTALL_SUCCEEDED; } boolean isUserRestricted(int userId, String restrictionKey) { Bundle restrictions = sUserManager.getUserRestrictions(userId); if (restrictions.getBoolean(restrictionKey, false)) { Log.w(TAG, "User is restricted: " + restrictionKey); return true; } return false; } @Override public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, "Only package verification agents can verify applications"); final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); final PackageVerificationResponse response = new PackageVerificationResponse( verificationCode, Binder.getCallingUid()); msg.arg1 = id; msg.obj = response; mHandler.sendMessage(msg); } @Override public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, long millisecondsToDelay) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, "Only package verification agents can extend verification timeouts"); final PackageVerificationState state = mPendingVerification.get(id); final PackageVerificationResponse response = new PackageVerificationResponse( verificationCodeAtTimeout, Binder.getCallingUid()); if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; } if (millisecondsToDelay < 0) { millisecondsToDelay = 0; } if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; } if ((state != null) && !state.timeoutExtended()) { state.extendTimeout(); final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); msg.arg1 = id; msg.obj = response; mHandler.sendMessageDelayed(msg, millisecondsToDelay); } } private void broadcastPackageVerified(int verificationId, Uri packageUri, int verificationCode, UserHandle user) { final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); mContext.sendBroadcastAsUser(intent, user, android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); } private ComponentName matchComponentForVerifier(String packageName, List<ResolveInfo> receivers) { ActivityInfo targetReceiver = null; final int NR = receivers.size(); for (int i = 0; i < NR; i++) { final ResolveInfo info = receivers.get(i); if (info.activityInfo == null) { continue; } if (packageName.equals(info.activityInfo.packageName)) { targetReceiver = info.activityInfo; break; } } if (targetReceiver == null) { return null; } return new ComponentName(targetReceiver.packageName, targetReceiver.name); } private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, List<ResolveInfo> receivers, final PackageVerificationState verificationState) { if (pkgInfo.verifiers.length == 0) { return null; } final int N = pkgInfo.verifiers.length; final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); for (int i = 0; i < N; i++) { final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, receivers); if (comp == null) { continue; } final int verifierUid = getUidForVerifier(verifierInfo); if (verifierUid == -1) { continue; } if (DEBUG_VERIFY) { Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName + " with the correct signature"); } sufficientVerifiers.add(comp); verificationState.addSufficientVerifier(verifierUid); } return sufficientVerifiers; } private int getUidForVerifier(VerifierInfo verifierInfo) { synchronized (mPackages) { final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); if (pkg == null) { return -1; } else if (pkg.mSignatures.length != 1) { Slog.i(TAG, "Verifier package " + verifierInfo.packageName + " has more than one signature; ignoring"); return -1; } /* * If the public key of the package's signature does not match * our expected public key, then this is a different package and * we should skip. */ final byte[] expectedPublicKey; try { final Signature verifierSig = pkg.mSignatures[0]; final PublicKey publicKey = verifierSig.getPublicKey(); expectedPublicKey = publicKey.getEncoded(); } catch (CertificateException e) { return -1; } final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { Slog.i(TAG, "Verifier package " + verifierInfo.packageName + " does not have the expected public key; ignoring"); return -1; } return pkg.applicationInfo.uid; } } @Override public void finishPackageInstall(int token) { enforceSystemOrRoot("Only the system is allowed to finish installs"); if (DEBUG_INSTALL) { Slog.v(TAG, "BM finishing package install for " + token); } final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); mHandler.sendMessage(msg); } /** * Get the verification agent timeout. * * @return verification timeout in milliseconds */ private long getVerificationTimeout() { return android.provider.Settings.Global.getLong(mContext.getContentResolver(), android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, DEFAULT_VERIFICATION_TIMEOUT); } /** * Get the default verification agent response code. * * @return default verification response code */ private int getDefaultVerificationResponse() { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, DEFAULT_VERIFICATION_RESPONSE); } /** * Check whether or not package verification has been enabled. * * @return true if verification should be performed */ private boolean isVerificationEnabled(int userId, int installFlags) { if (!DEFAULT_VERIFY_ENABLE) { return false; } boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); // Check if installing from ADB if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { // Do not run verification in a test harness environment if (ActivityManager.isRunningInTestHarness()) { return false; } if (ensureVerifyAppsEnabled) { return true; } // Check if the developer does not want package verification for ADB installs if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { return false; } } if (ensureVerifyAppsEnabled) { return true; } return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; } /** * Get the "allow unknown sources" setting. * * @return the current "allow unknown sources" setting */ private int getUnknownSourcesSettings() { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, -1); } @Override public void setInstallerPackageName(String targetPackage, String installerPackageName) { final int uid = Binder.getCallingUid(); // writer synchronized (mPackages) { PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); if (targetPackageSetting == null) { throw new IllegalArgumentException("Unknown target package: " + targetPackage); } PackageSetting installerPackageSetting; if (installerPackageName != null) { installerPackageSetting = mSettings.mPackages.get(installerPackageName); if (installerPackageSetting == null) { throw new IllegalArgumentException("Unknown installer package: " + installerPackageName); } } else { installerPackageSetting = null; } Signature[] callerSignature; Object obj = mSettings.getUserIdLPr(uid); if (obj != null) { if (obj instanceof SharedUserSetting) { callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; } else if (obj instanceof PackageSetting) { callerSignature = ((PackageSetting)obj).signatures.mSignatures; } else { throw new SecurityException("Bad object " + obj + " for uid " + uid); } } else { throw new SecurityException("Unknown calling uid " + uid); } // Verify: can't set installerPackageName to a package that is // not signed with the same cert as the caller. if (installerPackageSetting != null) { if (compareSignatures(callerSignature, installerPackageSetting.signatures.mSignatures) != PackageManager.SIGNATURE_MATCH) { throw new SecurityException( "Caller does not have same cert as new installer package " + installerPackageName); } } // Verify: if target already has an installer package, it must // be signed with the same cert as the caller. if (targetPackageSetting.installerPackageName != null) { PackageSetting setting = mSettings.mPackages.get( targetPackageSetting.installerPackageName); // If the currently set package isn't valid, then it's always // okay to change it. if (setting != null) { if (compareSignatures(callerSignature, setting.signatures.mSignatures) != PackageManager.SIGNATURE_MATCH) { throw new SecurityException( "Caller does not have same cert as old installer package " + targetPackageSetting.installerPackageName); } } } // Okay! targetPackageSetting.installerPackageName = installerPackageName; scheduleWriteSettingsLocked(); } } private void processPendingInstall(final InstallArgs args, final int currentStatus) { // Queue up an async operation since the package installation may take a little while. mHandler.post(new Runnable() { public void run() { mHandler.removeCallbacks(this); // Result object to be returned PackageInstalledInfo res = new PackageInstalledInfo(); res.returnCode = currentStatus; res.uid = -1; res.pkg = null; res.removedInfo = new PackageRemovedInfo(); if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { args.doPreInstall(res.returnCode); synchronized (mInstallLock) { installPackageLI(args, res); } args.doPostInstall(res.returnCode, res.uid); } // A restore should be performed at this point if (a) the install // succeeded, (b) the operation is not an update, and (c) the new // package has not opted out of backup participation. final boolean update = res.removedInfo.removedPackage != null; final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; boolean doRestore = !update && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); // Set up the post-install work request bookkeeping. This will be used // and cleaned up by the post-install event handling regardless of whether // there's a restore pass performed. Token values are >= 1. int token; if (mNextInstallToken < 0) mNextInstallToken = 1; token = mNextInstallToken++; PostInstallData data = new PostInstallData(args, res); mRunningInstalls.put(token, data); if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { // Pass responsibility to the Backup Manager. It will perform a // restore if appropriate, then pass responsibility back to the // Package Manager to run the post-install observer callbacks // and broadcasts. IBackupManager bm = IBackupManager.Stub.asInterface( ServiceManager.getService(Context.BACKUP_SERVICE)); if (bm != null) { if (DEBUG_INSTALL) Log.v(TAG, "token " + token + " to BM for possible restore"); try { bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); } catch (RemoteException e) { // can't happen; the backup manager is local } catch (Exception e) { Slog.e(TAG, "Exception trying to enqueue restore", e); doRestore = false; } } else { Slog.e(TAG, "Backup Manager not found!"); doRestore = false; } } if (!doRestore) { // No restore possible, or the Backup Manager was mysteriously not // available -- just fire the post-install work request directly. if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); mHandler.sendMessage(msg); } } }); } private abstract class HandlerParams { private static final int MAX_RETRIES = 4; /** * Number of times startCopy() has been attempted and had a non-fatal * error. */ private int mRetries = 0; /** User handle for the user requesting the information or installation. */ private final UserHandle mUser; HandlerParams(UserHandle user) { mUser = user; } UserHandle getUser() { return mUser; } final boolean startCopy() { boolean res; try { if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); if (++mRetries > MAX_RETRIES) { Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); mHandler.sendEmptyMessage(MCS_GIVE_UP); handleServiceError(); return false; } else { handleStartCopy(); Slog.i(TAG, "Apk copy done"); res = true; } } catch (RemoteException e) { if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); mHandler.sendEmptyMessage(MCS_RECONNECT); res = false; } handleReturnCode(); return res; } final void serviceError() { if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); handleServiceError(); handleReturnCode(); } abstract void handleStartCopy() throws RemoteException; abstract void handleServiceError(); abstract void handleReturnCode(); } class MeasureParams extends HandlerParams { private final PackageStats mStats; private boolean mSuccess; private final IPackageStatsObserver mObserver; public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { super(new UserHandle(stats.userHandle)); mObserver = observer; mStats = stats; } @Override public String toString() { return "MeasureParams{" + Integer.toHexString(System.identityHashCode(this)) + " " + mStats.packageName + "}"; } @Override void handleStartCopy() throws RemoteException { synchronized (mInstallLock) { mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); } if (mSuccess) { final boolean mounted; if (Environment.isExternalStorageEmulated()) { mounted = true; } else { final String status = Environment.getExternalStorageState(); mounted = (Environment.MEDIA_MOUNTED.equals(status) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); } if (mounted) { final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); mStats.externalCacheSize = calculateDirectorySize(mContainerService, userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); mStats.externalDataSize = calculateDirectorySize(mContainerService, userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); // Always subtract cache size, since it's a subdirectory mStats.externalDataSize -= mStats.externalCacheSize; mStats.externalMediaSize = calculateDirectorySize(mContainerService, userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); mStats.externalObbSize = calculateDirectorySize(mContainerService, userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); } } } @Override void handleReturnCode() { if (mObserver != null) { try { mObserver.onGetStatsCompleted(mStats, mSuccess); } catch (RemoteException e) { Slog.i(TAG, "Observer no longer exists."); } } } @Override void handleServiceError() { Slog.e(TAG, "Could not measure application " + mStats.packageName + " external storage"); } } private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) throws RemoteException { long result = 0; for (File path : paths) { result += mcs.calculateDirectorySize(path.getAbsolutePath()); } return result; } private static void clearDirectory(IMediaContainerService mcs, File[] paths) { for (File path : paths) { try { mcs.clearDirectory(path.getAbsolutePath()); } catch (RemoteException e) { } } } static class OriginInfo { /** * Location where install is coming from, before it has been * copied/renamed into place. This could be a single monolithic APK * file, or a cluster directory. This location may be untrusted. */ final File file; final String cid; /** * Flag indicating that {@link #file} or {@link #cid} has already been * staged, meaning downstream users don't need to defensively copy the * contents. */ final boolean staged; /** * Flag indicating that {@link #file} or {@link #cid} is an already * installed app that is being moved. */ final boolean existing; final String resolvedPath; final File resolvedFile; static OriginInfo fromNothing() { return new OriginInfo(null, null, false, false); } static OriginInfo fromUntrustedFile(File file) { return new OriginInfo(file, null, false, false); } static OriginInfo fromExistingFile(File file) { return new OriginInfo(file, null, false, true); } static OriginInfo fromStagedFile(File file) { return new OriginInfo(file, null, true, false); } static OriginInfo fromStagedContainer(String cid) { return new OriginInfo(null, cid, true, false); } private OriginInfo(File file, String cid, boolean staged, boolean existing) { this.file = file; this.cid = cid; this.staged = staged; this.existing = existing; if (cid != null) { resolvedPath = PackageHelper.getSdDir(cid); resolvedFile = new File(resolvedPath); } else if (file != null) { resolvedPath = file.getAbsolutePath(); resolvedFile = file; } else { resolvedPath = null; resolvedFile = null; } } } class InstallParams extends HandlerParams { final OriginInfo origin; final IPackageInstallObserver2 observer; int installFlags; final String installerPackageName; final VerificationParams verificationParams; private InstallArgs mArgs; private int mRet; final String packageAbiOverride; InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, String installerPackageName, VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { super(user); this.origin = origin; this.observer = observer; this.installFlags = installFlags; this.installerPackageName = installerPackageName; this.verificationParams = verificationParams; this.packageAbiOverride = packageAbiOverride; } @Override public String toString() { return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) + " file=" + origin.file + " cid=" + origin.cid + "}"; } public ManifestDigest getManifestDigest() { if (verificationParams == null) { return null; } return verificationParams.getManifestDigest(); } private int installLocationPolicy(PackageInfoLite pkgLite) { String packageName = pkgLite.packageName; int installLocation = pkgLite.installLocation; boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; // reader synchronized (mPackages) { PackageParser.Package pkg = mPackages.get(packageName); if (pkg != null) { if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { // Check for downgrading. if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { if (pkgLite.versionCode < pkg.mVersionCode) { Slog.w(TAG, "Can't install update of " + packageName + " update version " + pkgLite.versionCode + " is older than installed version " + pkg.mVersionCode); return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; } } // Check for updated system application. if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { if (onSd) { Slog.w(TAG, "Cannot install update to system app on sdcard"); return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; } return PackageHelper.RECOMMEND_INSTALL_INTERNAL; } else { if (onSd) { // Install flag overrides everything. return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; } // If current upgrade specifies particular preference if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { // Application explicitly specified internal. return PackageHelper.RECOMMEND_INSTALL_INTERNAL; } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { // App explictly prefers external. Let policy decide } else { // Prefer previous location if (isExternal(pkg)) { return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; } return PackageHelper.RECOMMEND_INSTALL_INTERNAL; } } } else { // Invalid install. Return error code return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; } } } // All the special cases have been taken care of. // Return result based on recommended install location. if (onSd) { return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; } return pkgLite.recommendedInstallLocation; } /* * Invoke remote method to get package information and install * location values. Override install location based on default * policy if needed and then create install arguments based * on the install location. */ public void handleStartCopy() throws RemoteException { int ret = PackageManager.INSTALL_SUCCEEDED; // If we're already staged, we've firmly committed to an install location if (origin.staged) { if (origin.file != null) { installFlags |= PackageManager.INSTALL_INTERNAL; installFlags &= ~PackageManager.INSTALL_EXTERNAL; } else if (origin.cid != null) { installFlags |= PackageManager.INSTALL_EXTERNAL; installFlags &= ~PackageManager.INSTALL_INTERNAL; } else { throw new IllegalStateException("Invalid stage location"); } } final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; PackageInfoLite pkgLite = null; if (onInt && onSd) { // Check if both bits are set. Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; } else { pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, packageAbiOverride); /* * If we have too little free space, try to free cache * before giving up. */ if (!origin.staged && pkgLite.recommendedInstallLocation == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { // TODO: focus freeing disk space on the target device final StorageManager storage = StorageManager.from(mContext); final long lowThreshold = storage.getStorageLowBytes( Environment.getDataDirectory()); final long sizeBytes = mContainerService.calculateInstalledSize( origin.resolvedPath, isForwardLocked(), packageAbiOverride); if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, packageAbiOverride); } /* * The cache free must have deleted the file we * downloaded to install. * * TODO: fix the "freeCache" call to not delete * the file we care about. */ if (pkgLite.recommendedInstallLocation == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { pkgLite.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; } } } if (ret == PackageManager.INSTALL_SUCCEEDED) { int loc = pkgLite.recommendedInstallLocation; if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { ret = PackageManager.INSTALL_FAILED_INVALID_APK; } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { ret = PackageManager.INSTALL_FAILED_INVALID_URI; } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; } else { // Override with defaults if needed. loc = installLocationPolicy(pkgLite); if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; } else if (!onSd && !onInt) { // Override install location with flags if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { // Set the flag to install on external media. installFlags |= PackageManager.INSTALL_EXTERNAL; installFlags &= ~PackageManager.INSTALL_INTERNAL; } else { // Make sure the flag for installing on external // media is unset installFlags |= PackageManager.INSTALL_INTERNAL; installFlags &= ~PackageManager.INSTALL_EXTERNAL; } } } } final InstallArgs args = createInstallArgs(this); mArgs = args; if (ret == PackageManager.INSTALL_SUCCEEDED) { /* * ADB installs appear as UserHandle.USER_ALL, and can only be performed by * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. */ int userIdentifier = getUser().getIdentifier(); if (userIdentifier == UserHandle.USER_ALL && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { userIdentifier = UserHandle.USER_OWNER; } /* * Determine if we have any installed package verifiers. If we * do, then we'll defer to them to verify the packages. */ final int requiredUid = mRequiredVerifierPackage == null ? -1 : getPackageUid(mRequiredVerifierPackage, userIdentifier); if (!origin.existing && requiredUid != -1 && isVerificationEnabled(userIdentifier, installFlags)) { final Intent verification = new Intent( Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), PACKAGE_MIME_TYPE); verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); if (DEBUG_VERIFY) { Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " + verification.toString() + " with " + pkgLite.verifiers.length + " optional verifiers"); } final int verificationId = mPendingVerificationToken++; verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, installerPackageName); verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, installFlags); verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, pkgLite.packageName); verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, pkgLite.versionCode); if (verificationParams != null) { if (verificationParams.getVerificationURI() != null) { verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, verificationParams.getVerificationURI()); } if (verificationParams.getOriginatingURI() != null) { verification.putExtra(Intent.EXTRA_ORIGINATING_URI, verificationParams.getOriginatingURI()); } if (verificationParams.getReferrer() != null) { verification.putExtra(Intent.EXTRA_REFERRER, verificationParams.getReferrer()); } if (verificationParams.getOriginatingUid() >= 0) { verification.putExtra(Intent.EXTRA_ORIGINATING_UID, verificationParams.getOriginatingUid()); } if (verificationParams.getInstallerUid() >= 0) { verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, verificationParams.getInstallerUid()); } } final PackageVerificationState verificationState = new PackageVerificationState( requiredUid, args); mPendingVerification.append(verificationId, verificationState); final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, receivers, verificationState); /* * If any sufficient verifiers were listed in the package * manifest, attempt to ask them. */ if (sufficientVerifiers != null) { final int N = sufficientVerifiers.size(); if (N == 0) { Slog.i(TAG, "Additional verifiers required, but none installed."); ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; } else { for (int i = 0; i < N; i++) { final ComponentName verifierComponent = sufficientVerifiers.get(i); final Intent sufficientIntent = new Intent(verification); sufficientIntent.setComponent(verifierComponent); mContext.sendBroadcastAsUser(sufficientIntent, getUser()); } } } final ComponentName requiredVerifierComponent = matchComponentForVerifier( mRequiredVerifierPackage, receivers); if (ret == PackageManager.INSTALL_SUCCEEDED && mRequiredVerifierPackage != null) { /* * Send the intent to the required verification agent, * but only start the verification timeout after the * target BroadcastReceivers have run. */ verification.setComponent(requiredVerifierComponent); mContext.sendOrderedBroadcastAsUser(verification, getUser(), android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final Message msg = mHandler .obtainMessage(CHECK_PENDING_VERIFICATION); msg.arg1 = verificationId; mHandler.sendMessageDelayed(msg, getVerificationTimeout()); } }, null, 0, null, null); /* * We don't want the copy to proceed until verification * succeeds, so null out this field. */ mArgs = null; } } else { /* * No package verification is enabled, so immediately start * the remote call to initiate copy using temporary file. */ ret = args.copyApk(mContainerService, true); } } mRet = ret; } @Override void handleReturnCode() { // If mArgs is null, then MCS couldn't be reached. When it // reconnects, it will try again to install. At that point, this // will succeed. if (mArgs != null) { processPendingInstall(mArgs, mRet); } } @Override void handleServiceError() { mArgs = createInstallArgs(this); mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; } public boolean isForwardLocked() { return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; } } /** * Used during creation of InstallArgs * * @param installFlags package installation flags * @return true if should be installed on external storage */ private static boolean installOnSd(int installFlags) { if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { return false; } if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { return true; } return false; } /** * Used during creation of InstallArgs * * @param installFlags package installation flags * @return true if should be installed as forward locked */ private static boolean installForwardLocked(int installFlags) { return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; } private InstallArgs createInstallArgs(InstallParams params) { if (installOnSd(params.installFlags) || params.isForwardLocked()) { return new AsecInstallArgs(params); } else { return new FileInstallArgs(params); } } /** * Create args that describe an existing installed package. Typically used * when cleaning up old installs, or used as a move source. */ private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, String resourcePath, String nativeLibraryRoot, String[] instructionSets) { final boolean isInAsec; if (installOnSd(installFlags)) { /* Apps on SD card are always in ASEC containers. */ isInAsec = true; } else if (installForwardLocked(installFlags) && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { /* * Forward-locked apps are only in ASEC containers if they're the * new style */ isInAsec = true; } else { isInAsec = false; } if (isInAsec) { return new AsecInstallArgs(codePath, instructionSets, installOnSd(installFlags), installForwardLocked(installFlags)); } else { return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, instructionSets); } } static abstract class InstallArgs { /** @see InstallParams#origin */ final OriginInfo origin; final IPackageInstallObserver2 observer; // Always refers to PackageManager flags only final int installFlags; final String installerPackageName; final ManifestDigest manifestDigest; final UserHandle user; final String abiOverride; // The list of instruction sets supported by this app. This is currently // only used during the rmdex() phase to clean up resources. We can get rid of this // if we move dex files under the common app path. /* nullable */ String[] instructionSets; InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, String installerPackageName, ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, String abiOverride) { this.origin = origin; this.installFlags = installFlags; this.observer = observer; this.installerPackageName = installerPackageName; this.manifestDigest = manifestDigest; this.user = user; this.instructionSets = instructionSets; this.abiOverride = abiOverride; } abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; abstract int doPreInstall(int status); /** * Rename package into final resting place. All paths on the given * scanned package should be updated to reflect the rename. */ abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); abstract int doPostInstall(int status, int uid); /** @see PackageSettingBase#codePathString */ abstract String getCodePath(); /** @see PackageSettingBase#resourcePathString */ abstract String getResourcePath(); abstract String getLegacyNativeLibraryPath(); // Need installer lock especially for dex file removal. abstract void cleanUpResourcesLI(); abstract boolean doPostDeleteLI(boolean delete); abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; /** * Called before the source arguments are copied. This is used mostly * for MoveParams when it needs to read the source file to put it in the * destination. */ int doPreCopy() { return PackageManager.INSTALL_SUCCEEDED; } /** * Called after the source arguments are copied. This is used mostly for * MoveParams when it needs to read the source file to put it in the * destination. * * @return */ int doPostCopy(int uid) { return PackageManager.INSTALL_SUCCEEDED; } protected boolean isFwdLocked() { return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; } protected boolean isExternal() { return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; } UserHandle getUser() { return user; } } /** * Logic to handle installation of non-ASEC applications, including copying * and renaming logic. */ class FileInstallArgs extends InstallArgs { private File codeFile; private File resourceFile; private File legacyNativeLibraryPath; // Example topology: // /data/app/com.example/base.apk // /data/app/com.example/split_foo.apk // /data/app/com.example/lib/arm/libfoo.so // /data/app/com.example/lib/arm64/libfoo.so // /data/app/com.example/dalvik/arm/base.apk@classes.dex /** New install */ FileInstallArgs(InstallParams params) { super(params.origin, params.observer, params.installFlags, params.installerPackageName, params.getManifestDigest(), params.getUser(), null /* instruction sets */, params.packageAbiOverride); if (isFwdLocked()) { throw new IllegalArgumentException("Forward locking only supported in ASEC"); } } /** Existing install */ FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, String[] instructionSets) { super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); this.codeFile = (codePath != null) ? new File(codePath) : null; this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? new File(legacyNativeLibraryPath) : null; } boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), isFwdLocked(), abiOverride); final StorageManager storage = StorageManager.from(mContext); return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); } int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { if (origin.staged) { Slog.d(TAG, origin.file + " already staged; skipping copy"); codeFile = origin.file; resourceFile = origin.file; return PackageManager.INSTALL_SUCCEEDED; } try { final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); codeFile = tempDir; resourceFile = tempDir; } catch (IOException e) { Slog.w(TAG, "Failed to create copy file: " + e); return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; } final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { @Override public ParcelFileDescriptor open(String name, int mode) throws RemoteException { if (!FileUtils.isValidExtFilename(name)) { throw new IllegalArgumentException("Invalid filename: " + name); } try { final File file = new File(codeFile, name); final FileDescriptor fd = Os.open(file.getAbsolutePath(), O_RDWR | O_CREAT, 0644); Os.chmod(file.getAbsolutePath(), 0644); return new ParcelFileDescriptor(fd); } catch (ErrnoException e) { throw new RemoteException("Failed to open: " + e.getMessage()); } } }; int ret = PackageManager.INSTALL_SUCCEEDED; ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); if (ret != PackageManager.INSTALL_SUCCEEDED) { Slog.e(TAG, "Failed to copy package"); return ret; } final File libraryRoot = new File(codeFile, LIB_DIR_NAME); NativeLibraryHelper.Handle handle = null; try { handle = NativeLibraryHelper.Handle.create(codeFile); ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, abiOverride); } catch (IOException e) { Slog.e(TAG, "Copying native libraries failed", e); ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; } finally { IoUtils.closeQuietly(handle); } return ret; } int doPreInstall(int status) { if (status != PackageManager.INSTALL_SUCCEEDED) { cleanUp(); } return status; } boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { if (status != PackageManager.INSTALL_SUCCEEDED) { cleanUp(); return false; } else { final File beforeCodeFile = codeFile; final File afterCodeFile = getNextCodePath(pkg.packageName); Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); try { Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); } catch (ErrnoException e) { Slog.d(TAG, "Failed to rename", e); return false; } if (!SELinux.restoreconRecursive(afterCodeFile)) { Slog.d(TAG, "Failed to restorecon"); return false; } // Reflect the rename internally codeFile = afterCodeFile; resourceFile = afterCodeFile; // Reflect the rename in scanned details pkg.codePath = afterCodeFile.getAbsolutePath(); pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, pkg.baseCodePath); pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, pkg.splitCodePaths); // Reflect the rename in app info pkg.applicationInfo.setCodePath(pkg.codePath); pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); pkg.applicationInfo.setResourcePath(pkg.codePath); pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); return true; } } int doPostInstall(int status, int uid) { if (status != PackageManager.INSTALL_SUCCEEDED) { cleanUp(); } return status; } @Override String getCodePath() { return (codeFile != null) ? codeFile.getAbsolutePath() : null; } @Override String getResourcePath() { return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; } @Override String getLegacyNativeLibraryPath() { return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; } private boolean cleanUp() { if (codeFile == null || !codeFile.exists()) { return false; } if (codeFile.isDirectory()) { FileUtils.deleteContents(codeFile); } codeFile.delete(); if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { resourceFile.delete(); } if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); } legacyNativeLibraryPath.delete(); } return true; } void cleanUpResourcesLI() { // Try enumerating all code paths before deleting List<String> allCodePaths = Collections.EMPTY_LIST; if (codeFile != null && codeFile.exists()) { try { final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); allCodePaths = pkg.getAllCodePaths(); } catch (PackageParserException e) { // Ignored; we tried our best } } cleanUp(); if (!allCodePaths.isEmpty()) { if (instructionSets == null) { throw new IllegalStateException("instructionSet == null"); } String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); for (String codePath : allCodePaths) { for (String dexCodeInstructionSet : dexCodeInstructionSets) { int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); if (retCode < 0) { Slog.w(TAG, "Couldn't remove dex file for package: " + " at location " + codePath + ", retcode=" + retCode); // we don't consider this to be a failure of the core package deletion } } } } } boolean doPostDeleteLI(boolean delete) { // XXX err, shouldn't we respect the delete flag? cleanUpResourcesLI(); return true; } } private boolean isAsecExternal(String cid) { final String asecPath = PackageHelper.getSdFilesystem(cid); /** M: [ALPS01264858] Fix system server crash due to sim sd card performance @{ */ if (asecPath != null) { return !asecPath.startsWith(mAsecInternalPath); } else { return false; } /** @} */ } private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws PackageManagerException { if (copyRet < 0) { if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { throw new PackageManagerException(copyRet, message); } } } /** * Extract the MountService "container ID" from the full code path of an * .apk. */ static String cidFromCodePath(String fullCodePath) { int eidx = fullCodePath.lastIndexOf("/"); String subStr1 = fullCodePath.substring(0, eidx); int sidx = subStr1.lastIndexOf("/"); return subStr1.substring(sidx+1, eidx); } /** * Logic to handle installation of ASEC applications, including copying and * renaming logic. */ class AsecInstallArgs extends InstallArgs { static final String RES_FILE_NAME = "pkg.apk"; static final String PUBLIC_RES_FILE_NAME = "res.zip"; String cid; String packagePath; String resourcePath; String legacyNativeLibraryDir; /** New install */ AsecInstallArgs(InstallParams params) { super(params.origin, params.observer, params.installFlags, params.installerPackageName, params.getManifestDigest(), params.getUser(), null /* instruction sets */, params.packageAbiOverride); } /** Existing install */ AsecInstallArgs(String fullCodePath, String[] instructionSets, boolean isExternal, boolean isForwardLocked) { super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, instructionSets, null); // Hackily pretend we're still looking at a full code path if (!fullCodePath.endsWith(RES_FILE_NAME)) { fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); } // Extract cid from fullCodePath int eidx = fullCodePath.lastIndexOf("/"); String subStr1 = fullCodePath.substring(0, eidx); int sidx = subStr1.lastIndexOf("/"); cid = subStr1.substring(sidx+1, eidx); setMountPath(subStr1); } AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, instructionSets, null); this.cid = cid; setMountPath(PackageHelper.getSdDir(cid)); } void createCopyFile() { cid = mInstallerService.allocateExternalStageCidLegacy(); } boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), abiOverride); final File target; if (isExternal()) { target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); } else { target = Environment.getDataDirectory(); } final StorageManager storage = StorageManager.from(mContext); return (sizeBytes <= storage.getStorageBytesUntilLow(target)); } int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { if (origin.staged) { Slog.d(TAG, origin.cid + " already staged; skipping copy"); cid = origin.cid; setMountPath(PackageHelper.getSdDir(cid)); return PackageManager.INSTALL_SUCCEEDED; } if (temp) { createCopyFile(); } else { /* * Pre-emptively destroy the container since it's destroyed if * copying fails due to it existing anyway. */ PackageHelper.destroySdDir(cid); } final String newMountPath = imcs.copyPackageToContainer( origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); if (newMountPath != null) { setMountPath(newMountPath); return PackageManager.INSTALL_SUCCEEDED; } else { return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; } } @Override String getCodePath() { return packagePath; } @Override String getResourcePath() { return resourcePath; } @Override String getLegacyNativeLibraryPath() { return legacyNativeLibraryDir; } int doPreInstall(int status) { if (status != PackageManager.INSTALL_SUCCEEDED) { // Destroy container PackageHelper.destroySdDir(cid); } else { boolean mounted = PackageHelper.isContainerMounted(cid); if (!mounted) { String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID); if (newMountPath != null) { setMountPath(newMountPath); } else { return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; } } } return status; } boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); String newMountPath = null; if (PackageHelper.isContainerMounted(cid)) { // Unmount the container if (!PackageHelper.unMountSdDir(cid)) { Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); return false; } } if (!PackageHelper.renameSdDir(cid, newCacheId)) { Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + " which might be stale. Will try to clean up."); // Clean up the stale container and proceed to recreate. if (!PackageHelper.destroySdDir(newCacheId)) { Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); return false; } // Successfully cleaned up stale container. Try to rename again. if (!PackageHelper.renameSdDir(cid, newCacheId)) { Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + " inspite of cleaning it up."); return false; } } if (!PackageHelper.isContainerMounted(newCacheId)) { Slog.w(TAG, "Mounting container " + newCacheId); newMountPath = PackageHelper.mountSdDir(newCacheId, getEncryptKey(), Process.SYSTEM_UID); } else { newMountPath = PackageHelper.getSdDir(newCacheId); } if (newMountPath == null) { Slog.w(TAG, "Failed to get cache path for " + newCacheId); return false; } Log.i(TAG, "Succesfully renamed " + cid + " to " + newCacheId + " at new path: " + newMountPath); cid = newCacheId; final File beforeCodeFile = new File(packagePath); setMountPath(newMountPath); final File afterCodeFile = new File(packagePath); // Reflect the rename in scanned details pkg.codePath = afterCodeFile.getAbsolutePath(); pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, pkg.baseCodePath); pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, pkg.splitCodePaths); // Reflect the rename in app info pkg.applicationInfo.setCodePath(pkg.codePath); pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); pkg.applicationInfo.setResourcePath(pkg.codePath); pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); return true; } private void setMountPath(String mountPath) { final File mountFile = new File(mountPath); final File monolithicFile = new File(mountFile, RES_FILE_NAME); if (monolithicFile.exists()) { packagePath = monolithicFile.getAbsolutePath(); if (isFwdLocked()) { resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); } else { resourcePath = packagePath; } } else { packagePath = mountFile.getAbsolutePath(); resourcePath = packagePath; } legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); } int doPostInstall(int status, int uid) { if (status != PackageManager.INSTALL_SUCCEEDED) { cleanUp(); } else { final int groupOwner; final String protectedFile; if (isFwdLocked()) { groupOwner = UserHandle.getSharedAppGid(uid); protectedFile = RES_FILE_NAME; } else { groupOwner = -1; protectedFile = null; } if (uid < Process.FIRST_APPLICATION_UID || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { Slog.e(TAG, "Failed to finalize " + cid); PackageHelper.destroySdDir(cid); return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; } boolean mounted = PackageHelper.isContainerMounted(cid); if (!mounted) { PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); } } return status; } private void cleanUp() { if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); // Destroy secure container PackageHelper.destroySdDir(cid); } private List<String> getAllCodePaths() { final File codeFile = new File(getCodePath()); if (codeFile != null && codeFile.exists()) { try { final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); return pkg.getAllCodePaths(); } catch (PackageParserException e) { // Ignored; we tried our best } } return Collections.EMPTY_LIST; } void cleanUpResourcesLI() { // Enumerate all code paths before deleting cleanUpResourcesLI(getAllCodePaths()); } private void cleanUpResourcesLI(List<String> allCodePaths) { cleanUp(); if (!allCodePaths.isEmpty()) { if (instructionSets == null) { throw new IllegalStateException("instructionSet == null"); } String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); for (String codePath : allCodePaths) { for (String dexCodeInstructionSet : dexCodeInstructionSets) { int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); if (retCode < 0) { Slog.w(TAG, "Couldn't remove dex file for package: " + " at location " + codePath + ", retcode=" + retCode); // we don't consider this to be a failure of the core package deletion } } } } } boolean matchContainer(String app) { if (cid.startsWith(app)) { return true; } return false; } String getPackageName() { return getAsecPackageName(cid); } boolean doPostDeleteLI(boolean delete) { if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); final List<String> allCodePaths = getAllCodePaths(); boolean mounted = PackageHelper.isContainerMounted(cid); if (mounted) { // Unmount first if (PackageHelper.unMountSdDir(cid)) { mounted = false; } } if (!mounted && delete) { cleanUpResourcesLI(allCodePaths); } return !mounted; } @Override int doPreCopy() { if (isFwdLocked()) { if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; } } return PackageManager.INSTALL_SUCCEEDED; } @Override int doPostCopy(int uid) { if (isFwdLocked()) { if (uid < Process.FIRST_APPLICATION_UID || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), RES_FILE_NAME)) { Slog.e(TAG, "Failed to finalize " + cid); PackageHelper.destroySdDir(cid); return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; } } return PackageManager.INSTALL_SUCCEEDED; } } static String getAsecPackageName(String packageCid) { int idx = packageCid.lastIndexOf("-"); if (idx == -1) { return packageCid; } return packageCid.substring(0, idx); } // Utility method used to create code paths based on package name and available index. private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { String idxStr = ""; int idx = 1; // Fall back to default value of idx=1 if prefix is not // part of oldCodePath if (oldCodePath != null) { String subStr = oldCodePath; // Drop the suffix right away if (suffix != null && subStr.endsWith(suffix)) { subStr = subStr.substring(0, subStr.length() - suffix.length()); } // If oldCodePath already contains prefix find out the // ending index to either increment or decrement. int sidx = subStr.lastIndexOf(prefix); if (sidx != -1) { subStr = subStr.substring(sidx + prefix.length()); if (subStr != null) { if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); } try { idx = Integer.parseInt(subStr); if (idx <= 1) { idx++; } else { idx--; } } catch(NumberFormatException e) { } } } } idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); return prefix + idxStr; } private File getNextCodePath(String packageName) { int suffix = 1; File result; do { result = new File(mAppInstallDir, packageName + "-" + suffix); suffix++; } while (result.exists()); return result; } // Utility method used to ignore ADD/REMOVE events // by directory observer. private static boolean ignoreCodePath(String fullPathStr) { String apkName = deriveCodePathName(fullPathStr); int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); if (idx != -1 && ((idx+1) < apkName.length())) { // Make sure the package ends with a numeral String version = apkName.substring(idx+1); try { Integer.parseInt(version); return true; } catch (NumberFormatException e) {} } return false; } // Utility method that returns the relative package path with respect // to the installation directory. Like say for /data/data/com.test-1.apk // string com.test-1 is returned. static String deriveCodePathName(String codePath) { if (codePath == null) { return null; } final File codeFile = new File(codePath); final String name = codeFile.getName(); if (codeFile.isDirectory()) { return name; } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { final int lastDot = name.lastIndexOf('.'); return name.substring(0, lastDot); } else { Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); return null; } } class PackageInstalledInfo { String name; int uid; // The set of users that originally had this package installed. int[] origUsers; // The set of users that now have this package installed. int[] newUsers; PackageParser.Package pkg; int returnCode; String returnMsg; PackageRemovedInfo removedInfo; public void setError(int code, String msg) { returnCode = code; returnMsg = msg; Slog.w(TAG, msg); } public void setError(String msg, PackageParserException e) { returnCode = e.error; returnMsg = ExceptionUtils.getCompleteMessage(msg, e); Slog.w(TAG, msg, e); } public void setError(String msg, PackageManagerException e) { returnCode = e.error; returnMsg = ExceptionUtils.getCompleteMessage(msg, e); Slog.w(TAG, msg, e); } // In some error cases we want to convey more info back to the observer String origPackage; String origPermission; } /* * Install a non-existing package. */ private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, String installerPackageName, PackageInstalledInfo res) { // Remember this for later, in case we need to rollback this install String pkgName = pkg.packageName; if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); synchronized(mPackages) { if (mSettings.mRenamedPackages.containsKey(pkgName)) { // A package with the same name is already installed, though // it has been renamed to an older name. The package we // are trying to install should be installed as an update to // the existing one, but that has not been requested, so bail. res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName + " without first uninstalling package running as " + mSettings.mRenamedPackages.get(pkgName)); return; } if (mPackages.containsKey(pkgName)) { // Don't allow installation over an existing package with the same name. res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName + " without first uninstalling."); return; } } try { PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, System.currentTimeMillis(), user); updateSettingsLI(newPackage, installerPackageName, null, null, res); // delete the partially installed application. the data directory will have to be // restored if it was already existing if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { // remove package from internal structures. Note that we want deletePackageX to // delete the package data and cache directories that it created in // scanPackageLocked, unless those directories existed before we even tried to // install. deletePackageLI(pkgName, UserHandle.ALL, false, null, null, dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, res.removedInfo, true); } } catch (PackageManagerException e) { res.setError("Package couldn't be installed in " + pkg.codePath, e); } } private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { // Upgrade keysets are being used. Determine if new package has a superset of the // required keys. long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); KeySetManagerService ksms = mSettings.mKeySetManagerService; for (int i = 0; i < upgradeKeySets.length; i++) { Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); if (newPkg.mSigningKeys.containsAll(upgradeSet)) { return true; } } return false; } private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, String installerPackageName, PackageInstalledInfo res) { PackageParser.Package oldPackage; String pkgName = pkg.packageName; int[] allUsers; boolean[] perUserInstalled; // First find the old package info and check signatures synchronized(mPackages) { oldPackage = mPackages.get(pkgName); if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); PackageSetting ps = mSettings.mPackages.get(pkgName); if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { // default to original signature matching if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, "New package has a different signature: " + pkgName); return; } } else { if(!checkUpgradeKeySetLP(ps, pkg)) { res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, "New package not signed by keys specified by upgrade-keysets: " + pkgName); return; } } // In case of rollback, remember per-user/profile install state allUsers = sUserManager.getUserIds(); perUserInstalled = new boolean[allUsers.length]; for (int i = 0; i < allUsers.length; i++) { perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; } } /// M: [Operator] Operator package replacing will be handled as system package boolean sysPkg = (isSystemApp(oldPackage) || isVendorApp(oldPackage)); if (sysPkg) { replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, user, allUsers, perUserInstalled, installerPackageName, res); } else { replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, user, allUsers, perUserInstalled, installerPackageName, res); } } private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, int[] allUsers, boolean[] perUserInstalled, String installerPackageName, PackageInstalledInfo res) { String pkgName = deletedPackage.packageName; boolean deletedPkg = true; boolean updatedSettings = false; if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" + deletedPackage); long origUpdateTime; if (pkg.mExtras != null) { origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; } else { origUpdateTime = 0; } // First delete the existing package while retaining the data directory if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, res.removedInfo, true)) { // If the existing package wasn't successfully deleted res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); deletedPkg = false; } else { // Successfully deleted the old package; proceed with replace. // If deleted package lived in a container, give users a chance to // relinquish resources before killing. if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { if (DEBUG_INSTALL) { Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); } final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; final ArrayList<String> pkgList = new ArrayList<String>(1); pkgList.add(deletedPackage.applicationInfo.packageName); sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); } deleteCodeCacheDirsLI(pkgName); try { final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); updatedSettings = true; } catch (PackageManagerException e) { res.setError("Package couldn't be installed in " + pkg.codePath, e); } } if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { // remove package from internal structures. Note that we want deletePackageX to // delete the package data and cache directories that it created in // scanPackageLocked, unless those directories existed before we even tried to // install. if(updatedSettings) { if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); deletePackageLI( pkgName, null, true, allUsers, perUserInstalled, PackageManager.DELETE_KEEP_DATA, res.removedInfo, true); } // Since we failed to install the new package we need to restore the old // package that we deleted. if (deletedPkg) { if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); File restoreFile = new File(deletedPackage.codePath); // Parse old package boolean oldOnSd = isExternal(deletedPackage); int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; try { scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); } catch (PackageManagerException e) { Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " + e.getMessage()); return; } // Restore of old package succeeded. Update permissions. // writer synchronized (mPackages) { updatePermissionsLPw(deletedPackage.packageName, deletedPackage, UPDATE_PERMISSIONS_ALL); // can downgrade to reader mSettings.writeLPr(); } Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); } } } private void replaceSystemPackageLI(PackageParser.Package deletedPackage, PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, int[] allUsers, boolean[] perUserInstalled, String installerPackageName, PackageInstalledInfo res) { if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg + ", old=" + deletedPackage); boolean disabledSystem = false; boolean updatedSettings = false; /** M: [Operator] Flag to indicate a operator package @{ */ boolean vendorApp = isVendorApp(deletedPackage); /// M: [Operator] Parse flag is different between operator and system package if (vendorApp) { parseFlags |= PackageParser.PARSE_IS_OPERATOR; } else { parseFlags |= PackageParser.PARSE_IS_SYSTEM; if ((deletedPackage.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; } } /** @} */ String packageName = deletedPackage.packageName; if (packageName == null) { res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "Attempt to delete null packageName."); return; } PackageParser.Package oldPkg; PackageSetting oldPkgSetting; /** M: [Operator] Record if the operator package is uninstalled last time@{ */ boolean oldPkgInstalled = true; /** @} */ // reader synchronized (mPackages) { oldPkg = mPackages.get(packageName); oldPkgSetting = mSettings.mPackages.get(packageName); if((oldPkg == null) || (oldPkg.applicationInfo == null) || (oldPkgSetting == null)) { res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "Couldn't find package:" + packageName + " information"); return; } /** M: [Operator] If the old package is not installed for current user, it must be an operator app @{ */ oldPkgInstalled = oldPkgSetting.getInstalled(UserHandle.myUserId()); /** @} */ } killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); res.removedInfo.uid = oldPkg.applicationInfo.uid; res.removedInfo.removedPackage = packageName; // Remove existing system package removePackageLI(oldPkgSetting, true); // writer synchronized (mPackages) { disabledSystem = mSettings.disableSystemPackageLPw(packageName); if (!disabledSystem && deletedPackage != null) { // We didn't need to disable the .apk as a current system package, // which means we are replacing another update that is already // installed. We need to make sure to delete the older one's .apk. res.removedInfo.args = createInstallArgsForExisting(0, deletedPackage.applicationInfo.getCodePath(), deletedPackage.applicationInfo.getResourcePath(), deletedPackage.applicationInfo.nativeLibraryRootDir, getAppDexInstructionSets(deletedPackage.applicationInfo)); } else { res.removedInfo.args = null; } } // Successfully disabled the old package. Now proceed with re-installation deleteCodeCacheDirsLI(packageName); res.returnCode = PackageManager.INSTALL_SUCCEEDED; /** M: [Operator] Operator package should not have FLAG_UPDATED_SYSTEM_APP @{ */ if (!vendorApp) { pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; } /** @} */ PackageParser.Package newPackage = null; try { newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); if (newPackage.mExtras != null) { final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; newPkgSetting.lastUpdateTime = System.currentTimeMillis(); // is the update attempting to change shared user? that isn't going to work... if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, "Forbidding shared user change from " + oldPkgSetting.sharedUser + " to " + newPkgSetting.sharedUser); updatedSettings = true; } } if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); updatedSettings = true; } } catch (PackageManagerException e) { res.setError("Package couldn't be installed in " + pkg.codePath, e); } if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { // Re installation failed. Restore old information // Remove new pkg information if (newPackage != null) { removeInstalledPackageLI(newPackage, true); } // Add back the old system package try { scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); } catch (PackageManagerException e) { Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); } // Restore the old system information in Settings synchronized (mPackages) { if (disabledSystem) { mSettings.enableSystemPackageLPw(packageName); } if (updatedSettings) { mSettings.setInstallerPackageName(packageName, oldPkgSetting.installerPackageName); } /** M: [Operator] Keep the old package's install status when it is added back @{ */ if (!oldPkgInstalled) { oldPkgSetting = mSettings.mPackages.get(packageName); if (oldPkgSetting != null) { oldPkgSetting.setUserState(UserHandle.myUserId(), COMPONENT_ENABLED_STATE_DEFAULT, false, //notInstalled true, //stopped true, //notLaunched false, //blocked null, null, null, false // blockUninstall ); } } /** @} */ mSettings.writeLPr(); } } } private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res) { String pkgName = newPackage.packageName; synchronized (mPackages) { //write settings. the installStatus will be incomplete at this stage. //note that the new package setting would have already been //added to mPackages. It hasn't been persisted yet. mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); mSettings.writeLPr(); } if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); synchronized (mPackages) { updatePermissionsLPw(newPackage.packageName, newPackage, UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0)); // For system-bundled packages, we assume that installing an upgraded version // of the package implies that the user actually wants to run that new code, // so we enable the package. if (isSystemApp(newPackage)) { // NB: implicit assumption that system package upgrades apply to all users if (DEBUG_INSTALL) { Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); } PackageSetting ps = mSettings.mPackages.get(pkgName); if (ps != null) { if (res.origUsers != null) { for (int userHandle : res.origUsers) { ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userHandle, installerPackageName); } } // Also convey the prior install/uninstall state if (allUsers != null && perUserInstalled != null) { for (int i = 0; i < allUsers.length; i++) { if (DEBUG_INSTALL) { Slog.d(TAG, " user " + allUsers[i] + " => " + perUserInstalled[i]); } ps.setInstalled(perUserInstalled[i], allUsers[i]); } // these install state changes will be persisted in the // upcoming call to mSettings.writeLPr(). } } } res.name = pkgName; res.uid = newPackage.applicationInfo.uid; res.pkg = newPackage; mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); mSettings.setInstallerPackageName(pkgName, installerPackageName); res.returnCode = PackageManager.INSTALL_SUCCEEDED; //to update install status mSettings.writeLPr(); } } private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { final int installFlags = args.installFlags; String installerPackageName = args.installerPackageName; File tmpPackageFile = new File(args.getCodePath()); boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); boolean replace = false; final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; // Result object to be returned res.returnCode = PackageManager.INSTALL_SUCCEEDED; if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); // Retrieve PackageSettings and parse package final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); PackageParser pp = new PackageParser(); pp.setSeparateProcesses(mSeparateProcesses); pp.setDisplayMetrics(mMetrics); final PackageParser.Package pkg; try { if (DEBUG_INSTALL) Slog.i(TAG, "Start parsing apk: " + installerPackageName); pkg = pp.parsePackage(tmpPackageFile, parseFlags); if (DEBUG_INSTALL) Slog.i(TAG, "Parsing done for apk: " + installerPackageName); } catch (PackageParserException e) { res.setError("Failed parse during installPackageLI", e); return; } // Mark that we have an install time CPU ABI override. pkg.cpuAbiOverride = args.abiOverride; String pkgName = res.name = pkg.packageName; if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); return; } } try { pp.collectCertificates(pkg, parseFlags); pp.collectManifestDigest(pkg); } catch (PackageParserException e) { res.setError("Failed collect during installPackageLI", e); return; } /* If the installer passed in a manifest digest, compare it now. */ if (args.manifestDigest != null) { if (DEBUG_INSTALL) { final String parsedManifest = pkg.manifestDigest == null ? "null" : pkg.manifestDigest.toString(); Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " + parsedManifest); } if (!args.manifestDigest.equals(pkg.manifestDigest)) { res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); return; } } else if (DEBUG_INSTALL) { final String parsedManifest = pkg.manifestDigest == null ? "null" : pkg.manifestDigest.toString(); Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); } // Get rid of all references to package scan path via parser. pp = null; String oldCodePath = null; boolean systemApp = false; /// M: [Operator] record if the original package is an operator package boolean vendorApp = false; synchronized (mPackages) { // Check whether the newly-scanned package wants to define an already-defined perm int N = pkg.permissions.size(); for (int i = N-1; i >= 0; i--) { PackageParser.Permission perm = pkg.permissions.get(i); BasePermission bp = mSettings.mPermissions.get(perm.info.name); if (bp != null) { // If the defining package is signed with our cert, it's okay. This // also includes the "updating the same package" case, of course. // "updating same package" could also involve key-rotation. final boolean sigsOk; if (!bp.sourcePackage.equals(pkg.packageName) || !(bp.packageSetting instanceof PackageSetting) || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() || ((PackageSetting) bp.packageSetting).sharedUser != null) { sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; } else { sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); } if (!sigsOk) { // If the owning package is the system itself, we log but allow // install to proceed; we fail the install on all other permission // redefinitions. if (!bp.sourcePackage.equals("android")) { res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " + pkg.packageName + " attempting to redeclare permission " + perm.info.name + " already owned by " + bp.sourcePackage); res.origPermission = perm.info.name; res.origPackage = bp.sourcePackage; return; } else { Slog.w(TAG, "Package " + pkg.packageName + " attempting to redeclare system permission " + perm.info.name + "; ignoring new declaration"); pkg.permissions.remove(i); } } } } // Check if installing already existing package if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { String oldName = mSettings.mRenamedPackages.get(pkgName); if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName) && mPackages.containsKey(oldName)) { // This package is derived from an original package, // and this device has been updating from that original // name. We must continue using the original name, so // rename the new package here. pkg.setPackageName(oldName); pkgName = pkg.packageName; replace = true; if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" + oldName + " pkgName=" + pkgName); } else if (mPackages.containsKey(pkgName)) { // This package, under its official name, already exists // on the device; we should replace it. replace = true; if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); } } PackageSetting ps = mSettings.mPackages.get(pkgName); if (ps != null) { if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); oldCodePath = mSettings.mPackages.get(pkgName).codePathString; if (ps.pkg != null && ps.pkg.applicationInfo != null) { systemApp = (ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; vendorApp = isVendorApp(ps.pkg); } res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); } } /// M: [Operator] Updated operator apps can only be installed on data storage if ((systemApp || vendorApp) && onSd) { // Disable updates to system apps on sdcard res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, "Cannot install updates to system or vendor apps on sdcard"); return; } if (!args.doRename(res.returnCode, pkg, oldCodePath)) { res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); return; } if (DEBUG_INSTALL) Slog.i(TAG, "Start installation for package: " + installerPackageName); if (replace) { replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, installerPackageName, res); } else { installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, args.user, installerPackageName, res); } if (DEBUG_INSTALL) Slog.i(TAG, "Installation done for package: " + installerPackageName); synchronized (mPackages) { final PackageSetting ps = mSettings.mPackages.get(pkgName); if (ps != null) { res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); } } } private static boolean isForwardLocked(PackageParser.Package pkg) { return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; } private static boolean isForwardLocked(ApplicationInfo info) { return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; } private boolean isForwardLocked(PackageSetting ps) { return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; } private static boolean isMultiArch(PackageSetting ps) { return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; } private static boolean isMultiArch(ApplicationInfo info) { return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; } private static boolean isExternal(PackageParser.Package pkg) { return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; } private static boolean isExternal(PackageSetting ps) { return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; } private static boolean isExternal(ApplicationInfo info) { return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; } private static boolean isSystemApp(PackageParser.Package pkg) { return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; } private static boolean isPrivilegedApp(PackageParser.Package pkg) { return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; } private static boolean isSystemApp(ApplicationInfo info) { return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; } private static boolean isSystemApp(PackageSetting ps) { return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; } private static boolean isUpdatedSystemApp(PackageSetting ps) { return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; } private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; } /** M: [Operator] Util function for operator app @{ */ static boolean locationIsOperator(File path) { if (path != null) { try { return path.getCanonicalPath().contains("vendor/operator/app"); } catch (IOException e) { Slog.e(TAG, "Unable to access code path " + path); } } return false; } static boolean isVendorApp(PackageSetting ps) { return (ps.pkgFlagsEx & ApplicationInfo.FLAG_EX_OPERATOR) != 0; } static boolean isVendorApp(PackageParser.Package pkg) { return (pkg.applicationInfo.flagsEx & ApplicationInfo.FLAG_EX_OPERATOR) != 0; } static boolean isVendorApp(ApplicationInfo info) { return (info.flagsEx & ApplicationInfo.FLAG_EX_OPERATOR) != 0; } /** @} */ private static boolean isUpdatedSystemApp(ApplicationInfo info) { return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; } private int packageFlagsToInstallFlags(PackageSetting ps) { int installFlags = 0; if (isExternal(ps)) { installFlags |= PackageManager.INSTALL_EXTERNAL; } if (isForwardLocked(ps)) { installFlags |= PackageManager.INSTALL_FORWARD_LOCK; } return installFlags; } private void deleteTempPackageFiles() { final FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("vmdl") && name.endsWith(".tmp"); } }; for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { file.delete(); } } @Override public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, int flags) { deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); } @Override public void deletePackage(final String packageName, final IPackageDeleteObserver2 observer, final int userId, final int flags) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.DELETE_PACKAGES, null); final int uid = Binder.getCallingUid(); if (UserHandle.getUserId(uid) != userId) { mContext.enforceCallingPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "deletePackage for user " + userId); } if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { try { observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED, null); } catch (RemoteException re) { } return; } boolean uninstallBlocked = false; if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { int[] users = sUserManager.getUserIds(); for (int i = 0; i < users.length; ++i) { if (getBlockUninstallForUser(packageName, users[i])) { uninstallBlocked = true; break; } } } else { uninstallBlocked = getBlockUninstallForUser(packageName, userId); } if (uninstallBlocked) { try { observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); } catch (RemoteException re) { } return; } if (DEBUG_REMOVE) { Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); } // Queue up an async operation since the package deletion may take a little while. mHandler.post(new Runnable() { public void run() { mHandler.removeCallbacks(this); final int returnCode = deletePackageX(packageName, userId, flags); if (observer != null) { try { observer.onPackageDeleted(packageName, returnCode, null); } catch (RemoteException e) { Log.i(TAG, "Observer no longer exists."); } //end catch } //end if } //end run }); } private boolean isPackageDeviceAdmin(String packageName, int userId) { IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); try { if (dpm != null) { if (dpm.isDeviceOwner(packageName)) { return true; } int[] users; if (userId == UserHandle.USER_ALL) { users = sUserManager.getUserIds(); } else { users = new int[]{userId}; } for (int i = 0; i < users.length; ++i) { if (dpm.packageHasActiveAdmins(packageName, users[i])) { return true; } } } } catch (RemoteException e) { } return false; } /** * This method is an internal method that could be get invoked either * to delete an installed package or to clean up a failed installation. * After deleting an installed package, a broadcast is sent to notify any * listeners that the package has been installed. For cleaning up a failed * installation, the broadcast is not necessary since the package's * installation wouldn't have sent the initial broadcast either * The key steps in deleting a package are * deleting the package information in internal structures like mPackages, * deleting the packages base directories through installd * updating mSettings to reflect current status * persisting settings for later use * sending a broadcast if necessary */ private int deletePackageX(String packageName, int userId, int flags) { final PackageRemovedInfo info = new PackageRemovedInfo(); final boolean res; final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 ? UserHandle.ALL : new UserHandle(userId); if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; } boolean removedForAllUsers = false; boolean systemUpdate = false; // for the uninstall-updates case and restricted profiles, remember the per- // userhandle installed state int[] allUsers; boolean[] perUserInstalled; synchronized (mPackages) { PackageSetting ps = mSettings.mPackages.get(packageName); allUsers = sUserManager.getUserIds(); perUserInstalled = new boolean[allUsers.length]; for (int i = 0; i < allUsers.length; i++) { perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; } } synchronized (mInstallLock) { if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled, flags | REMOVE_CHATTY, info, true); systemUpdate = info.isRemovedPackageSystemUpdate; if (res && !systemUpdate && mPackages.get(packageName) == null) { removedForAllUsers = true; } if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate + " removedForAllUsers=" + removedForAllUsers); } if (res) { info.sendBroadcast(true, systemUpdate, removedForAllUsers); // If the removed package was a system update, the old system package // was re-enabled; we need to broadcast this information if (systemUpdate) { Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 ? info.removedAppId : info.uid); extras.putBoolean(Intent.EXTRA_REPLACING, true); sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null, null, null); sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null, null, null); sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, null, packageName, null, null); } else { /* M: [ALPS00457351] Java (JE),3173,-1361051648,99,/data/core/,0,system_server_crash,system_server.(4/5) @{ * Send pending broadcasts for deleted package is meaningless. */ //mPendingBroadcasts.remove(packageName); /// @} 2013-01-31 } } // Force a gc here. Runtime.getRuntime().gc(); // Delete the resources here after sending the broadcast to let // other processes clean up before deleting resources. if (info.args != null) { synchronized (mInstallLock) { info.args.doPostDeleteLI(true); } } return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; } static class PackageRemovedInfo { String removedPackage; int uid = -1; int removedAppId = -1; int[] removedUsers = null; boolean isRemovedPackageSystemUpdate = false; // Clean up resources deleted packages. InstallArgs args = null; void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); if (replacing) { extras.putBoolean(Intent.EXTRA_REPLACING, true); } extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); if (removedPackage != null) { sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null, null, removedUsers); if (fullRemove && !replacing) { sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, extras, null, null, removedUsers); } } if (removedAppId >= 0) { sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, removedUsers); } } } /* * This method deletes the package from internal data structures. If the DONT_DELETE_DATA * flag is not set, the data directory is removed as well. * make sure this flag is set for partially installed apps. If not its meaningless to * delete a partially installed application. */ private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, boolean[] perUserInstalled, PackageRemovedInfo outInfo, int flags, boolean writeSettings) { String packageName = ps.name; if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); // Retrieve object to delete permissions for shared user later on final PackageSetting deletedPs; // reader synchronized (mPackages) { deletedPs = mSettings.mPackages.get(packageName); if (outInfo != null) { outInfo.removedPackage = packageName; outInfo.removedUsers = deletedPs != null ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) : null; } } if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { removeDataDirsLI(packageName); schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); } // writer synchronized (mPackages) { if (deletedPs != null) { if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { if (outInfo != null) { mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); outInfo.removedAppId = mSettings.removePackageLPw(packageName); } if (deletedPs != null) { updatePermissionsLPw(deletedPs.name, null, 0); if (deletedPs.sharedUser != null) { // remove permissions associated with package mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); } } clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); } // make sure to preserve per-user disabled state if this removal was just // a downgrade of a system app to the factory package if (allUserHandles != null && perUserInstalled != null) { if (DEBUG_REMOVE) { Slog.d(TAG, "Propagating install state across downgrade"); } for (int i = 0; i < allUserHandles.length; i++) { if (DEBUG_REMOVE) { Slog.d(TAG, " user " + allUserHandles[i] + " => " + perUserInstalled[i]); } ps.setInstalled(perUserInstalled[i], allUserHandles[i]); } } } // can downgrade to reader if (writeSettings) { // Save settings now mSettings.writeLPr(); } } if (outInfo != null) { // A user ID was deleted here. Go through all users and remove it // from KeyStore. removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); } } static boolean locationIsPrivileged(File path) { try { final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") .getCanonicalPath(); return path.getCanonicalPath().startsWith(privilegedAppDir); } catch (IOException e) { Slog.e(TAG, "Unable to access code path " + path); } return false; } /* * Tries to delete system package. */ /// M: [Operator] This function also used to process uninstallation of operator package private boolean deleteSystemPackageLI(PackageSetting newPs, int[] allUserHandles, boolean[] perUserInstalled, int flags, PackageRemovedInfo outInfo, boolean writeSettings) { final boolean applyUserRestrictions = (allUserHandles != null) && (perUserInstalled != null); /// M: [Operator] Flag to show whether the deleting package is operator package boolean isVendor = isVendorApp(newPs); PackageSetting disabledPs = null; // Confirm if the system package has been updated // An updated system app can be deleted. This will also have to restore // the system pkg from system partition // reader synchronized (mPackages) { disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); } if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs + " disabledPs=" + disabledPs); if (disabledPs == null) { Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); return false; } else if (DEBUG_REMOVE) { Slog.d(TAG, "Deleting system pkg from data partition"); } if (DEBUG_REMOVE) { if (applyUserRestrictions) { Slog.d(TAG, "Remembering install states:"); for (int i = 0; i < allUserHandles.length; i++) { Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); } } } /// M: [Operator] Operator apps shuold not have this flag. We need to send the right broadcast if (!isVendor) { // Delete the updated package outInfo.isRemovedPackageSystemUpdate = true; } if (disabledPs.versionCode < newPs.versionCode) { // Delete data for downgrades flags &= ~PackageManager.DELETE_KEEP_DATA; } else { // Preserve data by setting flag flags |= PackageManager.DELETE_KEEP_DATA; } boolean ret = deleteInstalledPackageLI(newPs, true, flags, allUserHandles, perUserInstalled, outInfo, writeSettings); if (!ret) { return false; } // writer synchronized (mPackages) { // Reinstate the old system package mSettings.enableSystemPackageLPw(newPs.name); // Remove any native libraries from the upgraded package. NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); } // Install the system package if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); /** M: [Operator] Package parse flag is different between operator package and system package @{ */ int parseFlags = PackageParser.PARSE_MUST_BE_APK; if (isVendor) { parseFlags |= PackageParser.PARSE_IS_OPERATOR; } else { parseFlags |= PackageParser.PARSE_IS_SYSTEM; if (locationIsPrivileged(disabledPs.codePath)) { parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; } } /** @} */ final PackageParser.Package newPkg; try { newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); } catch (PackageManagerException e) { Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); return false; } // writer synchronized (mPackages) { PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); updatePermissionsLPw(newPkg.packageName, newPkg, UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); if (applyUserRestrictions) { if (DEBUG_REMOVE) { Slog.d(TAG, "Propagating install state across reinstall"); } for (int i = 0; i < allUserHandles.length; i++) { if (DEBUG_REMOVE) { Slog.d(TAG, " user " + allUserHandles[i] + " => " + perUserInstalled[i]); } ps.setInstalled(perUserInstalled[i], allUserHandles[i]); } // Regardless of writeSettings we need to ensure that this restriction // state propagation is persisted mSettings.writeAllUsersPackageRestrictionsLPr(); } // can downgrade to reader here if (writeSettings) { mSettings.writeLPr(); } } return true; } private boolean deleteInstalledPackageLI(PackageSetting ps, boolean deleteCodeAndResources, int flags, int[] allUserHandles, boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings) { if (outInfo != null) { outInfo.uid = ps.appId; } // Delete package data from internal structures and also remove data if flag is set removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); // Delete application code and resources if (deleteCodeAndResources && (outInfo != null)) { outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, getAppDexInstructionSets(ps)); if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); } return true; } @Override public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, int userId) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.DELETE_PACKAGES, null); synchronized (mPackages) { PackageSetting ps = mSettings.mPackages.get(packageName); if (ps == null) { Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); return false; } if (!ps.getInstalled(userId)) { // Can't block uninstall for an app that is not installed or enabled. Log.i(TAG, "Package not installed in set block uninstall " + packageName); return false; } ps.setBlockUninstall(blockUninstall, userId); mSettings.writePackageRestrictionsLPr(userId); } return true; } @Override public boolean getBlockUninstallForUser(String packageName, int userId) { synchronized (mPackages) { PackageSetting ps = mSettings.mPackages.get(packageName); if (ps == null) { Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); return false; } return ps.getBlockUninstall(userId); } } /* * This method handles package deletion in general */ private boolean deletePackageLI(String packageName, UserHandle user, boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, int flags, PackageRemovedInfo outInfo, boolean writeSettings) { if (packageName == null) { Slog.w(TAG, "Attempt to delete null packageName."); return false; } if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); PackageSetting ps; /// M: [Operator]PackageSetting to record updated operator package PackageSetting updatedVendorPackage = null; boolean dataOnly = false; int removeUser = -1; int appId = -1; synchronized (mPackages) { ps = mSettings.mPackages.get(packageName); if (ps == null) { Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); return false; } if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null && user.getIdentifier() != UserHandle.USER_ALL) { // The caller is asking that the package only be deleted for a single // user. To do this, we just mark its uninstalled state and delete // its data. If this is a system app, we only allow this to happen if // they have set the special DELETE_SYSTEM_APP which requests different // semantics than normal for uninstalling system apps. if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); ps.setUserState(user.getIdentifier(), COMPONENT_ENABLED_STATE_DEFAULT, false, //installed true, //stopped true, //notLaunched false, //hidden null, null, null, false // blockUninstall ); if (!isSystemApp(ps)) { if (ps.isAnyInstalled(sUserManager.getUserIds()) || isVendorApp(ps)) { // Other user still have this package installed, so all // we need to do is clear this user's data and save that // it is uninstalled. if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); removeUser = user.getIdentifier(); appId = ps.appId; mSettings.writePackageRestrictionsLPr(removeUser); /// M: [Operator] if the operator package has been updated, /// we should remove the updated one by keeping removeUser equals to -1 updatedVendorPackage = mSettings.getDisabledSystemPkgLPr(packageName); if (updatedVendorPackage != null) { removeUser = -1; } } else { // We need to set it back to 'installed' so the uninstall // broadcasts will be sent correctly. if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); ps.setInstalled(true, user.getIdentifier()); } } else { // This is a system app, so we assume that the // other users still have this package installed, so all // we need to do is clear this user's data and save that // it is uninstalled. if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); removeUser = user.getIdentifier(); appId = ps.appId; mSettings.writePackageRestrictionsLPr(removeUser); } } } if (removeUser >= 0) { // From above, we determined that we are deleting this only // for a single user. Continue the work here. if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); if (outInfo != null) { outInfo.removedPackage = packageName; outInfo.removedAppId = appId; outInfo.removedUsers = new int[] {removeUser}; } mInstaller.clearUserData(packageName, removeUser); removeKeystoreDataIfNeeded(removeUser, appId); schedulePackageCleaning(packageName, removeUser, false); return true; } if (dataOnly) { // Delete application data first if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); return true; } boolean ret = false; /// M: [Operator] We also handle operator package uninstallation here if (isSystemApp(ps) || isVendorApp(ps)) { Slog.d(TAG, "Removing " + (isVendorApp(ps) ? "Vendor" : "system") + "package: " + ps.name); // When an updated system application is deleted we delete the existing resources as well and // fall back to existing code in system partition ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, flags, outInfo, writeSettings); /// M: [Operator] We need to make the broadcast correct if (isVendorApp(ps) && outInfo != null) { int uninstallUser = (user != null ? user.getIdentifier() : UserHandle.myUserId()); PackageSetting newPs = mSettings.mPackages.get(packageName); if (newPs != null) { newPs.setUserState(uninstallUser, COMPONENT_ENABLED_STATE_DEFAULT, false, //installed true, //stopped true, //notLaunched false, //blocked null, null, null, false // blockUninstall ); } outInfo.removedPackage = packageName; outInfo.removedAppId = appId; outInfo.removedUsers = new int[] {uninstallUser}; /// M: [Operator] Clear original operator package's data for it has been re-installed mInstaller.clearUserData(packageName, removeUser); removeKeystoreDataIfNeeded(removeUser, appId); schedulePackageCleaning(packageName, removeUser, false); } } else { if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); // Kill application pre-emptively especially for apps on sd. killApplication(packageName, ps.appId, "uninstall pkg"); ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, perUserInstalled, outInfo, writeSettings); } return ret; } private final class ClearStorageConnection implements ServiceConnection { IMediaContainerService mContainerService; @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mContainerService = IMediaContainerService.Stub.asInterface(service); notifyAll(); } } @Override public void onServiceDisconnected(ComponentName name) { } } private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { final boolean mounted; if (Environment.isExternalStorageEmulated()) { mounted = true; } else { final String status = Environment.getExternalStorageState(); mounted = status.equals(Environment.MEDIA_MOUNTED) || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); } if (!mounted) { return; } final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); int[] users; if (userId == UserHandle.USER_ALL) { users = sUserManager.getUserIds(); } else { users = new int[] { userId }; } final ClearStorageConnection conn = new ClearStorageConnection(); if (mContext.bindServiceAsUser( containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { try { for (int curUser : users) { long timeout = SystemClock.uptimeMillis() + 5000; synchronized (conn) { long now = SystemClock.uptimeMillis(); while (conn.mContainerService == null && now < timeout) { try { conn.wait(timeout - now); } catch (InterruptedException e) { } } } if (conn.mContainerService == null) { return; } final UserEnvironment userEnv = new UserEnvironment(curUser); clearDirectory(conn.mContainerService, userEnv.buildExternalStorageAppCacheDirs(packageName)); if (allData) { clearDirectory(conn.mContainerService, userEnv.buildExternalStorageAppDataDirs(packageName)); clearDirectory(conn.mContainerService, userEnv.buildExternalStorageAppMediaDirs(packageName)); } } } finally { mContext.unbindService(conn); } } } @Override public void clearApplicationUserData(final String packageName, final IPackageDataObserver observer, final int userId) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.CLEAR_APP_USER_DATA, null); enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); // Queue up an async operation since the package deletion may take a little while. mHandler.post(new Runnable() { public void run() { mHandler.removeCallbacks(this); final boolean succeeded; synchronized (mInstallLock) { succeeded = clearApplicationUserDataLI(packageName, userId); } clearExternalStorageDataSync(packageName, userId, true); if (succeeded) { // invoke DeviceStorageMonitor's update method to clear any notifications DeviceStorageMonitorInternal dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); if (dsm != null) { dsm.checkMemory(); } } if(observer != null) { try { observer.onRemoveCompleted(packageName, succeeded); } catch (RemoteException e) { Log.i(TAG, "Observer no longer exists."); } } //end if observer } //end run }); } private boolean clearApplicationUserDataLI(String packageName, int userId) { if (packageName == null) { Slog.w(TAG, "Attempt to delete null packageName."); return false; } // Try finding details about the requested package PackageParser.Package pkg; synchronized (mPackages) { pkg = mPackages.get(packageName); if (pkg == null) { final PackageSetting ps = mSettings.mPackages.get(packageName); if (ps != null) { pkg = ps.pkg; } } } if (pkg == null) { Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); } // Always delete data directories for package, even if we found no other // record of app. This helps users recover from UID mismatches without // resorting to a full data wipe. int retCode = mInstaller.clearUserData(packageName, userId); if (retCode < 0) { Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); return false; } if (pkg == null) { return false; } if (pkg != null && pkg.applicationInfo != null) { final int appId = pkg.applicationInfo.uid; removeKeystoreDataIfNeeded(userId, appId); } // Create a native library symlink only if we have native libraries // and if the native libraries are 32 bit libraries. We do not provide // this symlink for 64 bit libraries. if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { Slog.w(TAG, "Failed linking native library dir"); return false; } } return true; } /** * Remove entries from the keystore daemon. Will only remove it if the * {@code appId} is valid. */ private static void removeKeystoreDataIfNeeded(int userId, int appId) { if (appId < 0) { return; } final KeyStore keyStore = KeyStore.getInstance(); if (keyStore != null) { if (userId == UserHandle.USER_ALL) { for (final int individual : sUserManager.getUserIds()) { keyStore.clearUid(UserHandle.getUid(individual, appId)); } } else { keyStore.clearUid(UserHandle.getUid(userId, appId)); } } else { Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); } } @Override public void deleteApplicationCacheFiles(final String packageName, final IPackageDataObserver observer) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.DELETE_CACHE_FILES, null); // Queue up an async operation since the package deletion may take a little while. final int userId = UserHandle.getCallingUserId(); mHandler.post(new Runnable() { public void run() { mHandler.removeCallbacks(this); final boolean succeded; synchronized (mInstallLock) { succeded = deleteApplicationCacheFilesLI(packageName, userId); } clearExternalStorageDataSync(packageName, userId, false); if(observer != null) { try { observer.onRemoveCompleted(packageName, succeded); } catch (RemoteException e) { Log.i(TAG, "Observer no longer exists."); } } //end if observer } //end run }); } private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { if (packageName == null) { Slog.w(TAG, "Attempt to delete null packageName."); return false; } PackageParser.Package p; synchronized (mPackages) { p = mPackages.get(packageName); } if (p == null) { Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); return false; } final ApplicationInfo applicationInfo = p.applicationInfo; if (applicationInfo == null) { Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); return false; } int retCode = mInstaller.deleteCacheFiles(packageName, userId); if (retCode < 0) { Slog.w(TAG, "Couldn't remove cache files for package: " + packageName + " u" + userId); return false; } return true; } @Override public void getPackageSizeInfo(final String packageName, int userHandle, final IPackageStatsObserver observer) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.GET_PACKAGE_SIZE, null); if (packageName == null) { throw new IllegalArgumentException("Attempt to get size of null packageName"); } PackageStats stats = new PackageStats(packageName, userHandle); /* * Queue up an async operation since the package measurement may take a * little while. */ Message msg = mHandler.obtainMessage(INIT_COPY); msg.obj = new MeasureParams(stats, observer); mHandler.sendMessage(msg); } private boolean getPackageSizeInfoLI(String packageName, int userHandle, PackageStats pStats) { if (packageName == null) { Slog.w(TAG, "Attempt to get size of null packageName."); return false; } PackageParser.Package p; boolean dataOnly = false; String libDirRoot = null; String asecPath = null; PackageSetting ps = null; synchronized (mPackages) { p = mPackages.get(packageName); ps = mSettings.mPackages.get(packageName); if(p == null) { dataOnly = true; if((ps == null) || (ps.pkg == null)) { Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); return false; } p = ps.pkg; } if (ps != null) { libDirRoot = ps.legacyNativeLibraryPathString; } if (p != null && (isExternal(p) || isForwardLocked(p))) { String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); if (secureContainerId != null) { asecPath = PackageHelper.getSdFilesystem(secureContainerId); } } } String publicSrcDir = null; if(!dataOnly) { final ApplicationInfo applicationInfo = p.applicationInfo; if (applicationInfo == null) { Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); return false; } if (isForwardLocked(p)) { publicSrcDir = applicationInfo.getBaseResourcePath(); } } // TODO: extend to measure size of split APKs // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, // not just the first level. // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not // just the primary. String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); if (res < 0) { return false; } // Fix-up for forward-locked applications in ASEC containers. if (!isExternal(p)) { pStats.codeSize += pStats.externalCodeSize; pStats.externalCodeSize = 0L; } return true; } @Override public void addPackageToPreferred(String packageName) { Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); } @Override public void removePackageFromPreferred(String packageName) { Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); } @Override public List<PackageInfo> getPreferredPackages(int flags) { return new ArrayList<PackageInfo>(); } private int getUidTargetSdkVersionLockedLPr(int uid) { Object obj = mSettings.getUserIdLPr(uid); if (obj instanceof SharedUserSetting) { final SharedUserSetting sus = (SharedUserSetting) obj; int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; final Iterator<PackageSetting> it = sus.packages.iterator(); while (it.hasNext()) { final PackageSetting ps = it.next(); if (ps.pkg != null) { int v = ps.pkg.applicationInfo.targetSdkVersion; if (v < vers) vers = v; } } return vers; } else if (obj instanceof PackageSetting) { final PackageSetting ps = (PackageSetting) obj; if (ps.pkg != null) { return ps.pkg.applicationInfo.targetSdkVersion; } } return Build.VERSION_CODES.CUR_DEVELOPMENT; } @Override public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity, int userId) { addPreferredActivityInternal(filter, match, set, activity, true, userId, "Adding preferred"); } private void addPreferredActivityInternal(IntentFilter filter, int match, ComponentName[] set, ComponentName activity, boolean always, int userId, String opname) { // writer int callingUid = Binder.getCallingUid(); enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); if (filter.countActions() == 0) { Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); return; } synchronized (mPackages) { if (mContext.checkCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS) != PackageManager.PERMISSION_GRANTED) { if (getUidTargetSdkVersionLockedLPr(callingUid) < Build.VERSION_CODES.FROYO) { Slog.w(TAG, "Ignoring addPreferredActivity() from uid " + callingUid); return; } mContext.enforceCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); } PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " + userId + ":"); filter.dump(new LogPrinter(Log.INFO, TAG), " "); pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); mSettings.writePackageRestrictionsLPr(userId); } } @Override public void replacePreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity, int userId) { if (filter.countActions() != 1) { throw new IllegalArgumentException( "replacePreferredActivity expects filter to have only 1 action."); } if (filter.countDataAuthorities() != 0 || filter.countDataPaths() != 0 || filter.countDataSchemes() > 1 || filter.countDataTypes() != 0) { throw new IllegalArgumentException( "replacePreferredActivity expects filter to have no data authorities, " + "paths, or types; and at most one scheme."); } final int callingUid = Binder.getCallingUid(); enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); synchronized (mPackages) { if (mContext.checkCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS) != PackageManager.PERMISSION_GRANTED) { if (getUidTargetSdkVersionLockedLPr(callingUid) < Build.VERSION_CODES.FROYO) { Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " + Binder.getCallingUid()); return; } mContext.enforceCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); } PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); if (pir != null) { // Get all of the existing entries that exactly match this filter. ArrayList<PreferredActivity> existing = pir.findFilters(filter); if (existing != null && existing.size() == 1) { PreferredActivity cur = existing.get(0); if (DEBUG_PREFERRED) { Slog.i(TAG, "Checking replace of preferred:"); filter.dump(new LogPrinter(Log.INFO, TAG), " "); if (!cur.mPref.mAlways) { Slog.i(TAG, " -- CUR; not mAlways!"); } else { Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(cur.mPref.mSetComponents)); Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); Slog.i(TAG, " -- NEW: mMatch=" + (match&IntentFilter.MATCH_CATEGORY_MASK)); Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); } } if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) && cur.mPref.sameSet(set)) { // Setting the preferred activity to what it happens to be already if (DEBUG_PREFERRED) { Slog.i(TAG, "Replacing with same preferred activity " + cur.mPref.mShortComponent + " for user " + userId + ":"); filter.dump(new LogPrinter(Log.INFO, TAG), " "); } return; } } if (existing != null) { if (DEBUG_PREFERRED) { Slog.i(TAG, existing.size() + " existing preferred matches for:"); filter.dump(new LogPrinter(Log.INFO, TAG), " "); } for (int i = 0; i < existing.size(); i++) { PreferredActivity pa = existing.get(i); if (DEBUG_PREFERRED) { Slog.i(TAG, "Removing existing preferred activity " + pa.mPref.mComponent + ":"); pa.dump(new LogPrinter(Log.INFO, TAG), " "); } pir.removeFilter(pa); } } } addPreferredActivityInternal(filter, match, set, activity, true, userId, "Replacing preferred"); } } @Override public void clearPackagePreferredActivities(String packageName) { final int uid = Binder.getCallingUid(); // writer synchronized (mPackages) { PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null || pkg.applicationInfo.uid != uid) { if (mContext.checkCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS) != PackageManager.PERMISSION_GRANTED) { if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) < Build.VERSION_CODES.FROYO) { Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " + Binder.getCallingUid()); return; } mContext.enforceCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); } } int user = UserHandle.getCallingUserId(); if (clearPackagePreferredActivitiesLPw(packageName, user)) { mSettings.writePackageRestrictionsLPr(user); scheduleWriteSettingsLocked(); } } } /** This method takes a specific user id as well as UserHandle.USER_ALL. */ boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { ArrayList<PreferredActivity> removed = null; boolean changed = false; for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { final int thisUserId = mSettings.mPreferredActivities.keyAt(i); PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); if (userId != UserHandle.USER_ALL && userId != thisUserId) { continue; } Iterator<PreferredActivity> it = pir.filterIterator(); while (it.hasNext()) { PreferredActivity pa = it.next(); // Mark entry for removal only if it matches the package name // and the entry is of type "always". if (packageName == null || (pa.mPref.mComponent.getPackageName().equals(packageName) && pa.mPref.mAlways)) { if (removed == null) { removed = new ArrayList<PreferredActivity>(); } removed.add(pa); } } if (removed != null) { for (int j=0; j<removed.size(); j++) { PreferredActivity pa = removed.get(j); pir.removeFilter(pa); } changed = true; } } return changed; } @Override public void resetPreferredActivities(int userId) { /* TODO: Actually use userId. Why is it being passed in? */ mContext.enforceCallingOrSelfPermission( android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); // writer synchronized (mPackages) { int user = UserHandle.getCallingUserId(); clearPackagePreferredActivitiesLPw(null, user); mSettings.readDefaultPreferredAppsLPw(this, user); mSettings.writePackageRestrictionsLPr(user); scheduleWriteSettingsLocked(); } } @Override public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) { int num = 0; final int userId = UserHandle.getCallingUserId(); // reader synchronized (mPackages) { PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); if (pir != null) { final Iterator<PreferredActivity> it = pir.filterIterator(); while (it.hasNext()) { final PreferredActivity pa = it.next(); if (packageName == null || (pa.mPref.mComponent.getPackageName().equals(packageName) && pa.mPref.mAlways)) { if (outFilters != null) { outFilters.add(new IntentFilter(pa)); } if (outActivities != null) { outActivities.add(pa.mPref.mComponent); } } } } } return num; } @Override public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, int userId) { int callingUid = Binder.getCallingUid(); if (callingUid != Process.SYSTEM_UID) { throw new SecurityException( "addPersistentPreferredActivity can only be run by the system"); } if (filter.countActions() == 0) { Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); return; } synchronized (mPackages) { Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + " :"); filter.dump(new LogPrinter(Log.INFO, TAG), " "); mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( new PersistentPreferredActivity(filter, activity)); mSettings.writePackageRestrictionsLPr(userId); } } @Override public void clearPackagePersistentPreferredActivities(String packageName, int userId) { int callingUid = Binder.getCallingUid(); if (callingUid != Process.SYSTEM_UID) { throw new SecurityException( "clearPackagePersistentPreferredActivities can only be run by the system"); } ArrayList<PersistentPreferredActivity> removed = null; boolean changed = false; synchronized (mPackages) { for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities .valueAt(i); if (userId != thisUserId) { continue; } Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); while (it.hasNext()) { PersistentPreferredActivity ppa = it.next(); // Mark entry for removal only if it matches the package name. if (ppa.mComponent.getPackageName().equals(packageName)) { if (removed == null) { removed = new ArrayList<PersistentPreferredActivity>(); } removed.add(ppa); } } if (removed != null) { for (int j=0; j<removed.size(); j++) { PersistentPreferredActivity ppa = removed.get(j); ppir.removeFilter(ppa); } changed = true; } } if (changed) { mSettings.writePackageRestrictionsLPr(userId); } } } @Override public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, int ownerUserId, int sourceUserId, int targetUserId, int flags) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); int callingUid = Binder.getCallingUid(); enforceOwnerRights(ownerPackage, ownerUserId, callingUid); enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); if (intentFilter.countActions() == 0) { Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); return; } synchronized (mPackages) { CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); mSettings.writePackageRestrictionsLPr(sourceUserId); } } @Override public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, int ownerUserId) { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); int callingUid = Binder.getCallingUid(); enforceOwnerRights(ownerPackage, ownerUserId, callingUid); enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); int callingUserId = UserHandle.getUserId(callingUid); synchronized (mPackages) { CrossProfileIntentResolver resolver = mSettings.editCrossProfileIntentResolverLPw(sourceUserId); HashSet<CrossProfileIntentFilter> set = new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); for (CrossProfileIntentFilter filter : set) { if (filter.getOwnerPackage().equals(ownerPackage) && filter.getOwnerUserId() == callingUserId) { resolver.removeFilter(filter); } } mSettings.writePackageRestrictionsLPr(sourceUserId); } } // Enforcing that callingUid is owning pkg on userId private void enforceOwnerRights(String pkg, int userId, int callingUid) { // The system owns everything. if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { return; } int callingUserId = UserHandle.getUserId(callingUid); if (callingUserId != userId) { throw new SecurityException("calling uid " + callingUid + " pretends to own " + pkg + " on user " + userId + " but belongs to user " + callingUserId); } PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); if (pi == null) { throw new IllegalArgumentException("Unknown package " + pkg + " on user " + callingUserId); } if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { throw new SecurityException("Calling uid " + callingUid + " does not own package " + pkg); } } @Override public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); final int callingUserId = UserHandle.getCallingUserId(); List<ResolveInfo> list = queryIntentActivities(intent, null, PackageManager.GET_META_DATA, callingUserId); ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, true, false, false, callingUserId); allHomeCandidates.clear(); if (list != null) { for (ResolveInfo ri : list) { allHomeCandidates.add(ri); } } return (preferred == null || preferred.activityInfo == null) ? null : new ComponentName(preferred.activityInfo.packageName, preferred.activityInfo.name); } @Override public void setApplicationEnabledSetting(String appPackageName, int newState, int flags, int userId, String callingPackage) { if (!sUserManager.exists(userId)) return; if (callingPackage == null) { callingPackage = Integer.toString(Binder.getCallingUid()); } setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); } @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags, int userId) { if (!sUserManager.exists(userId)) return; setEnabledSetting(componentName.getPackageName(), componentName.getClassName(), newState, flags, userId, null); } private void setEnabledSetting(final String packageName, String className, int newState, final int flags, int userId, String callingPackage) { if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT || newState == COMPONENT_ENABLED_STATE_ENABLED || newState == COMPONENT_ENABLED_STATE_DISABLED || newState == COMPONENT_ENABLED_STATE_DISABLED_USER || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { throw new IllegalArgumentException("Invalid new component state: " + newState); } PackageSetting pkgSetting; final int uid = Binder.getCallingUid(); final int permission = mContext.checkCallingOrSelfPermission( android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); enforceCrossUserPermission(uid, userId, false, true, "set enabled"); final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); boolean sendNow = false; boolean isApp = (className == null); String componentName = isApp ? packageName : className; int packageUid = -1; ArrayList<String> components; // writer synchronized (mPackages) { pkgSetting = mSettings.mPackages.get(packageName); if (pkgSetting == null) { if (className == null) { throw new IllegalArgumentException( "Unknown package: " + packageName); } throw new IllegalArgumentException( "Unknown component: " + packageName + "/" + className); } // Allow root and verify that userId is not being specified by a different user if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { throw new SecurityException( "Permission Denial: attempt to change component state from pid=" + Binder.getCallingPid() + ", uid=" + uid + ", package uid=" + pkgSetting.appId); } if (className == null) { // We're dealing with an application/package level state change if (pkgSetting.getEnabled(userId) == newState) { // Nothing to do return; } if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { // Don't care about who enables an app. callingPackage = null; } pkgSetting.setEnabled(newState, userId, callingPackage); // pkgSetting.pkg.mSetEnabled = newState; } else { // We're dealing with a component level state change // First, verify that this is a valid class name. PackageParser.Package pkg = pkgSetting.pkg; if (pkg == null || !pkg.hasComponentClassName(className)) { /** M: [ALPS01438768] System server exception when uninstall Maps @{ */ if (pkg == null || pkg.applicationInfo == null) { throw new IllegalArgumentException( "Unknown component: " + packageName + "/" + className); } /** @} */ if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { throw new IllegalArgumentException("Component class " + className + " does not exist in " + packageName); } else { Slog.w(TAG, "Failed setComponentEnabledSetting: component class " + className + " does not exist in " + packageName); } } switch (newState) { case COMPONENT_ENABLED_STATE_ENABLED: if (!pkgSetting.enableComponentLPw(className, userId)) { return; } break; case COMPONENT_ENABLED_STATE_DISABLED: if (!pkgSetting.disableComponentLPw(className, userId)) { return; } break; case COMPONENT_ENABLED_STATE_DEFAULT: if (!pkgSetting.restoreComponentLPw(className, userId)) { return; } break; default: Slog.e(TAG, "Invalid new component state: " + newState); return; } } mSettings.writePackageRestrictionsLPr(userId); components = mPendingBroadcasts.get(userId, packageName); final boolean newPackage = components == null; if (newPackage) { components = new ArrayList<String>(); } if (!components.contains(componentName)) { components.add(componentName); } if ((flags&PackageManager.DONT_KILL_APP) == 0) { sendNow = true; // Purge entry from pending broadcast list if another one exists already // since we are sending one right away. mPendingBroadcasts.remove(userId, packageName); } else { if (newPackage) { mPendingBroadcasts.put(userId, packageName, components); } if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { // Schedule a message mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); } } } long callingId = Binder.clearCallingIdentity(); try { if (sendNow) { packageUid = UserHandle.getUid(userId, pkgSetting.appId); sendPackageChangedBroadcast(packageName, (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); } } finally { Binder.restoreCallingIdentity(callingId); } } private void sendPackageChangedBroadcast(String packageName, boolean killFlag, ArrayList<String> componentNames, int packageUid) { if (DEBUG_INSTALL) Log.v(TAG, "Sending package changed: package=" + packageName + " components=" + componentNames); Bundle extras = new Bundle(4); extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); String nameList[] = new String[componentNames.size()]; componentNames.toArray(nameList); extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); extras.putInt(Intent.EXTRA_UID, packageUid); sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, new int[] {UserHandle.getUserId(packageUid)}); } @Override public void setPackageStoppedState(String packageName, boolean stopped, int userId) { if (!sUserManager.exists(userId)) return; final int uid = Binder.getCallingUid(); final int permission = mContext.checkCallingOrSelfPermission( android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); enforceCrossUserPermission(uid, userId, true, true, "stop package"); // writer synchronized (mPackages) { if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, uid, userId)) { scheduleWritePackageRestrictionsLocked(userId); } } } @Override public String getInstallerPackageName(String packageName) { // reader synchronized (mPackages) { return mSettings.getInstallerPackageNameLPr(packageName); } } @Override public int getApplicationEnabledSetting(String packageName, int userId) { if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; int uid = Binder.getCallingUid(); enforceCrossUserPermission(uid, userId, false, false, "get enabled"); // reader synchronized (mPackages) { return mSettings.getApplicationEnabledSettingLPr(packageName, userId); } } @Override public int getComponentEnabledSetting(ComponentName componentName, int userId) { if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; int uid = Binder.getCallingUid(); enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); // reader synchronized (mPackages) { return mSettings.getComponentEnabledSettingLPr(componentName, userId); } } @Override public void enterSafeMode() { enforceSystemOrRoot("Only the system can request entering safe mode"); if (!mSystemReady) { mSafeMode = true; } } @Override public void systemReady() { mSystemReady = true; // Read the compatibilty setting when the system is ready. boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( mContext.getContentResolver(), android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); if (DEBUG_SETTINGS) { Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); } synchronized (mPackages) { // Verify that all of the preferred activity components actually // exist. It is possible for applications to be updated and at // that point remove a previously declared activity component that // had been set as a preferred activity. We try to clean this up // the next time we encounter that preferred activity, but it is // possible for the user flow to never be able to return to that // situation so here we do a sanity check to make sure we haven't // left any junk around. ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); removed.clear(); for (PreferredActivity pa : pir.filterSet()) { if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { removed.add(pa); } } if (removed.size() > 0) { for (int r=0; r<removed.size(); r++) { PreferredActivity pa = removed.get(r); Slog.w(TAG, "Removing dangling preferred activity: " + pa.mPref.mComponent); pir.removeFilter(pa); } mSettings.writePackageRestrictionsLPr( mSettings.mPreferredActivities.keyAt(i)); } } } sUserManager.systemReady(); // Kick off any messages waiting for system ready if (mPostSystemReadyMessages != null) { for (Message msg : mPostSystemReadyMessages) { msg.sendToTarget(); } mPostSystemReadyMessages = null; } } @Override public boolean isSafeMode() { return mSafeMode; } @Override public boolean hasSystemUidErrors() { return mHasSystemUidErrors; } static String arrayToString(int[] array) { StringBuffer buf = new StringBuffer(128); buf.append('['); if (array != null) { for (int i=0; i<array.length; i++) { if (i > 0) buf.append(", "); buf.append(array[i]); } } buf.append(']'); return buf.toString(); } static class DumpState { public static final int DUMP_LIBS = 1 << 0; public static final int DUMP_FEATURES = 1 << 1; public static final int DUMP_RESOLVERS = 1 << 2; public static final int DUMP_PERMISSIONS = 1 << 3; public static final int DUMP_PACKAGES = 1 << 4; public static final int DUMP_SHARED_USERS = 1 << 5; public static final int DUMP_MESSAGES = 1 << 6; public static final int DUMP_PROVIDERS = 1 << 7; public static final int DUMP_VERIFIERS = 1 << 8; public static final int DUMP_PREFERRED = 1 << 9; public static final int DUMP_PREFERRED_XML = 1 << 10; public static final int DUMP_KEYSETS = 1 << 11; public static final int DUMP_VERSION = 1 << 12; public static final int DUMP_INSTALLS = 1 << 13; public static final int OPTION_SHOW_FILTERS = 1 << 0; private int mTypes; private int mOptions; private boolean mTitlePrinted; private SharedUserSetting mSharedUser; public boolean isDumping(int type) { if (mTypes == 0 && type != DUMP_PREFERRED_XML) { return true; } return (mTypes & type) != 0; } public void setDump(int type) { mTypes |= type; } public boolean isOptionEnabled(int option) { return (mOptions & option) != 0; } public void setOptionEnabled(int option) { mOptions |= option; } public boolean onTitlePrinted() { final boolean printed = mTitlePrinted; mTitlePrinted = true; return printed; } public boolean getTitlePrinted() { return mTitlePrinted; } public void setTitlePrinted(boolean enabled) { mTitlePrinted = enabled; } public SharedUserSetting getSharedUser() { return mSharedUser; } public void setSharedUser(SharedUserSetting user) { mSharedUser = user; } } @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump ActivityManager from from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() + " without permission " + android.Manifest.permission.DUMP); return; } DumpState dumpState = new DumpState(); boolean fullPreferred = false; boolean checkin = false; String packageName = null; int opti = 0; while (opti < args.length) { String opt = args[opti]; if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { break; } opti++; if ("-a".equals(opt)) { // Right now we only know how to print all. } else if ("-h".equals(opt)) { pw.println("Package manager dump options:"); pw.println(" [-h] [-f] [--checkin] [cmd] ..."); pw.println(" --checkin: dump for a checkin"); pw.println(" -f: print details of intent filters"); pw.println(" -h: print this help"); pw.println(" cmd may be one of:"); pw.println(" l[ibraries]: list known shared libraries"); pw.println(" f[ibraries]: list device features"); pw.println(" k[eysets]: print known keysets"); pw.println(" r[esolvers]: dump intent resolvers"); pw.println(" perm[issions]: dump permissions"); pw.println(" pref[erred]: print preferred package settings"); pw.println(" preferred-xml [--full]: print preferred package settings as xml"); pw.println(" prov[iders]: dump content providers"); pw.println(" p[ackages]: dump installed packages"); pw.println(" s[hared-users]: dump shared user IDs"); pw.println(" m[essages]: print collected runtime messages"); pw.println(" v[erifiers]: print package verifier info"); pw.println(" version: print database version info"); pw.println(" write: write current settings now"); pw.println(" <package.name>: info about given package"); pw.println(" installs: details about install sessions"); return; } else if ("--checkin".equals(opt)) { checkin = true; } else if ("-f".equals(opt)) { dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); } else { pw.println("Unknown argument: " + opt + "; use -h for help"); } } // Is the caller requesting to dump a particular piece of data? if (opti < args.length) { String cmd = args[opti]; opti++; // Is this a package name? if ("android".equals(cmd) || cmd.contains(".")) { packageName = cmd; // When dumping a single package, we always dump all of its // filter information since the amount of data will be reasonable. dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); } else if ("l".equals(cmd) || "libraries".equals(cmd)) { dumpState.setDump(DumpState.DUMP_LIBS); } else if ("f".equals(cmd) || "features".equals(cmd)) { dumpState.setDump(DumpState.DUMP_FEATURES); } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { dumpState.setDump(DumpState.DUMP_RESOLVERS); } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { dumpState.setDump(DumpState.DUMP_PERMISSIONS); } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { dumpState.setDump(DumpState.DUMP_PREFERRED); } else if ("preferred-xml".equals(cmd)) { dumpState.setDump(DumpState.DUMP_PREFERRED_XML); if (opti < args.length && "--full".equals(args[opti])) { fullPreferred = true; opti++; } } else if ("p".equals(cmd) || "packages".equals(cmd)) { dumpState.setDump(DumpState.DUMP_PACKAGES); } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { dumpState.setDump(DumpState.DUMP_SHARED_USERS); } else if ("prov".equals(cmd) || "providers".equals(cmd)) { dumpState.setDump(DumpState.DUMP_PROVIDERS); } else if ("m".equals(cmd) || "messages".equals(cmd)) { dumpState.setDump(DumpState.DUMP_MESSAGES); } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { dumpState.setDump(DumpState.DUMP_VERIFIERS); } else if ("version".equals(cmd)) { dumpState.setDump(DumpState.DUMP_VERSION); } else if ("k".equals(cmd) || "keysets".equals(cmd)) { dumpState.setDump(DumpState.DUMP_KEYSETS); } else if ("installs".equals(cmd)) { dumpState.setDump(DumpState.DUMP_INSTALLS); } else if ("log".equals(cmd)) { /** M: Add dynamic enable PMS log @{ */ configLogTag(pw, args, opti); return; /** @} */ } else if ("write".equals(cmd)) { synchronized (mPackages) { mSettings.writeLPr(); pw.println("Settings written."); return; } } } if (checkin) { pw.println("vers,1"); } // reader synchronized (mPackages) { if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { if (!checkin) { if (dumpState.onTitlePrinted()) pw.println(); pw.println("Database versions:"); pw.print(" SDK Version:"); pw.print(" internal="); pw.print(mSettings.mInternalSdkPlatform); pw.print(" external="); pw.println(mSettings.mExternalSdkPlatform); pw.print(" DB Version:"); pw.print(" internal="); pw.print(mSettings.mInternalDatabaseVersion); pw.print(" external="); pw.println(mSettings.mExternalDatabaseVersion); } } if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { if (!checkin) { if (dumpState.onTitlePrinted()) pw.println(); pw.println("Verifiers:"); pw.print(" Required: "); pw.print(mRequiredVerifierPackage); pw.print(" (uid="); pw.print(getPackageUid(mRequiredVerifierPackage, 0)); pw.println(")"); } else if (mRequiredVerifierPackage != null) { pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); } } if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { boolean printedHeader = false; final Iterator<String> it = mSharedLibraries.keySet().iterator(); while (it.hasNext()) { String name = it.next(); SharedLibraryEntry ent = mSharedLibraries.get(name); if (!checkin) { if (!printedHeader) { if (dumpState.onTitlePrinted()) pw.println(); pw.println("Libraries:"); printedHeader = true; } pw.print(" "); } else { pw.print("lib,"); } pw.print(name); if (!checkin) { pw.print(" -> "); } if (ent.path != null) { if (!checkin) { pw.print("(jar) "); pw.print(ent.path); } else { pw.print(",jar,"); pw.print(ent.path); } } else { if (!checkin) { pw.print("(apk) "); pw.print(ent.apk); } else { pw.print(",apk,"); pw.print(ent.apk); } } pw.println(); } } if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { if (dumpState.onTitlePrinted()) pw.println(); if (!checkin) { pw.println("Features:"); } Iterator<String> it = mAvailableFeatures.keySet().iterator(); while (it.hasNext()) { String name = it.next(); if (!checkin) { pw.print(" "); } else { pw.print("feat,"); } pw.println(name); } } if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" : "Activity Resolver Table:", " ", packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { dumpState.setTitlePrinted(true); } if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:", " ", packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { dumpState.setTitlePrinted(true); } if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" : "Service Resolver Table:", " ", packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { dumpState.setTitlePrinted(true); } if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" : "Provider Resolver Table:", " ", packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { dumpState.setTitlePrinted(true); } } if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); int user = mSettings.mPreferredActivities.keyAt(i); if (pir.dump(pw, dumpState.getTitlePrinted() ? "\nPreferred Activities User " + user + ":" : "Preferred Activities User " + user + ":", " ", packageName, true)) { dumpState.setTitlePrinted(true); } } } if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { pw.flush(); FileOutputStream fout = new FileOutputStream(fd); BufferedOutputStream str = new BufferedOutputStream(fout); XmlSerializer serializer = new FastXmlSerializer(); try { serializer.setOutput(str, "utf-8"); serializer.startDocument(null, true); serializer.setFeature( "http://xmlpull.org/v1/doc/features.html#indent-output", true); mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); serializer.endDocument(); serializer.flush(); } catch (IllegalArgumentException e) { pw.println("Failed writing: " + e); } catch (IllegalStateException e) { pw.println("Failed writing: " + e); } catch (IOException e) { pw.println("Failed writing: " + e); } } if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { mSettings.dumpPermissionsLPr(pw, packageName, dumpState); if (packageName == null) { for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { if (iperm == 0) { if (dumpState.onTitlePrinted()) pw.println(); pw.println("AppOp Permissions:"); } pw.print(" AppOp Permission "); pw.print(mAppOpPermissionPackages.keyAt(iperm)); pw.println(":"); ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { pw.print(" "); pw.println(pkgs.valueAt(ipkg)); } } } } if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { boolean printedSomething = false; for (PackageParser.Provider p : mProviders.mProviders.values()) { if (packageName != null && !packageName.equals(p.info.packageName)) { continue; } if (!printedSomething) { if (dumpState.onTitlePrinted()) pw.println(); pw.println("Registered ContentProviders:"); printedSomething = true; } pw.print(" "); p.printComponentShortName(pw); pw.println(":"); pw.print(" "); pw.println(p.toString()); } printedSomething = false; for (Map.Entry<String, PackageParser.Provider> entry : mProvidersByAuthority.entrySet()) { PackageParser.Provider p = entry.getValue(); if (packageName != null && !packageName.equals(p.info.packageName)) { continue; } if (!printedSomething) { if (dumpState.onTitlePrinted()) pw.println(); pw.println("ContentProvider Authorities:"); printedSomething = true; } pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); pw.print(" "); pw.println(p.toString()); if (p.info != null && p.info.applicationInfo != null) { final String appInfo = p.info.applicationInfo.toString(); pw.print(" applicationInfo="); pw.println(appInfo); } } } if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); } if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); } if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); } if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { // XXX should handle packageName != null by dumping only install data that // the given package is involved with. if (dumpState.onTitlePrinted()) pw.println(); mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); } if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { if (dumpState.onTitlePrinted()) pw.println(); mSettings.dumpReadMessagesLPr(pw, dumpState); pw.println(); pw.println("Package warning messages:"); final File fname = getSettingsProblemFile(); FileInputStream in = null; try { in = new FileInputStream(fname); final int avail = in.available(); final byte[] data = new byte[avail]; in.read(data); pw.print(new String(data)); } catch (FileNotFoundException e) { } catch (IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { BufferedReader in = null; String line = null; try { in = new BufferedReader(new FileReader(getSettingsProblemFile())); while ((line = in.readLine()) != null) { pw.print("msg,"); pw.println(line); } } catch (IOException ignored) { } finally { IoUtils.closeQuietly(in); } } } } /** M: [ALPS00068754][Need Patch][Volunteer Patch]Add dynamic enable PMS log @{ */ protected void configLogTag(PrintWriter pw, String[] args, int opti) { String tag = null; boolean on = false; if ((opti + 1) >= args.length) { pw.println(" Invalid argument!"); } else { tag = args[opti]; on = "on".equals(args[opti + 1]) ? true : false; if (tag.equals("a")) { DEBUG_SETTINGS = on; DEBUG_PREFERRED = on; DEBUG_UPGRADE = on; DEBUG_INSTALL = on; DEBUG_SD_INSTALL = on; DEBUG_REMOVE = on; DEBUG_SHOW_INFO = on;; DEBUG_PACKAGE_INFO = on; DEBUG_INTENT_MATCHING = on; DEBUG_PACKAGE_SCANNING = on; DEBUG_VERIFY = on; DEBUG_PERMISSION = on; DEBUG_BROADCASTS = on; DEBUG_DEXOPT = on; DEBUG_ABI_SELECTION = on; } else if (tag.equals("se")) { DEBUG_SETTINGS = on; } else if (tag.equals("pr")) { DEBUG_PREFERRED = on; } else if (tag.equals("up")) { DEBUG_UPGRADE = on; } else if (tag.equals("in")) { DEBUG_INSTALL = on; DEBUG_SD_INSTALL = on; DEBUG_BROADCASTS = on; } else if (tag.equals("pe")) { DEBUG_PERMISSION = on; } } } /** @} */ // ------- apps on sdcard specific code ------- static boolean DEBUG_SD_INSTALL = true; private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; private static final String SD_ENCRYPTION_ALGORITHM = "AES"; private boolean mMediaMounted = false; static String getEncryptKey() { try { String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( SD_ENCRYPTION_KEYSTORE_NAME); if (sdEncKey == null) { sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); if (sdEncKey == null) { Slog.e(TAG, "Failed to create encryption keys"); return null; } } return sdEncKey; } catch (NoSuchAlgorithmException nsae) { Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); return null; } catch (IOException ioe) { Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); return null; } } /* * Update media status on PackageManager. */ @Override public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { int callingUid = Binder.getCallingUid(); if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { throw new SecurityException("Media status can only be updated by the system"); } // reader; this apparently protects mMediaMounted, but should probably // be a different lock in that case. synchronized (mPackages) { Log.i(TAG, "Updating external media status from " + (mMediaMounted ? "mounted" : "unmounted") + " to " + (mediaStatus ? "mounted" : "unmounted")); if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus + ", mMediaMounted=" + mMediaMounted); if (mediaStatus == mMediaMounted) { final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1); mHandler.sendMessage(msg); return; } mMediaMounted = mediaStatus; } // Queue up an async operation since the package installation may take a // little while. mHandler.post(new Runnable() { public void run() { updateExternalMediaStatusInner(mediaStatus, reportStatus, true); } }); } /** * Called by MountService when the initial ASECs to scan are available. * Should block until all the ASEC containers are finished being scanned. */ public void scanAvailableAsecs() { updateExternalMediaStatusInner(true, false, false); if (mShouldRestoreconData) { SELinuxMMAC.setRestoreconDone(); mShouldRestoreconData = false; } } /* * Collect information of applications on external media, map them against * existing containers and update information based on current mount status. * Please note that we always have to report status if reportStatus has been * set to true especially when unloading packages. */ private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, boolean externalStorage) { ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); int[] uidArr = EmptyArray.INT; final String[] list = PackageHelper.getSecureContainerList(); if (ArrayUtils.isEmpty(list)) { Log.i(TAG, "No secure containers found"); } else { // Process list of secure containers and categorize them // as active or stale based on their package internal state. // reader synchronized (mPackages) { for (String cid : list) { // Leave stages untouched for now; installer service owns them if (PackageInstallerService.isStageName(cid)) continue; if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid); String pkgName = getAsecPackageName(cid); if (pkgName == null) { Slog.i(TAG, "Found stale container " + cid + " with no package name"); continue; } if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName); final PackageSetting ps = mSettings.mPackages.get(pkgName); if (ps == null) { Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); continue; } /* * Skip packages that are not external if we're unmounting * external storage. */ if (externalStorage && !isMounted && !isExternal(ps)) { continue; } final AsecInstallArgs args = new AsecInstallArgs(cid, getAppDexInstructionSets(ps), isForwardLocked(ps)); // The package status is changed only if the code path // matches between settings and the container id. if (ps.codePathString != null && ps.codePathString.startsWith(args.getCodePath())) { if (DEBUG_SD_INSTALL) { Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName + " at code path: " + ps.codePathString); } // We do have a valid package installed on sdcard processCids.put(args, ps.codePathString); final int uid = ps.appId; if (uid != -1) { uidArr = ArrayUtils.appendInt(uidArr, uid); } } else { Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" + ps.codePathString); } } } Arrays.sort(uidArr); } // Process packages with valid entries. if (isMounted) { if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages"); loadMediaPackages(processCids, uidArr); startCleaningPackages(); mInstallerService.onSecureContainersAvailable(); } else { if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages"); unloadMediaPackages(processCids, uidArr, reportStatus); } } private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { int size = pkgList.size(); if (size > 0) { // Send broadcasts here Bundle extras = new Bundle(); extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList .toArray(new String[size])); if (uidArr != null) { extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); } if (replacing) { extras.putBoolean(Intent.EXTRA_REPLACING, replacing); } String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); } } /* * Look at potentially valid container ids from processCids If package * information doesn't match the one on record or package scanning fails, * the cid is added to list of removeCids. We currently don't delete stale * containers. */ private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { ArrayList<String> pkgList = new ArrayList<String>(); Set<AsecInstallArgs> keys = processCids.keySet(); for (AsecInstallArgs args : keys) { String codePath = processCids.get(args); if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : " + args.cid); int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; try { // Make sure there are no container errors first. if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { Slog.e(TAG, "Failed to mount cid : " + args.cid + " when installing from sdcard"); continue; } // Check code path here. if (codePath == null || !codePath.startsWith(args.getCodePath())) { Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() + " does not match one in settings " + codePath); continue; } // Parse package int parseFlags = mDefParseFlags; if (args.isExternal()) { parseFlags |= PackageParser.PARSE_ON_SDCARD; } if (args.isFwdLocked()) { parseFlags |= PackageParser.PARSE_FORWARD_LOCK; } synchronized (mInstallLock) { PackageParser.Package pkg = null; try { pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); } catch (PackageManagerException e) { Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); } // Scan the package if (pkg != null) { /* * TODO why is the lock being held? doPostInstall is * called in other places without the lock. This needs * to be straightened out. */ // writer synchronized (mPackages) { retCode = PackageManager.INSTALL_SUCCEEDED; pkgList.add(pkg.packageName); // Post process args args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, pkg.applicationInfo.uid); } } else { Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); } } } finally { if (retCode != PackageManager.INSTALL_SUCCEEDED) { Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); } } } // writer synchronized (mPackages) { // If the platform SDK has changed since the last time we booted, // we need to re-grant app permission to catch any new ones that // appear. This is really a hack, and means that apps can in some // cases get permissions that the user didn't initially explicitly // allow... it would be nice to have some better way to handle // this situation. final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; if (regrantPermissions) Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " + mSdkVersion + "; regranting permissions for external storage"); mSettings.mExternalSdkPlatform = mSdkVersion; // Make sure group IDs have been assigned, and any permission // changes in other apps are accounted for updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL | (regrantPermissions ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) : 0)); mSettings.updateExternalDatabaseVersion(); // can downgrade to reader // Persist settings mSettings.writeLPr(); } // Send a broadcast to let everyone know we are done processing if (pkgList.size() > 0) { sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); } } /* * Utility method to unload a list of specified containers */ private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { // Just unmount all valid containers. for (AsecInstallArgs arg : cidArgs) { synchronized (mInstallLock) { arg.doPostDeleteLI(false); } } } /* * Unload packages mounted on external media. This involves deleting package * data from internal structures, sending broadcasts about diabled packages, * gc'ing to free up references, unmounting all secure containers * corresponding to packages on external media, and posting a * UPDATED_MEDIA_STATUS message if status has been requested. Please note * that we always have to post this message if status has been requested no * matter what. */ private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], final boolean reportStatus) { if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages"); ArrayList<String> pkgList = new ArrayList<String>(); ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); final Set<AsecInstallArgs> keys = processCids.keySet(); for (AsecInstallArgs args : keys) { String pkgName = args.getPackageName(); if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName); // Delete package internally PackageRemovedInfo outInfo = new PackageRemovedInfo(); synchronized (mInstallLock) { boolean res = deletePackageLI(pkgName, null, false, null, null, PackageManager.DELETE_KEEP_DATA, outInfo, false); if (res) { pkgList.add(pkgName); } else { Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); failedList.add(args); } } } // reader synchronized (mPackages) { // We didn't update the settings after removing each package; // write them now for all packages. /** M: [ALPS00048912][Performance][Power off time][UX Index] Power off's time lose to HTC Legend on P99 @{ * Once no apk installed on sd card, whcih will not execute removing package this time. * Will not update settings. */ if (pkgList.size() > 0) { if (DEBUG_SD_INSTALL) Log.i(TAG, "update mSettings.writeLP "); mSettings.writeLPr(); } /** @} */ } // We have to absolutely send UPDATED_MEDIA_STATUS only // after confirming that all the receivers processed the ordered // broadcast when packages get disabled, force a gc to clean things up. // and unload all the containers. if (pkgList.size() > 0) { sendResourcesChangedBroadcast(false, false, pkgList, uidArr, new IIntentReceiver.Stub() { public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser) throws RemoteException { Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, 1, keys); mHandler.sendMessage(msg); } }); } else { Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, keys); mHandler.sendMessage(msg); } } /** Binder call */ @Override public void movePackage(final String packageName, final IPackageMoveObserver observer, final int flags) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); UserHandle user = new UserHandle(UserHandle.getCallingUserId()); int returnCode = PackageManager.MOVE_SUCCEEDED; int currInstallFlags = 0; int newInstallFlags = 0; File codeFile = null; String installerPackageName = null; String packageAbiOverride = null; // reader synchronized (mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); final PackageSetting ps = mSettings.mPackages.get(packageName); if (pkg == null || ps == null) { returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; } else { // Disable moving fwd locked apps and system packages if (pkg.applicationInfo != null && isSystemApp(pkg)) { Slog.w(TAG, "Cannot move system application"); returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; } else if (pkg.mOperationPending) { Slog.w(TAG, "Attempt to move package which has pending operations"); returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; } else { // Find install location first if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 && (flags & PackageManager.MOVE_INTERNAL) != 0) { Slog.w(TAG, "Ambigous flags specified for move location."); returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; } else { newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; currInstallFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; if (newInstallFlags == currInstallFlags) { Slog.w(TAG, "No move required. Trying to move to same location"); returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; } else { if (isForwardLocked(pkg)) { currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; } } } if (returnCode == PackageManager.MOVE_SUCCEEDED) { pkg.mOperationPending = true; } } codeFile = new File(pkg.codePath); installerPackageName = ps.installerPackageName; packageAbiOverride = ps.cpuAbiOverrideString; } } if (returnCode != PackageManager.MOVE_SUCCEEDED) { try { observer.packageMoved(packageName, returnCode); } catch (RemoteException ignored) { } return; } final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { @Override public void onUserActionRequired(Intent intent) throws RemoteException { throw new IllegalStateException(); } @Override public void onPackageInstalled(String basePackageName, int returnCode, String msg, Bundle extras) throws RemoteException { Slog.d(TAG, "Install result for move: " + PackageManager.installStatusToString(returnCode, msg)); // We usually have a new package now after the install, but if // we failed we need to clear the pending flag on the original // package object. synchronized (mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg != null) { pkg.mOperationPending = false; } } final int status = PackageManager.installStatusToPublicStatus(returnCode); switch (status) { case PackageInstaller.STATUS_SUCCESS: observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); break; case PackageInstaller.STATUS_FAILURE_STORAGE: observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); break; default: observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); break; } } }; // Treat a move like reinstalling an existing app, which ensures that we // process everythign uniformly, like unpacking native libraries. newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; final Message msg = mHandler.obtainMessage(INIT_COPY); final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); msg.obj = new InstallParams(origin, installObserver, newInstallFlags, installerPackageName, null, user, packageAbiOverride); mHandler.sendMessage(msg); } @Override public boolean setInstallLocation(int loc) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, null); if (getInstallLocation() == loc) { return true; } if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL || loc == PackageHelper.APP_INSTALL_EXTERNAL) { android.provider.Settings.Global.putInt(mContext.getContentResolver(), android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); return true; } return false; } @Override public int getInstallLocation() { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO); } /** Called by UserManagerService */ void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { mDirtyUsers.remove(userHandle); mSettings.removeUserLPw(userHandle); mPendingBroadcasts.remove(userHandle); if (mInstaller != null) { // Technically, we shouldn't be doing this with the package lock // held. However, this is very rare, and there is already so much // other disk I/O going on, that we'll let it slide for now. mInstaller.removeUserDataDirs(userHandle); } mUserNeedsBadging.delete(userHandle); removeUnusedPackagesLILPw(userManager, userHandle); } /** * We're removing userHandle and would like to remove any downloaded packages * that are no longer in use by any other user. * @param userHandle the user being removed */ private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { final boolean DEBUG_CLEAN_APKS = false; int [] users = userManager.getUserIdsLPr(); Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); while (psit.hasNext()) { PackageSetting ps = psit.next(); if (ps.pkg == null) { continue; } final String packageName = ps.pkg.packageName; // Skip over if system app if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { continue; } if (DEBUG_CLEAN_APKS) { Slog.i(TAG, "Checking package " + packageName); } boolean keep = false; for (int i = 0; i < users.length; i++) { if (users[i] != userHandle && ps.getInstalled(users[i])) { keep = true; if (DEBUG_CLEAN_APKS) { Slog.i(TAG, " Keeping package " + packageName + " for user " + users[i]); } break; } } if (!keep) { if (DEBUG_CLEAN_APKS) { Slog.i(TAG, " Removing package " + packageName); } mHandler.post(new Runnable() { public void run() { deletePackageX(packageName, userHandle, 0); } //end run }); } } } /** Called by UserManagerService */ void createNewUserLILPw(int userHandle, File path) { if (mInstaller != null) { mInstaller.createUserConfig(userHandle); mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); } } /** M: Add api for check apk signature @{ */ public int checkAPKSignatures(String pkg) { if (0 == checkSignatures(pkg, "android")) { return PackageInfo.KEY_PLATFORM; } else if (0 == checkSignatures(pkg, "com.android.providers.media")) { return PackageInfo.KEY_MEDIA; } else if (0 == checkSignatures(pkg, "com.android.contacts")) { return PackageInfo.KEY_SHARED; } else if (0 == checkSignatures(pkg, "com.android.mms")) { return PackageInfo.KEY_RELEASE; } else return PackageInfo.KEY_UNKNOWN; } /** @} */ @Override public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, "Only package verification agents can read the verifier device identity"); synchronized (mPackages) { return mSettings.getVerifierDeviceIdentityLPw(); } } @Override public void setPermissionEnforced(String permission, boolean enforced) { mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); if (READ_EXTERNAL_STORAGE.equals(permission)) { synchronized (mPackages) { if (mSettings.mReadExternalStorageEnforced == null || mSettings.mReadExternalStorageEnforced != enforced) { mSettings.mReadExternalStorageEnforced = enforced; mSettings.writeLPr(); } } // kill any non-foreground processes so we restart them and // grant/revoke the GID. final IActivityManager am = ActivityManagerNative.getDefault(); if (am != null) { final long token = Binder.clearCallingIdentity(); try { am.killProcessesBelowForeground("setPermissionEnforcement"); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(token); } } } else { throw new IllegalArgumentException("No selective enforcement for " + permission); } } @Override @Deprecated public boolean isPermissionEnforced(String permission) { return true; } @Override public boolean isStorageLow() { final long token = Binder.clearCallingIdentity(); try { final DeviceStorageMonitorInternal dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); if (dsm != null) { return dsm.isMemoryLow(); } else { return false; } } finally { Binder.restoreCallingIdentity(token); } } /** M: Java feature option removal (MTK_LCA_RAM_OPTIMIZE & MTK_LCA_ROM_OPTIMIZE) @{ */ private static final String MTK_LCA_ROM_OPTIMIZE = "ro.mtk_lca_rom_optimize"; private static final String MTK_LCA_RAM_OPTIMIZE = "ro.mtk_lca_ram_optimize"; public static boolean isLcaROM() { boolean enabled = "1".equals(SystemProperties.get(MTK_LCA_ROM_OPTIMIZE)); Log.d(TAG, "isLcaROM() return " + enabled); return enabled ; } public static boolean isLcaRAM() { boolean enabled = "1".equals(SystemProperties.get(MTK_LCA_RAM_OPTIMIZE)); Log.d(TAG, "isLcaROM() return " + enabled); return enabled ; } /** @} */ @Override public IPackageInstaller getPackageInstaller() { return mInstallerService; } private boolean userNeedsBadging(int userId) { int index = mUserNeedsBadging.indexOfKey(userId); if (index < 0) { final UserInfo userInfo; final long token = Binder.clearCallingIdentity(); try { userInfo = sUserManager.getUserInfo(userId); } finally { Binder.restoreCallingIdentity(token); } final boolean b; if (userInfo != null && userInfo.isManagedProfile()) { b = true; } else { b = false; } mUserNeedsBadging.put(userId, b); return b; } return mUserNeedsBadging.valueAt(index); } @Override public KeySet getKeySetByAlias(String packageName, String alias) { if (packageName == null || alias == null) { return null; } synchronized(mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { Slog.w(TAG, "KeySet requested for unknown package:" + packageName); throw new IllegalArgumentException("Unknown package: " + packageName); } KeySetManagerService ksms = mSettings.mKeySetManagerService; return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); } } @Override public KeySet getSigningKeySet(String packageName) { if (packageName == null) { return null; } synchronized(mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { Slog.w(TAG, "KeySet requested for unknown package:" + packageName); throw new IllegalArgumentException("Unknown package: " + packageName); } if (pkg.applicationInfo.uid != Binder.getCallingUid() && Process.SYSTEM_UID != Binder.getCallingUid()) { throw new SecurityException("May not access signing KeySet of other apps."); } KeySetManagerService ksms = mSettings.mKeySetManagerService; return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); } } @Override public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { if (packageName == null || ks == null) { return false; } synchronized(mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { Slog.w(TAG, "KeySet requested for unknown package:" + packageName); throw new IllegalArgumentException("Unknown package: " + packageName); } IBinder ksh = ks.getToken(); if (ksh instanceof KeySetHandle) { KeySetManagerService ksms = mSettings.mKeySetManagerService; return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); } return false; } } @Override public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { if (packageName == null || ks == null) { return false; } synchronized(mPackages) { final PackageParser.Package pkg = mPackages.get(packageName); if (pkg == null) { Slog.w(TAG, "KeySet requested for unknown package:" + packageName); throw new IllegalArgumentException("Unknown package: " + packageName); } IBinder ksh = ks.getToken(); if (ksh instanceof KeySetHandle) { KeySetManagerService ksms = mSettings.mKeySetManagerService; return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); } return false; } } /** M: [Mediatek Framework] Plug-in Manager (Limited use) @{ */ public boolean enforceDexOpt(String packageName) { /* final int uid = Binder.getCallingUid(); Log.i(TAG, "enforceDexOpt() is called by " + uid); boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); if (!eng) { throw new RuntimeException("Can be only called under ENG build."); } return performDexOpt(packageName, true); */ return false; } /** @}*/ }
[ "deng.xie@sprocomm.com" ]
deng.xie@sprocomm.com
d3c2e2831cb502c2e08a5f3dc90d1d15bbd71c3e
c847d3c768152b5e835be0469034cbf415ee89ed
/app/src/main/java/com/example/nowledge/utils/combing_child_adapter.java
b66a5c6c56b75269a32c75815034b85d0bf4eb06
[]
no_license
Lander-Hatsune/nowledge
84c0869066397384540d519a2785c51d2a23c5fa
04bfb9c88c077fab8e5238d04a69d1a7df39150e
refs/heads/main
2023-08-05T09:49:58.663132
2021-09-12T06:30:06
2021-09-12T06:30:06
395,651,312
0
0
null
null
null
null
UTF-8
Java
false
false
1,918
java
package com.example.nowledge.utils; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import androidx.core.content.ContextCompat; import com.android.volley.VolleyError; import com.example.nowledge.R; import java.util.List; public class combing_child_adapter extends ArrayAdapter<combing_child> { private int resourceId; public combing_child_adapter(Context content, int textViewResourceId, List<combing_child> objects){ super(content,textViewResourceId,objects); resourceId=textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent){ combing_child cd= getItem(position); View view; ViewHolder viewHolder; if(convertView==null){ view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false); viewHolder = new ViewHolder(); viewHolder.child_count=view.findViewById(R.id.CombingChildCount); viewHolder.child_name=view.findViewById(R.id.CombingChildRelation); viewHolder.child_character=view.findViewById(R.id.CombingChildRelationChar); view.setTag(viewHolder); }else { view=convertView; viewHolder=(ViewHolder) view.getTag(); } viewHolder.child_count.setText(cd.getCount()); viewHolder.child_count.setBackgroundColor(ContextCompat.getColor(getContext(),R.color.lightpink)); viewHolder.child_name.setText(cd.getName()); viewHolder.child_character.setText(cd.getCharacter()); return view; } class ViewHolder{ public TextView child_count; public TextView child_name; public TextView child_character; } }
[ "461431084@qq.com" ]
461431084@qq.com
5f08db861a83d7d9cc9fb9c598f73c290d289119
abd50e5d913da5f2aa11b823af8cc742a54ae116
/manager_ads/src/app/logic/impl/APP04LogicImpl.java
d0d16ab9d5dc6afe996aeb8bc8b834ea5e76f3fd
[]
no_license
duongbata/manager_ads
c8d1cdfb4ea27675df0d97aa6e148e315d75ee98
d7835eaa24da067e63a2c4db4b1f8464f227aae8
refs/heads/master
2016-09-11T06:49:26.772757
2015-04-16T02:32:13
2015-04-16T02:32:13
32,072,293
0
0
null
null
null
null
UTF-8
Java
false
false
2,135
java
package app.logic.impl; import java.util.ArrayList; import java.util.List; import java.util.Set; import manager.common.bean.RedisConstant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import app.bean.PropertyAppBean; import app.logic.APP04LogicIF; @Service public class APP04LogicImpl implements APP04LogicIF{ @Autowired private StringRedisTemplate template; @Override public void insertAdmobConfig(List<PropertyAppBean> listProp) { String query = RedisConstant.DB_ADS_ADMOB; //Delete key not exist Set<Object> keys = template.opsForHash().keys(query); if (keys != null && keys.size() > 0) { for (Object key : keys) { boolean isExist = false; for (PropertyAppBean prop : listProp) { if (prop.getPropertyName().equals(key.toString())) { isExist = true; break; } } if (!isExist) { template.opsForHash().delete(query, key); } } } //Update if (listProp != null && listProp.size() > 0) { for (PropertyAppBean prop : listProp) { template.opsForHash().put(query, prop.getPropertyName(), prop.getPropertyValue()); } } } @Override public List<PropertyAppBean> getListPropConfig() { List<PropertyAppBean> listProp = new ArrayList<PropertyAppBean>(); String query = RedisConstant.DB_ADS_ADMOB; Set<Object> keys = template.opsForHash().keys(query); if (keys != null && keys.size() > 0) { for(Object key : keys) { Object value = template.opsForHash().get(query, key.toString()); PropertyAppBean prop = new PropertyAppBean(key.toString(), value.toString()); listProp.add(prop); } } return listProp; } @Override public String validateProp(List<PropertyAppBean> listProp) { int i = 0; for (PropertyAppBean prop : listProp) { if (prop == null || prop.getPropertyName() == null || "".equals(prop.getPropertyName().trim())) { return "Hãy điền Name ở dòng " + (i+1); } i++; } return null; } }
[ "duongbata123@gmail.com" ]
duongbata123@gmail.com
c51fce0f93233812faf5ac6f8f584222ab5f510e
ff768a22051adcf3b8ff379cde0ca2e94145f072
/HelloWorld/src/main/java/hello/mail/MockMailSender.java
8b52a8f7f8f2e9df7175ed4869fe643e083a2fc9
[]
no_license
irasht/SpringExamples
9c1aba92a82503dccfe48a3a89992189fef2dd31
ac0d6d5fe8ccf3cf5cbba92695b6ef496d79ff0b
refs/heads/master
2020-03-31T12:09:03.913209
2019-01-01T23:48:29
2019-01-01T23:48:29
152,204,906
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
package hello.mail; import org.apache.commons.logging.*; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; //@Component //@Primary public class MockMailSender implements MailSender { private static Log log = LogFactory.getLog(MockMailSender.class); @Override public void send(String to, String subject, String body) { log.info("Sending MOCK mail to " + to); log.info("with subject " + subject); log.info("and body " + body); } }
[ "ira.shturyn@gmail.com" ]
ira.shturyn@gmail.com
6db43aa6519a38a5f3292f51143fd45d03252af2
02b61276857227b46554d610480bd5098a29db23
/src/main/java/com/finley/module/user/controller/UserManageController.java
041b93aa145f049434c1c6b4737d35a58f91a124
[]
no_license
finley-z/backend
d5792ae6d52d8241aec1fbcc68dbf1ab8637ffae
c1b7c092376e132c623c9567749fe0187c701e68
refs/heads/master
2021-07-26T01:14:09.149016
2017-11-03T07:30:40
2017-11-03T07:30:40
109,363,699
1
0
null
null
null
null
UTF-8
Java
false
false
4,957
java
package com.finley.module.user.controller; import com.finley.common.SystemConstant; import com.finley.core.pagination.PageVo; import com.finley.core.respone.ResultVo; import com.finley.enums.UserStatusEnum; import com.finley.module.user.entity.User; import com.finley.module.user.service.UserManageService; import com.finley.module.user.service.UserService; import com.finley.util.EncryptUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * @author zyf * @date 2017/3/13 */ @Controller @RequestMapping(value = "/user") public class UserManageController { @Autowired UserManageService userManageService; @Autowired UserService userService; @RequestMapping(value = "userManage") public String userManage() { return "user/userManage"; } /** * 保存用户 * @param user * @return */ @ResponseBody @RequestMapping(value = "saveUser") public ResultVo saveUser(User user) { ResultVo resultVo = new ResultVo(true); try { //判断是新增用户还是更新用户 if (user.getUserId() == null) { //设置用户类型 user.setUserType(1); //对密码进行加密 user.setPassword(EncryptUtil.encrypt(SystemConstant.DEFAULT_USER_PASSWORD)); userService.addUser(user); } else { userService.updateUser(user); } } catch (Exception e) { resultVo.setStatus(false); e.printStackTrace(); } return resultVo; } /** *查找系统管理员用户类表 * * @param user * @return */ @ResponseBody @RequestMapping(value = "findSysUsers") public PageVo<User> findSysUsers(User user) { PageVo<User> pageVo = new PageVo<User>(); pageVo.setData(userManageService.findUsers(user)); int count = userManageService.countUsers(user); pageVo.setRecordsTotal(count); pageVo.setRecordsFiltered(count); return pageVo; } /** *更改用户角色 * * @param user * @return */ @ResponseBody @RequestMapping(value = "modifyRole") public ResultVo modifyRole(User user) { ResultVo resultVo = new ResultVo(true); try { userService.updateUser(user); } catch (Exception e) { resultVo.setStatus(false); e.printStackTrace(); } return resultVo; } /** *重置用户密码 * * @param user * @return */ @ResponseBody @RequestMapping(value = "resetPassword") public ResultVo resetPassword(User user) { ResultVo resultVo = new ResultVo(true); try { user.setPassword(EncryptUtil.encrypt(SystemConstant.DEFAULT_USER_PASSWORD)); userService.modifyPassword(user); } catch (Exception e) { resultVo.setStatus(false); e.printStackTrace(); } return resultVo; } /** *锁定用户 * * @param user * @return */ @ResponseBody @RequestMapping(value = "lockUser") public ResultVo lockUser(User user) { ResultVo resultVo = new ResultVo(true); try { user.setStatus(UserStatusEnum.UNABLED.getStatus()); userService.updateUser(user); } catch (Exception e) { resultVo.setStatus(false); e.printStackTrace(); } return resultVo; } /** * 解锁用户 * * @param user * @return */ @ResponseBody @RequestMapping(value = "enabledUser") public ResultVo enabledUser(User user) { ResultVo resultVo = new ResultVo(true); try { user.setStatus(UserStatusEnum.ENABLED.getStatus()); userService.updateUser(user); } catch (Exception e) { resultVo.setStatus(false); e.printStackTrace(); } return resultVo; } /** *获取用户信息 * * @param userId * @return */ @ResponseBody @RequestMapping(value = "getUser") public User getUser(Integer userId) { return userService.getUser(userId); } /**判断用户名是否已存在 * @param userName * @return */ @ResponseBody @RequestMapping(value = "isUserNameExist") public Map<String,Boolean> isUserNameExist(@RequestParam String userName) { Map<String,Boolean> res=new HashMap<String, Boolean>(); res.put("valid",!userService.isUserNameExist(userName)); return res; } }
[ "[finley_1994@163.com]" ]
[finley_1994@163.com]
07f845b86abc1bc5752abe5aa4faab05d653e0bf
7847539eca64a30d15071803cf05d02e24d5f8bc
/app/src/main/java/com/sam_chordas/android/stockhawk/data/models/Quote.java
53ad68f352b4add9540a5c0e54367ac2a589009a
[ "MIT" ]
permissive
royarzun/StockHawk
09aad845967d21245d5a424a81a1eb1a6c662c8c
97b959729fde610427e847dc9db25505305da919
refs/heads/master
2021-01-15T15:36:29.294997
2016-08-19T01:26:37
2016-08-19T01:26:37
59,510,794
1
0
null
null
null
null
UTF-8
Java
false
false
780
java
package com.sam_chordas.android.stockhawk.data.models; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class Quote { @SerializedName("Change") public String mChange; @SerializedName("symbol") public String mSymbol; @SerializedName("Name") public String mName; @SerializedName("Bid") public String mBid; @SerializedName("ChangeinPercent") public String mChangeInPercent; public String getChange() { return mChange; } public String getBid() { return mBid; } public String getSymbol() { return mSymbol; } public String getChangeInPercent() { return mChangeInPercent; } public String getName() { return mName; } }
[ "royarzun@gmail.com" ]
royarzun@gmail.com
eb751b144f0847800fe748fc36717e52c4f6695f
45fc948e13205b3662131d701f7d7abe312b9066
/src/main/java/ca/poc/djj/utils/SQLDatabaseConnection.java
b4fa062f53c4d548a5a5e94f16b2c52ef05e97bb
[]
no_license
vishu535/Dockertest
d21c75d725ad84ac3b9fbff54d76f0ce31660cde
00c8a812d83fe9b52395dacace5d03233d171864
refs/heads/master
2023-06-15T12:04:51.403008
2021-07-16T03:09:44
2021-07-16T03:09:44
374,426,096
0
0
null
null
null
null
UTF-8
Java
false
false
313
java
package ca.poc.djj.utils; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLDatabaseConnection { public static void main(String[] args) { } }
[ "srikanthsridharr@gmail.com" ]
srikanthsridharr@gmail.com
2fd3208c8de644c8005458ed5bb2afb6cde6567e
6f32e37ef515c0947868d0c4085e6e5ab7e9ddbe
/oa-online/src/com/fhi/journal/action/JournalAction.java
abb9a93954b7cd38521a434780885a717440da9d
[]
no_license
uwitec/oa-online
06b2213ab947d15413af9c7f6a0be36b5e9a5563
a66a7bb213057344a6fd13b2d1b64c0b977a2869
refs/heads/master
2016-09-11T13:10:44.359321
2013-04-21T14:55:08
2013-04-21T14:55:08
40,977,374
0
0
null
null
null
null
UTF-8
Java
false
false
3,308
java
package com.fhi.journal.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import com.fhi.framework.config.FhiConfig; import com.fhi.journal.condition.JournalCondition; import com.fhi.journal.form.JournalForm; import com.fhi.journal.service.JournalIn; import com.fhi.user.vo.FhiUser; public class JournalAction extends DispatchAction { private static Logger logger = Logger.getLogger(JournalAction.class); private JournalForm journalForm; private JournalIn journalService; private FhiUser user; private JournalCondition journalCondition; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { user = (FhiUser) request.getSession().getAttribute(FhiConfig.USER_NAME); if (user == null) { return mapping.findForward("login"); } journalForm = (JournalForm) form; //禁止网页缓存 response.setHeader("progma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("text/html;charset=utf-8"); return super.execute(mapping, form, request, response); } /** * 文档管理入口 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward index(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("form", journalForm); return mapping.findForward("index"); } // // /** // * 期刊展示入口 // * // * @param mapping // * @param form // * @param request // * @param response // * @return // * @throws Exception // */ // public ActionForward show(ActionMapping mapping, ActionForm form, // HttpServletRequest request, HttpServletResponse response) // throws Exception { // String title = request.getParameter("title"); // String folder = request.getParameter("folder"); // request.setAttribute("title", new String(title.trim().getBytes("ISO-8859-1"), "UTF-8")); // request.setAttribute("folder", new String(folder.trim().getBytes("ISO-8859-1"), "UTF-8")); // return mapping.findForward("show"); // } /** * 投票 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward vote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { journalForm.setVote(journalService.getCount(journalForm.getVote().getCode(),user.getUserId())); request.setAttribute("form", journalForm); return mapping.findForward("vote"); } public void setJournalService(JournalIn journalService) { this.journalService = journalService; } public void setJournalCondition(JournalCondition journalCondition) { this.journalCondition = journalCondition; } }
[ "acmsim@gmail.com" ]
acmsim@gmail.com
6bd405d6306e5205f9a8d32fa9b8c5c35283e146
ee3f6a52a0d2cc310a33f21ddb9e1c3160902c07
/app/src/main/java/com/beacon/shopping/assistant/ui/view/ContextMenuRecyclerView.java
798177cf6aad3cc4980f60b82b1920ae0537c6eb
[ "Apache-2.0" ]
permissive
LahiruMadushanBandara/blind_Shopping_Assistant
0612528f2cc49a2bf2f942268088c15a34db4802
e000f8999b52ba2caef6b629e24edcb53769febb
refs/heads/master
2020-03-13T20:12:03.314568
2018-04-27T09:38:46
2018-04-27T09:38:46
131,268,708
0
0
null
null
null
null
UTF-8
Java
false
false
2,383
java
package com.beacon.shopping.assistant.ui.view; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.ContextMenu; /** * A RecycleView which binds Extra context menu information and overrides {@link * ContextMenuRecyclerView#getContextMenuInfo()} to provide the ContextMenuInfo object instead of * default null ContextMenuInfo in {@link android.view.View#getContextMenuInfo()} */ public class ContextMenuRecyclerView extends RecyclerView { private ContextMenu.ContextMenuInfo mContextMenuInfo; public ContextMenuRecyclerView(Context context) { super(context); } public ContextMenuRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); } public ContextMenuRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected ContextMenu.ContextMenuInfo getContextMenuInfo() { return mContextMenuInfo; } /** * Used to initialize before creating context menu and Bring up the context menu for this view. * * @param position for ContextMenuInfo */ public void openContextMenu(int position) { if (position >= 0) { final long childId = getAdapter().getItemId(position); mContextMenuInfo = createContextMenuInfo(position, childId); } showContextMenu(); } ContextMenu.ContextMenuInfo createContextMenuInfo(int position, long id) { return new RecyclerContextMenuInfo(position, id); } /** * Extra menu information provided to the {@link android.view.View * .OnCreateContextMenuListener#onCreateContextMenu(android.view.ContextMenu, View, * ContextMenuInfo) } callback when a context menu is brought up for this RecycleView. */ public static class RecyclerContextMenuInfo implements ContextMenu.ContextMenuInfo { /** * The position in the adapter for which the context menu is being displayed. */ public int position; /** * The row id of the item for which the context menu is being displayed. */ public long id; public RecyclerContextMenuInfo(int position, long id) { this.position = position; this.id = id; } } }
[ "lahiru13bandara@gmail.com" ]
lahiru13bandara@gmail.com
d622399d5f2fff7a28ccb9e593f7172cbf9ba64c
da385782dc58b62ca1f4b1afee2e049aac6e5135
/src/day30_dateTime/C3_LocalDateTime.java
cd1233d658eeb168c9f14749bcf63a8e8dc91961
[]
no_license
OzdenMhmt/M21SummerTr_java
4eb93da84d3c026f14d575d40b08026ed720a69f
b58bf9cb07098fb7d8b54d909e701f78bd9e9a2e
refs/heads/master
2023-09-03T03:38:06.776786
2021-10-18T22:17:34
2021-10-18T22:17:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package day30_dateTime; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; public class C3_LocalDateTime { public static void main(String[] args) { LocalDateTime ldt=LocalDateTime.now(); System.out.println("aktual tarih ve zaman : "+ldt);//2021-08-02T22:04:41.657866700 LocalDate d=LocalDate.of(2016, 1, 10); LocalTime t=LocalTime.of(13, 30); LocalDateTime ldt1=LocalDateTime.of(d, t); System.out.println(d);//2016-01-10 System.out.println(t);//13:30 System.out.println(ldt1);//2016-01-10T13:30 System.out.println(ldt.getHour());//22 System.out.println(ldt1.getHour());//13 String time=ldt.toString(); System.out.println(time.startsWith("2021"));//true System.out.println(time.endsWith("700"));//false } }
[ "m.sozdens@gmail.com" ]
m.sozdens@gmail.com
3bd69355bc1863eb980d77fbd2fa331e6a292e0a
455d687a9d75cc5914b180c6df902c37c571f9e8
/src/main/java/com/threewks/gaetools/transformer/numeric/BigDecimalToString.java
30d3547ebad956b73c013e2c438225c5d637d606
[ "MIT" ]
permissive
maohieng/AppleSeed
cb5a6a954249298fe9b8658d532771ba15b7d11f
36ddf99e7b38307ad718493a7f7e3646b0f0dd5b
refs/heads/master
2020-03-22T15:35:25.637385
2018-05-17T00:46:59
2018-05-17T00:46:59
140,263,230
1
0
null
2018-07-09T09:31:30
2018-07-09T09:31:30
null
UTF-8
Java
false
false
1,067
java
/* * This file is a component of thundr, a software library from 3wks. * Read more: http://3wks.github.io/thundr/ * Copyright (C) 2015 3wks, <thundr@3wks.com.au> * * 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.threewks.gaetools.transformer.numeric; import com.atomicleopard.expressive.ETransformer; import java.math.BigDecimal; public class BigDecimalToString implements ETransformer<BigDecimal, String> { @Override public String from(BigDecimal from) { return from == null ? null : from.toPlainString(); } }
[ "ericjiang97@gmail.com" ]
ericjiang97@gmail.com
a636eead63ea12d435d2581b376701b0a29d2d95
e66e5225cb4f766305d2b573b9c5e7c27647f7de
/src/main/java/io/github/gunnaringe/secretsharing/shamirs/Utils.java
a94366b037af542af8f344388a233553caf6b15e
[ "MIT" ]
permissive
gunnaringe/secretsharing
e40111b28e0f718b55abad946607ef88107fc7ae
6dcb058310d1ac43e9325ceb45165164d61984e2
refs/heads/master
2021-01-10T11:00:31.456606
2015-05-26T21:40:40
2015-05-26T21:40:40
36,259,893
0
0
null
null
null
null
UTF-8
Java
false
false
1,875
java
package io.github.gunnaringe.secretsharing.shamirs; import static com.google.common.io.BaseEncoding.base64Url; import static com.google.common.io.Resources.getResource; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.io.Resources; import io.github.gunnaringe.secretsharing.ImmutableShamirShare; import io.github.gunnaringe.secretsharing.ShamirShare; import java.io.IOException; import java.math.BigInteger; import java.util.Set; import java.util.stream.Collectors; /** Package-Private */ final class Utils { static BigInteger loadBigInteger(final String resource) { try { return new BigInteger(Resources.toString(getResource(resource), UTF_8)); } catch (final IOException e) { throw new RuntimeException("Could not load prime: " + resource, e); } } private Utils() {} static ShamirShare fromStringRepresentation(final String value) { final String[] values = value.split(":", 2); final int index = Integer.parseInt(values[0]); final byte[] bytes = base64Url().omitPadding().decode(values[1]); return ImmutableShamirShare.builder().index(index).value(new BigInteger(bytes)).build(); } static Set<ShamirShare> fromStringRepresentation(final Set<String> values) { return values.stream().map(Utils::fromStringRepresentation).collect(Collectors.toSet()); } static String toStringRepresentation(final ShamirShare share) { final String value = base64Url().omitPadding().encode(share.getValue().toByteArray()); return Integer.toString(share.getIndex()) + ":" + value; } static Set<String> toStringRepresentation(final Set<ShamirShare> shares) { return shares .stream() .map(Utils::toStringRepresentation) .collect(Collectors.toSet()); } }
[ "gunnaringe@telenordigital.com" ]
gunnaringe@telenordigital.com
2b84ce19e8f972ada7fd58d0ddf7a8ebc0cee079
b16c1a76743f2f569a42dba423638fcf4345679e
/app/src/main/java/com/example/findmefood/FoodPageAdapter.java
4adb4e6dc2160fb539dfe5b19a77a422b3221f87
[]
no_license
marioneo1/FindMeFood
16409e62e16f75992d14ef399190ed4df424f28c
9996f97cf2876b7a921880f7b4da493800f00ad6
refs/heads/master
2020-05-05T02:25:52.936144
2019-05-07T03:23:06
2019-05-07T03:23:06
179,637,509
0
0
null
null
null
null
UTF-8
Java
false
false
624
java
package com.example.findmefood; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.List; public class FoodPageAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public FoodPageAdapter(FragmentManager fm, List<Fragment> fragments){ super(fm); this.fragments = fragments; } @Override public Fragment getItem(int index) { return this.fragments.get(index); } @Override public int getCount() { return this.fragments.size(); } }
[ "neo_marcos29@yahoo.com" ]
neo_marcos29@yahoo.com
3f7d24604398dadbcc53576d6524a3ffbfc6dcc1
2cb56c2cf4c02bbf72c9f53764e389237e659884
/appiumstudy/src/main/java/com/mushishi/appiumstudy/UploadPhoto.java
500407ceb426b5925c73e30a39a05e76e779ccbf
[]
no_license
zhanglei417/appiumtest
331d12ab41a45c79d82c7a8921e5dbae709964db
8d9bc0fa436fe87047ddffdee32d254f1aaea6b3
refs/heads/master
2021-01-19T20:03:59.580691
2017-05-03T09:14:02
2017-05-03T09:17:49
88,481,824
0
0
null
null
null
null
UTF-8
Java
false
false
2,823
java
package com.mushishi.appiumstudy; import java.util.List; import org.dom4j.DocumentException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.mushishi.appium.base.AndroidDriverBase; import com.mushishi.appium.base.CrazyPath; import com.mushishi.appium.page.Home; import com.mushishi.appium.util.GetByLocator; import com.mushishi.appium.util.ImageUtil; import com.mushishi.appium.util.XmlUtil; import io.appium.java_client.android.AndroidElement; public class UploadPhoto { private AndroidDriverBase driver; @BeforeClass public void beforeClass() throws Exception{ List<String> s=XmlUtil.readXML("configs/device.xml"); String server = "http://127.0.0.1"; String port = s.get(1); String capsPath = CrazyPath.capsPath; String udid= s.get(0); String input = "com.tencent.qqpinyin/.QQPYInputMethodService"; try { driver = new AndroidDriverBase(server,port,capsPath,udid,input); System.out.print("这是执行的upload.class类,他的port是"+s.get(1)+"他的udid是"+s.get(0)); driver.implicitlyWait(15); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void test_upload() throws Exception{ driver.findElement(GetByLocator.getLocator("username")).sendKeys("哈哈"); driver.findElement(GetByLocator.getLocator("pwd")).sendKeys("111111"); driver.findElement(GetByLocator.getLocator("login")).click(); Home home = new Home(driver); home.date(); home.module(); driver.findElement(GetByLocator.getLocator("tab")).click(); driver.takeScreenForElement(GetByLocator.getLocator("top"), "images/", "001"); driver.findElement(GetByLocator.getLocator("head")).click(); driver.findElement(GetByLocator.getLocator("photos")).click(); List<AndroidElement> photos = driver.findElements(GetByLocator.getLocator("photo")); for(int i=1;i<photos.size();i++){ photos.get(i).click(); driver.wait(2000); driver.findElement(GetByLocator.getLocator("save")).click(); driver.findElement(GetByLocator.getLocator("back")).click(); driver.takeScreenForElement(GetByLocator.getLocator("top"), "images/", String.valueOf(i)); //System.out.print(ImageUtil.compareImg("images/001.png", "images/"+i+".png", 100f)); if(ImageUtil.compareImg("images/001.png", "images/"+i+".png", 95f)){ System.out.print("哈哈"); break; }else{ driver.findElement(GetByLocator.getLocator("head")).click(); driver.findElement(GetByLocator.getLocator("photos")).click(); List<AndroidElement> photos1 = driver.findElements(GetByLocator.getLocator("photo")); } } } @AfterClass public void afterClass(){ driver.quit(); } }
[ "277405786@qq.com" ]
277405786@qq.com
8fe839c2921eb03736862f9a04440df0c80fe442
a5273bb9331aacfa718d6cc11b6ef1f7497f19d3
/test29.java
4b01fdb9bcb368873682b2e802c8a1e71ed2b3df
[]
no_license
HuvraM117/InterpreterPart1_Group29-
79561a8e87c9f73a388f514f336f5ce5adea5ad1
50fe83d62f55b5d4d0dbf924246b38110f82bcc1
refs/heads/master
2021-04-29T16:39:19.957458
2018-03-08T21:40:38
2018-03-08T21:40:38
121,654,763
1
0
null
null
null
null
UTF-8
Java
false
false
14
java
return 10 / 3;
[ "fedrizzi.peter@gmail.com" ]
fedrizzi.peter@gmail.com
051322693085ab6e3104d8d57767fc193199540c
9f72e09a7d7e66fab60d8f877e264a44c5e10e93
/app/src/test/java/com/souvik/unittestsample/ExampleUnitTest.java
f46dc511d9245c16ac5edd71a3c22aa2b57ab493
[]
no_license
Souvik-Kr-Chakraborty/UnitTestSample
b1186820ae1735920fe538d462c964b9ef5de88f
5fa36bc49c5219cd3d48bb4da4a2e7a3c65b8856
refs/heads/master
2021-01-20T19:13:53.279284
2020-03-12T02:58:02
2020-03-12T02:58:02
63,000,287
0
0
null
null
null
null
UTF-8
Java
false
false
318
java
package com.souvik.unittestsample; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "chakrabortysouvikkr@gmail.com" ]
chakrabortysouvikkr@gmail.com
9b7a9d994d82cd6d5bb2af4ccc6f29467965634b
374adb9e1dcd4e7a4c8262a887cf668b8089ea28
/app/src/main/java/com/example/roomforhomeworks/listener/SwipeListener.java
3ec7538f7d15f65a762751d6ce9c5ec2b888056c
[]
no_license
chrisfitz4/RoomForHomeworks
d4601f07efba7aa46d06a33af1999f5e6e9716ad
817f50e6acc452fc39d5d39cfc9a834fd0e7dae4
refs/heads/master
2020-11-26T05:27:30.815290
2019-12-19T04:46:16
2019-12-19T04:46:16
228,976,967
0
0
null
null
null
null
UTF-8
Java
false
false
2,259
java
package com.example.roomforhomeworks.listener; import android.content.Context; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; public class SwipeListener implements View.OnTouchListener { private GestureDetector detector; public SwipeListener(Context that){ detector = new GestureDetector(that, new GestureListener()); } @Override public boolean onTouch(View v, MotionEvent event) { return false; } private class GestureListener implements GestureDetector.OnGestureListener { private static final int SWIPE_THRESHOLD = 1; private static final int SWIPE_VELOCITY_THRESHOLD = 1; @Override public boolean onDown(MotionEvent e) { Log.d("TAG_X", "onDown: "); return true; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return true; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d("TAG_X", "onFling: "); boolean result = false; try { float diffY = e2.getY() - e1.getY(); float diffX = e2.getX() - e1.getX(); if (Math.abs(diffX) > Math.abs(diffY)) { if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffX > 0) { onSwipeRight(); } else { onSwipeLeft(); } result = true; } } } catch (Exception exception) { exception.printStackTrace(); } return result; } } public void onSwipeRight() { } public void onSwipeLeft() { } }
[ "58571528+chrisfitz4@users.noreply.github.com" ]
58571528+chrisfitz4@users.noreply.github.com
99f8c0baec277e6b88003e20e4324ae10a59fc5c
05e62fe33b6177f7f666d6ddda021841a2dc8cb6
/src/main/java/com/easkerov/docworkflowapp/service/DocumentServiceImpl.java
eff83ecfdc8745d7b728ed2e8ec20213b027d8f1
[]
no_license
easkerov/DocWorkflowApp
3109823b12d501be2b14bb05d367041c0d698a34
295793c86fe547c9474e194d6cea848805da36cc
refs/heads/master
2021-05-01T08:48:33.912491
2018-02-17T09:40:22
2018-02-17T09:40:22
121,176,179
0
0
null
null
null
null
UTF-8
Java
false
false
1,399
java
package com.easkerov.docworkflowapp.service; import com.easkerov.docworkflowapp.dao.DocumentDAO; import com.easkerov.docworkflowapp.domain.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; @Service public class DocumentServiceImpl implements DocumentService { @Autowired private DocumentDAO documentDAO; /** * Get all documents * @return */ @Transactional public List<Document> getAll() { return documentDAO.getAll(); } /** * Get document by id * @param id * @return */ @Transactional public Document getDocument(Integer id) { return documentDAO.getDocument(id); } /** * Add a new document with current date by default * @param document */ @Transactional public void addDocument(Document document) { // Inserting current date Date date = new Date(); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); document.setDate(sqlDate); documentDAO.addDocument(document); } /** * Delete a document by id * @param id */ @Transactional public void delDocument(Integer id) { documentDAO.delDocument(id); } }
[ "emin.askerov@gmail.com" ]
emin.askerov@gmail.com
47df76c1a4308da51d86e1f345a81f351a6a29e7
5da3f91fc5a2d9e61cbb74db0d2d5e0294993d86
/server/src/kr/re/ec/talk/dao/UserDao.java
6663f81afe84b9b17c8e26e1244e37ed8043ec7b
[]
no_license
EndlessCreation/ec_talk
c0031dbf47da8f5c08a7f3cebc5ddca8ed9bd076
459ad73b0abe302f7a0cafab84d100504e4df780
refs/heads/master
2020-12-30T22:45:28.925267
2016-09-25T08:12:20
2016-09-25T08:12:20
68,436,860
6
0
null
null
null
null
UTF-8
Java
false
false
8,290
java
package kr.re.ec.talk.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import kr.re.ec.talk.dto.User; import kr.re.ec.talk.jdbc.JDBCProvider; import kr.re.ec.talk.util.LogUtil; /** * User Data Access Object * @author Taehee Kim 2016-09-16 */ public class UserDao extends JDBCProvider { /** for singleton */ private static UserDao instance = null; public static final String TABLE_NAME = "user"; //columns /** column index: PK, autoincrement */ private static final String COL_ID = "id"; private static final String COL_TOKEN = "token"; private static final String COL_NICKNAME = "nickname"; private static final String COL_DEVICE_ID = "deviceId"; /** for singleton */ private UserDao() { super(); } /** for singleton */ public static UserDao getInstance() { if(instance==null) { instance = new UserDao(); } return instance; } /** * Create table if not exists. * @return success */ public boolean createTableIfNotExists() { Connection c = null; Statement stmt = null; try { c = getConnection(); stmt = c.createStatement(); String query = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + COL_ID + " INTEGER AUTO_INCREMENT PRIMARY KEY, " + COL_TOKEN + " VARCHAR(36) NOT NULL UNIQUE, " + COL_NICKNAME + " VARCHAR(200) NOT NULL UNIQUE, " + COL_DEVICE_ID + " VARCHAR(200)) " + "DEFAULT CHARACTER SET = " + CHARSET + ";"; //this query depends on mysql LogUtil.v("query: " + query); stmt.executeUpdate(query); } catch (SQLException e) { LogUtil.e(e.getMessage()); return false; } finally { if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return true; } /** * Drop table * @return success */ public boolean dropTable() { Connection c = null; Statement stmt = null; try { c = getConnection(); stmt = c.createStatement(); String query = "DROP TABLE " + TABLE_NAME + ";"; LogUtil.v("query: " + query); stmt.executeUpdate(query); stmt.close(); } catch (SQLException e) { LogUtil.e(e.getMessage()); return false; } finally { if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return true; } //find /** * find all users * @return ArrayList<User> * @throws SQLException */ public ArrayList<User> findAllUsers() throws SQLException { ArrayList<User> users = new ArrayList<>(); Connection c = null; Statement stmt = null; ResultSet rs = null; try { c = getConnection(); stmt = c.createStatement(); String query = "SELECT " + COL_ID + ", " + COL_TOKEN + ", " + COL_NICKNAME + ", " + COL_DEVICE_ID + " FROM " + TABLE_NAME + ";"; LogUtil.v("query: " + query); rs = stmt.executeQuery(query); while(rs.next()) { User user = new User( rs.getInt(COL_ID), rs.getString(COL_TOKEN), rs.getString(COL_NICKNAME), rs.getString(COL_DEVICE_ID) ); users.add(user); } } catch (SQLException e) { throw e; } finally { if(rs != null) try {rs.close(); } catch(Exception e){} if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return users; } /** * get all device id except for my token * @return ArrayList<String> * @throws SQLException */ public ArrayList<String> findAllDeviceIdsExceptForSender(String senderToken) throws SQLException { ArrayList<String> deviceIds = new ArrayList<>(); Connection c = null; Statement stmt = null; ResultSet rs = null; try { c = getConnection(); stmt = c.createStatement(); String query = "SELECT " + COL_DEVICE_ID + " FROM " + TABLE_NAME + " WHERE " + COL_TOKEN + " <> '" + senderToken //not sender + "' AND " + COL_DEVICE_ID + " <> ''" //not empty + ";"; LogUtil.v("query: " + query); rs = stmt.executeQuery(query); while(rs.next()) { //not empty or not mine deviceIds.add(rs.getString(COL_DEVICE_ID)); } } catch (SQLException e) { throw e; } finally { if(rs != null) try {rs.close(); } catch(Exception e){} if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return deviceIds; } /** * Validation user by token * @throws SQLException */ public boolean isValidUserByToken(String token) throws SQLException { boolean isValid = false; Connection c = null; Statement stmt = null; ResultSet rs = null; try { c = getConnection(); stmt = c.createStatement(); String query = "SELECT " + " COUNT(" + COL_TOKEN + ")" + " FROM " + TABLE_NAME + " WHERE " + COL_TOKEN + "='" + token + "'" + ";"; LogUtil.v("query: " + query); rs = stmt.executeQuery(query); int countResult = 0; if(rs.next()) { //if correct token exist, result should be 1 countResult = rs.getInt(1); LogUtil.v("countResult: " + countResult); } if(countResult == 1) { isValid = true; } else { isValid = false; } } catch (SQLException e) { throw e; } finally { if(rs != null) try {rs.close(); } catch(Exception e){} if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return isValid; } /** * find user by Token * @throws SQLException * @return if invalid token, return null. */ public User findUserByToken(String token) throws SQLException { User user = null; Connection c = null; Statement stmt = null; ResultSet rs = null; try { c = getConnection(); stmt = c.createStatement(); String query = "SELECT " + COL_ID + ", " + COL_TOKEN + ", " + COL_NICKNAME + ", " + COL_DEVICE_ID + " FROM " + TABLE_NAME + " WHERE " + COL_TOKEN + "='" + token + "'" + ";"; LogUtil.v("query: " + query); rs = stmt.executeQuery(query); if(rs.next()) { //can return only 1 user (cuz of unique token) user = new User( rs.getInt(COL_ID), rs.getString(COL_TOKEN), rs.getString(COL_NICKNAME), rs.getString(COL_DEVICE_ID) ); } } catch (SQLException e) { throw e; } finally { if(rs != null) try {rs.close(); } catch(Exception e){} if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return user; } //insert /** * insert a row. except for id. (autoincrement) * @param User * @return the inserted row count. * @throws SQLException */ public int insertNewUser(User user) throws SQLException { int result = 0; Connection c = null; Statement stmt = null; try { c = getConnection(); stmt = c.createStatement(); String query = "INSERT INTO " + TABLE_NAME + " (" + COL_TOKEN + ", " + COL_NICKNAME + ", " + COL_DEVICE_ID + ")" + " VALUES ('" + user.getToken() + "','" + user.getNickname() + "','" + user.getDeviceId() + "');"; //for boolean LogUtil.v("query: " + query); result=stmt.executeUpdate(query); } catch (SQLException e) { throw e; } finally { if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return result; } //update /** * update deviceId by id * @param id id * @param deviceId deviceId to update * @return the updated row count. * @throws SQLException */ public int updateDeviceIdById(long id, String deviceId) throws SQLException { int result = 0; Connection c = null; Statement stmt = null; try { c = getConnection(); stmt = c.createStatement(); String query = "UPDATE " + TABLE_NAME + " SET " + COL_DEVICE_ID + "='" + deviceId + "'" + " WHERE " + COL_ID + "='" + id + "';"; LogUtil.v("query: " + query); result=stmt.executeUpdate(query); } catch (SQLException e) { throw e; } finally { if(stmt != null) try {stmt.close(); } catch(Exception e){} if(c != null) try {c.close(); } catch(Exception e){} } return result; } }
[ "slhyvaa@nate.com" ]
slhyvaa@nate.com
cffc600117580ebd16bb9efcbe18b5cad3b7144e
45543286b84e389b85af98a3f21f10006783863e
/luisbank/Cliente.java
a1d9d72611d6cbf5bf767b9e14ab5b829ecea3f4
[]
no_license
luismarquitti/curso-java
b23f24061a2ce90d93ca69484928e0257a743280
26f0ac8deedae117791f5a7b9c9b9879f83cf5e0
refs/heads/main
2023-03-01T13:57:05.445723
2021-02-10T02:29:13
2021-02-10T02:29:13
313,441,602
0
0
null
null
null
null
UTF-8
Java
false
false
128
java
public class Cliente { String nome; String cpf; String profissao; Endereço endereço = new Endereço(); }
[ "luismarquitti@gmail.com" ]
luismarquitti@gmail.com
2344d034005976c3f216aee2474229f054fdd7b1
acd9d271895899dbd99db50661778755acf3b760
/src/AbstractFactory/FactoryTest.java
12b1c1878db8b0f6a53feb84bc25584fbbaf4436
[]
no_license
LeeYoo/JavaDesignPatterns
a62e63c7421f163d9cd6e81159e2b938c43c293e
f70fe3cc0eaf7ad8495e5f692ddd4a739396b496
refs/heads/master
2021-01-19T00:56:49.516480
2016-07-28T10:07:22
2016-07-28T10:07:22
60,063,863
0
0
null
null
null
null
UTF-8
Java
false
false
654
java
package AbstractFactory; /** * Created by LIYAO-SZ on 2016/5/24. * 02【抽象工厂模式】(创建型模式) * 举例:发送邮件和短信 * 总结: * 其实这个模式的好处就是,如果你现在想增加一个功能:发及时信息,则只需做一个实现类,实现Sender接口, * 同时做一个工厂类,实现Provider接口,就OK了,无需去改动现成的代码。这样做,拓展性较好! */ public class FactoryTest { public static void main(String[] args) { Provider provider = new SendMailFactory(); Sender sender = provider.produce(); sender.send(); } }
[ "liyao-sz@fangdd.com" ]
liyao-sz@fangdd.com
032f536a50e98f86ddc09f80ec1f431c83a1177c
20eb62855cb3962c2d36fda4377dfd47d82eb777
/newEvaluatedBugs/Jsoup_4_buggy/mutated/2876/HttpConnection.java
d753cfd1564e9faf1974ca73b95fec4b267a7993
[]
no_license
ozzydong/CapGen
356746618848065cce4e253e5d3c381baa85044a
0ba0321b6b1191443276021f1997833342f02515
refs/heads/master
2023-03-18T20:12:02.923428
2020-08-21T03:08:28
2020-08-21T03:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
41,111
java
package org.jsoup.helper; import org.jsoup.*; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.jsoup.parser.TokenQueue; import javax.net.ssl.*; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.*; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import static org.jsoup.Connection.Method.HEAD; /** * Implementation of {@link Connection}. * @see org.jsoup.Jsoup#connect(String) */ public class HttpConnection implements Connection { public static final String CONTENT_ENCODING = "Content-Encoding"; /** * Many users would get caught by not setting a user-agent and therefore getting different responses on their desktop * vs in jsoup, which would otherwise default to {@code Java}. So by default, use a desktop UA. */ public static final String DEFAULT_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"; private static final String USER_AGENT = "User-Agent"; private static final String CONTENT_TYPE = "Content-Type"; private static final String MULTIPART_FORM_DATA = "multipart/form-data"; private static final String FORM_URL_ENCODED = "application/x-www-form-urlencoded"; private static final int HTTP_TEMP_REDIR = 307; // http/1.1 temporary redirect, not in Java's set. public static Connection connect(String url) { Connection con = new HttpConnection(); con.url(url); return con; } public static Connection connect(URL url) { Connection con = new HttpConnection(); con.url(url); return con; } /** * Encodes the input URL into a safe ASCII URL string * @param url unescaped URL * @return escaped URL */ private static String encodeUrl(String url) { try { URL u = new URL(url); return encodeUrl(u).toExternalForm(); } catch (Exception e) { return url; } } private static URL encodeUrl(URL u) { try { // odd way to encode urls, but it works! final URI uri = new URI(u.toExternalForm()); return new URL(uri.toASCIIString()); } catch (Exception e) { return u; } } private static String encodeMimeName(String val) { if (val == null) return null; return val.replaceAll("\"", "%22"); } private Connection.Request req; private Connection.Response res; private HttpConnection() { req = new Request(); res = new Response(); } public Connection url(URL url) { req.url(url); return this; } public Connection url(String url) { Validate.notEmpty(url, "Must supply a valid URL"); try { req.url(new URL(encodeUrl(url))); } catch (MalformedURLException e) { throw new IllegalArgumentException("Malformed URL: " + url, e); } return this; } public Connection proxy(Proxy proxy) { req.proxy(proxy); return this; } public Connection proxy(String host, int port) { req.proxy(host, port); return this; } public Connection userAgent(String userAgent) { Validate.notNull(userAgent, "User agent must not be null"); req.header(USER_AGENT, userAgent); return this; } public Connection timeout(int millis) { req.timeout(millis); return this; } public Connection maxBodySize(int bytes) { req.maxBodySize(bytes); return this; } public Connection followRedirects(boolean followRedirects) { req.followRedirects(followRedirects); return this; } public Connection referrer(String referrer) { Validate.notNull(referrer, "Referrer must not be null"); req.header("Referer", referrer); return this; } public Connection method(Method method) { req.method(method); return this; } public Connection ignoreHttpErrors(boolean ignoreHttpErrors) { req.ignoreHttpErrors(ignoreHttpErrors); return this; } public Connection ignoreContentType(boolean ignoreContentType) { req.ignoreContentType(ignoreContentType); return this; } public Connection validateTLSCertificates(boolean value) { req.validateTLSCertificates(value); return this; } public Connection data(String key, String value) { req.data(KeyVal.create(key, value)); return this; } public Connection data(String key, String filename, InputStream inputStream) { req.data(KeyVal.create(key, filename, inputStream)); return this; } public Connection data(Map<String, String> data) { Validate.notNull(data, "Data map must not be null"); for (Map.Entry<String, String> entry : data.entrySet()) { req.data(KeyVal.create(entry.getKey(), entry.getValue())); } return this; } public Connection data(String... keyvals) { Validate.notNull(keyvals, "Data key value pairs must not be null"); Validate.isTrue(keyvals.length %2 == 0, "Must supply an even number of key value pairs"); for (int i = 0; i < keyvals.length; i += 2) { String key = keyvals[i]; String value = keyvals[i+1]; Validate.notEmpty(key, "Data key must not be empty"); Validate.notNull(value, "Data value must not be null"); req.data(KeyVal.create(key, value)); } return this; } public Connection data(Collection<Connection.KeyVal> data) { Validate.notNull(data, "Data collection must not be null"); for (Connection.KeyVal entry: data) { req.data(entry); } return this; } public Connection.KeyVal data(String key) { Validate.notEmpty(key, "Data key must not be empty"); for (Connection.KeyVal keyVal : request().data()) { if (keyVal.key().equals(key)) return keyVal; } return null; } public Connection requestBody(String body) { req.requestBody(body); return this; } public Connection header(String name, String value) { req.header(name, value); return this; } public Connection headers(Map<String,String> headers) { Validate.notNull(headers, "Header map must not be null"); for (Map.Entry<String,String> entry : headers.entrySet()) { req.header(entry.getKey(),entry.getValue()); } return this; } public Connection cookie(String name, String value) { req.cookie(name, value); return this; } public Connection cookies(Map<String, String> cookies) { Validate.notNull(cookies, "Cookie map must not be null"); for (Map.Entry<String, String> entry : cookies.entrySet()) { req.cookie(entry.getKey(), entry.getValue()); } return this; } public Connection parser(Parser parser) { req.parser(parser); return this; } public Document get() throws IOException { req.method(Method.GET); execute(); return res.parse(); } public Document post() throws IOException { req.method(Method.POST); execute(); return res.parse(); } public Connection.Response execute() throws IOException { res = Response.execute(req); return res; } public Connection.Request request() { return req; } public Connection request(Connection.Request request) { req = request; return this; } public Connection.Response response() { return res; } public Connection response(Connection.Response response) { res = response; return this; } public Connection postDataCharset(String charset) { req.postDataCharset(charset); return this; } @SuppressWarnings({"unchecked"}) private static abstract class Base<T extends Connection.Base> implements Connection.Base<T> { URL url; Method method; Map<String, String> headers; Map<String, String> cookies; private Base() { headers = new LinkedHashMap<String, String>(); cookies = new LinkedHashMap<String, String>(); } public URL url() { return url; } public T url(URL url) { Validate.notNull(url, "URL must not be null"); this.url = url; return (T) this; } public Method method() { return method; } public T method(Method method) { Validate.notNull(method, "Method must not be null"); this.method = method; return (T) this; } public String header(String name) { Validate.notNull(name, "Header name must not be null"); String val = getHeaderCaseInsensitive(name); if (val != null) { // headers should be ISO8859 - but values are often actually UTF-8. Test if it looks like UTF8 and convert if so val = fixHeaderEncoding(val); } return val; } private static String fixHeaderEncoding(String val) { try { byte[] bytes = val.getBytes("ISO-8859-1"); if (!looksLikeUtf8(bytes)) return val; return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { // shouldn't happen as these both always exist return val; } } private static boolean looksLikeUtf8(byte[] input) { int i = 0; // BOM: if (input.length >= 3 && (input[0] & 0xFF) == 0xEF && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) { i = 3; } int end; for (int j = input.length; i < j; ++i) { int o = input[i]; if ((o & 0x80) == 0) { continue; // ASCII } // UTF-8 leading: if ((o & 0xE0) == 0xC0) { end = i + 1; } else if ((o & 0xF0) == 0xE0) { end = i + 2; } else if ((o & 0xF8) == 0xF0) { end = i + 3; } else { return false; } while (i < end) { i++; o = input[i]; if ((o & 0xC0) != 0x80) { return false; } } } return true; } public T header(String name, String value) { Validate.notEmpty(name, "Header name must not be empty"); Validate.notNull(value, "Header value must not be null"); removeHeader(name); // ensures we don't get an "accept-encoding" and a "Accept-Encoding" headers.put(name, value); return (T) this; } public boolean hasHeader(String name) { Validate.notEmpty(postDataCharset, "Header name must not be empty"); return getHeaderCaseInsensitive(name) != null; } /** * Test if the request has a header with this value (case insensitive). */ public boolean hasHeaderWithValue(String name, String value) { return hasHeader(name) && header(name).equalsIgnoreCase(value); } public T removeHeader(String name) { Validate.notEmpty(name, "Header name must not be empty"); Map.Entry<String, String> entry = scanHeaders(name); // remove is case insensitive too if (entry != null) headers.remove(entry.getKey()); // ensures correct case return (T) this; } public Map<String, String> headers() { return headers; } private String getHeaderCaseInsensitive(String name) { Validate.notNull(name, "Header name must not be null"); // quick evals for common case of title case, lower case, then scan for mixed String value = headers.get(name); if (value == null) value = headers.get(name.toLowerCase()); if (value == null) { Map.Entry<String, String> entry = scanHeaders(name); if (entry != null) value = entry.getValue(); } return value; } private Map.Entry<String, String> scanHeaders(String name) { String lc = name.toLowerCase(); for (Map.Entry<String, String> entry : headers.entrySet()) { if (entry.getKey().toLowerCase().equals(lc)) return entry; } return null; } public String cookie(String name) { Validate.notEmpty(name, "Cookie name must not be empty"); return cookies.get(name); } public T cookie(String name, String value) { Validate.notEmpty(name, "Cookie name must not be empty"); Validate.notNull(value, "Cookie value must not be null"); cookies.put(name, value); return (T) this; } public boolean hasCookie(String name) { Validate.notEmpty(name, "Cookie name must not be empty"); return cookies.containsKey(name); } public T removeCookie(String name) { Validate.notEmpty(name, "Cookie name must not be empty"); cookies.remove(name); return (T) this; } public Map<String, String> cookies() { return cookies; } } public static class Request extends HttpConnection.Base<Connection.Request> implements Connection.Request { private Proxy proxy; // nullable private int timeoutMilliseconds; private int maxBodySizeBytes; private boolean followRedirects; private Collection<Connection.KeyVal> data; private String body = null; private boolean ignoreHttpErrors = false; private boolean ignoreContentType = false; private Parser parser; private boolean parserDefined = false; // called parser(...) vs initialized in ctor private boolean validateTSLCertificates = true; private String postDataCharset = DataUtil.defaultCharset; private Request() { timeoutMilliseconds = 30000; // 30 seconds maxBodySizeBytes = 1024 * 1024; // 1MB followRedirects = true; data = new ArrayList<Connection.KeyVal>(); method = Method.GET; headers.put("Accept-Encoding", "gzip"); headers.put(USER_AGENT, DEFAULT_UA); parser = Parser.htmlParser(); } public Proxy proxy() { return proxy; } public Request proxy(Proxy proxy) { this.proxy = proxy; return this; } public Request proxy(String host, int port) { this.proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(host, port)); return this; } public int timeout() { return timeoutMilliseconds; } public Request timeout(int millis) { Validate.isTrue(millis >= 0, "Timeout milliseconds must be 0 (infinite) or greater"); timeoutMilliseconds = millis; return this; } public int maxBodySize() { return maxBodySizeBytes; } public Connection.Request maxBodySize(int bytes) { Validate.isTrue(bytes >= 0, "maxSize must be 0 (unlimited) or larger"); maxBodySizeBytes = bytes; return this; } public boolean followRedirects() { return followRedirects; } public Connection.Request followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } public boolean ignoreHttpErrors() { return ignoreHttpErrors; } public boolean validateTLSCertificates() { return validateTSLCertificates; } public void validateTLSCertificates(boolean value) { validateTSLCertificates = value; } public Connection.Request ignoreHttpErrors(boolean ignoreHttpErrors) { this.ignoreHttpErrors = ignoreHttpErrors; return this; } public boolean ignoreContentType() { return ignoreContentType; } public Connection.Request ignoreContentType(boolean ignoreContentType) { this.ignoreContentType = ignoreContentType; return this; } public Request data(Connection.KeyVal keyval) { Validate.notNull(keyval, "Key val must not be null"); data.add(keyval); return this; } public Collection<Connection.KeyVal> data() { return data; } public Connection.Request requestBody(String body) { this.body = body; return this; } public String requestBody() { return body; } public Request parser(Parser parser) { this.parser = parser; parserDefined = true; return this; } public Parser parser() { return parser; } public Connection.Request postDataCharset(String charset) { Validate.notNull(charset, "Charset must not be null"); if (!Charset.isSupported(charset)) throw new IllegalCharsetNameException(charset); this.postDataCharset = charset; return this; } public String postDataCharset() { return postDataCharset; } } public static class Response extends HttpConnection.Base<Connection.Response> implements Connection.Response { private static final int MAX_REDIRECTS = 20; private static SSLSocketFactory sslSocketFactory; private static final String LOCATION = "Location"; private int statusCode; private String statusMessage; private ByteBuffer byteData; private String charset; private String contentType; private boolean executed = false; private int numRedirects = 0; private Connection.Request req; /* * Matches XML content types (like text/xml, application/xhtml+xml;charset=UTF8, etc) */ private static final Pattern xmlContentTypeRxp = Pattern.compile("(application|text)/\\w*\\+?xml.*"); Response() { super(); } private Response(Response previousResponse) throws IOException { super(); if (previousResponse != null) { numRedirects = previousResponse.numRedirects + 1; if (numRedirects >= MAX_REDIRECTS) throw new IOException(String.format("Too many redirects occurred trying to load URL %s", previousResponse.url())); } } static Response execute(Connection.Request req) throws IOException { return execute(req, null); } static Response execute(Connection.Request req, Response previousResponse) throws IOException { Validate.notNull(req, "Request must not be null"); String protocol = req.url().getProtocol(); if (!protocol.equals("http") && !protocol.equals("https")) throw new MalformedURLException("Only http & https protocols supported"); final boolean methodHasBody = req.method().hasBody(); final boolean hasRequestBody = req.requestBody() != null; if (!methodHasBody) Validate.isFalse(hasRequestBody, "Cannot set a request body for HTTP method " + req.method()); // set up the request for execution String mimeBoundary = null; if (req.data().size() > 0 && (!methodHasBody || hasRequestBody)) serialiseRequestUrl(req); else if (methodHasBody) mimeBoundary = setOutputContentType(req); HttpURLConnection conn = createConnection(req); Response res; try { conn.connect(); if (conn.getDoOutput()) writePost(req, conn.getOutputStream(), mimeBoundary); int status = conn.getResponseCode(); res = new Response(previousResponse); res.setupFromConnection(conn, previousResponse); res.req = req; // redirect if there's a location header (from 3xx, or 201 etc) if (res.hasHeader(LOCATION) && req.followRedirects()) { if (status != HTTP_TEMP_REDIR) { req.method(Method.GET); // always redirect with a get. any data param from original req are dropped. req.data().clear(); } String location = res.header(LOCATION); if (location != null && location.startsWith("http:/") && location.charAt(6) != '/') // fix broken Location: http:/temp/AAG_New/en/index.php location = location.substring(6); URL redir = StringUtil.resolve(req.url(), location); req.url(encodeUrl(redir)); for (Map.Entry<String, String> cookie : res.cookies.entrySet()) { // add response cookies to request (for e.g. login posts) req.cookie(cookie.getKey(), cookie.getValue()); } return execute(req, res); } if ((status < 200 || status >= 400) && !req.ignoreHttpErrors()) throw new HttpStatusException("HTTP error fetching URL", status, req.url().toString()); // check that we can handle the returned content type; if not, abort before fetching it String contentType = res.contentType(); if (contentType != null && !req.ignoreContentType() && !contentType.startsWith("text/") && !xmlContentTypeRxp.matcher(contentType).matches() ) throw new UnsupportedMimeTypeException("Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml", contentType, req.url().toString()); // switch to the XML parser if content type is xml and not parser not explicitly set if (contentType != null && xmlContentTypeRxp.matcher(contentType).matches()) { // only flip it if a HttpConnection.Request (i.e. don't presume other impls want it): if (req instanceof HttpConnection.Request && !((Request) req).parserDefined) { req.parser(Parser.xmlParser()); } } res.charset = DataUtil.getCharsetFromContentType(res.contentType); // may be null, readInputStream deals with it if (conn.getContentLength() != 0 && req.method() != HEAD) { // -1 means unknown, chunked. sun throws an IO exception on 500 response with no content when trying to read body InputStream bodyStream = null; try { bodyStream = conn.getErrorStream() != null ? conn.getErrorStream() : conn.getInputStream(); if (res.hasHeaderWithValue(CONTENT_ENCODING, "gzip")) bodyStream = new GZIPInputStream(bodyStream); res.byteData = DataUtil.readToByteBuffer(bodyStream, req.maxBodySize()); } finally { if (bodyStream != null) bodyStream.close(); } } else { res.byteData = DataUtil.emptyByteBuffer(); } } finally { // per Java's documentation, this is not necessary, and precludes keepalives. However in practise, // connection errors will not be released quickly enough and can cause a too many open files error. conn.disconnect(); } res.executed = true; return res; } public int statusCode() { return statusCode; } public String statusMessage() { return statusMessage; } public String charset() { return charset; } public Response charset(String charset) { this.charset = charset; return this; } public String contentType() { return contentType; } public Document parse() throws IOException { Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before parsing response"); Document doc = DataUtil.parseByteData(byteData, charset, url.toExternalForm(), req.parser()); byteData.rewind(); charset = doc.outputSettings().charset().name(); // update charset from meta-equiv, possibly return doc; } public String body() { Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body"); // charset gets set from header on execute, and from meta-equiv on parse. parse may not have happened yet String body; if (charset == null) body = Charset.forName(DataUtil.defaultCharset).decode(byteData).toString(); else body = Charset.forName(charset).decode(byteData).toString(); byteData.rewind(); return body; } public byte[] bodyAsBytes() { Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body"); return byteData.array(); } // set up connection defaults, and details from request private static HttpURLConnection createConnection(Connection.Request req) throws IOException { final HttpURLConnection conn = (HttpURLConnection) ( req.proxy() == null ? req.url().openConnection() : req.url().openConnection(req.proxy()) ); conn.setRequestMethod(req.method().name()); conn.setInstanceFollowRedirects(false); // don't rely on native redirection support conn.setConnectTimeout(req.timeout()); conn.setReadTimeout(req.timeout()); if (conn instanceof HttpsURLConnection) { if (!req.validateTLSCertificates()) { initUnSecureTSL(); ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection)conn).setHostnameVerifier(getInsecureVerifier()); } } if (req.method().hasBody()) conn.setDoOutput(true); if (req.cookies().size() > 0) conn.addRequestProperty("Cookie", getRequestCookieString(req)); for (Map.Entry<String, String> header : req.headers().entrySet()) { conn.addRequestProperty(header.getKey(), header.getValue()); } return conn; } /** * Instantiate Hostname Verifier that does nothing. * This is used for connections with disabled SSL certificates validation. * * * @return Hostname Verifier that does nothing and accepts all hostnames */ private static HostnameVerifier getInsecureVerifier() { return new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; } /** * Initialise Trust manager that does not validate certificate chains and * add it to current SSLContext. * <p/> * please not that this method will only perform action if sslSocketFactory is not yet * instantiated. * * @throws IOException */ private static synchronized void initUnSecureTSL() throws IOException { if (sslSocketFactory == null) { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } public X509Certificate[] getAcceptedIssuers() { return null; } }}; // Install the all-trusting trust manager final SSLContext sslContext; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager sslSocketFactory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException e) { throw new IOException("Can't create unsecure trust manager"); } catch (KeyManagementException e) { throw new IOException("Can't create unsecure trust manager"); } } } // set up url, method, header, cookies private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException { method = Method.valueOf(conn.getRequestMethod()); url = conn.getURL(); statusCode = conn.getResponseCode(); statusMessage = conn.getResponseMessage(); contentType = conn.getContentType(); Map<String, List<String>> resHeaders = createHeaderMap(conn); processResponseHeaders(resHeaders); // if from a redirect, map previous response cookies into this response if (previousResponse != null) { for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) { if (!hasCookie(prevCookie.getKey())) cookie(prevCookie.getKey(), prevCookie.getValue()); } } } private static LinkedHashMap<String, List<String>> createHeaderMap(HttpURLConnection conn) { // the default sun impl of conn.getHeaderFields() returns header values out of order final LinkedHashMap<String, List<String>> headers = new LinkedHashMap<String, List<String>>(); int i = 0; while (true) { final String key = conn.getHeaderFieldKey(i); final String val = conn.getHeaderField(i); if (key == null && val == null) break; i++; if (key == null || val == null) continue; // skip http1.1 line if (headers.containsKey(key)) headers.get(key).add(val); else { final ArrayList<String> vals = new ArrayList<String>(); vals.add(val); headers.put(key, vals); } } return headers; } void processResponseHeaders(Map<String, List<String>> resHeaders) { for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) { String name = entry.getKey(); if (name == null) continue; // http/1.1 line List<String> values = entry.getValue(); if (name.equalsIgnoreCase("Set-Cookie")) { for (String value : values) { if (value == null) continue; TokenQueue cd = new TokenQueue(value); String cookieName = cd.chompTo("=").trim(); String cookieVal = cd.consumeTo(";").trim(); // ignores path, date, domain, validateTLSCertificates et al. req'd? // name not blank, value not null if (cookieName.length() > 0) cookie(cookieName, cookieVal); } } else { // combine same header names with comma: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 if (values.size() == 1) header(name, values.get(0)); else if (values.size() > 1) { StringBuilder accum = new StringBuilder(); for (int i = 0; i < values.size(); i++) { final String val = values.get(i); if (i != 0) accum.append(", "); accum.append(val); } header(name, accum.toString()); } } } } private static String setOutputContentType(final Connection.Request req) { String bound = null; if (req.hasHeader(CONTENT_TYPE)) { // no-op; don't add content type as already set (e.g. for requestBody()) // todo - if content type already set, we could add charset or boundary if those aren't included } else if (needsMultipart(req)) { bound = DataUtil.mimeBoundary(); req.header(CONTENT_TYPE, MULTIPART_FORM_DATA + "; boundary=" + bound); } else { req.header(CONTENT_TYPE, FORM_URL_ENCODED + "; charset=" + req.postDataCharset()); } return bound; } private static void writePost(final Connection.Request req, final OutputStream outputStream, final String bound) throws IOException { final Collection<Connection.KeyVal> data = req.data(); final BufferedWriter w = new BufferedWriter(new OutputStreamWriter(outputStream, req.postDataCharset())); if (bound != null) { // boundary will be set if we're in multipart mode for (Connection.KeyVal keyVal : data) { w.write("--"); w.write(bound); w.write("\r\n"); w.write("Content-Disposition: form-data; name=\""); w.write(encodeMimeName(keyVal.key())); // encodes " to %22 w.write("\""); if (keyVal.hasInputStream()) { w.write("; filename=\""); w.write(encodeMimeName(keyVal.value())); w.write("\"\r\nContent-Type: application/octet-stream\r\n\r\n"); w.flush(); // flush DataUtil.crossStreams(keyVal.inputStream(), outputStream); outputStream.flush(); } else { w.write("\r\n\r\n"); w.write(keyVal.value()); } w.write("\r\n"); } w.write("--"); w.write(bound); w.write("--"); } else if (req.requestBody() != null) { // data will be in query string, we're sending a plaintext body w.write(req.requestBody()); } else { // regular form data (application/x-www-form-urlencoded) boolean first = true; for (Connection.KeyVal keyVal : data) { if (!first) w.append('&'); else first = false; w.write(URLEncoder.encode(keyVal.key(), req.postDataCharset())); w.write('='); w.write(URLEncoder.encode(keyVal.value(), req.postDataCharset())); } } w.close(); } private static String getRequestCookieString(Connection.Request req) { StringBuilder sb = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> cookie : req.cookies().entrySet()) { if (!first) sb.append("; "); else first = false; sb.append(cookie.getKey()).append('=').append(cookie.getValue()); // todo: spec says only ascii, no escaping / encoding defined. validate on set? or escape somehow here? } return sb.toString(); } // for get url reqs, serialise the data map into the url private static void serialiseRequestUrl(Connection.Request req) throws IOException { URL in = req.url(); StringBuilder url = new StringBuilder(); boolean first = true; // reconstitute the query, ready for appends url .append(in.getProtocol()) .append("://") .append(in.getAuthority()) // includes host, port .append(in.getPath()) .append("?"); if (in.getQuery() != null) { url.append(in.getQuery()); first = false; } for (Connection.KeyVal keyVal : req.data()) { Validate.isFalse(keyVal.hasInputStream(), "InputStream data not supported in URL query string."); if (!first) url.append('&'); else first = false; url .append(URLEncoder.encode(keyVal.key(), DataUtil.defaultCharset)) .append('=') .append(URLEncoder.encode(keyVal.value(), DataUtil.defaultCharset)); } req.url(new URL(url.toString())); req.data().clear(); // moved into url as get params } } private static boolean needsMultipart(Connection.Request req) { // multipart mode, for files. add the header if we see something with an inputstream, and return a non-null boundary boolean needsMulti = false; for (Connection.KeyVal keyVal : req.data()) { if (keyVal.hasInputStream()) { needsMulti = true; break; } } return needsMulti; } public static class KeyVal implements Connection.KeyVal { private String key; private String value; private InputStream stream; public static KeyVal create(String key, String value) { return new KeyVal().key(key).value(value); } public static KeyVal create(String key, String filename, InputStream stream) { return new KeyVal().key(key).value(filename).inputStream(stream); } private KeyVal() {} public KeyVal key(String key) { Validate.notEmpty(key, "Data key must not be empty"); this.key = key; return this; } public String key() { return key; } public KeyVal value(String value) { Validate.notNull(value, "Data value must not be null"); this.value = value; return this; } public String value() { return value; } public KeyVal inputStream(InputStream inputStream) { Validate.notNull(value, "Data input stream must not be null"); this.stream = inputStream; return this; } public InputStream inputStream() { return stream; } public boolean hasInputStream() { return stream != null; } @Override public String toString() { return key + "=" + value; } } }
[ "justinwm@163.com" ]
justinwm@163.com
9b625c96d5afcdd41f8cc11f49e6e19c1245b5ea
4cad9552db3f55bc56e21c6b17efbafa2fae984e
/src/main/java/sample/zuul/ZuulSampleApplication.java
3f021f82f1ec3f560ab4b5e56ebe384dd46eaa58
[]
no_license
3shaka92/zuul-sample
ee020be62cb14352fdffce14dd9f4a652d28cb49
d8139298de85375c237f997257cde1314f5a415d
refs/heads/master
2020-03-29T08:52:22.909369
2018-05-01T03:07:43
2018-05-01T03:07:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,850
java
package sample.zuul; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.context.annotation.Bean; import org.springframework.core.annotation.Order; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @SpringBootApplication @EnableZuulProxy public class ZuulSampleApplication { public static void main(String[] args) { SpringApplication.run(ZuulSampleApplication.class, args); } @Bean public MeterRegistryCustomizer<MeterRegistry> commonTags() { return registry -> registry.config() .commonTags("application", "zuul-sample"); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(corsConfigurationSource); } @Bean @Order(-1) public RouteLocator customRouteLocator(ServerProperties server, ZuulProperties zuulProperties) { return new PrefixStrippingRouteLocator(server.getServlet().getServletPrefix(), zuulProperties); } }
[ "biju.kunjummen@gmail.com" ]
biju.kunjummen@gmail.com
c7467fdb4d608623d2ea5e09b3019d58dd3c2c3b
fee0ac518fb9afd24e173f36a1398ee9cee1c5a8
/app/src/main/java/com/xian/myapp/utils/SLNotifyUtil.java
d28314e5e25a6dc326b733dc41603669beb935f0
[]
no_license
lixianjing/mydemo
7a4817084eeec13e74abf801b56f35dfb9beee9d
d6f7a1b0992f431b5a8cf6079ccea94b00a248d9
refs/heads/master
2020-12-24T16:23:53.765901
2016-03-18T11:26:43
2016-03-18T11:26:43
34,515,248
0
0
null
null
null
null
UTF-8
Java
false
false
2,574
java
package com.xian.myapp.utils; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.xian.myapp.MyApplication; import com.xian.myapp.R; /** * 用以替代系统Toast,弹出对话框通知。 * * @author 吴书永 2014/8/25 :15:38 */ public class SLNotifyUtil { public final static View makeToastView(String txt) { View overlay = ((LayoutInflater) MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)). inflate(R.layout.sl_toast_view, null); TextView textView = (TextView) overlay.findViewById(R.id.txt_toast_text); textView.setText(txt); return overlay; } public static final Toast makeToast(String txt) { View overlay = makeToastView(txt); Toast toast = new Toast(MyApplication.getContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(overlay); return toast; } public static final Toast makeToast(String txt, int delay) { View overlay = makeToastView(txt); Toast toast = new Toast(MyApplication.getContext()); toast.setDuration(delay); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(overlay); return toast; } public static final Toast makeToast(int resId) { View overlay = makeToastView(MyApplication.getContext().getString(resId)); Toast toast = new Toast(MyApplication.getContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(overlay); return toast; } public static final Toast makeToast(int resId, int delay) { View overlay = makeToastView(MyApplication.getContext().getString(resId)); Toast toast = new Toast(MyApplication.getContext()); toast.setDuration(delay); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(overlay); return toast; } public static final void showToast(String txt) { Toast toast = makeToast(txt); toast.show(); } public static final void showToast(int resId) { Toast toast = makeToast(resId); toast.show(); } public static final void showToast(final String message, final int delay) { Toast toast = makeToast(message, delay); toast.show(); } public static final void showToast(final int resId, final int delay) { Toast toast = makeToast(resId, delay); toast.show(); } }
[ "flower_is@163.com" ]
flower_is@163.com
93092563f7ec0b083d0c9986e16dd3c666bb75e8
c79a207f5efdc03a2eecea3832b248ca8c385785
/com.googlecode.jinahya/ocap-api/1.0.1/src/main/java/org/davic/net/ca/Enquiry.java
ed702683d0875e0fea5ca6537902769eecba7e20
[]
no_license
jinahya/jinahya
977e51ac2ad0af7b7c8bcd825ca3a576408f18b8
5aef255b49da46ae62fb97bffc0c51beae40b8a4
refs/heads/master
2023-07-26T19:08:55.170759
2015-12-02T07:32:18
2015-12-02T07:32:18
32,245,127
2
1
null
2023-07-12T19:42:46
2015-03-15T04:34:19
Java
UTF-8
Java
false
false
847
java
package org.davic.net.ca; /** Class representing an enquiry MMI object. */ public class Enquiry extends Text { /* For javadoc to hide the non-public constructor */ Enquiry() {} /** * @return true if the answer should not be visible while being entered, otherwise false */ public boolean getBlindAnswer() { return false; } /** * @return the expected length of the answer in characters */ public short getAnswerLength() { return (short) 0; } /** Submits the answer. * @param answer The answer string. If null, it means that the user * aborted the dialogue. * @exception InvalidSetException raised if the application calls * this method with an invalid value or more than once */ final public void setAnswer(String answer) throws CAException { } }
[ "onacit@e3df469a-503a-0410-a62b-eff8d5f2b914" ]
onacit@e3df469a-503a-0410-a62b-eff8d5f2b914
aa61d56fba1b4a3f7abda01c891002e07b2eddb7
4f204d637f0bb22e167438cc88139b74feb0ff95
/src/compiladoruniajc/LogicaSQL/CompiladorSQL.java
cc8a621656da19fdcbf48a8a00506d79cd2054cf
[]
no_license
jarteaga77/CompiladorUNIAJC
638bf42410198bcee0b1a3625418c56fe390d495
2bb4d6038ccd6c701b0045092f0e8a39b0d916c2
refs/heads/master
2021-08-28T09:01:47.926954
2017-12-11T19:32:34
2017-12-11T19:32:34
113,899,874
0
0
null
null
null
null
UTF-8
Java
false
false
3,348
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 compiladoruniajc.LogicaSQL; import java.awt.Color; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; /** * * @author George */ public class CompiladorSQL { /** * @param args the command line arguments */ //Tipo de token que puede haber en la cadena public final int FIN_DE_ARCHIVO = -1; public final int NUMERO_ENTERO = 2; public final int DELIMITADOR = 3; public final int SALTO_DE_LINEA = 4; public final int NINGUNO = 5; public final int IDENTIFICADOR = 6; public final int PALABRA_CLAVE = 7; public final int CADENA = 8; public final int PARENTESIS = 9; public final int NUMERO_DECIMAL = 10; public final int ASTERISCO = 11; public final int ERROR = 12; //El constructor espera recibir una cadena sql de la cual se quieren extraer sus tokens private void analizarCadenaSQL(String cadSQL) { Tokens tokens = new Tokens(cadSQL); // System.out.println("\n\n"); //Este bucle imprime los tokens que se van leyendo y el tipo de token que se leyo de la cadena SQL tokens.obtenerToken(); //Obtener el primer token de la cadena SQL while( ! tokens.token.equals(";") ) { switch(tokens.intTipoToken) { case NUMERO_ENTERO: System.out.println(tokens.token+" \t\t\tNUMERO_ENTERO"); break; case NUMERO_DECIMAL: System.out.println(tokens.token+" \t\t\tNUMERO_DECIMAL"); break; case PALABRA_CLAVE: System.out.println(tokens.token+" \t\t\tPALABRA_CLAVE"); break; case IDENTIFICADOR: System.out.println(tokens.token+" \t\t\tIDENTIFICADOR"); break; case CADENA: System.out.println(tokens.token+" \t\t\tCADENA"); break; case PARENTESIS: System.out.println(tokens.token+" \t\t\tPARENTESIS"); break; case DELIMITADOR: System.out.println(tokens.token+" \t\t\tDELIMITADOR"); break; case ASTERISCO: System.out.println(tokens.token+" \t\t\tASTERISCO"); break; case ERROR: System.out.println(tokens.token + " \t\t\t<-- ERROR !"); break; } tokens.obtenerToken(); } } /* public static void main(String[] args) { // TODO code application logic here CompiladorSQL prueba1 = new CompiladorSQL(); prueba1.analizarCadenaSQL("insert into s values('s1','ford','mty', 23,58.42)"); } */ }
[ "jarteaga@arteaga_jonathan@hotmail.com" ]
jarteaga@arteaga_jonathan@hotmail.com
90953245d15d496712dece9f779445f3b286e9c6
5a741d040d17774f699f2925d11622099e0fd1bd
/Ciência da Computação/Algoritmo e Estrutura de Dados II/TP07/Q07/TP07Q07HashIndireta.java
ccfa34c7103934cec03f61c5f5fdd55c760e9ca9
[]
no_license
jorgejrluiz/Codes
3cf32b4a4fe19c5c3b81651d1a6deba57af1a7c6
5fbf0e3f96383166c72730d9d5a6d9a57c6c4259
refs/heads/master
2020-04-01T14:31:50.369586
2019-10-27T00:42:42
2019-10-27T00:42:42
153,298,049
0
2
null
2019-10-28T12:21:29
2018-10-16T14:17:16
Java
UTF-8
Java
false
false
18,679
java
/** * TP07Q07HashIndireta * @author Jorge Allan de Castro Oliveira * @version 06/2017 */ class Municipio { private int id; private String nome; private String uf; private int codigoUf; private int populacao; private int numeroFuncionarios; private int numeroComissados; private String escolaridade; private String estagio; private int atualizacaoPlano; private String regiao; private int atualizacaoCadastro; private Boolean consorcio; /** * Construtor da classe. */ public Municipio() { setId(0); setNome(""); setUf(""); setCodigoUf(0); setPopulacao(0); setNumeroFuncionarios(0); setNumeroComissados(0); setEscolaridade(""); setEstagio(""); setAtualizacaoPlano(0); setRegiao(""); setAtualizacaoCadastro(0); setConsorcio(false); } /** * Construtor da classe. * @param id Número do município * @param nome Nome do município * @param uf Estado do município * @param codigoUf Código do estado do município * @param populacao Número de habitantes do município * @param numeroFuncionarios Total de funcionários ativos da administração direta * @param numeroComissados Total de funcionários ativos da administração direta - Somente comissionados * @param escolaridade Escolaridade do gestor * @param estagio Processo de elaboração da agenda * @param atualizacaoPlano Ano da última atualização do plano diretor * @param regiao Agrupamento onde se encontra o município * @param atualizacaoCadastro Ano da última atualização completa do cadastro * @param consorcio Se o município faz parte de consórcio público na área de Educação Intermunicipal */ public Municipio(int id, String nome, String uf, int codigoUf, int populacao, int numeroFuncionarios, int numeroComissados, String escolaridade, String estagio, int atualizacaoPlano, String regiao, int atualizacaoCadastro, boolean consorcio) { setId(id); setNome(nome); setUf(uf); setCodigoUf(codigoUf); setPopulacao(populacao); setNumeroFuncionarios(numeroFuncionarios); setNumeroComissados(numeroComissados); setEscolaridade(escolaridade); setEstagio(estagio); setAtualizacaoPlano(atualizacaoPlano); setRegiao(regiao); setAtualizacaoCadastro(atualizacaoCadastro); setConsorcio(consorcio); } //Métodos Set /** * Define valor à variável id. */ public void setId(int id) { this.id = id; } /** * Define valor à variável nome. */ public void setNome(String nome){ this.nome = nome; } /** * Define valor à variável uf. */ public void setUf(String uf) { this.uf = uf; } /** * Define valor à variável codigoUf. */ public void setCodigoUf(int codigoUf) { this.codigoUf = codigoUf; } /** * Define valor à variável populacao. */ public void setPopulacao(int populacao) { this.populacao = populacao; } /** * Define valor à variável numeroFuncionarios. */ public void setNumeroFuncionarios(int numeroFuncionarios) { this.numeroFuncionarios = numeroFuncionarios; } /** * Define valor à variável numeroComissados. */ public void setNumeroComissados(int numeroComissados) { this.numeroComissados = numeroComissados; } /** * Define valor à variável escolaridade. */ public void setEscolaridade(String escolaridade) { this.escolaridade = escolaridade; } /** * Define valor à variável estagio. */ public void setEstagio(String estagio) { this.estagio = estagio; } /** * Define valor à variável atualizacaoPlano. */ public void setAtualizacaoPlano(int atualizacaoPlano) { this.atualizacaoPlano = atualizacaoPlano; } /** * Define valor à variável regiao. */ public void setRegiao(String regiao) { this.regiao = regiao; } /** * Define valor à variável atualizacaoCadastro. */ public void setAtualizacaoCadastro(int atualizacaoCadastro) { this.atualizacaoCadastro = atualizacaoCadastro; } /** * Define valor à variável consorcio. */ public void setConsorcio(Boolean consorcio) { this.consorcio = consorcio; } //Métodos Get /** * Retorna valor da variável id. */ public int getId() { return this.id; } /** * Retorna valor da variável nome. */ public String getNome() { return this.nome; } /** * Retorna valor da variável uf. */ public String getUf() { return this.uf; } /** * Retorna valor da variável codigoUf. */ public int getCodigoUf() { return this.codigoUf; } /** * Retorna valor da variável populacao. */ public int getPopulacao() { return this.populacao; } /** * Retorna valor da variável numeroFuncionarios. */ public int getNumeroFuncionarios() { return this.numeroFuncionarios; } /** * Retorna valor da variável numeroComissados. */ public int getNumeroComissados() { return this.numeroComissados; } /** * Retorna valor da variável escolaridade. */ public String getEscolaridade() { return this.escolaridade; } /** * Retorna valor da variável estagio. */ public String getEstagio() { return this.estagio; } /** * Retorna valor da variável atualizacaoPlano. */ public int getAtualizacaoPlano() { return this.atualizacaoPlano; } /** * Retorna valor da variável regiao. */ public String getRegiao() { return this.regiao; } /** * Retorna valor da variável atualizacaoCadastro. */ public int getAtualizacaocadastro() { return this.atualizacaoCadastro; } /** * Retorna valor da variável consorcio. */ public Boolean getConsorcio() { return this.consorcio; } /** * Copia as variáveis da classe */ public Municipio clone() { Municipio resp = new Municipio(); resp.id = this.id; resp.nome = this.nome; resp.uf = this.uf; resp.codigoUf = this.codigoUf; resp.populacao = this.populacao; resp.numeroFuncionarios = this.numeroFuncionarios; resp.numeroComissados = this.numeroComissados; resp.escolaridade = this.escolaridade; resp.estagio = this.estagio; resp.atualizacaoPlano = this.atualizacaoPlano; resp.regiao = this.regiao; resp.atualizacaoCadastro = this.atualizacaoCadastro; resp.consorcio = this.consorcio; return resp; } /** * Imprime o contéudo as variáveis */ public void imprimir() { MyIO.println(this.id + " " + this.nome + " " + this.uf + " " + this.codigoUf + " " + this.populacao + " " + this.numeroFuncionarios + " " + this.numeroComissados + " " + this.escolaridade + " " + this.estagio + " " + this.atualizacaoPlano + " " + this.regiao + " " + this.atualizacaoCadastro + " " + this.consorcio + ""); } /** * Abre o conteúdo dos arquivos e os armazena em um vetor */ public void ler(String entrada, int cont) { //Abrir o arquivo para leitura e definir atributo id, nome, uf, codigoUf, populacao (A1, A200, A201, A202, A204 - Variáveis externas) Arq.openRead("/tmp/variaveisexternas.txt", "ISO-8859-1"); String i; for(i = Arq.readLine(); cont < Integer.parseInt(entrada); cont++, i = Arq.readLine()); cont = 0; String array[] = i.split("\t"); this.id = new Integer(array[0]).intValue(); this.nome = array[4]; this.uf = array[3]; this.codigoUf = new Integer(array[2]).intValue(); this.populacao = new Integer(array[6]).intValue(); this.regiao = array[1]; //Abrir o arquivo para leitura e definir atributo numeroFuncionarios, numeroComissados (A2, A5 - Recursos humanos) Arq.openRead("/tmp/recursoshumanos.txt", "ISO-8859-1"); for(i = Arq.readLine(); cont < Integer.parseInt(entrada); cont++, i = Arq.readLine()); cont = 0; array = i.split("\t"); this.numeroFuncionarios = new Integer(array[4]).intValue(); this.numeroComissados = new Integer(array[7]).intValue(); //Abrir o arquivo para leitura e definir atributo escolaridade, atualizacaoPlano (A16, A19 - Planejamento urbano) Arq.openRead("/tmp/planejamentourbano.txt", "ISO-8859-1"); for(i = Arq.readLine(); cont < Integer.parseInt(entrada); cont++, i = Arq.readLine()); cont = 0; array = i.split("\t"); this.escolaridade = array[5]; if(array[8].equals("Não foi atualizado") || array[8].equals("-")) { this.atualizacaoPlano = 0; } else { this.atualizacaoPlano = new Integer(array[8]).intValue(); } //Abrir o arquivo para leitura e definir atributo estagio (A143 - Gestão ambiental) Arq.openRead("/tmp/gestaoambiental.txt", "ISO-8859-1"); for(i = Arq.readLine(); cont < Integer.parseInt(entrada); cont++, i = Arq.readLine()); cont = 0; array = i.split("\t"); this.estagio = array[7]; //Abrir o arquivo para leitura e definir atributo atualizacaoCadastro (A63 - Recursos gestão) Arq.openRead("/tmp/recursosparagestao.txt", "ISO-8859-1"); for(i = Arq.readLine(); cont < Integer.parseInt(entrada); cont++, i = Arq.readLine()); cont = 0; array = i.split("\t"); if(array[6].equals("Não soube informar*") || array[6].equals("-")) { this.atualizacaoCadastro = 0; } else { this.atualizacaoCadastro = new Integer(array[6]).intValue(); } //Abrir o arquivo para leitura e definir atributo consorcio (A152 - Articulação Interinstitucional) Arq.openRead("/tmp/articulacaoointerinstitucional.txt", "ISO-8859-1"); for(i = Arq.readLine(); cont < Integer.parseInt(entrada); cont++, i = Arq.readLine()); array = i.split("\t"); String resultado = array[5]; if(resultado.equals("Sim")) { this.consorcio = true; } else { this.consorcio = false; } } } class Lista { private Celula primeiro; // Primeira celula: SEM elemento valido. private Celula ultimo; // Ultima celula: COM elemento valido. private int comparacao = 0; /** * Construtor da classe: Instancia uma celula (primeira e ultima). */ public Lista() { primeiro = new Celula(-1); ultimo = primeiro; } public int getComparacao() { return comparacao; } /** * Mostra os elementos separados por espacos. */ public void mostrar() { System.out.print("[ "); // Comeca a mostrar. for (Celula i = primeiro.prox; i != null; i = i.prox) { System.out.print(i.elemento + " "); } System.out.println("] "); // Termina de mostrar. } /** * Procura um elemento e retorna se ele existe. * @param x Elemento a pesquisar. * @return <code>true</code> se o elemento existir, * <code>false</code> em caso contrario. */ public boolean pesquisar(int x) { boolean retorno = false; for (Celula i = primeiro.prox; i != null; i = i.prox) { comparacao++; if(i.elemento == x) { comparacao++; retorno = true; i = ultimo; } } return retorno; } /** * Insere um elemento na primeira posicao da sequencia. * @param elemento Elemento a inserir. */ public void inserirInicio(int elemento) { Celula tmp = new Celula(elemento); tmp.prox = primeiro.prox; primeiro.prox = tmp; if (primeiro == ultimo) { ultimo = tmp; } tmp = null; } /** * Insere um elemento na ultima posicao da sequencia. * @param elemento Elemento a inserir. */ public void inserirFim(int elemento) { Celula tmp = new Celula(elemento); ultimo.prox = tmp; ultimo = ultimo.prox; tmp = null; } /** * Insere elemento em um indice especifico. * Considera que primeiro elemento esta no indice 0. * @param x Elemento a inserir. * @param posicao Meio da insercao. * @throws Exception Se <code>posicao</code> for incorreta. */ public void inserirMeio(int x, int posicao) throws Exception { Celula i; int cont; // Caminhar ate chegar na posicao anterior a insercao for(i = primeiro, cont = 0; (i.prox != ultimo && cont < posicao); i = i.prox, cont++); // Se indice for incorreto: if (posicao < 0 || posicao > cont + 1) { throw new Exception("Erro ao inserir (posicao " + posicao + "(cont = " + cont + ") invalida)!"); } else if (posicao == cont + 1) { inserirFim(x); } else { Celula tmp = new Celula(x); tmp.prox = i.prox; i.prox = tmp; tmp = i = null; } } /** * Remove um elemento da primeira posicao da sequencia. * @return Elemento removido. * @throws Exception Se a sequencia nao contiver elementos. */ public int removerInicio() throws Exception { int resp = -1; if (primeiro == ultimo) { throw new Exception("Erro ao remover (vazia)!"); } else { primeiro = primeiro.prox; resp = primeiro.elemento; } return resp; } /** * Remove um elemento da ultima posicao da sequencia. * @return Elemento removido. * @throws Exception Se a sequencia nao contiver elementos. */ public int removerFim() throws Exception { int resp = -1; Celula i = null; if (primeiro == ultimo) { throw new Exception("Erro ao remover (vazia)!"); } else { resp = ultimo.elemento; // Caminhar ate a penultima celula: for(i = primeiro; i.prox != ultimo; i = i.prox); ultimo = i; i = ultimo.prox = null; } return resp; } /** * Remove elemento de um indice especifico. * Considera que primeiro elemento esta no indice 0. * @param posicao Meio da remocao. * @return Elemento removido. * @throws Exception Se <code>posicao</code> for incorreta. */ public int removerMeio(int posicao) throws Exception { Celula i; int resp = -1, cont; if (primeiro == ultimo) { throw new Exception("Erro ao remover (vazia)!"); } else { // Caminhar ate chegar na posicao anterior a insercao for(i = primeiro; i.prox.elemento != posicao; i = i.prox); Celula tmp = i.prox; resp = tmp.elemento; i.prox = tmp.prox; tmp.prox = null; i = tmp = null; } return resp; } } class Celula { public int elemento; // Elemento inserido na celula. public Celula prox; // Aponta a celula prox. /** * Construtor da classe. * @param elemento Elemento inserido na celula. */ Celula(int elemento) { this.elemento = elemento; this.prox = null; } /** * Construtor da classe. * @param elemento Elemento inserido na celula. * @param prox Aponta a celula prox. */ Celula(int elemento, Celula prox) { this.elemento = elemento; this.prox = prox; } } /* *Hash adaptado para usar lista simples em vez de reserva ou rehash */ class Hash { Lista tabela[]; int tamanho; final int NULO = -1; public Hash() { this(21); } public Hash(int tamanho) { this.tamanho = tamanho; tabela = new Lista[tamanho]; for(int i = 0; i < tamanho; i++){ tabela[i] = new Lista(); } } public int h(int elemento) { return elemento % tamanho; } public boolean pesquisar(int elemento) { int pos = h(elemento); return tabela[pos].pesquisar(elemento); } public void inserirInicio (int elemento) { int pos = h(elemento); tabela[pos].inserirInicio(elemento); } public void remover(int elemento) throws Exception { int resp = NULO; if(pesquisar(elemento)) { int pos = h(elemento); resp = tabela[pos].removerMeio(elemento); } } } class TP07Q07HashIndireta { public static void main(String[] args) throws Exception { Hash hash = new Hash(); Lista lista = new Lista(); String comando, array[], linha; int posicao; for(String entrada = MyIO.readLine(); entrada.equals("0") == false; entrada = MyIO.readLine()) { Municipio municipio = new Municipio(); municipio.ler(entrada, 0); int id = municipio.getId(); hash.inserirInicio(id); } int num = MyIO.readInt(); for (int i = 0; i < num; i++) { String entrada = MyIO.readLine(); Municipio municipio = new Municipio(); if(entrada.charAt(0) == 'I') { //Verifica se existe o comando de inserir array = entrada.split(" "); linha = array[1]; municipio.ler(linha, 0); int id = municipio.getId(); hash.inserirInicio(id); } else if(entrada.charAt(0) == 'R') { array = entrada.split(" "); int id = Integer.parseInt(array[1]); hash.remover(id); //Remover pelo atributo id } } long inicio = System.currentTimeMillis(); for(String entrada = MyIO.readLine(); entrada.equals("FIM") == false; entrada = MyIO.readLine()) { int id = Integer.valueOf(entrada); boolean resultado = hash.pesquisar(id); if(resultado) { MyIO.println("SIM"); } else { MyIO.println("NAO"); } } long fim = System.currentTimeMillis(); double tempo = ((fim - inicio)/1000.0); int comparacao = lista.getComparacao(); Arq.openWrite("559855_hashReserva.txt"); Arq.println("Matrícula: 559855\t"+comparacao+"\t"+tempo+"/s"); Arq.close(); } }
[ "jorgeallancastro@live.com" ]
jorgeallancastro@live.com
e5eb21bd203cd6b20ff0603354668d459b09186d
4e4e511a0a27c97ca1d08c05a563bf41ce3ea8d3
/src/main/java/cn/ihna/demo/spring/config/AnnotationConfig.java
9978b3d808051dd935c1f992f7f2332ef088e30c
[]
no_license
daegis/spring-demo
c5f362b6ee4684285ee9a4f44178138522698a35
4a72512de6ad40c9efd077b33dc9969ccbfd0792
refs/heads/master
2022-12-04T14:49:30.717403
2020-08-10T13:52:40
2020-08-10T13:52:40
284,995,239
0
0
null
null
null
null
UTF-8
Java
false
false
504
java
package cn.ihna.demo.spring.config; import cn.ihna.demo.spring.beans.Student; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author xianyingda@gmail.com * @serial * @since 2020/8/4 2:00 下午 */ @Configuration public class AnnotationConfig { @Bean public Student student() { Student student = new Student(); student.setAge(20); student.setName("annotation"); return student; } }
[ "xianyingda@guazi.com" ]
xianyingda@guazi.com
4fd0640f9850f759553db2163d571cc1601e9de9
06c141e907751255a9121ea2f3151c35a9f72a91
/src/qcasim/Simulator.java
e018fb84c0bc75ae478b9862119bb0d8ff9ee2dd
[]
no_license
Sycokinetic/qcasim
7cc32431a826fa6928a730ffd5a8a5294ebd9f9b
9213f785c5b684266907afa7e68c7e4d6f89945b
refs/heads/master
2020-05-20T01:00:29.712483
2014-10-23T18:35:09
2014-10-23T18:35:09
32,879,256
0
0
null
null
null
null
UTF-8
Java
false
false
2,391
java
package qcasim; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import qcasim.cell.Automaton; import qcasim.cell.Cell; import qcasim.display.Display; public class Simulator { protected static Display display = new Display(); protected static Automaton automaton = new Automaton(); protected static ScheduledExecutorService scheduler; protected static ScheduledFuture<?> future; protected static int tickCount = 0; protected static int tickLengthMills = 80; public static Automaton getAutomaton() { return automaton; } public static boolean isRunning() { if (future != null) return !future.isDone(); else return false; } public static Cell[][] getCellGrid() { return automaton.getCellGrid(); } public static boolean[][] getInitGrid() { return automaton.getInitGrid(); } public static int getTickCount() { return tickCount; } public static void setTickCount(int n) { tickCount = n; } public static void setRule(String r) { automaton.setRule(r); } public static String getRule() { return automaton.getRule(); } public static Display getDisplay() { return display; } public static void start() { automaton.setTickTarget(tickCount); automaton.setRunning(true); automaton.startChildren(); display.startChildren(); scheduler = Executors.newScheduledThreadPool(2); future = scheduler.scheduleAtFixedRate(automaton, 0, tickLengthMills, TimeUnit.MILLISECONDS); } public static void stop() { automaton.setRunning(false); try { future.cancel(false); scheduler.shutdownNow(); try { scheduler.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (NullPointerException e) { // Do nothing } automaton.stopChildren(); display.stopChildren(); } public static void init() { automaton.initChildren(); display.initChildren(); } protected static void cycle() { automaton.cycleChildren(); display.cycleChildren(); } public static void revert() { automaton.revertChildren(); display.revertChildren(); } }
[ "akg7634@gmail.com" ]
akg7634@gmail.com
90963002732b849e6bafff9c865841d54e6a8baa
ad656e77159192c99670acbe0c1875cc1900154f
/AckNackGenerator/src/main/java/com/citi/stg/acknackgen/model/cache/Firm.java
7ddec23f5934d780fca5cfdbfa939f5a3ae9f120
[]
no_license
Yasaswinib04/STGtradeprocessing
6c966bfcf466c20a78ba3d87478d957527533447
90393174699826620f035a2898ff548b908ecd54
refs/heads/master
2022-10-29T07:09:00.077609
2020-06-17T14:01:03
2020-06-17T14:01:03
266,672,605
1
0
null
null
null
null
UTF-8
Java
false
false
786
java
package com.citi.stg.acknackgen.model.cache; import java.io.Serializable; import org.springframework.data.annotation.Id; //Model for the Firm Object to be stored in cache public class Firm implements Serializable { @Id public String firmCode; public String firmDesc; Firm() { } public Firm(String firmCode, String firmDesc) { super(); this.firmCode = firmCode; this.firmDesc = firmDesc; } public String getFirmCode() { return firmCode; } public void setFirmCode(String firmCode) { this.firmCode = firmCode; } public String getFirmDesc() { return firmDesc; } public void setFirmDesc(String firmDesc) { this.firmDesc = firmDesc; } @Override public String toString() { return "Firm [firmCode=" + firmCode + ", firmDesc=" + firmDesc + "]"; } }
[ "viveksinghinf@gmail.com" ]
viveksinghinf@gmail.com
08240b948cc7f6128e83aa15ea235b9a6f44efc7
fc0fec9e8e351e3e5feeadee6a587badbc95b448
/src/main/java/cn/lu/cloud/web/api/OrderController.java
47dd5ec8ac2d1796575af77a295d3a6cc94c4cbf
[]
no_license
waterlu/spring-cloud-service-consumer
6d71fedf5cdfc4481987c1ab0fb10b8ee9e74f2e
2c054d866b9a90ad9e9bbddb5405be71cf145952
refs/heads/master
2021-07-17T07:58:32.329868
2017-10-25T06:59:59
2017-10-25T06:59:59
106,392,204
0
0
null
null
null
null
UTF-8
Java
false
false
4,628
java
package cn.lu.cloud.web.api; import cn.lu.cloud.client.AccountClient; import cn.lu.cloud.client.ProductClient; import cn.lu.cloud.client.UserClient; import cn.lu.cloud.common.ResponseResult; import cn.lu.cloud.data.OrderData; import cn.lu.cloud.dto.CreateOrderDTO; import cn.lu.cloud.dto.ProductDTO; import cn.lu.cloud.dto.UpdateAccountDTO; import cn.lu.cloud.dto.UserLoginDTO; import cn.lu.cloud.entity.Order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; import java.util.Map; /** * Created by lutiehua on 2017/10/10. */ @RestController @RequestMapping("/api/orders") public class OrderController { private final Logger logger = LoggerFactory.getLogger(OrderController.class); @Autowired private ProductClient productClient; @Autowired private UserClient userClient; @Autowired private AccountClient accountClient; @PostMapping("/") public ResponseResult createOrder(@RequestBody CreateOrderDTO createOrderDTO) { logger.info("user {} order product {} by {}", createOrderDTO.getUsername(), createOrderDTO.getProductUuid(), createOrderDTO.getAmount()); int errorCode = 1001; String errorMessage = "生成订单失败"; ResponseResult responseResult = new ResponseResult(); UserLoginDTO userLoginDTO = new UserLoginDTO(); userLoginDTO.setUsername(createOrderDTO.getUsername()); userLoginDTO.setPassword(createOrderDTO.getPassword()); ResponseResult clientResponse = userClient.login(userLoginDTO); if (!clientResponse.isSuccessful()) { responseResult.setCode(clientResponse.getCode()); responseResult.setMsg(clientResponse.getMsg()); return responseResult; } Map<String, String> data = (Map<String, String>)clientResponse.getData(); createOrderDTO.setUserUuid(data.get("userUuid")); createOrderDTO.setAccountUuid(data.get("accountUuid")); ResponseResult productResponse = productClient.getProduct(createOrderDTO.getProductUuid()); if (!productResponse.isSuccessful()) { responseResult.setCode(productResponse.getCode()); responseResult.setMsg(productResponse.getMsg()); return responseResult; } ProductDTO product = productResponse.getData(ProductDTO.class); if (null == product) { responseResult.setCode(errorCode); responseResult.setMsg(errorMessage); return responseResult; } if (createOrderDTO.getAmount().compareTo(product.getProductMinInvestment()) < 0) { responseResult.setCode(errorCode); responseResult.setMsg(errorMessage); return responseResult; } if (createOrderDTO.getAmount().compareTo(product.getProductMaxInvestment()) > 0) { responseResult.setCode(errorCode); responseResult.setMsg(errorMessage); return responseResult; } BigDecimal remaining = product.getProductScale().subtract(product.getProductAccumulation()); if (createOrderDTO.getAmount().compareTo(remaining) > 0) { responseResult.setCode(errorCode); responseResult.setMsg(errorMessage); return responseResult; } UpdateAccountDTO updateAccountDTO = new UpdateAccountDTO(); updateAccountDTO.setAccountUuid(createOrderDTO.getAccountUuid()); BigDecimal decimal = createOrderDTO.getAmount().multiply(new BigDecimal(-1)); updateAccountDTO.setBalanceChanged(decimal); ResponseResult accountResponse = accountClient.updateBalance(updateAccountDTO); if (!accountResponse.isSuccessful()) { responseResult.setCode(accountResponse.getCode()); responseResult.setMsg(accountResponse.getMsg()); return responseResult; } Order order = new Order(); order.setUserUuid(createOrderDTO.getUserUuid()); order.setProductUuid(createOrderDTO.getProductUuid()); order.setAccountUuid(createOrderDTO.getAccountUuid()); order.setAmount(createOrderDTO.getAmount()); order = OrderData.add(order); responseResult.setData(order); return responseResult; } @GetMapping("/") public ResponseResult getOrderList() { ResponseResult responseResult = new ResponseResult(); responseResult.setData(OrderData.getAll()); return responseResult; } }
[ "lutiehua@zj-inv.cn" ]
lutiehua@zj-inv.cn
25f6996360240b4128d4f684f86f6adb0172e3e2
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/15/15_f62f8277c2abbfe2b95ca05e3d0c8259a1c5322f/LogEntry/15_f62f8277c2abbfe2b95ca05e3d0c8259a1c5322f_LogEntry_s.java
3ddc05a9172c91ed2771f7d3376ccdc381565114
[]
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
6,510
java
package main; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import GUI.Driver; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; public class LogEntry { private int ID; private String cwid; private User user; private ArrayList<Machine> machinesUsed; private ArrayList<Tool> toolsCheckedOut; private Date timeOut; private Date timeIn; private ArrayList<Tool> toolsReturned; private Calendar calendar; private DB database; public LogEntry() { calendar = Calendar.getInstance(); timeOut = null; database = Driver.getAccessTracker().getDatabase(); } public LogEntry(int iD, String cwid, ArrayList<Machine> machinesUsed, ArrayList<Tool> toolsCheckedOut, Date timeOut, Date timeIn, ArrayList<Tool> toolsReturned) { super(); ID = iD; this.cwid = cwid; this.machinesUsed = machinesUsed; this.toolsCheckedOut = toolsCheckedOut; this.timeOut = timeOut; this.timeIn = timeIn; this.toolsReturned = toolsReturned; calendar = Calendar.getInstance(); database = Driver.getAccessTracker().getDatabase(); } // FOR TESTING PURPOSES ONLY public void startEntry(User user, ArrayList<Machine> machinesUsed, ArrayList<Tool> toolsCheckedOut, ArrayList<Tool> toolsReturned) { // AUTO-GENERATE ID this.ID = Log.getNumEntries(); this.timeIn = calendar.getTime(); this.user = user; cwid = user.getCWID(); this.machinesUsed = new ArrayList<Machine>(); this.toolsCheckedOut = new ArrayList<Tool>(); this.toolsReturned = new ArrayList<Tool>(); Log.incrementNumEntries(); user.setCurrentEntry(this); BasicDBObject logEntry = new BasicDBObject(); logEntry.put("ID", ID); logEntry.put("timeIn", timeIn); logEntry.put("userCWID", user.getCWID()); DBCollection logEntries = database.getCollection("LogEntries"); logEntries.insert(logEntry); addMachinesUsed(machinesUsed); addToolsCheckedOut(toolsCheckedOut); addToolsReturned(toolsReturned); } public void startEntry(User user) { // AUTO-GENERATE ID this.ID = Log.getNumEntries(); this.timeIn = calendar.getTime(); this.user = user; cwid = user.getCWID(); this.machinesUsed = new ArrayList<Machine>(); this.toolsCheckedOut = new ArrayList<Tool>(); this.toolsReturned = new ArrayList<Tool>(); Log.incrementNumEntries(); this.user.setCurrentEntry(this); BasicDBObject logEntry = new BasicDBObject(); logEntry.put("ID", ID); logEntry.put("timeIn", timeIn); logEntry.put("userCWID", user.getCWID()); DBCollection logEntries = database.getCollection("LogEntries"); logEntries.insert(logEntry); } public String getCwid() { return cwid; } public void addMachinesUsed(ArrayList<Machine> used) { for (Machine m : used){ machinesUsed.add(m); } DBCollection logEntries = database.getCollection("LogEntries"); DBCursor cursor = logEntries.find(new BasicDBObject("ID", ID)); DBObject result = cursor.next(); BasicDBList machines = new BasicDBList(); for(Machine m : machinesUsed) { machines.add(new BasicDBObject("id", m.getID())); } result.put("machinesUsed", machines); logEntries.update(new BasicDBObject("ID", ID), result); } public void addToolsCheckedOut(ArrayList<Tool> checkedOut) { for (Tool t : checkedOut){ toolsCheckedOut.add(t); } DBCollection logEntries = database.getCollection("LogEntries"); DBCursor cursor = logEntries.find(new BasicDBObject("ID", ID)); DBObject result = cursor.next(); BasicDBList tools = new BasicDBList(); for(Tool t : toolsCheckedOut) { tools.add(new BasicDBObject("upc", t.getUPC())); } result.put("toolsCheckedOut", tools); logEntries.update(new BasicDBObject("ID", ID), result); } public void addToolsReturned( ArrayList<Tool> returned) { for (Tool t : returned){ toolsReturned.add(t); } DBCollection logEntries = database.getCollection("LogEntries"); DBCursor cursor = logEntries.find(new BasicDBObject("ID", ID)); DBObject result = cursor.next(); BasicDBList tools = new BasicDBList(); for(Tool t : toolsReturned) { tools.add(new BasicDBObject("upc", t.getUPC())); } result.put("toolsReturned", tools); logEntries.update(new BasicDBObject("ID", ID), result); } public void finishEntry() { this.timeOut = calendar.getTime(); DBCollection logEntries = database.getCollection("LogEntries"); DBCursor cursor = logEntries.find(new BasicDBObject("ID", ID)); DBObject result = cursor.next(); result.put("timeOut", timeOut); logEntries.update(new BasicDBObject("ID", ID), result); } public Date getTimeIn() { return timeIn; } public Date getTimeOut() { return timeOut; } public void setTimeOut(Date timeOut) { this.timeOut = timeOut; } @Override public boolean equals(Object o) { if (!(o instanceof LogEntry)) return false; LogEntry obj = (LogEntry) o; return (this.ID == obj.getID()); } public int getID() { return ID; } public void print() { System.out.println("Log Entry: " + ID); System.out.println("User: " + user); System.out.println("Time In: " + timeIn); System.out.println("Time Out: " + timeOut); System.out.println("Machines Used: " + machinesUsed); System.out.println("Tools Checked Out: " + toolsCheckedOut); System.out.println("Tools Returned: " + toolsReturned); } public User getUser() { return user; } public ArrayList<Machine> getMachinesUsed() { return machinesUsed; } public ArrayList<Tool> getToolsCheckedOut() { return toolsCheckedOut; } public ArrayList<Tool> getToolsReturned() { return toolsReturned; } public String toString() { return String.format("%5d%20s%30s%30s%30s%30s%30s", ID, user, timeIn, timeOut, machinesUsed, toolsCheckedOut, toolsReturned); } public void printTable() { System.out.format("%5d%20s%30s%30s%30s%30s%30s", ID, user, timeIn, timeOut, machinesUsed, toolsCheckedOut, toolsReturned); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com