blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
019cbb5ba9738bb90d568229245fdae7f5688848
e70f75917e2af78bbffc4b376f98a0bb76fa9623
/Tetris/src/UserInterface/Layer.java
1faf3711febb1aed3d56f59dbe5af0a32e6d6587
[]
no_license
ZeyuLiu2203/Tetris
e79dafa8aebb704dd0febd25c947034d296c7f92
c2a5fb516bdfa372fd81fabd2ff42e84748f35e2
refs/heads/master
2021-08-23T23:25:27.369862
2017-12-07T02:33:37
2017-12-07T02:33:37
112,531,772
0
0
null
null
null
null
UTF-8
Java
false
false
1,723
java
package UserInterface; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import DTO.GameDTO; public abstract class Layer { // distance from top left corner to panel protected int x; protected int y; //size of panel private int width; private int height; private final int SIZE = 7; private final Image img = new ImageIcon("Graphics/Window/window.PNG").getImage(); private final int imgW = img.getWidth(null); private final int imgH = img.getHeight(null); protected GameDTO gameDTO = null; public void setGameDTO(GameDTO gameDTO){ this.gameDTO = gameDTO; } public Layer(int x, int y, int width, int height){ this.x = x; this.y = y; this.width = width; this.height = height; } public void createWindow(Graphics g){ g.drawImage(img, x, y, x+SIZE, y+ SIZE, 0,0, SIZE,SIZE, null); g.drawImage(img, x+SIZE, y, x+width-SIZE, y+ SIZE, SIZE,0, imgW - SIZE,SIZE, null); g.drawImage(img, x+width-SIZE, y, x+width, y+ SIZE, imgW - SIZE,0, imgW,SIZE, null); g.drawImage(img, x, y+SIZE, x+SIZE, y+height- SIZE, 0,SIZE, SIZE,imgH - SIZE, null); g.drawImage(img, x+SIZE, y+SIZE, x+width - SIZE, y+height- SIZE, SIZE,SIZE, imgW - SIZE,imgH - SIZE, null); g.drawImage(img, x+width - SIZE, y+SIZE, x+width, y+height- SIZE, imgW-SIZE,SIZE, imgW,imgH - SIZE, null); g.drawImage(img, x, y+height -SIZE, x+SIZE, y+height, 0,imgH-SIZE, SIZE,imgH, null); g.drawImage(img, x+SIZE, y+height - SIZE, x+width - SIZE, y+height, SIZE,imgH - SIZE, imgW - SIZE,imgH, null); g.drawImage(img, x+width - SIZE, y+height - SIZE, x+width , y+height, imgW - SIZE,imgH - SIZE, imgW,imgH , null); } public abstract void paint(Graphics g); }
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; } }
29efe96d6605be63ca5044973ff05cacc13b335f
08e55217c66f976a25a6dc773b52759404d50d5c
/Graphics/ZZZTradeScreen.java
e2bc2e3c9e083384860630b9fa03fa48c279e8dc
[ "MIT" ]
permissive
ethan-l-chen-24/Pandemic
884bb9684bffda207d7cbaec1a756c3923f9e44b
52d7701fa26a6c46b1f75874b72a6b9731b65f08
refs/heads/main
2023-06-22T20:24:15.816352
2021-07-23T20:04:14
2021-07-23T20:04:14
384,519,054
0
0
null
null
null
null
UTF-8
Java
false
false
3,230
java
package Graphics;/* Name: Ethan Chen Class: ZZZTradeScreen Description: JavaFX Graphics for Trade */ import Game.*; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; public class ZZZTradeScreen { // gives option for who to trade with and then what cards are available to trade public static void display(Game pandemic, Label updateLabel) { Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); VBox vbox = new VBox(); Label label = new Label("Who would you like to trade with? "); vbox.getChildren().add(label); City currCity = pandemic.currPlayer.getCurrCity(); ToggleGroup toggleGroup = new ToggleGroup(); LinkedList<Player> playersAvailableToTrade = new LinkedList(); for (Player p : pandemic.players) { if (p != null && !p.equals(pandemic.currPlayer) && p.getCurrCity().equals(pandemic.currPlayer.getCurrCity())) { RadioButton tradeWith = new RadioButton(p.getName()); tradeWith.setToggleGroup(toggleGroup); vbox.getChildren().add(tradeWith); playersAvailableToTrade.add(p); } } Label label2 = new Label("Tradeable Cards: "); vbox.getChildren().add(label2); ToggleGroup toggleGroup2 = new ToggleGroup(); LinkedList<PlayerCard> cards = new LinkedList(); for (PlayerCard c : pandemic.currPlayer.getHand()) { if (c != null) { if (c.getCardName().equals(currCity) || pandemic.currPlayer.getOperativeNumber() == 3) { cards.add(c); RadioButton tradeCard = new RadioButton(c.getCardName()); tradeCard.setToggleGroup(toggleGroup2); vbox.getChildren().add(tradeCard); } } } Button submit = new Button("Submit"); submit.setDisable(true); submit.setOnAction(e -> { int indexPlayer = toggleGroup.getToggles().indexOf(toggleGroup.getSelectedToggle()); int indexCard = toggleGroup2.getToggles().indexOf(toggleGroup2.getSelectedToggle()); Player playerToTradeWith = playersAvailableToTrade.get(indexPlayer); PlayerCard cardToTrade = cards.get(indexCard); pandemic.tradeCards(playerToTradeWith, cardToTrade); updateLabel.setText(pandemic.currPlayer.getName() + " has traded " + cardToTrade.getCardName() + " to " + playerToTradeWith.getName() + "."); stage.close(); }); toggleGroup2.selectedToggleProperty().addListener((v, oldValue, newValue) -> { submit.setDisable(false); }); vbox.getChildren().add(submit); vbox.setSpacing(20); vbox.setPadding(new Insets(10, 10, 10, 10)); Scene scene = new Scene(vbox, 500, 500); stage.setScene(scene); stage.setTitle("Trade"); stage.showAndWait(); } }
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 { }
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() { } }
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; } }
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; } }
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 + "]"; } }
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.
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; } }
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)); } }
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); } }
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
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++; } }
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); } }
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; } } }
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) { } }
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()); } }
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; } }
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; } }
8b76f292d9d451c24b700109c72e78f3752e1bb8
1ef02d0db088fcc09a08c245cd91b87ee480bfc4
/filesprocessing/filters/SuffixFilter.java
53d85abbee77456e1754b61c965f9406ab82ca77
[]
no_license
RotemAmsalem/mini-projects
5d9431bd2a183c09ca7d2fd74d03168e775be509
3a4a4a5544c65f5f350815da6056e6ce3f9861af
refs/heads/master
2022-07-24T14:42:29.743226
2020-05-19T18:25:00
2020-05-19T18:25:00
265,309,180
0
0
null
null
null
null
UTF-8
Java
false
false
1,150
java
package filesprocessing.filters; import filesprocessing.Filter; import java.io.File; import java.util.ArrayList; /*this class implements the suffix filter*/ public class SuffixFilter extends Filter { /*filtered the files which their names ends with the mentioned suffix*/ private String suffix; /** * construct the suffix filter * @param files - the files to be filtered * @param notFlag - a boolean value represent whether NOT occurs in the filter line or not. * @param suffix - the suffix which only files names ended up with will be filtered. */ SuffixFilter(ArrayList<File> files, Boolean notFlag, String suffix){ super(files, notFlag); this.suffix = suffix; filteredFiles = new ArrayList<>(); } @Override protected ArrayList<File> activateFilter() { for (File file: filesToFiler){ if (file.getName().endsWith(suffix)){ filteredFiles.add(file); } } if (notAppears){ return notSuffix(filteredFiles); } return filteredFiles; } }
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 } }
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; } }
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"); } }
6c7682309b0111b12838a3162408c6d34379dd05
4ec118b65711f7b893e2a28ff687af62378433be
/OnlineShop_v2.0/src/Main.java
5e1bc76dd32ce57568b9f2d631dfe0f62bf7764c
[]
no_license
Runnergo/cursoJava
05a82c972396b562ae6fcb2a12d2bcff92dd7c88
30a15863070fd4336c94a081e88ffcab2684dfec
refs/heads/master
2022-12-26T19:43:30.465395
2019-11-20T18:48:49
2019-11-20T18:48:49
215,093,033
0
0
null
null
null
null
UTF-8
Java
false
false
862
java
/* * Mejora de ejercicio 'Tienda online' * MOOC Helsinki 2ºParte week8_12.OnlineShop. * * Clase Main: Inicia aplicacion y controla sus posibles excepciones * * @author: Juan Jose Gonzalez Pozo * @version: V2.0 - 23/08/2019 */ import java.util.Scanner; public class Main { public static void main(String[] args) { Almacen almacen = new Almacen(); // Mensaje de bienvenida e inicio de programa // controlando las excepciones por entradas no deseadas Menu.titulo("Bienvenido a CIFO-Store", "*", "*", true); while (true) { try { Tienda tienda = new Tienda(almacen, new Scanner(System.in)); tienda.seleccionOpciones(); } catch (Exception e) { Menu.titulo("¡Error de Entrada! Reinicio Menu", "-", "-", true); } } } }
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, <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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(); } }
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; } }
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;
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(); } }
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; } }
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(); } }
b05aeb9dce82fd05b3ab144a9dc28c8c6806529e
ddaf41e0b8f4ad396710b1267ef65e6f7c1bead7
/Launcher/Launcher_Example/Game/FindMe/FindMe.java
bc7dde5a54476001c4855f7f252b8951ff38bba8
[]
no_license
Lolilop/TheBimbo
c8ad7ddf3910562d4eead6295a35f178deef1777
e473c345455044f042cc15c6b74d8a679c12db20
refs/heads/master
2020-05-03T04:11:20.600903
2019-04-26T10:42:19
2019-04-26T10:42:19
178,382,199
1
0
null
null
null
null
UTF-8
Java
false
false
853
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 Launcher_Example.Game.FindMe; /** * * @author JC */ public class FindMe { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here javax.swing.JFrame jFrame = new javax.swing.JFrame("A game"); jFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); jFrame.setSize(500, 500); jFrame.setResizable(false); jFrame.setLocationRelativeTo(null); FindMeGame game = new FindMeGame(jFrame.getContentPane()); jFrame.setVisible(true); } }
5ddf8a134a31cdbb212bd0365ea876a42f8e56ba
a890048f8d13294ab3a3afb45799f9c7e3341320
/src/FS/Objects/Team.java
f4d283a7fc759b912916d5a35eb8897c8deb7768
[ "MIT" ]
permissive
simpleC0de/Fussball
cd3f281cc70875452f2d0bca1b2bcadbfbfefec2
b2cbefd828478fbf860f9b5faf33d1e0d1d491bf
refs/heads/master
2021-01-18T20:51:59.649748
2017-04-02T15:42:14
2017-04-02T15:42:14
86,996,329
0
0
null
null
null
null
UTF-8
Java
false
false
1,552
java
package FS.Objects; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.util.ArrayList; /** * Created by root on 02.03.2017. */ public class Team { private ArrayList<Player> spieler = new ArrayList<>(); private ChatColor teamColor; private String teamName; private int goals; public Team(ArrayList<Player> spielerR, ChatColor teamCoolor, String name){ spieler = spielerR; teamColor = teamCoolor; teamName = name; goals = 0; } public void addPlayer(Player p){ if(!spieler.contains(p)){ spieler.add(p); } } public ArrayList<Player> getPlayers(){ return spieler; } public Player getPlayerbyIndex(int index){ return spieler.get(index); } public boolean isInTeam(Player p){ if(spieler.contains(p)){ return true; } return false; } public void removePlayer(Player p){ if(spieler.contains(p)){ spieler.remove(p); } } public String getTeamName(){ return teamName; } public ChatColor getTeamColor(){ return teamColor; } public void setTeamColor(ChatColor color){ teamColor = color; } public void setTeamName(String name){ teamName = name; } public void addGoal(){ goals ++; } public Integer getGoals(){ return goals; } }
5566b78d162f4a5c82533cc6c1941085147e1cb0
47f1e2a7772ecdb3e65ab3629e8436d60a4952de
/src/h2h/Loading.java
c0f67404e27190bc5ef12e3f819e396ce8f8119e
[]
no_license
RadasPesa/HeadToHead
e0ad58230f07c632ec988ade4bae9f8a0b2ea2f7
ddd5cb6b6a7f5148fdb5cb333a1b35ae75e4a3d5
refs/heads/master
2020-04-21T07:11:46.418858
2019-02-06T10:14:31
2019-02-06T10:14:31
169,386,687
0
0
null
null
null
null
UTF-8
Java
false
false
421
java
package h2h; class Loading { void tick() { if(DisplayTimer.loadingSecondsRemaining <= 0) { // LOADING FINISHED Game.getRandomQuestions(HeadToHead.difficulty); Game.scoreOfFirstPlayer = 0; Game.scoreOfSecondPlayer = 0; DisplayTimer.loadingSecondsRemaining = 3; HeadToHead.state = HeadToHead.STATE.GAME; } } }
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/[email protected] /** 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; } /** @}*/ }
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; } } }
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); } }
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(); }
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(); } }
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); } }
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(); } }
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); } }
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() { } }
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
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); } }
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(); } }
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@[email protected]" ]
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 + "]"; } }
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; } }
7ace2502b4a7fe8994e67b51708524b0857764d7
6b23d8ae464de075ad006c204bd7e946971b0570
/WEB-INF/plugin/common/src/jp/groupsession/v2/cmn/cmn170/Cmn170Model.java
1e2184df6858a08a327b2ca92ffc673c75964803
[]
no_license
kosuke8/gsession
a259c71857ed36811bd8eeac19c456aa8f96c61e
edd22517a22d1fb2c9339fc7f2a52e4122fc1992
refs/heads/master
2021-08-20T05:43:09.431268
2017-11-28T07:10:08
2017-11-28T07:10:08
112,293,459
0
0
null
null
null
null
UTF-8
Java
false
false
2,384
java
package jp.groupsession.v2.cmn.cmn170; import java.io.Serializable; import jp.co.sjts.util.NullDefault; /** * <br>[機 能] テーマ情報(画面表示用)を格納するModelクラス * <br>[解 説] * <br>[備 考] * * @author JTS */ public class Cmn170Model implements Serializable { /** CTM_SID mapping */ private int ctmSid__; /** CTM_PATH_IMG mapping */ private String ctmPathImg__; /** CTM_NAME mapping */ private String ctmName__; /** 登録人数 */ private int ctmPerCount__; /** * <p>Default Constructor */ public Cmn170Model() { } /** * <p>get CTM_SID value * @return CTM_SID value */ public int getCtmSid() { return ctmSid__; } /** * <p>set CTM_SID value * @param ctmSid CTM_SID value */ public void setCtmSid(int ctmSid) { ctmSid__ = ctmSid; } /** * <p>get CTM_PATH_IMG value * @return CTM_PATH_IMG value */ public String getCtmPathImg() { return ctmPathImg__; } /** * <p>set CTM_PATH_IMG value * @param ctmPathImg CTM_PATH_IMG value */ public void setCtmPathImg(String ctmPathImg) { ctmPathImg__ = ctmPathImg; } /** * <p>get CTM_NAME value * @return CTM_NAME value */ public String getCtmName() { return ctmName__; } /** * <p>set CTM_NAME value * @param ctmName CTM_NAME value */ public void setCtmName(String ctmName) { ctmName__ = ctmName; } /** * <p>get ctmPerCount value * @return ctmPerCount value */ public int getCtmPerCount() { return ctmPerCount__; } /** * <p>set ctmPerCount value * @param ctmPerCount ctmPerCount value */ public void setCtmPerCount(int ctmPerCount) { ctmPerCount__ = ctmPerCount; } /** * <p>to Csv String * @return Csv String */ public String toCsvString() { StringBuilder buf = new StringBuilder(); buf.append(ctmSid__); buf.append(","); buf.append(NullDefault.getString(ctmPathImg__, "")); buf.append(","); buf.append(NullDefault.getString(ctmName__, "")); return buf.toString(); } }
[ "PK140601-29@PK140601-29" ]
PK140601-29@PK140601-29
6884e2ca750a49fb9e333f554a2f26b6f36e6d50
ef0c1514e9af6de3ba4a20e0d01de7cc3a915188
/sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/ApplicationGatewayIpConfigurationInner.java
ee7f588c1b4cb97cfb42c415c964bfe93df38151
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
Azure/azure-sdk-for-java
0902d584b42d3654b4ce65b1dad8409f18ddf4bc
789bdc6c065dc44ce9b8b630e2f2e5896b2a7616
refs/heads/main
2023-09-04T09:36:35.821969
2023-09-02T01:53:56
2023-09-02T01:53:56
2,928,948
2,027
2,084
MIT
2023-09-14T21:37:15
2011-12-06T23:33:56
Java
UTF-8
Java
false
false
5,758
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.SubResource; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** IP configuration of an application gateway. Currently 1 public and 1 private IP configuration is allowed. */ @Fluent public final class ApplicationGatewayIpConfigurationInner extends SubResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(ApplicationGatewayIpConfigurationInner.class); /* * Properties of IP configuration of an application gateway. */ @JsonProperty(value = "properties") private ApplicationGatewayIpConfigurationPropertiesFormat innerProperties; /* * Name of the IP configuration that is unique within an Application * Gateway. */ @JsonProperty(value = "name") private String name; /* * A unique read-only string that changes whenever the resource is updated. */ @JsonProperty(value = "etag") private String etag; /* * Type of the resource. */ @JsonProperty(value = "type") private String type; /** * Get the innerProperties property: Properties of IP configuration of an application gateway. * * @return the innerProperties value. */ private ApplicationGatewayIpConfigurationPropertiesFormat innerProperties() { return this.innerProperties; } /** * Get the name property: Name of the IP configuration that is unique within an Application Gateway. * * @return the name value. */ public String name() { return this.name; } /** * Set the name property: Name of the IP configuration that is unique within an Application Gateway. * * @param name the name value to set. * @return the ApplicationGatewayIpConfigurationInner object itself. */ public ApplicationGatewayIpConfigurationInner withName(String name) { this.name = name; return this; } /** * Get the etag property: A unique read-only string that changes whenever the resource is updated. * * @return the etag value. */ public String etag() { return this.etag; } /** * Set the etag property: A unique read-only string that changes whenever the resource is updated. * * @param etag the etag value to set. * @return the ApplicationGatewayIpConfigurationInner object itself. */ public ApplicationGatewayIpConfigurationInner withEtag(String etag) { this.etag = etag; return this; } /** * Get the type property: Type of the resource. * * @return the type value. */ public String type() { return this.type; } /** * Set the type property: Type of the resource. * * @param type the type value to set. * @return the ApplicationGatewayIpConfigurationInner object itself. */ public ApplicationGatewayIpConfigurationInner withType(String type) { this.type = type; return this; } /** {@inheritDoc} */ @Override public ApplicationGatewayIpConfigurationInner withId(String id) { super.withId(id); return this; } /** * Get the subnet property: Reference of the subnet resource. A subnet from where application gateway gets its * private address. * * @return the subnet value. */ public SubResource subnet() { return this.innerProperties() == null ? null : this.innerProperties().subnet(); } /** * Set the subnet property: Reference of the subnet resource. A subnet from where application gateway gets its * private address. * * @param subnet the subnet value to set. * @return the ApplicationGatewayIpConfigurationInner object itself. */ public ApplicationGatewayIpConfigurationInner withSubnet(SubResource subnet) { if (this.innerProperties() == null) { this.innerProperties = new ApplicationGatewayIpConfigurationPropertiesFormat(); } this.innerProperties().withSubnet(subnet); return this; } /** * Get the provisioningState property: Provisioning state of the application gateway subnet resource. Possible * values are: 'Updating', 'Deleting', and 'Failed'. * * @return the provisioningState value. */ public String provisioningState() { return this.innerProperties() == null ? null : this.innerProperties().provisioningState(); } /** * Set the provisioningState property: Provisioning state of the application gateway subnet resource. Possible * values are: 'Updating', 'Deleting', and 'Failed'. * * @param provisioningState the provisioningState value to set. * @return the ApplicationGatewayIpConfigurationInner object itself. */ public ApplicationGatewayIpConfigurationInner withProvisioningState(String provisioningState) { if (this.innerProperties() == null) { this.innerProperties = new ApplicationGatewayIpConfigurationPropertiesFormat(); } this.innerProperties().withProvisioningState(provisioningState); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (innerProperties() != null) { innerProperties().validate(); } } }
548beef4b65e34369af471bbf13325267ff50e4c
00e3b812ae1c2c0a49a260d09db74645213e5928
/app/src/main/java/com/project/cams/fragments/adminfrag/StudentFragment.java
3d6045b0a5a9a6110fb94fa291b0bae2a2e900ac
[]
no_license
JaspreetKaur768702/Android-Project
636dcc7319d11b1a7d1a0a9c3536bb40685b0783
53dce25dd8bfa8d6fb200df9d6f37a377cf10182
refs/heads/master
2023-04-11T01:27:56.507323
2021-04-27T20:03:48
2021-04-27T20:03:48
362,224,562
0
0
null
null
null
null
UTF-8
Java
false
false
2,525
java
package com.project.cams.fragments.adminfrag; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.project.cams.DBhelperclasses.AllStudents; import com.project.cams.DBhelperclasses.AllTeacher; import com.project.cams.DBhelperclasses.DataBaseCAMS; import com.project.cams.MainActivity; import com.project.cams.Utility.Global; import com.project.cams.adapter.adminadapter.StudentAdapter; import com.project.cams.adapter.adminadapter.TeacherAdapter; import com.project.cams.databinding.StudentFragmentBinding; import com.project.cams.fragments.adminfrag.AddStudentFragment; import java.util.ArrayList; import java.util.List; public class StudentFragment extends Fragment { StudentFragmentBinding binding; StudentAdapter studentAdapter; RecyclerView mRecyclerView; DataBaseCAMS dataBase; Context mContext; List< AllStudents > mList; // required***************// public StudentFragment() { } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); mContext = context; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { dataBase = DataBaseCAMS.getInstance(mContext); binding = StudentFragmentBinding.inflate(getLayoutInflater()); initView(); SetStudents(); return binding.getRoot(); } private void initView() { mRecyclerView = binding.studentRecycler; MainActivity.floatingActionButton.bringToFront(); MainActivity.floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Global.changeFragment(getActivity(), new AddStudentFragment()); } }); } private void SetStudents() { mList = new ArrayList<>(); mList = dataBase.daoData().getAllStudents(); LinearLayoutManager layoutManager = new LinearLayoutManager(mContext); layoutManager.setOrientation(RecyclerView.VERTICAL); mRecyclerView.setLayoutManager(layoutManager); studentAdapter = new StudentAdapter(mList, mContext); mRecyclerView.setAdapter(studentAdapter); } }
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(); } }
d921f4e083e36ae77a0779599e2018ccfff98baf
27aabce551531eeec5c75cf8ea86d793f25d56dc
/src/main/java/sv/com/inventario/modelo/entity/Proveedor.java
daf7609b1302ccf65e936e0f4c8cd2ab784f074b
[]
no_license
iorantes/oauth2-jwt
28f9f382f2a55503f681547230432f2efac6b87c
c6146268db5dacd8284c0bc1f9a007e2a8ea69f5
refs/heads/master
2020-03-20T15:20:25.364396
2018-06-19T02:09:23
2018-06-19T02:09:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,678
java
package sv.com.inventario.modelo.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import javax.validation.constraints.NotNull; @SuppressWarnings("serial") @Entity @Table(name = "proveedor") @JsonIgnoreProperties(ignoreUnknown = true) public class Proveedor extends AbstractBaseEntity { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID_Prov") private Long id; @Column(name = "Nombre") private String nombre; @Column(name = "Direccion") private String direccion; @Column(name = "Telefono") private String telefono; @Column(name = "Email") private String email; public Proveedor() { } public Proveedor(@NotNull Long id, String nombre, String direccion, String telefono, String email) { this.id = id; this.nombre = nombre; this.direccion = direccion; this.telefono = telefono; this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
959025c215e79571cf9913abf409d02b1a0e804c
cc729146214cf447cbb68373b9d3026a940847bd
/form2/src/main/java/net/skhu/dto/Course.java
1f8cfd917998cd3f444b557b7557613c2f24463e
[]
no_license
nsap19/spring_practice
f90dd98c657a7e60ba565685101245deaeae65df
c98cd2901e1ee84e321de81048a70efc697ae1a9
refs/heads/master
2021-03-10T10:49:04.356356
2020-04-10T04:27:15
2020-04-10T04:27:15
246,446,277
0
1
null
null
null
null
UTF-8
Java
false
false
191
java
package net.skhu.dto; import java.sql.Date; import lombok.Data; @Data public class Course { int id; String courseName; int unit; Date startDate; int departmentId; int professorId; }
c10c0430fa679b777c99d68f0f2a8f79f0ba5d49
6b90615faf772fc6c8bc0403f8f3882848f55cc6
/baekjoon/14889/solution_ad2.java
9a6aaec44f28f67500db0ea04b384034be9ee4e0
[]
no_license
jr29jr/Study
3820185cc91c46b27c3c6fb3db46d818dbe07c87
73b24c7bb4e78fbd080f2e7a448b4d74b5cb12bc
refs/heads/master
2023-03-11T13:59:51.342155
2023-03-09T13:08:33
2023-03-09T13:08:33
202,529,359
0
0
null
null
null
null
UTF-8
Java
false
false
2,984
java
import java.io.*; import java.util.*; class Main{ static StringBuilder sb = new StringBuilder(); static FastReader scan = new FastReader(); static int N; static int[] check,ans; static int[][] stats; static int min=Integer.MAX_VALUE; static void input() { N=scan.nextInt(); stats=new int[N+1][N+1]; check=new int[N+1];//스타트 팀인지 확인 ans=new int[N/2+1]; for(int i=1;i<=N;i++) for(int j=1;j<=N;j++) stats[i][j]=scan.nextInt(); } //스타트와 링크의 stats합의 차를 계싼 static int calcStats(){ int linkS=0,startS=0;//링크와 스타트의 스테이터스 합 for(int i=1;i<=N;i++){ for(int j=i+1;j<=N;j++){ if(check[i] == check[j]){ //스타트 팀 if(check[i]==1){ startS+=stats[i][j]+stats[j][i]; } //링크팀 else{ linkS+=stats[i][j]+stats[j][i]; } } } } return Math.abs(startS-linkS); } //10명 뽑으면 만족 //k가 N/2번째 선수까지 뽑아야한다. static void rec_func(int k){ if(k == N/2+1){ //10명뽑은 경우 min=Math.min(min,calcStats()); } else{ //ans[k]는 0이잖아.. 이전방으로 가야지.. for(int i=ans[k-1]+1;i<=N;i++){ check[i]=1; ans[k]=i; rec_func(k+1); ans[k]=0; check[i]=0; } } } public static void main(String[] args) { input(); rec_func(1); System.out.println(min); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
e2575b6931c43269225755cba25a08f6cfc2a320
81cbb0310d9df813164081614abfd69485321d91
/app/src/main/java/com/zzhou/entrance/guard/module/ShowCamera.java
e24ee94481def6e79c0edd24f1c2ababb90b33c1
[]
no_license
gx625888/Entrance_Guard
f7fbbb7e602f1f6df5e45a2728981d039a193ebe
e7350607abf3ae9f699451af9a8f82605c01d16a
refs/heads/master
2020-05-02T19:32:03.452183
2019-07-03T01:29:27
2019-07-03T01:29:27
178,161,286
2
2
null
null
null
null
UTF-8
Java
false
false
4,562
java
package com.zzhou.entrance.guard.module; import java.io.IOException; import java.lang.reflect.Method; import android.app.Activity; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.AutoFocusCallback; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.zzhou.entrance.guard.R; import com.zzhou.entrance.guard.util.LogUtils; public class ShowCamera extends Activity implements SurfaceHolder.Callback { private SurfaceView surfaceview; private SurfaceHolder surfaceholder; private Camera camera = null; Camera.Parameters parameters; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera_surface); LogUtils.d("<<<<<ShowCamera>>>>>"); surfaceview = (SurfaceView) findViewById(R.id.surface_view1); surfaceholder = surfaceview.getHolder(); surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); surfaceholder.addCallback(this); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub camera.autoFocus(new AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success) { initCamera();// 实现相机的参数初始化 camera.cancelAutoFocus();// 只有加上了这一句,才会自动对焦。 } } }); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub // 获取camera对象 camera = Camera.open(); try { // 设置预览监听 camera.setPreviewDisplay(holder); Camera.Parameters parameters = camera.getParameters(); if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { parameters.set("orientation", "portrait"); camera.setDisplayOrientation(90); parameters.setRotation(90); } else { parameters.set("orientation", "landscape"); camera.setDisplayOrientation(0); parameters.setRotation(0); } camera.setParameters(parameters); // 启动摄像头预览 camera.startPreview(); System.out.println("camera.startpreview"); } catch (IOException e) { e.printStackTrace(); camera.release(); System.out.println("camera.release"); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub if (camera != null) { camera.stopPreview(); camera.release(); } } // 相机参数的初始化设置 private void initCamera() { LogUtils.d("<<<<<ShowCamera-initCamera>>>>>"); parameters = camera.getParameters(); parameters.setPictureFormat(PixelFormat.JPEG); // parameters.setPictureSize(surfaceView.getWidth(), // surfaceView.getHeight()); // 部分定制手机,无法正常识别该方法。 //parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);// 1连续对焦 setDispaly(parameters, camera); camera.setParameters(parameters); camera.startPreview(); camera.cancelAutoFocus();// 2如果要实现连续的自动对焦,这一句必须加上 } // 控制图像的正确显示方向 private void setDispaly(Camera.Parameters parameters, Camera camera) { if (Integer.parseInt(Build.VERSION.SDK) >= 8) { setDisplayOrientation(camera, 180); } else { parameters.setRotation(180); } } // 实现的图像的正确显示 private void setDisplayOrientation(Camera camera, int i) { Method downPolymorphic; try { downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class }); if (downPolymorphic != null) { downPolymorphic.invoke(camera, new Object[] { i }); } } catch (Exception e) { Log.e("Came_e", "图像出错"); } } }
5bad16922a6d432463447e8a5c520d41814db4ed
bdad988adbab760c5bd2b5af61f8181406cf8769
/src/main/java/com/example/gke/GkeApplication.java
bff73acf2077db7f0b9ccc6059bf8490b6320f86
[]
no_license
vinithanagu/GKE
89034034d3a5591270154f45a7015e352bf10975
a4d00489a8bcaca2eb00cd293d8bd67a3576de93
refs/heads/master
2023-03-19T12:42:52.505644
2021-03-15T22:37:34
2021-03-15T22:37:34
348,113,157
0
0
null
null
null
null
UTF-8
Java
false
false
302
java
package com.example.gke; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GkeApplication { public static void main(String[] args) { SpringApplication.run(GkeApplication.class, args); } }
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 [email protected] * @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; } }
0760d071090e898d8c356fe7b36f327c06d2ac49
46aed1858cf6649681db68d44dc07ec5ced4d5b7
/src/main/java/cn/edu/sjtu/se/dclab/server/entity/SecondGoods.java
c649caa7998184ad57e926f1ed42026f3543a561
[]
no_license
sjtudclab/community-server
6e564ca3803bce009329b39c6b31365eeb26eca7
a53a667a16b159f73339c38279fa5e85f6947dd0
refs/heads/master
2021-01-25T03:48:03.542442
2015-11-20T07:10:00
2015-11-20T07:10:00
31,941,829
0
0
null
null
null
null
UTF-8
Java
false
false
1,277
java
/** * */ package cn.edu.sjtu.se.dclab.server.entity; /** * @author chenhui * */ public class SecondGoods { private Integer id; private String category; private String type; private String title; private String imagePath; private String desc; private String owner; private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
b58f248d817d9b5b52e6796b925145d0a6db584f
98c87237cef2f37b8cafbc22d7eeb5a019ef92e1
/src/main/java/com/imooc/miaosha/vo/GoodsStockVo.java
c7f274479d6626cf49fe357791ef5b2508346724
[ "Apache-2.0" ]
permissive
yangbao/imooc
eb65f0c2cd9477ab9a940e87853e6170ab849e17
a74b80b5743fac7273029653adfa82518f9162dc
refs/heads/master
2021-05-03T06:16:09.908269
2018-03-07T09:13:23
2018-03-07T09:13:23
120,590,755
0
0
null
null
null
null
UTF-8
Java
false
false
401
java
package com.imooc.miaosha.vo; import com.imooc.miaosha.domain.Goods; public class GoodsStockVo { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private int stockCount; public int getStockCount() { return stockCount; } public void setStockCount(int stockCount) { this.stockCount = stockCount; } }
ff6d08b649f7f2752fd31a73416089d6a41bd8c0
6e4594667da81670bcaf8f763ea03ef692728490
/yourong-core/src/test/java/com/yourong/core/OverdueRepayLogManageTest.java
0e09e948877d3449a4210c58c53db4d6ca5e8b05
[]
no_license
cenbow/Daisy
d669db7e80677f9dc6162e78b1b150d31e649d56
29a83841acefbe55631b32c51f1f8af723bea20d
refs/heads/master
2021-01-20T08:31:54.755391
2017-04-28T09:40:28
2017-04-28T09:40:28
90,162,687
0
1
null
2017-05-03T15:11:00
2017-05-03T15:11:00
null
UTF-8
Java
false
false
1,398
java
package com.yourong.core; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import com.yourong.common.exception.ManagerException; import com.yourong.core.fin.manager.OverdueRepayLogManager; import com.yourong.core.fin.manager.UnderwriteLogManager; import com.yourong.core.ic.model.ProjectInterestBiz; /** * * @desc 逾期还款记录测试用例 * @author chaisen * 2016年3月14日上午11:02:33 */ public class OverdueRepayLogManageTest extends BaseTest { @Autowired private OverdueRepayLogManager overdueRepayLogManager; @Autowired private UnderwriteLogManager underwriteLogManager; /** * * @Description:保存逾期还款记录 * @return * @throws ManagerException * @author: chaisen * @time:2016年3月14日 上午11:07:57 */ //@Test @Rollback(false) public int saveOverdueRepayLogTest() throws ManagerException{ ProjectInterestBiz biz=new ProjectInterestBiz(); int i=overdueRepayLogManager.saveOverdueRepayLog(biz); return i; } /** * * @return 统计逾期记录数 * @throws ManagerException */ @Test @Rollback(false) public int countOverdueRepayLogByProjectIdTest() throws ManagerException{ int i=overdueRepayLogManager.countOverdueRepayLogByProjectId(984509394L); return i; } }
eff184fa58be156d54ed45cba48a4b9495f66e77
fad0336e694648bf28e9874d7bfb5bc88b236903
/PageRankwithHadoop/source Code/PageRankCombiner.java
5a235ad4f754219422bc3d9079b39414ab0f2fdf
[]
no_license
chandrimaghosh/parallel-data-processing
0ec5399d30a96c3ee2221cd12ecac9ecc35f71b7
e384ffe58ce59c16d35644683605214e819733f9
refs/heads/master
2021-07-17T01:26:43.108809
2017-10-23T23:16:24
2017-10-23T23:16:24
108,049,554
0
0
null
null
null
null
UTF-8
Java
false
false
1,652
java
package pagerank.pagerank; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Reducer.Context; import pagerank.pagerank.PageRankDriver.gloabalVariable; public class PageRankCombiner extends Reducer<Text,Node,Text,Node>{ double deltaTotal=0.0; private static double a=0.20; public void reduce(Text key,Iterable<Node> values,Context context)throws IOException, InterruptedException { long totalPages = context.getConfiguration().getLong("TotalPages",0); double PageRankSoFar=0.0; //Dangling node handle //Calculate the total delta from all the dangling nodes if (key.toString().equalsIgnoreCase("~Dnode")) { double deltaTotal=0.0; for (Node n:values) { deltaTotal=deltaTotal+n.pageRank; } //store delta in Context variable long longDelta=Double.doubleToLongBits(deltaTotal); context.getCounter(gloabalVariable.delta).setValue(longDelta); return; } //Calculate the page Rank for all the other nodes Node n =new Node(); n.isDangling=false; n.pageLinks=new ArrayList<String>(); n.pageRank=0.0; for(Node node:values) { if (!node.isDangling) { n.pageLinks=node.pageLinks; } PageRankSoFar=PageRankSoFar+node.pageRank; } //reducer all the contributiong pageRanks are added up and the new //page rank is calculated with the formula n.pageRank=PageRankSoFar; //System.out.println("pageRank:"+pageRank+"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+"Key"+key); context.write(key, n); } }
6cd53a7f4919c2f368e3aa003409528d5d266993
55e269125ae4a92691eee419543de6d9a639a900
/src/com/example/cim/fragment/PCToolFragment.java
dc4f79440c7d1bb3dc846de01daba2dc5f6d45e0
[]
no_license
calow/MyCIM
095c9ac638a87b6ee4fcfd2594cdf0f971525098
7fa87ce6ee090a96329aeb696c8e0c654cf49684
refs/heads/master
2021-01-21T04:42:09.143122
2016-06-23T09:59:00
2016-06-23T09:59:00
51,994,627
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
6,239
java
package com.example.cim.fragment; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import com.example.cim.R; import com.example.cim.adapter.ToolsAdapter; import com.example.cim.asynctask.AsyncTaskBase; import com.example.cim.model.ToolEntity; import com.example.cim.network.API; import com.example.cim.nio.constant.Constant; import com.example.cim.ui.ToolActivity; import com.example.cim.view.CustomListView; import com.example.cim.view.CustomListView.OnRefreshListener; import com.example.cim.view.LoadingView; import com.example.testwebview.WebviewActivity; public class PCToolFragment extends Fragment implements OnItemClickListener { private static final String TAG = "PCToolFragment"; private Context mContext; private View mBaseView; private View mSearchView; private CustomListView mCustomListView; private ToolsAdapter adapter; private LoadingView mLoadingView; LinkedList<ToolEntity> tes = new LinkedList<ToolEntity>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContext = getActivity(); mBaseView = inflater.inflate(R.layout.fragment_pctoollist, null); mSearchView = inflater.inflate(R.layout.common_search_l, null); findView(); init(); return mBaseView; } public void findView() { mCustomListView = (CustomListView) mBaseView .findViewById(R.id.lv_tools); mLoadingView = (LoadingView) mBaseView.findViewById(R.id.loading); } public void init() { adapter = new ToolsAdapter(mContext, tes, mCustomListView); mCustomListView.setAdapter(adapter); mCustomListView.addHeaderView(mSearchView); mCustomListView.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { new AsyncRefresh().execute(0); } }); mCustomListView.setOnItemClickListener(this); mCustomListView.setCanLoadMore(false); new ToolsAsyncTask(mLoadingView).execute(0); } private class ToolsAsyncTask extends AsyncTaskBase { List<ToolEntity> recentTes = new ArrayList<ToolEntity>(); public ToolsAsyncTask(LoadingView loadingView) { super(loadingView); } @Override protected Integer doInBackground(Integer... params) { int result = -1; recentTes = new ArrayList<ToolEntity>(); try { String response = API.httpPost(API.PcToolList_URL, null); if (response != null && !response.equals("") && !response.equals("null")) { JSONObject object = new JSONObject(response); JSONArray data = object.getJSONArray("data"); for (int i = 0; i < data.length(); i++) { JSONObject jsonObject = data.getJSONObject(i); ToolEntity entity = new ToolEntity(); entity.setToolId(jsonObject.getString("toolId")); entity.setToolName(jsonObject.getString("toolName")); entity.setPlateform(jsonObject.getString("platform")); entity.setDescription(jsonObject .getString("description")); entity.setTvId(jsonObject.getString("tvId")); recentTes.add(entity); } } if (recentTes.size() >= 0) { result = 1; } } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); tes.clear(); tes.addAll(recentTes); adapter.notifyDataSetChanged(); } @Override protected void onPreExecute() { super.onPreExecute(); } } private class AsyncRefresh extends AsyncTask<Integer, Integer, List<ToolEntity>> { private List<ToolEntity> recentTes = new ArrayList<ToolEntity>(); @Override protected List<ToolEntity> doInBackground(Integer... params) { recentTes = new ArrayList<ToolEntity>(); try { String response = API.httpPost(API.PcToolList_URL, null); if (response != null && !response.equals("") && !response.equals("null")) { JSONObject object = new JSONObject(response); JSONArray data = object.getJSONArray("data"); for (int i = 0; i < data.length(); i++) { JSONObject jsonObject = data.getJSONObject(i); ToolEntity entity = new ToolEntity(); entity.setToolId(jsonObject.getString("toolId")); entity.setToolName(jsonObject.getString("toolName")); entity.setPlateform(jsonObject.getString("platform")); entity.setDescription(jsonObject .getString("description")); entity.setTvId(jsonObject.getString("tvId")); recentTes.add(entity); } } }catch (Exception e) { e.printStackTrace(); } return recentTes; } @Override protected void onPostExecute(List<ToolEntity> result) { super.onPostExecute(result); if (result != null) { updateItemStatu(result); } mCustomListView.onRefreshComplete(); } @Override protected void onPreExecute() { super.onPreExecute(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (id > -1) { ToolEntity te = (ToolEntity) adapter.getItem(Integer .parseInt(String.valueOf(id))); Intent intent = new Intent(mContext, WebviewActivity.class); String url = Constant.SERVER_URL + "/tool/tool_run.action?toolId=" + te.getToolId(); intent.putExtra("url", url); intent.putExtra("title", te.getToolName()); mContext.startActivity(intent); Activity activity = (Activity)mContext; activity.overridePendingTransition(R.anim.activity_new, R.anim.activity_out); } else { System.out.println("ËÑË÷¿ò±»µã»÷£¡"); } } public void updateItemStatu(List<ToolEntity> list) { tes.clear(); tes.addAll(list); adapter.notifyDataSetChanged(); } }
d61b68111f66e6f10937f7d2f63c6adc1a7dc929
0782e865b9c436cf4b1b075d666bcef577e8feca
/core/src/main/java/org/mariotaku/uniqr/Canvas.java
4dc644dacda57c76f8908fa9df6af8adbbc06747
[ "Apache-2.0" ]
permissive
mariotaku/UniqR
38414066ca232472deeb0de0e705ab1828ca872d
d3ac6209978ae8aad5b5c494bba9a63f11c57c0c
refs/heads/master
2021-01-19T09:32:52.790103
2018-03-15T08:23:20
2018-03-15T08:23:20
87,766,188
27
1
null
null
null
null
UTF-8
Java
false
false
301
java
package org.mariotaku.uniqr; import org.jetbrains.annotations.NotNull; /** * Created by mariotaku on 2017/4/10. */ public interface Canvas<T> { int getWidth(); int getHeight(); void drawDot(int l, int t, int size, int color); @NotNull T produceResult(); void free(); }
29aa95cb37d38b5bb6209c7f4237d65b8c7ee0c1
0e75d26812f6e52385e5295e86c123ba6930ece0
/library1206/src/main/java/com/springboot/library/view/LibRequestBookView.java
2f397fab10a2e87022c54dcc1f7612d0a40a4d45
[]
no_license
valdetegjoni/library
486ce843f5ea497042282a52771380a78424c3d6
16514e0aba1cba4d49778a35c8dd4c6b9fa97345
refs/heads/master
2023-05-19T20:36:52.359236
2021-06-15T09:23:29
2021-06-15T09:23:29
374,036,862
0
0
null
null
null
null
UTF-8
Java
false
false
1,022
java
package com.springboot.library.view; import java.io.Serializable; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class LibRequestBookView implements Serializable { /** * */ private static final long serialVersionUID = -593941230481240388L; private Long id; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss") private Date requestDate; private LibBookView libBook; private LibCustomerView libCustomer; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getRequestDate() { return requestDate; } public void setRequestDate(Date requestDate) { this.requestDate = requestDate; } public LibBookView getLibBook() { return libBook; } public void setLibBook(LibBookView libBook) { this.libBook = libBook; } public LibCustomerView getLibCustomer() { return libCustomer; } public void setLibCustomer(LibCustomerView libCustomer) { this.libCustomer = libCustomer; } }
21a50162779795404d40e3b74be9b4639653df5b
6f2ab0b4c0d7da9dab517c2d09bd2cced9ebca3f
/src/main/java/com/example/SampleBackEnd/controller/SampleController.java
224482c82e65115b5cf4154d76f48b4af7c02d85
[]
no_license
ArunMuthu-NS/SampleBackEndApp
bc34c454cd17f68b3af6d01d15c571d0b6575387
bb86d150bdae04494b9b92610d2d3a7c6807143c
refs/heads/master
2021-01-02T05:07:03.298686
2020-02-10T12:17:15
2020-02-10T12:17:15
239,501,474
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package com.example.SampleBackEnd.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @RequestMapping(method = RequestMethod.GET, path = "") public String getMethod() { return "Hi there Arun"; } }
8597844c7fb493d2403daf2452fb872dcc5e4031
22a4d49f9bbfe9cd09f3c8bdcb55e5715a65e3a3
/chapter_001/src/main/java/ru/job4j/max/Max.java
7a20da213f8196d1848805a618a298bd2f93d43b
[ "Apache-2.0" ]
permissive
dpopkov/job4j
47b0511818a0a2539dc9e977036a6cc0bf0ed973
b96f49f7b9ccd0469bf059663d81b3bde739363c
refs/heads/master
2022-09-23T06:38:57.900348
2021-04-27T20:10:59
2021-04-27T20:10:59
145,213,360
1
2
Apache-2.0
2022-09-01T23:13:35
2018-08-18T11:08:19
Java
UTF-8
Java
false
false
722
java
package ru.job4j.max; /** * Contains methods for finding the maximum value. */ public class Max { /** * Finds maximum value of two integer numbers. * @param first first number * @param second second number * @return maximum value */ @SuppressWarnings("ManualMinMaxCalculation") public int max(int first, int second) { return first > second ? first : second; } /** * Finds maximum value of three integer numbers. * @param first first number * @param second second number * @param third third number * @return maximum value */ public int max(int first, int second, int third) { return max(max(first, second), third); } }
f6926d47fe0da42cf241138d05a8d7c5ab47e449
d74ae31c66c8493260e4dbf8b3cc87581337174c
/src/main/java/hello/service/Customer1730Service.java
58374e7a2ebaf9d7b3c6d6ba85757bccba6fda9e
[]
no_license
scratches/spring-data-gazillions
72e36c78a327f263f0de46fcee991473aa9fb92c
858183c99841c869d688cdbc4f2aa0f431953925
refs/heads/main
2021-06-07T13:20:08.279099
2018-08-16T12:13:37
2018-08-16T12:13:37
144,152,360
0
0
null
2021-04-26T17:19:34
2018-08-09T12:53:18
Java
UTF-8
Java
false
false
223
java
package hello.service; import org.springframework.stereotype.Service; import hello.repo.Customer1730Repository; @Service public class Customer1730Service { public Customer1730Service(Customer1730Repository repo) { } }
aaa94d5dc67b2dd5a330a12dd342800e497f9b8f
269bce0bf0e23f5e5f7b5d31167c8a804b62ae52
/comparator-tools/modagame/MODAGAME_hppc_0.6.1/src.main.java/com/carrotsearch/hppc/DoubleShortAssociativeContainer.java
59bc87d1210542493c8d58ef8c79e69bea133506
[]
no_license
acapulco-spl/acapulco_replication_package
5c4378b7662d6aa10f11f52a9fa8793107b34d6d
7de4d9a96c11977f0cd73d761a4f8af1e0e064e0
refs/heads/master
2023-04-15T17:40:14.003166
2022-04-13T08:37:11
2022-04-13T08:37:11
306,005,002
3
1
null
2022-04-11T17:35:06
2020-10-21T11:39:59
Java
UTF-8
Java
false
false
4,171
java
package com.carrotsearch.hppc; import java.util.Iterator; import com.carrotsearch.hppc.cursors.*; import com.carrotsearch.hppc.predicates.*; import com.carrotsearch.hppc.procedures.*; /** * An associative container (alias: map, dictionary) from keys to (one or possibly more) values. * Object keys must fulfill the contract of {@link Object#hashCode()} and {@link Object#equals(Object)}. * * <p>Note that certain associative containers (like multimaps) may return the same key-value pair * multiple times from iterators.</p> * * @see DoubleContainer */ @javax.annotation.Generated(date = "2014-09-08T10:42:29+0200", value = "HPPC generated from: DoubleShortAssociativeContainer.java") public interface DoubleShortAssociativeContainer extends Iterable<DoubleShortCursor> { /** * Returns a cursor over the entries (key-value pairs) in this map. The iterator is * implemented as a cursor and it returns <b>the same cursor instance</b> on every * call to {@link Iterator#next()}. To read the current key and value use the cursor's * public fields. An example is shown below. * <pre> * for (IntShortCursor c : intShortMap) * { * System.out.println(&quot;index=&quot; + c.index * + &quot; key=&quot; + c.key * + &quot; value=&quot; + c.value); * } * </pre> * * <p>The <code>index</code> field inside the cursor gives the internal index inside * the container's implementation. The interpretation of this index depends on * to the container. */ @Override public Iterator<DoubleShortCursor> iterator(); /** * Returns <code>true</code> if this container has an association to a value for * the given key. */ public boolean containsKey(double key); /** * @return Returns the current size (number of assigned keys) in the container. */ public int size(); /** * @return Return <code>true</code> if this hash map contains no assigned keys. */ public boolean isEmpty(); /** * Removes all keys (and associated values) present in a given container. An alias to: * <pre> * keys().removeAll(container) * </pre> * but with no additional overhead. * * @return Returns the number of elements actually removed as a result of this call. */ public int removeAll(DoubleContainer container); /** * Removes all keys (and associated values) for which the predicate returns <code>true</code>. * An alias to: * <pre> * keys().removeAll(container) * </pre> * but with no additional overhead. * * @return Returns the number of elements actually removed as a result of this call. */ public int removeAll(DoublePredicate predicate); /** * Applies a given procedure to all keys-value pairs in this container. Returns the argument (any * subclass of {@link DoubleShortProcedure}. This lets the caller to call methods of the argument * by chaining the call (even if the argument is an anonymous type) to retrieve computed values, * for example. */ public <T extends DoubleShortProcedure> T forEach(T procedure); /** * Clear all keys and values in the container. */ public void clear(); /** * Returns a collection of keys of this container. The returned collection is a view * over the key set and any modifications (if allowed) introduced to the collection will * propagate to the associative container immediately. */ public DoubleCollection keys(); /** * Returns a container view of all values present in this container. The returned collection is a view * over the key set and any modifications (if allowed) introduced to the collection will * propagate to the associative container immediately. */ public ShortContainer values(); }
27936c100f53233f83c45774865e3ec288602be7
45cf3c2a261ebaaea73decf5cc5a4c8f0869d686
/anhanx-server-oauth/src/main/java/top/dfghhj/anhanx/oauth/config/AccessTokenConfig.java
d743decd08d1e171455dfa1cbc1d5a80055155bb
[]
no_license
Dfghhj/Anhanx
395ac52c9f85fea434b28c8bcc5bc206389f5404
215e2659c82634e10f69afa1c8da7e5300369dea
refs/heads/master
2022-06-22T04:39:04.271673
2020-06-04T03:11:55
2020-06-04T03:11:55
229,233,707
0
0
null
2022-06-17T02:44:35
2019-12-20T09:30:35
Java
UTF-8
Java
false
false
686
java
package top.dfghhj.anhanx.oauth.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; import javax.annotation.Resource; @Configuration public class AccessTokenConfig { @Resource RedisConnectionFactory redisConnectionFactory; @Bean TokenStore tokenStore() { // return new InMemoryTokenStore(); return new RedisTokenStore(redisConnectionFactory); } }
33e9fe0719436a4153c4a3cd109bbd3c030dbdb3
6528a167cecb327d8c5d633e189c6fb970b96793
/src/main/java/hellojpa/JpaMain.java
e73e6a227100010d609e2c108ec420239d87e9da
[]
no_license
JMSSUN/jpa-basic
23fef336b55faf246f122641c018224fcb70cdec
5f16fd896ff11a57d49a2a193ee6430403241a9f
refs/heads/master
2023-04-20T13:59:08.921084
2021-05-06T09:38:24
2021-05-06T09:38:24
363,932,914
0
0
null
null
null
null
UTF-8
Java
false
false
1,752
java
package hellojpa; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import java.util.List; public class JpaMain { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try { /* ****insert Member member = new Member(); member.setId(2L); member.setName("HelloB"); m.persist(member); ****삭제 em.remove(findMember); ****찾기 Member findMember = em.find(Member.class, 1L); System.out.println("findMember.id = "+findMember.getId()); ****수정 findMember.setName("HelloJPA"); List<Member> result = em.createQuery("select m from Member as m", Member.class).getResultList(); for (Member member : result) { System.out.println("member = " + member.getName()); } */ // 비영속 // Member member = new Member(); // member.setId(101L); // member.setName("HelloJPA"); // 영속 // em.persist(member); Member m = new Member(); m.setId(2L); m.setUsername("B"); m.setRoleType(RoleType.ADMIN); em.persist(m); tx.commit(); } catch(Exception e) { tx.rollback(); } finally { em.close(); } emf.close(); } }
a2f2be5eeb12aedca62f472b17a1c57ce4638f8d
6fb79b4aff47c99e86b1fd2e86a32ba89d121cac
/src/main/java/io/swagger/model/Auth1GetconfigResVcodelonginconfig.java
c64bca7b68c1051c65c8723f4c541dc1179a2140
[]
no_license
honor-zlc/swagger-spring
723fdbb8e11590f371b66c165c6b114137d3e7eb
15939f402102d8434101f7158e88019a33b04c7f
refs/heads/master
2022-12-11T19:48:24.466061
2020-09-10T09:09:22
2020-09-10T09:09:22
294,359,371
1
0
null
null
null
null
UTF-8
Java
false
false
2,969
java
package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * 登录验证码配置信息 */ @ApiModel(description = "登录验证码配置信息") @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-09-10T06:15:45.348Z[GMT]") public class Auth1GetconfigResVcodelonginconfig { @JsonProperty("isenable") private Boolean isenable = null; @JsonProperty("passwderrcnt") private Long passwderrcnt = null; public Auth1GetconfigResVcodelonginconfig isenable(Boolean isenable) { this.isenable = isenable; return this; } /** * 是否启用登录验证码功能 * @return isenable **/ @ApiModelProperty(required = true, value = "是否启用登录验证码功能") @NotNull public Boolean isIsenable() { return isenable; } public void setIsenable(Boolean isenable) { this.isenable = isenable; } public Auth1GetconfigResVcodelonginconfig passwderrcnt(Long passwderrcnt) { this.passwderrcnt = passwderrcnt; return this; } /** * 达到开启登录验证码的密码出错次数 * @return passwderrcnt **/ @ApiModelProperty(required = true, value = "达到开启登录验证码的密码出错次数") @NotNull public Long getPasswderrcnt() { return passwderrcnt; } public void setPasswderrcnt(Long passwderrcnt) { this.passwderrcnt = passwderrcnt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Auth1GetconfigResVcodelonginconfig auth1GetconfigResVcodelonginconfig = (Auth1GetconfigResVcodelonginconfig) o; return Objects.equals(this.isenable, auth1GetconfigResVcodelonginconfig.isenable) && Objects.equals(this.passwderrcnt, auth1GetconfigResVcodelonginconfig.passwderrcnt); } @Override public int hashCode() { return Objects.hash(isenable, passwderrcnt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Auth1GetconfigResVcodelonginconfig {\n"); sb.append(" isenable: ").append(toIndentedString(isenable)).append("\n"); sb.append(" passwderrcnt: ").append(toIndentedString(passwderrcnt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
557d4a58f494643bb570d87984a038c1d4ddceed
685dbe1807ced2175ae90e277bb2c77c14b23af4
/src/main/java/com/hallila/teller/config/ApplicationConfig.java
8647f461d331e433a3c020c28b63457fc9fcf985
[]
no_license
Ram2305/bank-application
4e9ba64fd11f683dad01d047bb90635ce94a5a0f
5838188bb7aae4019a51e02e23564fa5dedc8b2f
refs/heads/master
2023-03-16T14:54:33.128644
2017-01-29T20:39:03
2017-01-29T20:39:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
683
java
package com.hallila.teller.config; import com.hallila.teller.App; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Controller; @Configuration @ComponentScan(basePackageClasses = App.class, excludeFilters = @ComponentScan.Filter({Controller.class, Configuration.class})) class ApplicationConfig { /* @Bean public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocation(new ClassPathResource("/persistence.properties")); return ppc; } */ }
209aec6a4d1c05af519bb4c40234e8b3cf526c36
5e316c355d6838c7828bda1d49c900deb19b127e
/DevWorks/Java/BattleShipBoVersion/src/demo1/message/SystemMessage.java
c07f3b61a76d8ea7bb09d0548d6146c89ec3e7db
[]
no_license
Mtnrunrmidge/Bo_Battleship_Server
b46d40b4a93608c25b7289dc7cb852a4139d28f1
6854fe60a428de6a19a3cfdd6990cc4f396c8517
refs/heads/master
2020-03-25T22:26:07.173132
2018-08-10T01:52:19
2018-08-10T01:52:19
144,222,991
0
0
null
null
null
null
UTF-8
Java
false
false
1,982
java
package demo1.message; import demo1.GridStatus; import demo1.GridType; import demo1.Player; public class SystemMessage extends Message{ public enum SystemResponse {ACK, DENY, READY, START, OVER} private SystemResponse sr; private String winner; private GridType[][] gt; public SystemMessage(String username, SystemResponse sr) { super(null); this.sr = sr; setWinner(username); } public SystemMessage(SystemResponse sr) { super(null); this.sr = sr; setWinner(null); } public SystemMessage(SystemResponse sr, GridType[][] gt) { super(null); this.sr = sr; setWinner(null); this.gt = gt; } // start game signal from server to clients public static SystemMessage getReadyMessage(GridType[][] gt) { return new SystemMessage(SystemResponse.READY, gt); } // start game signal from server to clients public static SystemMessage getStartMessage() { return new SystemMessage(SystemResponse.START); } public static SystemMessage getAckMessage() { return new SystemMessage(SystemResponse.ACK); } public static SystemMessage getDenyMessage() { return new SystemMessage(SystemResponse.DENY); } public static SystemMessage getGameOverMessage(String username) { return new SystemMessage(username, SystemResponse.OVER); } public SystemResponse getSystemResponse() { return sr; } public String getWinner() { return winner; } public void setWinner(String winner) { this.winner = winner; } public GridType[][] getGt() { return gt; } @Override public MessageType getMessageType() { return MessageType.SYSTEM; } @Override public String toString() { return "SystemMessage{" + "sr=" + sr + ", winner='" + winner + '\'' + '}'; } }
66121d38dba97cef9837ba2d4f326c5768ff5ec1
10f1f8965b7baf90a176785f6cfb44149351f484
/app/src/main/java/com/xyoye/dandanplay/ui/weight/material/MaterialBottomNavigationView.java
cd06121b7cbb4e21e0bcdedd432d027546bcafbf
[ "MIT" ]
permissive
andylao62/DanDanPlayForAndroid
3c581f52c63b2ec5df1df98c4869717a11e40598
3d8176f2289702f12ddddfb0a41e450e0da92a2e
refs/heads/master
2023-02-18T02:44:23.189746
2021-01-18T07:18:24
2021-01-18T07:18:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,461
java
package com.xyoye.dandanplay.ui.weight.material; import android.content.Context; import android.util.AttributeSet; import androidx.annotation.Nullable; import com.xyoye.dandanplay.R; import skin.support.design.widget.SkinMaterialBottomNavigationView; import skin.support.widget.SkinCompatBackgroundHelper; public class MaterialBottomNavigationView extends SkinMaterialBottomNavigationView { private SkinCompatBackgroundHelper backgroundHelper; public MaterialBottomNavigationView(Context context) { this(context,null); } public MaterialBottomNavigationView(Context context, @Nullable AttributeSet attrs) { this(context,attrs, R.attr.bottomNavigationStyle); } public MaterialBottomNavigationView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); backgroundHelper = new SkinCompatBackgroundHelper(this); backgroundHelper.loadFromAttributes(attrs, defStyleAttr); } @Override public void setBackgroundResource(int resid) { super.setBackgroundResource(resid); if (backgroundHelper != null) { backgroundHelper.onSetBackgroundResource(resid); } } private void applyBackground() { if (backgroundHelper != null) { backgroundHelper.applySkin(); } } @Override public void applySkin() { super.applySkin(); applyBackground(); } }
3d7934ae971e2eb0c69802f17e0e74e65085504e
697a645b01b51e821ff8b048eda54c78e59ad58d
/app/src/main/java/com/byd/vtdr/fragment/FragmentPhotoPreview.java
d6f1337f65801c223ac926db67937b8a2e7b63c3
[]
no_license
1214658495/VTDR_backup
88054aac8808634a64fb7542c55b5f9ab6f0957a
98d7899eeb29dc879aea62809f04a5f82a5c7377
refs/heads/master
2020-03-22T19:09:32.999353
2018-07-18T01:46:35
2018-07-18T01:46:36
140,509,744
1
0
null
null
null
null
UTF-8
Java
false
false
18,398
java
package com.byd.vtdr.fragment; import android.app.Activity; import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.byd.vtdr.ActivityImagesViewPager; import com.byd.vtdr.MainActivity; import com.byd.vtdr.Model; import com.byd.vtdr.R; import com.byd.vtdr.RemoteCam; import com.byd.vtdr.ServerConfig; import com.byd.vtdr.connectivity.IFragmentListener; import com.byd.vtdr.utils.DownloadUtil; import com.byd.vtdr.view.CustomDialog; import com.byd.vtdr.view.MyViewPager; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import uk.co.senab.photoview.PhotoView; import uk.co.senab.photoview.PhotoViewAttacher; /** * Created by byd_tw on 2018/3/15. */ public class FragmentPhotoPreview extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private static CustomDialog customDialog = null; private ArrayList<Model> mParam1; private int mParam2; Unbinder unbinder; @BindView(R.id.vp_viewPager) MyViewPager vpViewPager; @BindView(R.id.tv_vpIndex) TextView tvVpIndex; @BindView(R.id.btn_back_to_gridview) ImageButton btnBackToGridview; @BindView(R.id.tv_title_photo) TextView tvTitlePhoto; @BindView(R.id.rl_bar_showTitle) RelativeLayout rlBarShowTitle; @BindView(R.id.btn_share_preview) ImageButton btnSharePreview; @BindView(R.id.btn_delete_preview) ImageButton btnDeletePreview; @BindView(R.id.btn_zoom) ImageButton btnZoom; @BindView(R.id.ll_bar_editPhoto) LinearLayout llBarEditPhoto; private static RemoteCam mRemoteCam; private MyImagesPagerAdapter myImagesPagerAdapter; private ArrayList<Model> photoLists; private static int currentItem; private static final int FADE_OUT = 1; private IFragmentListener mListener; public boolean reload = false; public boolean customDialogOR = false; public static FragmentPhotoPreview newInstance() { FragmentPhotoPreview fragmentPhotoPreview = new FragmentPhotoPreview(); return fragmentPhotoPreview; } public void setRemoteCam(RemoteCam mRemoteCam) { this.mRemoteCam = mRemoteCam; } public FragmentPhotoPreview() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); Bundle bundle = getArguments();//从activity传过来的Bundle if (bundle != null) { photoLists = (ArrayList<Model>) bundle.getSerializable("mPhotoList"); currentItem = (bundle.getInt("position")); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.frament_photo_preview, container, false); unbinder = ButterKnife.bind(this, view); if (savedInstanceState != null) { ArrayList<String> name = savedInstanceState.getStringArrayList("name"); ArrayList<String> time = savedInstanceState.getStringArrayList("time"); ArrayList<Integer> size = savedInstanceState.getIntegerArrayList("size"); photoLists = new ArrayList<>(); int length = name.size(); for (int i = 0; i < length; i++) { Model temp = new Model(name.get(i), time.get(i), size.get(i)); photoLists.add(temp); } currentItem = (savedInstanceState.getInt("position")); customDialogOR = savedInstanceState.getBoolean("customDialogOR"); } if (photoLists.size() != 0) { initData(); } reload = true; return view; } // TODO: Rename method, update argument and hook method into UI event @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (IFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement IFragmentListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onDestroyView() { mHandler.removeCallbacksAndMessages(null); super.onDestroyView(); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private void initData() { myImagesPagerAdapter = new MyImagesPagerAdapter(photoLists, this); vpViewPager.setAdapter(myImagesPagerAdapter); vpViewPager.setCurrentItem(currentItem, false); vpViewPager.setOffscreenPageLimit(0); // tvVpIndex.setText(currentItem + 1 + "/" + urlList.size()); tvTitlePhoto.setText(photoLists.get(currentItem).getName()); tvVpIndex.setText(currentItem + 1 + "/" + photoLists.size()); vpViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { super.onPageSelected(position); currentItem = position; tvVpIndex.setText(currentItem + 1 + "/" + photoLists.size()); tvTitlePhoto.setText(photoLists.get(currentItem).getName()); } }); if (customDialogOR) { Dialoagview(); } Message msg = mHandler.obtainMessage(FADE_OUT); mHandler.removeMessages(FADE_OUT); mHandler.sendMessageDelayed(msg, 3000); } @OnClick({R.id.btn_back_to_gridview, R.id.btn_share_preview, R.id.btn_export_preview, R.id.btn_delete_preview, R.id .btn_zoom}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.btn_back_to_gridview: // TODO: 2017/11/29 删除完成了,需要去更新gridview reload = false; ((MainActivity) getActivity()).updateCardData(); getActivity().getSupportFragmentManager().popBackStack(); break; case R.id.btn_share_preview: sharePhoto(); break; case R.id.btn_export_preview: countsDownload(); break; case R.id.btn_delete_preview: Dialoagview(); break; case R.id.btn_zoom: Intent intent = new Intent(view.getContext(), ActivityImagesViewPager.class); intent.putExtra("mPhotoList", photoLists); intent.putExtra("position", currentItem); startActivity(intent); break; default: break; } } private final MyHandler mHandler = new MyHandler(this); public static class MyHandler extends Handler { private WeakReference<FragmentPhotoPreview> mFragmentPhotoPreview; MyHandler(FragmentPhotoPreview fragmentPhotoPreview) { mFragmentPhotoPreview = new WeakReference<>(fragmentPhotoPreview); } @Override public void handleMessage(Message msg) { FragmentPhotoPreview fragmentPhotoPreview = mFragmentPhotoPreview.get(); if (fragmentPhotoPreview != null) { switch (msg.what) { case FADE_OUT: if (fragmentPhotoPreview.rlBarShowTitle.getVisibility() == View.VISIBLE) { fragmentPhotoPreview.rlBarShowTitle.setVisibility(View.INVISIBLE); } if (fragmentPhotoPreview.llBarEditPhoto.getVisibility() == View.VISIBLE) { fragmentPhotoPreview.llBarEditPhoto.setVisibility(View.INVISIBLE); } break; default: break; } } } } public class MyImagesPagerAdapter extends PagerAdapter { private ArrayList<Model> mPhotoLists; private MainActivity activity; MyImagesPagerAdapter(ArrayList<Model> mPhotoLists, FragmentPhotoPreview activity) { // this.imageUrls = imageUrls; this.mPhotoLists = mPhotoLists; this.activity = (MainActivity) getActivity(); } @Override public Object instantiateItem(ViewGroup container, int position) { // String url = imageUrls.get(position); // String url = "http://" + ServerConfig.VTDRIP + "/SD0/NORMAL/" + // model.getName(); String url = "http://" + ServerConfig.VTDRIP + "/SD0/PHOTO/" + mPhotoLists.get (position).getName(); PhotoView photoView = new PhotoView(activity); Glide.with(activity).load(url).into(photoView); container.addView(photoView); photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() { @Override public void onPhotoTap(View view, float v, float v1) { showTitleBar(); } @Override public void onOutsidePhotoTap() { showTitleBar(); } }); return photoView; } void showTitleBar() { // 如下考虑算法优化 if (rlBarShowTitle.getVisibility() == View.VISIBLE) { rlBarShowTitle.setVisibility(View.INVISIBLE); } else { rlBarShowTitle.setVisibility(View.VISIBLE); } if (llBarEditPhoto.getVisibility() == View.VISIBLE) { llBarEditPhoto.setVisibility(View.INVISIBLE); } else { llBarEditPhoto.setVisibility(View.VISIBLE); } } @Override public int getCount() { // return imageUrls != null ? imageUrls.size() : 0; return mPhotoLists != null ? mPhotoLists.size() : 0; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } } @Override public void onSaveInstanceState(Bundle outState) { ArrayList<String> name = new ArrayList<>(); ArrayList<String> time = new ArrayList<>(); ArrayList<Integer> size = new ArrayList<>(); int flag = photoLists.size(); for (int i = 0; i < flag; i++) { name.add(photoLists.get(i).getName()); time.add(photoLists.get(i).getTime()); size.add(photoLists.get(i).getSize()); } outState.putStringArrayList("name", name); outState.putStringArrayList("time", time); outState.putIntegerArrayList("size", size); outState.putInt("position", currentItem); outState.putBoolean("customDialogOR", customDialogOR); super.onSaveInstanceState(outState); } public void Dialoagview() { try { if ((this.customDialog != null) && this.customDialog.isShowing()) { this.customDialog.dismiss(); } } catch (final IllegalArgumentException e) { } catch (final Exception e) { } finally { this.customDialog = null; } customDialogOR = true; CustomDialog.Builder builder = new CustomDialog.Builder(getActivity()); customDialog = builder.cancelTouchOut(false).view(R.layout .fragment_doublebutton_dialog).style(R.style.CustomDialog).setTitle (getString(R.string.del_image_sure)).addViewOnclick(R.id.btn_dialogSure, new View.OnClickListener() { @Override public void onClick(View view) { String fileHead; fileHead = "/tmp/SD0/PHOTO/"; customDialogOR = false; mRemoteCam.deleteFile((String) (fileHead + photoLists.get(currentItem) .getName())); photoLists.remove(currentItem); if (currentItem == 0 && photoLists.size() == 0) { customDialog.dismiss(); reload = false; ((MainActivity) getActivity()).updateCardData(); getActivity().getSupportFragmentManager().popBackStack(); } else { if (currentItem == photoLists.size()) { currentItem--; tvVpIndex.setText(currentItem + 1 + "/" + photoLists.size()); tvTitlePhoto.setText(photoLists.get(currentItem).getName()); myImagesPagerAdapter.notifyDataSetChanged(); // ((MainActivity)getActivity()).updateCardData(); customDialog.dismiss(); } else { tvVpIndex.setText(currentItem + 1 + "/" + photoLists.size()); tvTitlePhoto.setText(photoLists.get(currentItem).getName()); myImagesPagerAdapter.notifyDataSetChanged(); customDialog.dismiss(); } } } }).addViewOnclick(R.id.btn_dialogCancel, new View.OnClickListener() { @Override public void onClick(View view) { customDialogOR = false; customDialog.dismiss(); } }).build(); customDialog.show(); } private void countsDownload() { String mGetFileName; mGetFileName = "http://" + ServerConfig.VTDRIP + "/SD0/PHOTO/" + photoLists.get (currentItem).getName(); String fileName = Environment.getExternalStorageDirectory() + "/行车记录仪" + mGetFileName .substring(mGetFileName.lastIndexOf('/')); File file = new File(fileName); if (!file.exists()) { DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService (Context.DOWNLOAD_SERVICE); //创建下载任务,downloadUrl就是下载链接 DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mGetFileName)); //指定下载路径和下载文件名 request.setDestinationInExternalPublicDir("/行车记录仪/", photoLists.get(currentItem) .getName()); //不显示下载界面 request.setVisibleInDownloadsUi(true); downloadManager.enqueue(request); Toast.makeText(getActivity(), R.string.Download_completed, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), R.string.File_downloaded, Toast.LENGTH_SHORT).show(); } } private void sharePhoto() { String mGetFileName; mGetFileName = "http://" + ServerConfig.VTDRIP + "/SD0/PHOTO/" + photoLists.get (currentItem).getName(); String fileName = Environment.getExternalStorageDirectory() + "/行车记录仪" + mGetFileName .substring(mGetFileName.lastIndexOf('/')); final File file = new File(fileName); if (!file.exists()) { final DownloadUtil downloadUtil = DownloadUtil.get(); downloadUtil.download(mGetFileName, "行车记录仪", new DownloadUtil.OnDownloadListener() { @Override public void onDownloadSuccess() { Uri imageUri = Uri.fromFile(file); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri); shareIntent.setType("image/*"); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_to))); } @Override public void onDownloading(final int progress) { } @Override public void onDownloadFailed() { } @Override public void onDownloadStart() { } }); } else { Uri imageUri = Uri.fromFile(file); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri); shareIntent.setType("image/*"); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_to))); } } }
191c0f9ed7eb219327293f39bc96eb4a3e831ad5
cad0610a31b22e5eb15aed7034dbb3db31052b8b
/reddit/src/main/java/com/ackerman/reddit/aspect/HomeAspect.java
9becf4e5124e7de056ccfb6e3d09f6e99e009701
[]
no_license
TTLIUJJ/XMU_REDDIT
7e446cb21446827c37c4e75a5ddcf5b06a3da3ea
6707e96c195f4f3440eac9b901a2c3e1678ae9d8
refs/heads/master
2021-05-06T14:42:38.332993
2017-12-18T06:43:35
2017-12-18T06:43:35
113,393,053
0
0
null
null
null
null
UTF-8
Java
false
false
2,311
java
package com.ackerman.reddit.aspect; import com.ackerman.reddit.model.News; import com.ackerman.reddit.model.User; import com.ackerman.reddit.utils.Entity; import com.ackerman.reddit.utils.HostHolder; import com.ackerman.reddit.utils.JedisUtil; import com.ackerman.reddit.utils.ViewObject; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.support.BindingAwareModelMap; import java.util.List; @Aspect @Component public class HomeAspect { private static Logger logger = LoggerFactory.getLogger(HomeAspect.class); @Autowired private HostHolder hostHolder; @Autowired private JedisUtil jedisUtil; @After("execution(* com.ackerman.reddit.controller.HomeController.*(..))") public void after(JoinPoint joinPoint){ BindingAwareModelMap map = null; try{ User user = hostHolder.getUser(); if(user == null){ return ; } for(Object object: joinPoint.getArgs()){ if(object instanceof BindingAwareModelMap){ map = (BindingAwareModelMap) object; break; } } if(map == null){ return; } List<ViewObject> vos = (List<ViewObject>) map.get("vos"); //收藏的key是一个用户对应多个新闻 String collectionsKey = Entity.getMyCollectKey(user.getId()); for(ViewObject vo : vos){ News news = (News)vo.get("news"); if(jedisUtil.sismember(collectionsKey, String.valueOf(news.getId()))){ vo.set("collected", 1); } //然而举报的key是一个新闻对应多个用户 String reportedKey = Entity.getReportNewsKey(news.getId()); if(jedisUtil.sismember(reportedKey, String.valueOf(user.getId()))){ vo.set("reported", 1); } } }catch (Exception e){ e.getStackTrace(); } } }
30a8f0820ece3dfe1d202009a2623ebf6b475a07
2d7ea13433243b1804b847793055c8d9b4b840f0
/src/main/java/com/howie/easyexcelmethodencapsulation/excel/ExcelListener.java
6fcef0e79c246efc2b0643bf93d5d77ea817727b
[]
no_license
runfengxin/springboot-easyexcel
0e8a0ba4bfa9a8b73f8e81a1e01450dcf230c4f8
d1a52030284043ef74b35f42ddd9079d0e809ca6
refs/heads/master
2020-05-04T14:22:24.149407
2019-04-03T02:24:28
2019-04-03T02:24:28
179,193,954
0
1
null
null
null
null
UTF-8
Java
false
false
1,597
java
package com.howie.easyexcelmethodencapsulation.excel; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA * * @Author yuanhaoyue [email protected] * @Description 监听类,可以自定义 * @Date 2018-06-05 * @Time 16:58 */ public class ExcelListener extends AnalysisEventListener { //自定义用于暂时存储data。 //可以通过实例获取该值 private List<Object> datas = new ArrayList<>(); /** * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据 */ @Override public void invoke(Object object, AnalysisContext context) { //数据存储到list,供批量处理,或后续自己业务逻辑处理。 datas.add(object); //根据业务自行 do something doSomething(); /* 如数据过大,可以进行定量分批处理 if(datas.size()<=100){ datas.add(object); }else { doSomething(); datas = new ArrayList<Object>(); } */ } /** * 根据业务自行实现该方法 */ private void doSomething() { } @Override public void doAfterAllAnalysed(AnalysisContext context) { /* datas.clear(); 解析结束销毁不用的资源 */ } public List<Object> getDatas() { return datas; } public void setDatas(List<Object> datas) { this.datas = datas; } }
cbad3fba91992a112f3a4913a374a2d5d5d49bfb
82b839181fbddf77af2489541a6600667af44b28
/app/src/main/java/sudo/nasaspaceapps/cryosphere/restBlogger/model/Blog.java
bc5b1050f759bf179d8c4d0a8488007a34e79cdf
[]
no_license
Kapil706/cryosphere
e971f87990b85f294dc7f82f46c0b16123c12ebe
4e80ad022a335d1a26d2f98f00302d42f852f603
refs/heads/master
2020-04-02T03:39:52.982807
2018-10-21T05:46:56
2018-10-21T05:46:56
153,977,491
1
0
null
2018-10-21T05:46:01
2018-10-21T05:46:01
null
UTF-8
Java
false
false
357
java
package sudo.nasaspaceapps.cryosphere.restBlogger.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Blog { @SerializedName("id") @Expose private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
e36478b0a0a1a7dde9a72672cc467ae643528ed3
1ae2b0bb2d314462581120ee33f5f35fe8654cd9
/src/main/java/com/app/web/rest/UserResource.java
d30b70aec0675ca8f421730fbe30515a4d911a80
[]
no_license
BulkSecurityGeneratorProject/OfficerManagement
e60f1483a1a90ad908c6bb5829c1c6f6a127606d
803e996c33bb1cb2aea93c3e5e885022216c9416
refs/heads/master
2022-12-26T10:00:39.028089
2019-05-31T05:05:44
2019-05-31T05:05:44
296,590,136
0
0
null
2020-09-18T10:33:08
2020-09-18T10:33:07
null
UTF-8
Java
false
false
8,788
java
package com.app.web.rest; import com.app.config.Constants; import com.app.domain.User; import com.app.repository.UserRepository; import com.app.security.AuthoritiesConstants; import com.app.service.MailService; import com.app.service.UserService; import com.app.service.dto.UserDTO; import com.app.web.rest.errors.BadRequestAlertException; import com.app.web.rest.errors.EmailAlreadyUsedException; import com.app.web.rest.errors.LoginAlreadyUsedException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * REST controller for managing users. * <p> * This class accesses the {@link User} entity, and needs to fetch its collection of authorities. * <p> * For a normal use-case, it would be better to have an eager relationship between User and Authority, * and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join * which would be good for performance. * <p> * We use a View Model and a DTO for 3 reasons: * <ul> * <li>We want to keep a lazy association between the user and the authorities, because people will * quite often do relationships with the user, and we don't want them to get the authorities all * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users' * application because of this use-case.</li> * <li> Not having an outer join causes n+1 requests to the database. This is not a real issue as * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests, * but then all authorities come from the cache, so in fact it's much better than doing an outer join * (which will get lots of data from the database, for each HTTP call).</li> * <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li> * </ul> * <p> * Another option would be to have a specific JPA entity graph to handle this case. */ @RestController @RequestMapping("/api") public class UserResource { private final Logger log = LoggerFactory.getLogger(UserResource.class); @Value("${jhipster.clientApp.name}") private String applicationName; private final UserService userService; private final UserRepository userRepository; private final MailService mailService; public UserResource(UserService userService, UserRepository userRepository, MailService mailService) { this.userService = userService; this.userRepository = userRepository; this.mailService = mailService; } /** * {@code POST /users} : Creates a new user. * <p> * Creates a new user if the login and email are not already used, and sends an * mail with an activation link. * The user needs to be activated on creation. * * @param userDTO the user to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new user, or with status {@code 400 (Bad Request)} if the login or email is already in use. * @throws URISyntaxException if the Location URI syntax is incorrect. * @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use. */ @PostMapping("/users") @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException { log.debug("REST request to save User : {}", userDTO); if (userDTO.getId() != null) { throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); // Lowercase the user login before comparing with database } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { throw new LoginAlreadyUsedException(); } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { throw new EmailAlreadyUsedException(); } else { User newUser = userService.createUser(userDTO); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) .headers(HeaderUtil.createAlert(applicationName, "userManagement.created", newUser.getLogin())) .body(newUser); } } /** * {@code PUT /users} : Updates an existing User. * * @param userDTO the user to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user. * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use. * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use. */ @PutMapping("/users") @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { log.debug("REST request to update User : {}", userDTO); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new EmailAlreadyUsedException(); } existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new LoginAlreadyUsedException(); } Optional<UserDTO> updatedUser = userService.updateUser(userDTO); return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert(applicationName, "userManagement.updated", userDTO.getLogin())); } /** * {@code GET /users} : get all users. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. */ @GetMapping("/users") public ResponseEntity<List<UserDTO>> getAllUsers(@RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder, Pageable pageable) { final Page<UserDTO> page = userService.getAllManagedUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * Gets a list of all roles. * @return a string list of all roles. */ @GetMapping("/users/authorities") @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public List<String> getAuthorities() { return userService.getAuthorities(); } /** * {@code GET /users/:login} : get the "login" user. * * @param login the login of the user to find. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. */ @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") public ResponseEntity<UserDTO> getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return ResponseUtil.wrapOrNotFound( userService.getUserWithAuthoritiesByLogin(login) .map(UserDTO::new)); } /** * {@code DELETE /users/:login} : delete the "login" User. * * @param login the login of the user to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<Void> deleteUser(@PathVariable String login) { log.debug("REST request to delete User: {}", login); userService.deleteUser(login); return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, "userManagement.deleted", login)).build(); } }
c3210f3efcb8f0938d6ff26a04317ed813075b29
0f5f6cc9e73d9be8500d088b26dc4d0385fbae7b
/app/src/main/java/com/example/anuradha/balloonhit/MainActivity.java
f4d9795cbc6e3fc163c543ccef4450d81bd47206
[]
no_license
anu19s/HitBalloon
ff041b0ee9924b15cd5f22d01e57a00d06074391
386e97de776ce0cce02bd1ebf2373e5b3d0e2d68
refs/heads/master
2021-09-22T09:44:56.411474
2018-09-07T14:58:41
2018-09-07T14:58:41
78,795,470
0
0
null
null
null
null
UTF-8
Java
false
false
8,217
java
package com.example.anuradha.balloonhit; import android.graphics.Color; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; //import java.sql.Date; import java.util.Random; import java.util.*; import java.util.Date; public class MainActivity extends AppCompatActivity implements Balloon.BalloonListener { private static final int MIN_ANIMATION_DELAY=500; private static final int MAX_ANIMATION_DELAY=1500; private static final int MIN_ANIMATION_DURATION=1000; private static final int MAX_ANIMATION_DURATION=8000; private static final int NUMBER_OF_PINS=5; private ViewGroup mContentView; private int[] mBalloonColors=new int[3]; private int mNextColor, mScreenWidth, mScreenHeight; private int mLevel; private int mScore,mPinUsed; TextView mScoreDisplay,mLevelDisplay; private List<ImageView>mPinImages=new ArrayList(); private List<Balloon> mBalloons =new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBalloonColors[0] = Color.argb(255, 255, 0, 0); mBalloonColors[1] = Color.argb(255, 0, 255, 0); mBalloonColors[2] = Color.argb(255, 0, 0, 255); getWindow().setBackgroundDrawableResource(R.drawable.modern_background); mContentView = (ViewGroup) findViewById(R.id.activity_main); setToFullScreen(); ViewTreeObserver viewTreeObserver = mContentView.getViewTreeObserver(); if (viewTreeObserver.isAlive()) { viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this); mScreenWidth = mContentView.getWidth(); mScreenHeight = mContentView.getHeight(); } }); } mContentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setToFullScreen(); } }); mScoreDisplay = (TextView) findViewById(R.id.score_display); mLevelDisplay =(TextView) findViewById(R.id.level_display); mPinImages.add((ImageView) findViewById(R.id.pushpin1)); mPinImages.add((ImageView) findViewById(R.id.pushpin2)); mPinImages.add((ImageView) findViewById(R.id.pushpin3)); mPinImages.add((ImageView) findViewById(R.id.pushpin4)); mPinImages.add((ImageView) findViewById(R.id.pushpin5)); updateDisplay(); } // mContentView.setOnTouchListener(new View.OnTouchListener() { // @Override // public boolean onTouch(View v, MotionEvent event) { // if (event.getAction() == MotionEvent.ACTION_UP) { // Balloon b = new Balloon(MainActivity.this, mBalloonColors[mNextColor], 100); // b.setX(event.getX()); // b.setY(mScreenHeight); // mContentView.addView(b); // b.releaseBalloon(mScreenHeight,3000); // if (mNextColor+1 ==mBalloonColors.length) { // mNextColor = 0; // } // else { // mNextColor++; // // } // } // return false; // } // }); // } private void setToFullScreen() { ViewGroup rootLayout=(ViewGroup) findViewById(R.id.activity_main); rootLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } @Override protected void onResume(){ super.onResume(); setToFullScreen(); } private void startLevel() { mLevel++; updateDisplay(); BalloonLauncher launcher=new BalloonLauncher(); launcher.execute(mLevel); } public void goButtonClickHandler(View view) { startLevel(); } @Override public void popBalloon(Balloon balloon, boolean userTouch){ mContentView.removeView(balloon); mBalloons.remove(balloon); if (userTouch){ mScore++; } else { mPinUsed++; if (mPinUsed<=mPinImages.size()) { mPinImages.get(mPinUsed-1) .setImageResource(R.drawable.pin_off); } if (mPinUsed== NUMBER_OF_PINS) { gameOver(true); return; } else { Toast.makeText(this,"Missed that one",Toast.LENGTH_SHORT).show(); } } updateDisplay(); } private void gameOver(boolean b){ Toast.makeText(this,"Game Over", Toast.LENGTH_SHORT).show(); for (Balloon balloon : mBalloons) { mContentView.removeView(balloon); balloon.setPopped(true); } mBalloons.clear(); } private void updateDisplay() { mScoreDisplay.setText(String.valueOf(mScore)); mLevelDisplay.setText(String.valueOf(mLevel)); } private class BalloonLauncher extends AsyncTask<Integer, Integer, Void> { @Override protected Void doInBackground(Integer... params) { if (params.length != 1) { throw new AssertionError( "Expected 1 param for current level"); } int level = params[0]; int maxDelay = Math.max(MIN_ANIMATION_DELAY, (MAX_ANIMATION_DELAY - ((level - 1) * 500))); int minDelay = maxDelay / 2; int balloonsLaunched = 0; while (balloonsLaunched < 3) { // Get a random horizontal position for the next balloon Date date = new Date(); Random random = new Random(date.getTime()); int xPosition = random.nextInt(mScreenWidth - 200); publishProgress(xPosition); balloonsLaunched++; // Wait a random number of milliseconds before looping int delay = random.nextInt(minDelay) + minDelay; try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int xPosition = values[0]; launchBalloon(xPosition); } } private void launchBalloon(int x) { Balloon balloon = new Balloon(this, mBalloonColors[mNextColor], 150); mBalloons.add(balloon); if (mNextColor + 1 == mBalloonColors.length) { mNextColor = 0; } else { mNextColor++; } // Set balloon vertical position and dimensions, add to container balloon.setX(x); balloon.setY(mScreenHeight + balloon.getHeight()); mContentView.addView(balloon); // Let 'er fly int duration = Math.max(MIN_ANIMATION_DURATION, MAX_ANIMATION_DURATION - (mLevel * 1000)); balloon.releaseBalloon(mScreenHeight, duration); } }
e305412334d7d98ff81fbb4e136e75791c63a09b
c748f85e44e2cef0031c0956c15ef81b7e52f016
/src/se/sogeti/tdd/chicken/dao/CustomerDAO.java
d5cfb78cc95f794bd82dc9ba388b848a9b8a2eef
[]
no_license
demassinner/tddCrashCourse
bb1af3b0175d44d239390de9a8b900a693535ca9
697de7a971039f6ae4275f0de7dcd98ced2414be
refs/heads/master
2020-06-04T18:17:12.070215
2012-11-09T11:24:11
2012-11-09T11:24:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
169
java
package se.sogeti.tdd.chicken.dao; import java.sql.SQLException; public interface CustomerDAO { void save(String name, int customerNumer) throws SQLException; }
d9f67e38c614b37e7d3b7ab5c921981aba93ff33
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/31/31_aea40246ebba961979de05aa6048d56ce4c01771/LTLFormulaVisitor/31_aea40246ebba961979de05aa6048d56ce4c01771_LTLFormulaVisitor_t.java
01f91314d4676e0db4a720ab9e677ab437389ed5
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
9,211
java
package de.b2tla.ltl; import java.io.IOException; import java.io.PushbackReader; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; import de.b2tla.analysis.MachineContext; import de.b2tla.exceptions.LTLParseException; import de.b2tla.exceptions.ScopeException; import de.b2tla.prettyprint.TLAPrinter; import de.be4.classicalb.core.parser.BParser; import de.be4.classicalb.core.parser.exceptions.BException; import de.be4.classicalb.core.parser.node.AIdentifierExpression; import de.be4.classicalb.core.parser.node.Node; import de.be4.classicalb.core.parser.node.TIdentifierLiteral; import de.be4.ltl.core.parser.analysis.DepthFirstAdapter; import de.be4.ltl.core.parser.internal.LtlLexer; import de.be4.ltl.core.parser.lexer.Lexer; import de.be4.ltl.core.parser.lexer.LexerException; import de.be4.ltl.core.parser.node.AActionLtl; import de.be4.ltl.core.parser.node.AEnabledLtl; import de.be4.ltl.core.parser.node.AExistsLtl; import de.be4.ltl.core.parser.node.AForallLtl; import de.be4.ltl.core.parser.node.AHistoricallyLtl; import de.be4.ltl.core.parser.node.AOnceLtl; import de.be4.ltl.core.parser.node.AReleaseLtl; import de.be4.ltl.core.parser.node.ASinceLtl; import de.be4.ltl.core.parser.node.AStrongFairLtl; import de.be4.ltl.core.parser.node.ATriggerLtl; import de.be4.ltl.core.parser.node.AUnparsedLtl; import de.be4.ltl.core.parser.node.AUntilLtl; import de.be4.ltl.core.parser.node.AWeakFairLtl; import de.be4.ltl.core.parser.node.AWeakuntilLtl; import de.be4.ltl.core.parser.node.AYesterdayLtl; import de.be4.ltl.core.parser.node.PLtl; import de.be4.ltl.core.parser.node.Start; import de.be4.ltl.core.parser.parser.Parser; import de.be4.ltl.core.parser.parser.ParserException; public class LTLFormulaVisitor extends DepthFirstAdapter { private final String name; private final Start ltlFormulaStart; private final MachineContext machineContext; private final LinkedHashMap<de.be4.ltl.core.parser.node.Node, de.be4.classicalb.core.parser.node.Node> ltlNodeToBNodeTable; private final ArrayList<LTLBPredicate> bPredicates; private final Hashtable<String, AIdentifierExpression> ltlIdentifierTable; private ArrayList<Hashtable<String, AIdentifierExpression>> contextTable; public ArrayList<LTLBPredicate> getBPredicates() { return bPredicates; } public Collection<AIdentifierExpression> getParameter() { return ltlIdentifierTable.values(); } public AIdentifierExpression getLTLIdentifier(String identifier) { return ltlIdentifierTable.get(identifier); } public LinkedHashMap<de.be4.ltl.core.parser.node.Node, de.be4.classicalb.core.parser.node.Node> getUnparsedHashTable() { return ltlNodeToBNodeTable; } public de.be4.classicalb.core.parser.node.Node getBAst( de.be4.ltl.core.parser.node.Node unparsedLtl) { return ltlNodeToBNodeTable.get(unparsedLtl); } public String getName() { return this.name; } public LTLFormulaVisitor(String name, String ltlFormula, MachineContext machineContext) { this.name = name; this.ltlFormulaStart = parse(ltlFormula); this.machineContext = machineContext; this.bPredicates = new ArrayList<LTLBPredicate>(); this.ltlNodeToBNodeTable = new LinkedHashMap<de.be4.ltl.core.parser.node.Node, de.be4.classicalb.core.parser.node.Node>(); this.ltlIdentifierTable = new Hashtable<String, AIdentifierExpression>(); this.contextTable = new ArrayList<Hashtable<String, AIdentifierExpression>>(); } public void start() { ltlFormulaStart.apply(this); } public Start getLTLFormulaStart() { return ltlFormulaStart; } public void printLTLFormula(TLAPrinter tlaPrinter) { LTLFormulaPrinter ltlFormulaPrinter = new LTLFormulaPrinter(tlaPrinter, this); } public static Start parse(String ltlFormula) { StringReader reader = new StringReader(ltlFormula); PushbackReader r = new PushbackReader(reader); Lexer l = new LtlLexer(r); Parser p = new Parser(l); Start ast = null; try { ast = p.parse(); } catch (Exception e) { e.printStackTrace(); throw new LTLParseException(e.getMessage()); } return ast; } @Override public void caseAUnparsedLtl(AUnparsedLtl node) { de.be4.classicalb.core.parser.node.Start start = parseBPredicate(node .getPredicate().getText()); ltlNodeToBNodeTable.put(node, start); LTLBPredicate ltlBPredicate = new LTLBPredicate(getUnifiedContext(), start); this.bPredicates.add(ltlBPredicate); machineContext.checkLTLBPredicate(ltlBPredicate); } private de.be4.classicalb.core.parser.node.Start parseBPredicate(String text) { String bPredicate = "#PREDICATE " + text; BParser parser = new BParser("Testing"); de.be4.classicalb.core.parser.node.Start start = null; try { start = parser.parse(bPredicate, false); } catch (BException e) { e.printStackTrace(); } return start; } @Override public void caseAExistsLtl(AExistsLtl node) { handleQuantification(node, node.getExistsIdentifier().getText(), node .getPredicate().getText(), node.getLtl()); } @Override public void caseAForallLtl(AForallLtl node) { handleQuantification(node, node.getForallIdentifier().getText(), node .getPredicate().getText(), node.getLtl()); } private void handleQuantification(de.be4.ltl.core.parser.node.Node node, String parameterName, String bPredicateString, PLtl ltl) { // create an identifier (b ast node) for the parameter of the // quantification List<TIdentifierLiteral> list = new ArrayList<TIdentifierLiteral>(); list.add(new TIdentifierLiteral(parameterName)); AIdentifierExpression parameterNode = new AIdentifierExpression(list); // add the created identifier to the current context Hashtable<String, AIdentifierExpression> currentContext = new Hashtable<String, AIdentifierExpression>(); currentContext.put(parameterName, parameterNode); this.contextTable.add(currentContext); // collection the all parameters in ltlIdentifierTable.put(parameterName, parameterNode); // parse the b predicate and create a reference to the b ast node de.be4.classicalb.core.parser.node.Start start = parseBPredicate(bPredicateString); ltlNodeToBNodeTable.put(node, start); // collect all identifiers which can be used in the bPredicate and // verify the bPredicate LTLBPredicate ltlBPredicate = new LTLBPredicate(getUnifiedContext(), start); this.bPredicates.add(ltlBPredicate); machineContext.checkLTLBPredicate(ltlBPredicate); // remaining LTL formula ltl.apply(this); // remove currentContext from contextTable contextTable.remove(contextTable.size() - 1); } private LinkedHashMap<String, Node> getUnifiedContext() { LinkedHashMap<String, Node> context = new LinkedHashMap<String, Node>(); for (int i = 0; i < contextTable.size(); i++) { context.putAll(contextTable.get(i)); } return context; } @Override public void caseAEnabledLtl(AEnabledLtl node) { String operationName = node.getOperation().getText(); if (!machineContext.getOperations().containsKey(operationName)) { throw new ScopeException("Unkown operation " + operationName + "."); } } @Override public void caseAWeakFairLtl(AWeakFairLtl node) { String operationName = node.getOperation().getText(); if (!machineContext.getOperations().containsKey(operationName)) { throw new ScopeException("Unkown operation " + operationName + "."); } } @Override public void caseAStrongFairLtl(AStrongFairLtl node) { String operationName = node.getOperation().getText(); if (!machineContext.getOperations().containsKey(operationName)) { throw new ScopeException("Unkown operation " + operationName + "."); } } public void inAUntilLtl(AUntilLtl node) { throw new ScopeException( "The 'until' operator is not supported by TLC."); } public void inAWeakuntilLtl(AWeakuntilLtl node) { throw new ScopeException( "The 'weak until' operator is not supported by TLC."); } public void inAReleaseLtl(AReleaseLtl node) { throw new ScopeException( "The 'release' operator is not supported by TLC."); } public void inASinceLtl(ASinceLtl node) { throw new ScopeException( "The 'since' operator is not supported by TLC."); } public void inATriggerLtl(ATriggerLtl node) { throw new ScopeException( "The 'trigger' operator is not supported by TLC."); } public void inAHistoricallyLtl(AHistoricallyLtl node) { throw new ScopeException( "The 'history' operator is not supported by TLC."); } public void inAOnceLtl(AOnceLtl node) { throw new ScopeException("The 'once' operator is not supported by TLC."); } public void inAYesterdayLtl(AYesterdayLtl node) { throw new ScopeException( "The 'yesterday' operator is not supported by TLC."); } @Override public void caseAActionLtl(AActionLtl node) { throw new ScopeException( "The '[...]' operator is not supported by TLC."); } }
e29875f0d4cc76f0747a1c8319a4a4586c75db2b
e9d4fc15c616e3861b7df783bdea702f305c13c7
/otranse-os/samples/pss/src/main/java/com/lanyotech/pps/service/IOrderInfoService.java
46bea2bd0e9de0d845a53882d8fd2e2df790fdc8
[]
no_license
lingxfeng/myproject
00ef0ebae258f1d5d187bf0be23dac653fcead23
1b14f47208cc456b68e2cb811a2a71c302be23d9
refs/heads/master
2021-01-13T05:02:00.200042
2017-02-07T08:01:51
2017-02-07T08:01:51
81,179,980
0
4
null
2020-03-14T10:57:39
2017-02-07T07:33:06
JavaScript
UTF-8
Java
false
false
1,480
java
package com.lanyotech.pps.service; import java.io.Serializable; import java.util.List; import java.util.Map; import cn.disco.core.support.query.IQueryObject; import cn.disco.web.tools.IPageList; import com.lanyotech.pps.domain.OrderInfo; import com.lanyotech.pps.query.OrderInfoItemQuery; /** * OrderInfoService * @author Disco Framework */ public interface IOrderInfoService { /** * 保存一个OrderInfo,如果保存成功返回该对象的id,否则返回null * * @param instance * @return 保存成功的对象的Id */ Long addOrderInfo(OrderInfo instance); /** * 根据一个ID得到OrderInfo * * @param id * @return */ OrderInfo getOrderInfo(Long id); /** * 删除一个OrderInfo * @param id * @return */ boolean delOrderInfo(Long id); /** * 批量删除OrderInfo * @param ids * @return */ boolean batchDelOrderInfos(List<Serializable> ids); /** * 通过一个查询对象得到OrderInfo * * @param properties * @return */ IPageList getOrderInfoBy(IQueryObject queryObject); /** * 更新一个OrderInfo * @param id 需要更新的OrderInfo的id * @param dir 需要更新的OrderInfo */ boolean updateOrderInfo(Long id,OrderInfo instance); /** * 删除订单明细条目 * @param id * @return */ boolean delOrderInfoItem(Long id); /** * 销售统计 * @param query * @param groupBy * @return */ List<Map> statistics(OrderInfoItemQuery query,String groupBy); }
fa54dd4f6456fb341fd91eab673f6232708c7825
946b89cc2a9954ec81d86ae103720a8c02bc60dd
/DiaMon/src/net/sf/dvstar/android/diamon/charts/BudgetPieChart.java
f68d7cdba4034f97f61e3c8361bbe205f0f24ee0
[]
no_license
dmvstar/diamon
10b7858111c00765dd6f1b028c6cba59df2d97e2
080ea3568ada4ac0db30d02def1bb913578f3654
refs/heads/master
2021-01-10T13:00:28.830799
2015-09-28T20:26:41
2015-09-28T20:26:41
43,241,836
0
0
null
null
null
null
UTF-8
Java
false
false
1,947
java
/** * Copyright (C) 2009, 2010 SC 4ViewSoft SRL * * 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 net.sf.dvstar.android.diamon.charts; import org.achartengine.ChartFactory; import org.achartengine.renderer.DefaultRenderer; import android.content.Context; import android.content.Intent; import android.graphics.Color; /** * Budget demo pie chart. */ public class BudgetPieChart extends AbstractDemoChart { /** * Returns the chart name. * * @return the chart name */ public String getName() { return "Budget chart"; } /** * Returns the chart description. * * @return the chart description */ public String getDesc() { return "The budget per project for this year (pie chart)"; } /** * Executes the chart demo. * * @param context the context * @return the built intent */ public Intent execute(Context context) { double[] values = new double[] { 12, 14, 11, 10, 19 }; int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW, Color.CYAN }; DefaultRenderer renderer = buildCategoryRenderer(colors); renderer.setZoomButtonsVisible(true); renderer.setZoomEnabled(true); renderer.setChartTitleTextSize(20); return ChartFactory.getPieChartIntent(context, buildCategoryDataset("Project budget", values), renderer, "Budget"); } }
0b1950a9598c26a9a6855e1d39f3fae3ea2c0492
d67f6450b24fb08f2f61b74dcdecce3025ee3efc
/gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/set9/light/Card9_079.java
4f3d67a1dfed1ce830d71882da66e2397628bdb2
[ "MIT" ]
permissive
cburyta/gemp-swccg-public
00a974d042195e69d3c104e61e9ee5bd48728f9a
05529086de91ecb03807fda820d98ec8a1465246
refs/heads/master
2023-01-09T12:45:33.347296
2020-10-26T14:39:28
2020-10-26T14:39:28
309,400,711
0
0
MIT
2020-11-07T04:57:04
2020-11-02T14:47:59
null
UTF-8
Java
false
false
1,979
java
package com.gempukku.swccgo.cards.set9.light; import com.gempukku.swccgo.cards.AbstractCapitalStarship; import com.gempukku.swccgo.cards.AbstractPermanentAboard; import com.gempukku.swccgo.cards.AbstractPermanentPilot; import com.gempukku.swccgo.common.Icon; import com.gempukku.swccgo.common.ModelType; import com.gempukku.swccgo.common.PlayCardOptionId; import com.gempukku.swccgo.common.Side; import com.gempukku.swccgo.filters.Filter; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import java.util.Collections; import java.util.List; /** * Set: Death Star II * Type: Starship * Subtype: Capital * Title: Mon Calamari Star Cruiser */ public class Card9_079 extends AbstractCapitalStarship { public Card9_079() { super(Side.LIGHT, 1, 8, 7, 5, null, 3, 9, "Mon Calamari Star Cruiser"); setLore("Mon Cal MC80 cruiser. Originally a civilian ship. Converted to military use following the liberation of Mon Calamari from the Empire."); setGameText("Deploys only at Mon Calamari or any Rebel Base. May add 5 pilots, 6 passengers, 1 vehicle and 3 starfighters. Has ship-docking capability. Permanent pilot aboard provides ability of 2."); addIcons(Icon.DEATH_STAR_II, Icon.PILOT, Icon.NAV_COMPUTER, Icon.SCOMP_LINK); addModelType(ModelType.MON_CALAMARI_STAR_CRUISER); setPilotCapacity(5); setPassengerCapacity(6); setVehicleCapacity(1); setStarfighterCapacity(3); } @Override protected Filter getGameTextValidDeployTargetFilter(SwccgGame game, PhysicalCard self, PlayCardOptionId playCardOptionId, boolean asReact) { return Filters.or(Filters.Deploys_at_Mon_Calamari, Filters.Deploys_at_Rebel_Base); } @Override protected List<? extends AbstractPermanentAboard> getGameTextPermanentsAboard() { return Collections.singletonList(new AbstractPermanentPilot(2) {}); } }
b3f5379b8acc72562b54c50441900765349c47a0
620c5286cb25b90508e9f45bc66b253dfa6bcd3b
/src/main/java/com/company/models/interfaces/IBuyDao.java
2f3595e171acbaf9fba63978b277a260c3906c2f
[]
no_license
kozhamseitova/Market
37134d93420881559586f7f235c2305593401d4d
8fb36da826f1cd7608b509ff7c3e0ea2d3195877
refs/heads/master
2022-12-29T04:51:31.136677
2020-10-18T15:02:37
2020-10-18T15:02:37
303,419,051
0
0
null
null
null
null
UTF-8
Java
false
false
239
java
package com.company.models.interfaces; import com.company.models.ShoppingCart; import java.util.List; public interface IBuyDao { void addProductsToBuy(ShoppingCart shoppingCart); List getProductsFromBuyByUserId(long user_id); }
a33a5acb41d04c02fff061e140cbfa27f177448b
aa024b8784fa58b3cb385d70731285811f295af5
/app/src/main/java/com/example/map/Pockemon.java
d5a4e4838a818d594e92f03ac84bed261cdbdb1f
[]
no_license
Dimpy1997-cyber/Pokemon-game
13a2de2bffab63af8b87aa9e029993eeb12b0c0b
536fcaa489ec684b752bec2d8ffaa4a236a8f81a
refs/heads/master
2020-08-03T04:57:11.121379
2019-09-29T08:39:15
2019-09-29T08:39:15
211,630,865
1
0
null
null
null
null
UTF-8
Java
false
false
565
java
package com.example.map; import android.location.Location; public class Pockemon { public int Image; public String name; public String des; public double power; public boolean isCatch; public Location location; Pockemon(int Image,String name,String des, double power,double lat, double lag){ this.Image=Image; this.name=name; this.des=des; this.power=power; this.isCatch=false; location=new Location(name); location.setLongitude(lag); location.setLatitude(lat); } }
8f62312e5db56cec737c7eea494636496bdbc377
eff1a032650191a196b80a738e9e48e878b59671
/src/main/java/org/jrivets/util/HttpClientBuilder.java
9daadb70b934d8ef801125225a063bcf27e537d5
[ "Apache-2.0" ]
permissive
obattalov/jrivets-beans
38808a6b7e7e081a8cf816d51e80b0ff6544aa38
2e7f6ec22f7139dc5e13023d5ab4b9cb84551c91
refs/heads/master
2020-12-11T02:02:24.726276
2015-10-05T20:15:46
2015-10-05T20:15:46
36,919,765
0
0
null
2015-06-05T07:51:36
2015-06-05T07:51:35
null
UTF-8
Java
false
false
3,664
java
package org.jrivets.util; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; public final class HttpClientBuilder { private Integer socketReadTimeout; private Integer connectionTimeout; private Integer maxConnections; private boolean trustAll; public HttpClientBuilder() { } public HttpClientBuilder withSocketReadTimeout(int socketReadTimeout) { this.socketReadTimeout = socketReadTimeout; return this; } public HttpClientBuilder withConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public HttpClientBuilder withMaxConnections(int maxConnections) { this.maxConnections = maxConnections; return this; } public HttpClientBuilder withTrustAll(boolean trustAll) { this.trustAll = trustAll; return this; } public HttpClient build() { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 8080, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, trustAll ? buildTrustAllSSLSocketFactory() : SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); if (maxConnections != null) { connectionManager.setDefaultMaxPerRoute(maxConnections); connectionManager.setMaxTotal(maxConnections); } HttpParams httpParams = new BasicHttpParams(); if (socketReadTimeout != null) { httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketReadTimeout); } if (connectionTimeout != null) { httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); } HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setParams(httpParams); return httpClient; } private SSLSocketFactory buildTrustAllSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } }}, new SecureRandom()); return new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { return null; } } }
498c12516ce1f18788ae9cf08fda1f8124636ed8
20b9b0d883ca35f51a554910288f900a6613d687
/src/util/InputTest.java
89ae89ce683cfe59a743c16462efd0fd56298e94
[]
no_license
bmarchambault/codeup-java-exercises
8a84e18f7bdf97842e1a2525458a8f9d5c5912c8
e4c29c6ce4316ff54cec1891307613cca58dad50
refs/heads/master
2023-01-06T12:42:29.070662
2020-10-16T17:49:17
2020-10-16T17:49:17
268,579,265
0
0
null
null
null
null
UTF-8
Java
false
false
284
java
package util; public class InputTest { public static void main(String[] args) { Input user = new Input(); user.getString(); user.yesNo(); user.getInt(3, 15); user.getInt(); user.getDouble(4.95, 100.50); user.getDouble(); } }
925e310afffbc145c28cf6b2b921eb818b360f05
57af218d590618506f8ef2ced921d1744449cfe7
/src/iae/s20/Order.java
d26f1ffb5e3a93210ceacb0acb4bffecf7a86d90
[]
no_license
payamdowlatyari/inf124-assignment4
dfa6e9cae563490c8a0dacd98c5a99e81566ca5c
bc6d607e3de3126d49b97cdf9fca090ff44bcda1
refs/heads/master
2022-10-08T11:56:05.400734
2020-06-07T19:41:59
2020-06-07T19:41:59
268,226,870
0
0
null
null
null
null
UTF-8
Java
false
false
2,468
java
package iae.s20; public class Order { private int id; private String email; private String phone; private String address; private String city; private String state; private int zip; private String method; private String cardname; private String cardnumber; private int expmonth; private int expyear; private int cvv; private String name; private double totalPrice; public Order() { this.id = Integer.MIN_VALUE; this.email = ""; this.phone= ""; this.address = ""; this.city = ""; this.state = ""; this.zip = 0; this.method = ""; this.cardname = ""; this.cardnumber = ""; this.expyear = 0; this.expmonth = 0; this.cvv = Integer.MIN_VALUE; this.name = ""; this.totalPrice = Double.MIN_NORMAL; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getZip() { return zip; } public void setZip(int zip) { this.zip = zip; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getCardname() { return cardname; } public void setCardname(String cardname) { this.cardname = cardname; } public String getCardnumber() { return cardnumber; } public void setCardnumber(String cardnumber) { this.cardnumber = cardnumber; } public int getExpmonth() { return expmonth; } public void setExpmonth(int expmonth) { this.expmonth = expmonth; } public int getExpyear() { return expyear; } public void setExpyear(int expyear) { this.expyear = expyear; } public int getCvv() { return cvv; } public void setCvv(int cvv) { this.cvv = cvv; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } }
9bbc988245b812fb36af359d505969f6a07b2416
79f8d4dc231f175beb3a67010c9901de971ab55f
/src/main/java/com/product/service/UserDetailsServiceImpl.java
69bdc9220e0ee1df88c39d71c0d1a9c871b335db
[]
no_license
naveenreddy127y1a0351/Digi-Tech
6d68db7944f6f326ed4601278a1e7b9a1f7ba10b
5941c6edc9a2c913e7095ee52afde01992b15e8c
refs/heads/master
2021-01-12T09:10:18.297492
2017-09-01T21:43:16
2017-09-01T21:43:16
76,780,493
0
0
null
null
null
null
UTF-8
Java
false
false
1,065
java
package com.product.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.product.dao.UserDetailsDAO; import com.product.model.UserDetails; import com.product.model.UserDetails1; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserDetailsDAO userdetailsdao; public String addUser(UserDetails ud) { return userdetailsdao.addUser(ud); } public UserDetails1 loginCheck(UserDetails ud) { return userdetailsdao.loginCheck(ud); } public UserDetails1 getUserById(String uid) { return userdetailsdao.getUserById(uid); } public void editUser(UserDetails1 ud) { userdetailsdao.editUser(ud); } public List<UserDetails1> getAllUsers() { return userdetailsdao.getAllUsers(); } public void enableUser(String uid) { userdetailsdao.enableUser(uid); } public void disbleUser(String uid) { userdetailsdao.disableUser(uid); } }
76b9739ebe0bc009ac72f8f94549a1f223aaf6a4
bc3fcd470ce5c2d59fe1d4d70ed84e32a96a53bd
/ds/Problem9.java
ee7133aa348862df1633ea1c73c64e5a251a36d5
[]
no_license
ShreyasVH/ds-and-algo
95a626edc92bf57a87bbb6899ecd07415aa96d73
41a227a6133ab5a4f94d2e350dea547f0be290d9
refs/heads/master
2023-01-24T05:41:45.368977
2023-01-18T15:06:30
2023-01-18T15:06:30
244,600,905
0
0
null
null
null
null
UTF-8
Java
false
false
1,002
java
/* Print the sequence similar to the column labels in sheets. Ex: A, B, .... Z, AA, AB, ...... ZZ, AAA, AAB, ........ ZZZ ........... */ public class Problem9 { public static void main(String[] args) { // getSequenceString(675); getSequence(677); // getSequence(100); } public static void getSequence(int n) { for(int i = 1; i <= n; i++) { System.out.println(i + " => " + getSequenceString(i)); } } public static String getSequenceString(int n) { String sequence = ""; int digitCount = (int) Math.ceil(Math.log(n) / Math.log(26)); System.out.println("DigitCount: " + digitCount); for(int j = digitCount; j > 1; j--) { int placeValue = (int) Math.pow(26, j - 1); int multiplier = (int) (n / Math.pow(26, j - 1)); n = Math.max(n % placeValue, 1); sequence = sequence + (char) ((int) 'A' + multiplier - 1); } sequence = sequence + (char) ((int) 'A' + n - 1); return sequence; } } /* Time Complexity: O(logn) Space Complexity: O(1) */
bb832167daee3e95e7973fb18523fd7b928bb874
93be3f0d6b828c74f3525f0e3de14901e54ec351
/src/sample/RemoveHistory.java
b7df127e9f987ce7629b65fea358043b9c26f5ed
[]
no_license
ASherstobitov/TaskManagerFX
d800de53fda3514fdc82eb1d41668d12b5cd6437
26d92b5c8880022f1582ac9fffd22a20f4067be3
refs/heads/master
2022-04-26T15:29:38.420200
2020-04-28T15:52:15
2020-04-28T15:52:15
259,680,207
0
0
null
null
null
null
UTF-8
Java
false
false
261
java
package sample; public class RemoveHistory extends History { private int index; public RemoveHistory(String nameTask, int index) { super(nameTask); this.index = index; } public int getIndex() { return index; } }
dd457a9732f7b6f9c549ef6039f5be6699f947c1
65f6408508079a69bac592c8b894938ef79719db
/src/main/java/demasse/recipe/demasserecipe/bootstrap/RecipeBootstrap.java
8954ea446a243bf312c33d738474e3c9bd1eb5d2
[]
no_license
demasseb/demasserecipe
32274f45323d73019df27f36b97a542186f96594
f833a85e6ea0e41587f2413263befcf65ae0a77b
refs/heads/master
2020-06-13T06:42:59.656636
2019-07-01T00:43:39
2019-07-01T00:43:39
194,574,956
0
0
null
null
null
null
UTF-8
Java
false
false
5,045
java
package demasse.recipe.demasserecipe.bootstrap; import demasse.recipe.demasserecipe.domain.*; import demasse.recipe.demasserecipe.respositories.UnitOfMeasureRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import demasse.recipe.demasserecipe.domain.Recipe; import demasse.recipe.demasserecipe.respositories.CategoryRepository; import demasse.recipe.demasserecipe.respositories.RecipeRepository; import javax.transaction.Transactional; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Slf4j @Component public class RecipeBootstrap implements ApplicationListener<ContextRefreshedEvent> { private final CategoryRepository categoryRepository; private final RecipeRepository recipeRepository; private final UnitOfMeasureRepository unitOfMeasureRepository; public RecipeBootstrap(CategoryRepository categoryRepository, RecipeRepository recipeRepository, UnitOfMeasureRepository unitOfMeasureRepository) { this.categoryRepository = categoryRepository; this.recipeRepository = recipeRepository; this.unitOfMeasureRepository = unitOfMeasureRepository; } private List<Recipe> getRecipe() { List<Recipe> recipes = new ArrayList<>(2); Optional<UnitOfMeasure> eachUomOptional = unitOfMeasureRepository.findByUom("Ounce"); if (!eachUomOptional.isPresent()) { throw new RuntimeException("Expected UOM Not Found"); } Optional<UnitOfMeasure> tableSpoonUomOptional = unitOfMeasureRepository.findByUom("Tablespoon"); if (!tableSpoonUomOptional.isPresent()) { throw new RuntimeException("Expected UOM Not Found"); } Optional<UnitOfMeasure> teaSpoonUomOptional = unitOfMeasureRepository.findByUom("Teaspoon"); if (!teaSpoonUomOptional.isPresent()) { throw new RuntimeException("Expected UOM Not Found"); } Optional<UnitOfMeasure> pintUomOptional = unitOfMeasureRepository.findByUom("Pinch"); if (!pintUomOptional.isPresent()) { throw new RuntimeException("Expected UOM Not Found"); } Optional<UnitOfMeasure> cupUomOptional = unitOfMeasureRepository.findByUom("Cup"); if (!cupUomOptional.isPresent()) { throw new RuntimeException("Expected UOM Not Found"); } UnitOfMeasure eachUom = eachUomOptional.get(); UnitOfMeasure tableSpoonUom = tableSpoonUomOptional.get(); UnitOfMeasure teaSpoonUOM = teaSpoonUomOptional.get(); UnitOfMeasure pintuom = pintUomOptional.get(); UnitOfMeasure cupuom = cupUomOptional.get(); Optional<Category> americanCategoryOptional = categoryRepository.findByDescription("American"); if (!americanCategoryOptional.isPresent()) { throw new RuntimeException("Expected Category Not Found"); } Optional<Category> mexicanCategoryOptional = categoryRepository.findByDescription("Mexican"); if (!mexicanCategoryOptional.isPresent()) { throw new RuntimeException("Expected Category Not Found"); } Category americanCategory = americanCategoryOptional.get(); Category mexicanCategory = mexicanCategoryOptional.get(); Recipe guacRecipe = new Recipe(); guacRecipe.setDescription("Perfect Guacamole"); guacRecipe.setPrepTime(10); guacRecipe.setCookTime(10); guacRecipe.setDifficulty(Difficulty.EASY); guacRecipe.setDirection("Na so it is done"); Notes guacNotes = new Notes(); guacRecipe.setNotes(guacNotes); guacRecipe.getIngredients().add(new Ingredient("ripe avocados", new BigDecimal(2), eachUom,guacRecipe)); guacRecipe.getIngredients().add(new Ingredient("Naso", new BigDecimal(2), eachUom,guacRecipe)); guacRecipe.getCategories().add(americanCategory); guacRecipe.getCategories().add(mexicanCategory); recipes.add(guacRecipe); Recipe tacRecipe = new Recipe(); tacRecipe.setDescription("Perfect Tacos"); tacRecipe.setPrepTime(10); tacRecipe.setCookTime(10); tacRecipe.setDifficulty(Difficulty.MODERATE); tacRecipe.setDirection("Nor be so dear"); Notes tacNotes = new Notes(); tacRecipe.setNotes(tacNotes); tacRecipe.getIngredients().add(new Ingredient("ripe dude", new BigDecimal(2), eachUom,tacRecipe)); tacRecipe.getIngredients().add(new Ingredient("Naso bighead", new BigDecimal(2), eachUom,tacRecipe)); tacRecipe.getCategories().add(americanCategory); tacRecipe.getCategories().add(mexicanCategory); recipes.add(tacRecipe); return recipes; } @Override @Transactional public void onApplicationEvent(ContextRefreshedEvent event) { recipeRepository.saveAll(getRecipe()); } }
7d0f043ae9b781411f52d409b19d4ecc1ecc4900
211ec31a7f09435b4c5d491139a2831c98e0f69c
/BestarProject/Widget/src/com/huoqiu/widget/db/DownloadFileDB.java
0ac36fac6ae54b04cc492bd9929ea42f619beee3
[ "Apache-2.0" ]
permissive
bestarandyan/ShoppingMall
6e8ac0ee3a5ae7a91541d04b1fba8d2d1496875c
ee93b393b982bdfe77d26182a2317f2c439c12fc
refs/heads/master
2021-01-01T05:49:52.010094
2015-01-23T10:29:59
2015-01-23T10:29:59
29,727,539
2
1
null
null
null
null
UTF-8
Java
false
false
6,105
java
package com.huoqiu.widget.db; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; /** * 数据库中文件下载记录的操作,包括:插入,删除,更�? * * @author shenyamin * */ public class DownloadFileDB { // 数据库字�?path, thid, done public static final String COL_PATH = "File_Path"; public static final String COL_THID = "File_Thid"; public static final String COL_DONE = "File_Done"; public static final String TABLE_NAME = "DownloadFileRecord";// 数据表名 private static DatabaseUtil helper; public DownloadFileDB(Context context) { helper = new DatabaseUtil(context); } /** * 插入数据 * * @param model * DownLoadFileModel实体�? */ public boolean insert(DownloadFileModel model) { try { SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL( "INSERT INTO " + TABLE_NAME + "(" + COL_PATH + ", " + COL_THID + ", " + COL_DONE + ") VALUES(?, ?, ?)", new Object[] { model.getPath(), model.getThid(), model.getDone() }); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } /** * 删除记录 * * @param path * URL路径 * @param thid * 线程id */ // public void delete(String path, int thid) { // SQLiteDatabase db = helper.getWritableDatabase(); // db.execSQL("DELETE FROM " + TABLE_NAME // + " WHERE " + COL_PATH + "=? AND " + COL_THID + "=?", new Object[] { // path, thid }); // } /** * 更新记录 * * @param model * DownLoadFileModel实体�? */ public boolean update(DownloadFileModel model) { try { SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL( "UPDATE " + TABLE_NAME + " SET " + COL_DONE + "=? WHERE " + COL_PATH + "=? AND " + COL_THID + "=?", new Object[] { model.getDone(), model.getPath(), model.getThid() }); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } /** * 查询表中的某�?��记录 * * @param path * URL路径 * @param thid * 线程Id * @return */ public DownloadFileModel query(String path, int thid) { DownloadFileModel model = null; Cursor c = null; try { SQLiteDatabase db = helper.getWritableDatabase(); String sql = "SELECT " + COL_PATH + ", " + COL_THID + ", " + COL_DONE + " FROM " + TABLE_NAME + " WHERE " + COL_PATH + "=? AND " + COL_THID + "=?"; c = db.rawQuery(sql, new String[] { path, String.valueOf(thid) }); if (c.moveToNext()) { model = new DownloadFileModel(c.getString(0), c.getInt(1), c.getInt(2)); return model; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } finally { if (c != null) { c.close(); } } return null; } /** * 查询APK下载是否完成 * * @param path * URL路径 * @param thid * 线程Id * @return */ // public int queryDownloadOver(String path) { // Cursor c = null; // try { // SQLiteDatabase db = helper.getWritableDatabase(); // String sql = "SELECT " + COL_DONE + " FROM " + TABLE_NAME // + " WHERE " + COL_PATH + "=? AND " + COL_THID + " = -9999";// -9999已经下载完成的标�? // c = db.rawQuery(sql, new String[] { path }); // if (c.moveToNext()) { // return c.getInt(0); // } // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // return 0; // } finally { // if (c != null) // c.close(); // } // // return 0; // } /** * 删除下载记录 * * @param path * 文件路径 * @param len */ public boolean deleteAll(String path, int len) { Cursor c = null; try { SQLiteDatabase db = helper.getWritableDatabase(); String sel = "SELECT SUM(" + COL_DONE + ") FROM " + TABLE_NAME + " WHERE " + COL_PATH + "=?"; c = db.rawQuery(sel, new String[] { path }); if (c.moveToNext()) { int result = c.getInt(0); if (result == len) { db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COL_PATH + "=? ", new Object[] { path }); // 删除下载记录后,插入�?��新的记录包含本次下载的url,apk的大小,-9999作为标识以便下次提取这条记录 // insert(new DownloadFileModel(path, -9999, len)); return true; } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } finally { if (c != null) { c.close(); } } return false; } /** * 删除�?��路径为path的下载记�? * * @param path * 文件路径 */ public boolean deleteDownloadRecord(String path) { Cursor c = null; try { SQLiteDatabase db = helper.getWritableDatabase(); String sel = "SELECT 1 FROM " + TABLE_NAME + " WHERE " + COL_PATH + "=? ";// + COL_THID +"= -9999" c = db.rawQuery(sel, new String[] { path }); if (c.moveToNext()) { db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COL_PATH + "=? ", new Object[] { path });// AND "+ COL_THID +"= // -9999" return true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } finally { if (c != null) { c.close(); } } return false; } /** * 查询是否有未完成的记�? * �?true;没有:false; * @param path * @return */ public boolean queryUndone(String path) { Cursor c = null; try { SQLiteDatabase db = helper.getWritableDatabase(); String undo = "SELECT " + COL_PATH + " FROM " + TABLE_NAME + " WHERE "+ COL_PATH +" = '"+ path +"'";//+ COL_THID +"=-9999 c = db.rawQuery(undo, null); if(c.moveToNext()){ return true; } } catch (Exception e) { e.printStackTrace(); return false; } finally{ if(c != null){ c.close(); } } return false; } }
31c914a22403fe2f62033835fb495d29499b6b9b
0c51a150f3b03d4272143b2de4daa1626f1263a1
/src/main/java/com/bm/index/controller/IndexController.java
29ad0f1c8bc513a810099d45c0d149f0cadd94c8
[]
no_license
zhaoyunnian-xb/dcdb
c29016ae18d46d138acc33d32094c643be04176b
2d7fc4d4f4385386032f550dd0ee27c7d56bc218
refs/heads/master
2023-01-14T04:55:02.231896
2020-11-27T01:08:14
2020-11-27T01:08:14
316,149,482
1
1
null
null
null
null
UTF-8
Java
false
false
3,938
java
package com.bm.index.controller; import com.bm.index.dao.source1.DcdbBmmbnrDao; import com.bm.index.dao.source1.DcdbDbDao; import com.bm.index.model.DcdbDb; import com.bm.index.model.UserEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("index") public class IndexController { @Autowired DcdbDbDao dcdbDbDao; @Autowired DcdbBmmbnrDao dcdbBmmbnrDao; public final static Map<Integer, String> nodeMap = new HashMap<Integer, String>() { { put(1,"新建"); put(2, "内勤接收"); put(3, "承办人办理"); put(4, "部门负责人审核"); put(5, "承办人办理"); put(6, "督查室办理"); } }; @RequestMapping() public String index(HttpSession session, String id,String username, Model model){ UserEntity loginUser =new UserEntity(); // 用户查询 // List<UserEntity> users = dcdbBmmbnrDao.loginQuery(id); List<UserEntity> users = dcdbBmmbnrDao.loginQueryByName(username); // session存放 if (users != null && users.size() > 0) { loginUser = users.get(0); model.addAttribute("bmmc", users.get(0).getBmmc()); model.addAttribute("username", users.get(0).getName()); } session.setAttribute("User",loginUser); return "index"; } @RequestMapping("/updateDb.do") @ResponseBody public String updateDb(DcdbDb dcdbDb){ String ajzt=dcdbDb.getAjzt(); //判断当前节点是不是整个节点的最后一部,3为整个节点的最后一步 if(ajzt.equals("2")){ Integer nodeid=Integer.valueOf(dcdbDb.getNodeid()); dcdbDb.setNodeid(nodeid+1+""); dcdbDb.setAjzt("1"); dcdbDb.setNodename(nodeMap.get(Integer.valueOf(dcdbDb.getNodeid()))); //如果是承办人办理之后的节点没有待办事件了,因为只有审批的权限 dcdbDb.setAjzt("2"); }else{ Integer zt=Integer.valueOf(ajzt); dcdbDb.setAjzt(zt+1+""); } //更新操作 int i= dcdbDbDao.updateByExampleSelective(dcdbDb); return i+""; } /** * 模板下载 * @add */ @RequestMapping(value = "/download.do", method = { RequestMethod.GET, RequestMethod.POST }) public void documentDownload(HttpServletRequest request, String fileName,HttpServletResponse response, HttpSession session) { // 文书获取 String url = session.getServletContext().getRealPath("/") + "download/file/"; String realFile = url + fileName; try { fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "\\(") .replaceAll("%29", "\\)").replaceAll("%3B", ";").replaceAll("%40", "@").replaceAll("%23", "\\#") .replaceAll("%26", "\\&"); response.setHeader("content-disposition", "attachment;filename=" + fileName); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("UTF-8"); // 输入流 InputStream fis = new BufferedInputStream(new FileInputStream(realFile)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
165200c897af4c2318e74738428f04d4802826bc
a4f94f4701a59cafc7407aed2d525b2dff985c95
/core/typesystemIntegration/source/jetbrains/mps/typesystem/checking/FakeEditorContext.java
37e526190fe8183ff450ba401293c4b63973aad8
[]
no_license
jamice/code-orchestra-core
ffda62860f5b117386aa6455f4fdf61661abbe9e
b2bbf8362be2e2173864c294c635badb2e27ecc6
refs/heads/master
2021-01-15T13:24:53.517854
2013-05-09T21:39:28
2013-05-09T21:39:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
728
java
package jetbrains.mps.typesystem.checking; import codeOrchestra.actionscript.parsing.FakeEditorComponent; import jetbrains.mps.nodeEditor.EditorComponent; import jetbrains.mps.nodeEditor.EditorContext; import jetbrains.mps.smodel.IOperationContext; import jetbrains.mps.smodel.SModel; import jetbrains.mps.smodel.SNode; /** * @author Alexander Eliseyev */ public class FakeEditorContext extends EditorContext { private static final SNode FAKE_NODE = new SNode(null, "null", false); public FakeEditorContext(SModel model, IOperationContext operationContext) { super(new FakeEditorComponent(operationContext), model, operationContext); } @Override public SNode getSelectedNode() { return FAKE_NODE; } }
b867a261804f40eca54119ee3dff4cecd1071bf2
5fde289dd1a8a50c7721018a3386f2b674caeca1
/src/Android Frontend/app/src/main/java/com/work/prepmaster/ProfileActivity.java
bebe2a4addd76bc45ff6b5a1a2830cf752c50cc3
[]
no_license
MKayhan8/PrepMaster
4efb48f9f0d29030f8e913d1bc926c94f68e7313
73beba450075f4b17b84ec92691a057eb647c274
refs/heads/master
2020-05-02T23:25:43.492154
2019-03-27T20:09:24
2019-03-27T20:09:24
178,279,733
1
0
null
2019-03-28T20:46:22
2019-03-28T20:46:21
null
UTF-8
Java
false
false
1,205
java
package com.work.prepmaster; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { private Button back, options, statistic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); back = findViewById(R.id.buttonProfileBack); back.setOnClickListener(this); options = findViewById(R.id.buttonProfileOptions); options.setOnClickListener(this); statistic = findViewById(R.id.buttonStatistic); statistic.setOnClickListener(this); } @Override public void onClick(View view) { Intent intentOptions = new Intent(this,ProfileOptionsActivity.class); Intent intentStatistic = new Intent(this,StatisticActivity.class); if(view == back) onBackPressed(); if(view == options) startActivity(intentOptions); if(view == statistic) startActivity(intentStatistic); } }