diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java b/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java index deb2879..5c6eb08 100644 --- a/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java +++ b/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java @@ -1,187 +1,187 @@ package ru.spbau.bioinf.tagfinder; import java.io.BufferedReader; import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import ru.spbau.bioinf.tagfinder.util.ReaderUtil; public class IntencityTableGenerator { private static String file1 = "bar_exp_annotated_proper_none_intencity"; private static String file2 = "bar_exp_annotated_correct_none_intencity"; public static void main(String[] args) throws Exception { double[][] res = new double[100][3]; printTable(res, file1, "Percentage of spectra in the $\\STbar$ data set, such that all their top-scoring tags of length $\\ell$ are proper (+) or improper (-).", "label16"); TexTableGenerator.createThreeRowsTable(res, "Average percentage of proper top-scoring tags of a given length", "", "label10"); tableTopscoreAllAndAvg(); } public static void tableTopscoreAllAndAvg() throws Exception { double[][] res; res = new double[100][3]; printTable(res, file2, "Percentage of spectra in the $\\STbar$ data set, such that all their top-scoring tags of length $\\ell$ are correct (+) or incorrect (-).", "all-top-scoring"); TexTableGenerator.createThreeRowsTable(res, "Average percentage of correct top-scoring tags of a given length", "correct top-scoring tags", "avg-top-scoring"); } private static void printTable(double[][] res, String file, String caption, String label) throws Exception { double[][] res2 = new double[6][]; int max = 0; for (int gap = 1; gap <= 3; gap++) { BufferedReader in = ReaderUtil.createInputReader(new File("res", "share_" + file + "_" + gap + ".txt")); double[] good = new double[100]; double[] bad = new double[100]; double[] both = new double[100]; List<Double>[] percentage = new List[100]; do { String s = in.readLine(); if (s.contains(",")) { break; } if (s.indexOf(" ") == 0) { break; } long[] data = CalculateRelation.getData(s); int pos = 2; int d = 1; while (pos < data.length) { max = Math.max(max, d); if (data[pos] == 0) { bad[d]++; } else if (data[pos + 1] <= data[pos]) { good[d]++; } else { both[d]++; } if (percentage[d] == null) { percentage[d] = new ArrayList<Double>(); } percentage[d].add(data[pos] * 100.0d / (data[pos] + data[pos + 1])); d++; pos += 2; } } while (true); double[] ans = new double[max]; for (int i = 1; i <= max; i++) { double total = 0; for (double v : percentage[i]) { total += v; } ans[i - 1] = total / percentage[i].size(); } res[gap - 1] = ans; res2[2 * gap - 2 ] = new double[max]; res2[2 * gap - 1] = new double[max]; for (int i = 1; i <= max; i++) { double total = good[i] + bad[i] + both[i]; res2[2 * gap - 2][i - 1] = 100 * good[i] / total; res2[2 * gap - 1][i - 1] = 100 * bad[i] / total; } } int width = 19; System.out.println("\\begin{landscape}\n"); for (int start = 1; start <= max; start += width) { int end = Math.min(start + width - 1, max); System.out.print("\\begin{table}[ht]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|c|cc|c|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } int cols = end - start + 1; System.out.println("}\n" + " \\hline\n" + " \\multicolumn{3}{|c|}{ } & \\multicolumn{ " + cols + "}{|c|}{$k$} \\\\\n" + " \\cline{4-" + (cols + 3) + " }\n" + " \\multicolumn{3}{|c|}{ } "); for (int i = start; i <= end; i++) { System.out.print(" & " + i); } for (int row = 0; row < 6; row++) { System.out.print("\\\\\n"); if (row % 2 == 0) { System.out.print("\\hline\n" + " \\multirow{2}{*}{" + (row / 2 + 1) + "-aa}& \\multirow{2}{*}{spectra (\\%)} "); } else { System.out.println(" & "); } System.out.println(" & " + (row % 2 == 0 ? "+" : "--")); for (int i = start; i <= end; i++) { System.out.print(" & "); if (res2[row].length > i - 1) { System.out.print(ValidTags.df.format(res2[row][i-1])); } } } System.out.println(" \\\\\n" + " \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == max) { System.out.println("\\caption{" + caption + "}\n" + "\\label{table:all-top-scoring}\n"); } System.out.println("\\vspace{3mm}\n" + "\\end{table}"); } System.out.println("\\end{landscape}"); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{" + label + "}"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:" + label + "}\n" + "\\end{figure}\n"); PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", label + ".dat")); PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", label + ".gpl")); - gplFile.print("set terminal postscript eps color \"Helvetica\" 22\n" + + gplFile.print("set terminal postscript eps color lw 4 \"Helvetica\" 22\n" + "set out \"" + label + ".eps\"\n" + "set ylabel \"spectra (%)\"\n" + "set xlabel \"tag length (l)\"\n" + "plot"); gplFile.println("\"plots/" + label + ".dat\" using 1:2 title 't=1 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:3 title 't=1 -' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:4 title 't=2 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:5 title 't=2 -' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:6 title 't=3 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:7 title 't=3 -' with linespoints"); gplFile.close(); for (int i = 1; i <=14; i++) { dataFile.print(i + " "); for (int j = 0; j < 6; j++) { dataFile.print(res2[j].length > i - 1 ? (res2[j][i-1]): " "); dataFile.print(" "); } dataFile.println(); } dataFile.close(); } }
true
true
private static void printTable(double[][] res, String file, String caption, String label) throws Exception { double[][] res2 = new double[6][]; int max = 0; for (int gap = 1; gap <= 3; gap++) { BufferedReader in = ReaderUtil.createInputReader(new File("res", "share_" + file + "_" + gap + ".txt")); double[] good = new double[100]; double[] bad = new double[100]; double[] both = new double[100]; List<Double>[] percentage = new List[100]; do { String s = in.readLine(); if (s.contains(",")) { break; } if (s.indexOf(" ") == 0) { break; } long[] data = CalculateRelation.getData(s); int pos = 2; int d = 1; while (pos < data.length) { max = Math.max(max, d); if (data[pos] == 0) { bad[d]++; } else if (data[pos + 1] <= data[pos]) { good[d]++; } else { both[d]++; } if (percentage[d] == null) { percentage[d] = new ArrayList<Double>(); } percentage[d].add(data[pos] * 100.0d / (data[pos] + data[pos + 1])); d++; pos += 2; } } while (true); double[] ans = new double[max]; for (int i = 1; i <= max; i++) { double total = 0; for (double v : percentage[i]) { total += v; } ans[i - 1] = total / percentage[i].size(); } res[gap - 1] = ans; res2[2 * gap - 2 ] = new double[max]; res2[2 * gap - 1] = new double[max]; for (int i = 1; i <= max; i++) { double total = good[i] + bad[i] + both[i]; res2[2 * gap - 2][i - 1] = 100 * good[i] / total; res2[2 * gap - 1][i - 1] = 100 * bad[i] / total; } } int width = 19; System.out.println("\\begin{landscape}\n"); for (int start = 1; start <= max; start += width) { int end = Math.min(start + width - 1, max); System.out.print("\\begin{table}[ht]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|c|cc|c|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } int cols = end - start + 1; System.out.println("}\n" + " \\hline\n" + " \\multicolumn{3}{|c|}{ } & \\multicolumn{ " + cols + "}{|c|}{$k$} \\\\\n" + " \\cline{4-" + (cols + 3) + " }\n" + " \\multicolumn{3}{|c|}{ } "); for (int i = start; i <= end; i++) { System.out.print(" & " + i); } for (int row = 0; row < 6; row++) { System.out.print("\\\\\n"); if (row % 2 == 0) { System.out.print("\\hline\n" + " \\multirow{2}{*}{" + (row / 2 + 1) + "-aa}& \\multirow{2}{*}{spectra (\\%)} "); } else { System.out.println(" & "); } System.out.println(" & " + (row % 2 == 0 ? "+" : "--")); for (int i = start; i <= end; i++) { System.out.print(" & "); if (res2[row].length > i - 1) { System.out.print(ValidTags.df.format(res2[row][i-1])); } } } System.out.println(" \\\\\n" + " \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == max) { System.out.println("\\caption{" + caption + "}\n" + "\\label{table:all-top-scoring}\n"); } System.out.println("\\vspace{3mm}\n" + "\\end{table}"); } System.out.println("\\end{landscape}"); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{" + label + "}"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:" + label + "}\n" + "\\end{figure}\n"); PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", label + ".dat")); PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", label + ".gpl")); gplFile.print("set terminal postscript eps color \"Helvetica\" 22\n" + "set out \"" + label + ".eps\"\n" + "set ylabel \"spectra (%)\"\n" + "set xlabel \"tag length (l)\"\n" + "plot"); gplFile.println("\"plots/" + label + ".dat\" using 1:2 title 't=1 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:3 title 't=1 -' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:4 title 't=2 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:5 title 't=2 -' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:6 title 't=3 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:7 title 't=3 -' with linespoints"); gplFile.close(); for (int i = 1; i <=14; i++) { dataFile.print(i + " "); for (int j = 0; j < 6; j++) { dataFile.print(res2[j].length > i - 1 ? (res2[j][i-1]): " "); dataFile.print(" "); } dataFile.println(); } dataFile.close(); }
private static void printTable(double[][] res, String file, String caption, String label) throws Exception { double[][] res2 = new double[6][]; int max = 0; for (int gap = 1; gap <= 3; gap++) { BufferedReader in = ReaderUtil.createInputReader(new File("res", "share_" + file + "_" + gap + ".txt")); double[] good = new double[100]; double[] bad = new double[100]; double[] both = new double[100]; List<Double>[] percentage = new List[100]; do { String s = in.readLine(); if (s.contains(",")) { break; } if (s.indexOf(" ") == 0) { break; } long[] data = CalculateRelation.getData(s); int pos = 2; int d = 1; while (pos < data.length) { max = Math.max(max, d); if (data[pos] == 0) { bad[d]++; } else if (data[pos + 1] <= data[pos]) { good[d]++; } else { both[d]++; } if (percentage[d] == null) { percentage[d] = new ArrayList<Double>(); } percentage[d].add(data[pos] * 100.0d / (data[pos] + data[pos + 1])); d++; pos += 2; } } while (true); double[] ans = new double[max]; for (int i = 1; i <= max; i++) { double total = 0; for (double v : percentage[i]) { total += v; } ans[i - 1] = total / percentage[i].size(); } res[gap - 1] = ans; res2[2 * gap - 2 ] = new double[max]; res2[2 * gap - 1] = new double[max]; for (int i = 1; i <= max; i++) { double total = good[i] + bad[i] + both[i]; res2[2 * gap - 2][i - 1] = 100 * good[i] / total; res2[2 * gap - 1][i - 1] = 100 * bad[i] / total; } } int width = 19; System.out.println("\\begin{landscape}\n"); for (int start = 1; start <= max; start += width) { int end = Math.min(start + width - 1, max); System.out.print("\\begin{table}[ht]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|c|cc|c|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } int cols = end - start + 1; System.out.println("}\n" + " \\hline\n" + " \\multicolumn{3}{|c|}{ } & \\multicolumn{ " + cols + "}{|c|}{$k$} \\\\\n" + " \\cline{4-" + (cols + 3) + " }\n" + " \\multicolumn{3}{|c|}{ } "); for (int i = start; i <= end; i++) { System.out.print(" & " + i); } for (int row = 0; row < 6; row++) { System.out.print("\\\\\n"); if (row % 2 == 0) { System.out.print("\\hline\n" + " \\multirow{2}{*}{" + (row / 2 + 1) + "-aa}& \\multirow{2}{*}{spectra (\\%)} "); } else { System.out.println(" & "); } System.out.println(" & " + (row % 2 == 0 ? "+" : "--")); for (int i = start; i <= end; i++) { System.out.print(" & "); if (res2[row].length > i - 1) { System.out.print(ValidTags.df.format(res2[row][i-1])); } } } System.out.println(" \\\\\n" + " \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == max) { System.out.println("\\caption{" + caption + "}\n" + "\\label{table:all-top-scoring}\n"); } System.out.println("\\vspace{3mm}\n" + "\\end{table}"); } System.out.println("\\end{landscape}"); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{" + label + "}"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:" + label + "}\n" + "\\end{figure}\n"); PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", label + ".dat")); PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", label + ".gpl")); gplFile.print("set terminal postscript eps color lw 4 \"Helvetica\" 22\n" + "set out \"" + label + ".eps\"\n" + "set ylabel \"spectra (%)\"\n" + "set xlabel \"tag length (l)\"\n" + "plot"); gplFile.println("\"plots/" + label + ".dat\" using 1:2 title 't=1 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:3 title 't=1 -' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:4 title 't=2 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:5 title 't=2 -' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:6 title 't=3 +' with linespoints,\\"); gplFile.println("\"plots/" + label + ".dat\" using 1:7 title 't=3 -' with linespoints"); gplFile.close(); for (int i = 1; i <=14; i++) { dataFile.print(i + " "); for (int j = 0; j < 6; j++) { dataFile.print(res2[j].length > i - 1 ? (res2[j][i-1]): " "); dataFile.print(" "); } dataFile.println(); } dataFile.close(); }
diff --git a/src/org/eob/Eob1Settings.java b/src/org/eob/Eob1Settings.java index 619cf1a..44f94ac 100644 --- a/src/org/eob/Eob1Settings.java +++ b/src/org/eob/Eob1Settings.java @@ -1,349 +1,349 @@ package org.eob; import org.eob.enums.GameSupportType; import org.eob.enums.WallType; import org.eob.model.ItemType; import org.eob.model.SubItemType; import org.eob.model.Wall; import java.util.Arrays; /** * User: Bifrost * Date: 10/25/12 * Time: 12:33 AM */ public class Eob1Settings { @SuppressWarnings("UnusedDeclaration") public static void init() { //-------------- // --- Items --- //-------------- ItemType Axe = new ItemType(0x00, "axe", "Axe", "hand_axe"); ItemType Longsword = new ItemType(0x01, "long_sword", "Long Sword", "long_sword"); ItemType Dart = new ItemType(0x04, "dart", "Dart", "shuriken"); ItemType Dagger = new ItemType(0x05, "dagger", "Dagger", "dagger"); ItemType DwarvenPotion = new ItemType(0x06, "dwarven_potion", "Dwarven potion", "potion_healing"); ItemType Bow = new ItemType(0x07, "bow", "Bow", "short_bow"); ItemType Spear = new ItemType(0x09, "spear", "Spear", "legionary_spear"); ItemType Mace = new ItemType(0x0B, "mace", "Mace", "knoffer"); ItemType Sling = new ItemType(0x0E, "sling", "Sling", "sling"); ItemType Dart2 = new ItemType(0x0F, "dart", "Dart", "shuriken"); ItemType Arrow = new ItemType(0x10, "arrow", "Arrow", "arrow"); ItemType Rock = new ItemType(0x12, "rock", "Rock", "rock"); ItemType Chainmail = new ItemType(0x14, "chainmail", "Chainmail", "ring_mail"); ItemType DwarvenHelmet = new ItemType(0x15, "dwarven_helmet", "Dwarven Helmet", "full_helmet"); ItemType LeatherArmor = new ItemType(0x16, "leather_armor", "Leather Armor", "leather_brigandine"); ItemType Shield = new ItemType(0x1B, "shield", "Shield", "round_shield"); ItemType LockPicks = new ItemType(0x1C, "lock_picks", "Lock picks", "machine_part_south"); ItemType Rations = new ItemType(0x1F, "rations", "Rations", "pitroot_bread"); ItemType LeatherBoots = new ItemType(0x20, "leather_boots", "Leather boots", "leather_boots"); ItemType Bones = new ItemType(0x21, "bones", "Bones", "remains_of_toorum"); ItemType MageScroll = new ItemType(0x22, "mage_scroll", "Mage scroll", "scroll"); ItemType ClericScroll = new ItemType(0x23, "cleric_scroll", "Cleric scroll", "scroll"); ItemType TextScroll = new ItemType(0x24, "scroll", "Text scroll", "scroll"); ItemType Stone = new ItemType(0x25, "stone", "Stone", "rock"); ItemType Key = new ItemType(0x26, "key", "Key", "brass_key"); // Different keys ItemType Potion = new ItemType(0x27, "potion", "Potion", "potion_healing"); ItemType Gem = new ItemType(0x28, "gem", "Gem", "blue_gem"); // Gems of different colors (red and blue) ItemType Robe = new ItemType(0x29, "robe", "Robe", "peasant_tunic"); ItemType MedallionOfAdornment = new ItemType(0x2c, "medallion_of_adornment", "Medallion of Adornment", "spirit_mirror_pendant"); ItemType Ring = new ItemType(0x2a, "ring", "Ring", "hardstone_bracelet"); // There are no rings in Grimrock, we need to replace them with bracelets ItemType Ring2 = new ItemType(0x2f, "ring2", "Ring", "bracelet_tirin"); // This one has no power (found in lv 4, x=11,y=29) ItemType Wand = new ItemType(0x30, "wand", "Wand", "whitewood_wand"); //----------------- // --- SubItems --- //----------------- // Text scroll SubItemType TextScroll1 = new SubItemType(47, TextScroll, "text1", "", "Unknown text"); SubItemType TextScroll2 = new SubItemType(48, TextScroll, "text2", "", "Unknown text"); SubItemType TextScroll3 = new SubItemType(49, TextScroll, "text3", "", "Unknown text"); SubItemType TextScroll4 = new SubItemType(50, TextScroll, "text4", "", "Unknown text"); // Cleric scroll SubItemType ClericScrollBless = new SubItemType(1, ClericScroll, "bless", "Bless", "1L"); SubItemType ClericScrollCureLightWnds = new SubItemType(2, ClericScroll, "cure_light_wnds", "Cure Light Wounds", "1L"); SubItemType ClericScrollCauseLightWnds = new SubItemType(3, ClericScroll, "cause_light_wnds", "Cause Light Wounds", "1L"); SubItemType ClericScrollDetectMagic = new SubItemType(4, ClericScroll, "detect_magic", "Detect Magic", "1L"); SubItemType ClericScrollProtectEvil = new SubItemType(5, ClericScroll, "protect_evil", "Protect-Evil", "1L"); SubItemType ClericScrollAid = new SubItemType(6, ClericScroll, "aid", "Aid", "2L"); SubItemType ClericScrollFlameBlade = new SubItemType(7, ClericScroll, "flame_blade", "Flame Blade", "2L"); SubItemType ClericScrollHoldPerson = new SubItemType(8, ClericScroll, "hold_person", "Hold Person", "2L"); SubItemType ClericScrollSlowPoison = new SubItemType(9, ClericScroll, "slow_poison", "Slow Poison", "2L"); SubItemType ClericScrollCreateFood = new SubItemType(10, ClericScroll, "create_food", "Create Food", "3L"); SubItemType ClericScrollDispelMagic = new SubItemType(11, ClericScroll, "dispel_magic", "Dispel Magic", "3L"); SubItemType ClericScrollMagicalVestment = new SubItemType(12, ClericScroll, "magical_vestment", "Magical Vestment", "3L"); SubItemType ClericScrollPrayer = new SubItemType(13, ClericScroll, "prayer", "Prayer", "3L"); SubItemType ClericScrollRemoveParalysis = new SubItemType(14, ClericScroll, "remove_paralysis", "Remove Paralysis", "3L"); SubItemType ClericScrollCureSeriousWnds = new SubItemType(15, ClericScroll, "cure_serious_wnds", "Cure Serious Wounds", "4L"); SubItemType ClericScrollCauseSeriousWnds = new SubItemType(16, ClericScroll, "cause_serious_wnds", "Cause Serious Wounds", "4L"); SubItemType ClericScrollNeutralPoison = new SubItemType(17, ClericScroll, "neutral_poison", "Neutral-Poison", "4L"); SubItemType ClericScrollProtectEvil10 = new SubItemType(18, ClericScroll, "protect_evil10", "Protect-Evil 10'", "4L"); SubItemType ClericScrollCureCriticalWnds = new SubItemType(20, ClericScroll, "cure_critical_wnds", "Cure Critical Wounds", "5L"); SubItemType ClericScrollCauseCriticalWnds = new SubItemType(21, ClericScroll, "cause_critical_wnds", "Cause Critical Wounds", "5L"); SubItemType ClericScrollFlameStrike = new SubItemType(22, ClericScroll, "flame_strike", "Flame Strike", "5L"); SubItemType ClericScrollRaiseDead = new SubItemType(23, ClericScroll, "raise_dead", "Raise Dead", "5L"); // Mage scroll SubItemType MageScrollArmor = new SubItemType(1, MageScroll, "armor", "Armor", "1L"); SubItemType MageScrollBurningHands = new SubItemType(2, MageScroll, "burning_hands", "Burning Hands", "1L"); SubItemType MageScrollDetectMagic = new SubItemType(3, MageScroll, "detect_magic", "Detect Magic", "1L"); SubItemType MageScrollMagicMissile = new SubItemType(4, MageScroll, "magic_missile", "Magic Missile", "1L"); SubItemType MageScrollReadMagic = new SubItemType(5, MageScroll, "read_magic", "Read Magic", "1L"); SubItemType MageScrollShield = new SubItemType(6, MageScroll, "shield", "Shield", "1L"); SubItemType MageScrollShockingGrasp = new SubItemType(7, MageScroll, "shocking_grasp", "Shocking Grasp", "1L"); SubItemType MageScrollInvisibility = new SubItemType(8, MageScroll, "invisibility", "Invisibility", "2L"); SubItemType MageScrollKnock = new SubItemType(9, MageScroll, "knock", "Knock", "2L"); SubItemType MageScrollMsAcidArrow = new SubItemType(10, MageScroll, "ms_acid_arrow", "M's Acid Arrow", "2L"); SubItemType MageScrollStinkingCloud = new SubItemType(11, MageScroll, "stinking_cloud", "Stinking Cloud", "2L"); SubItemType MageScrollDispelMagic = new SubItemType(12, MageScroll, "dispel_magic", "Dispel Magic", "3L"); SubItemType MageScrollFireball = new SubItemType(13, MageScroll, "fireball", "Fireball", "3L"); SubItemType MageScrollFlameArrow = new SubItemType(14, MageScroll, "flame_arrow", "Flame Arrow", "3L"); SubItemType MageScrollHaste = new SubItemType(15, MageScroll, "haste", "Haste", "3L"); SubItemType MageScrollHoldPerson = new SubItemType(16, MageScroll, "hold_person", "Hold Person", "3L"); SubItemType MageScrollInvisibility10 = new SubItemType(17, MageScroll, "invisibility 10'", "Invisibility 10'", "3L"); SubItemType MageScrollLightningBolt = new SubItemType(18, MageScroll, "lightning_bolt", "Lightning Bolt", "3L"); SubItemType MageScrollVampiricTouch = new SubItemType(19, MageScroll, "vampiric_touch", "Vampiric Touch", "3L"); SubItemType MageScrollFear = new SubItemType(20, MageScroll, "fear", "Fear", "4L"); SubItemType MageScrollIceStorm = new SubItemType(21, MageScroll, "ice_storm", "Ice Storm", "4L"); SubItemType MageScrollStoneSkin = new SubItemType(22, MageScroll, "stone_skin", "Stone Skin", "4L"); SubItemType MageScrollCloudKill = new SubItemType(23, MageScroll, "cloud_kill", "Cloud Kill", "5L"); SubItemType MageScrollConeOfCold = new SubItemType(24, MageScroll, "cone_of_cold", "Cone of Cold", "5L"); SubItemType MageScrollHoldMonster = new SubItemType(25, MageScroll, "hold_monster", "Hold Monster", "5L"); // Potion SubItemType PotionGiantStrength = new SubItemType(1, Potion, "giant_strength", "Giant Strength", ""); SubItemType PotionHealing = new SubItemType(2, Potion, "healing", "Healing", ""); SubItemType PotionExtraHealing = new SubItemType(3, Potion, "extra_healing", "Extra Healing", ""); SubItemType PotionPoison = new SubItemType(4, Potion, "poison", "Poison", ""); SubItemType PotionVitality = new SubItemType(5, Potion, "vitality", "Vitality", ""); SubItemType PotionSpeed = new SubItemType(6, Potion, "speed", "Speed", ""); SubItemType PotionInvisibility = new SubItemType(7, Potion, "invisibility", "Invisibility", ""); SubItemType PotionCurePoison = new SubItemType(8, Potion, "cure_poison", "Cure Poison", ""); // Dwarven potion SubItemType DwarvenPotionHealing = new SubItemType(8, Potion, "healing", "Healing", ""); // Key SubItemType KeySilver = new SubItemType(1, Key, "silver", "", ""); SubItemType KeyGold = new SubItemType(2, Key, "gold", "", ""); SubItemType KeyDwarven = new SubItemType(3, Key, "dwarven", "", ""); SubItemType KeySimple = new SubItemType(4, Key, "", "", ""); SubItemType KeySkull = new SubItemType(5, Key, "skull", "", ""); SubItemType KeyDrow = new SubItemType(6, Key, "drow", "", ""); SubItemType KeyJeweled = new SubItemType(7, Key, "jeweled", "", ""); SubItemType KeyRuby = new SubItemType(8, Key, "ruby", "", ""); // Wand SubItemType WandLightningBolt = new SubItemType(1, Wand, "lightning_bolt", "Lightning Bolt", ""); SubItemType WandConeOfCold = new SubItemType(2, Wand, "cone_of_cold", "Cone of Cold", ""); SubItemType WandCureSeriousWounds = new SubItemType(3, Wand, "cure_serious_wnds", "Cure Serious Wounds", ""); SubItemType WandFireball = new SubItemType(4, Wand, "fireball", "Fireball", ""); SubItemType WandSlivias = new SubItemType(5, Wand, "slivias", "Slivias", "Move 1 square away"); SubItemType WandMagicMissile = new SubItemType(6, Wand, "magic_missile", "Magic Missile", ""); SubItemType WandMagicalVestment = new SubItemType(7, Wand, "magical_vestment", "Magical Vestment", ""); // Rations SubItemType RationsBasic = new SubItemType(25, Rations, "", "Rations", ""); SubItemType RationsIron = new SubItemType(50, Rations, "iron", "Iron Rations", ""); // Bones SubItemType HumanBones = new SubItemType(1, Bones, "human", "", ""); SubItemType HalflingBones = new SubItemType(6, Bones, "halfling", "", ""); // Dart SubItemType DartPlus1 = new SubItemType(1, Dart, "plus1", "+1", "", ""); SubItemType DartPlus2 = new SubItemType(2, Dart, "plus2", "+2", "", ""); SubItemType DartPlus3 = new SubItemType(3, Dart, "plus3", "+3", "", ""); SubItemType DartPlus4 = new SubItemType(4, Dart, "plus4", "+4", "", ""); SubItemType DartPlus5 = new SubItemType(5, Dart, "plus5", "+5", "", ""); SubItemType Dart2Plus1 = new SubItemType(1, Dart2, "plus1", "+1", "", ""); SubItemType Dart2Plus2 = new SubItemType(2, Dart2, "plus2", "+2", "", ""); SubItemType Dart2Plus3 = new SubItemType(3, Dart2, "plus3", "+3", "", ""); SubItemType Dart2Plus4 = new SubItemType(4, Dart2, "plus4", "+4", "", ""); SubItemType Dart2Plus5 = new SubItemType(5, Dart2, "plus5", "+5", "", ""); // Stone SubItemType StoneHolySymbol = new SubItemType(1, Stone, "holy_symbol", "", ""); SubItemType StoneNecklace = new SubItemType(2, Stone, "necklace", "", ""); SubItemType StoneOrb = new SubItemType(3, Stone, "orb", "", ""); SubItemType StoneDagger = new SubItemType(4, Stone, "dagger", "", ""); SubItemType StoneMedallion = new SubItemType(5, Stone, "medallion", "", ""); SubItemType StoneScepter = new SubItemType(6, Stone, "scepter", "", ""); // Dagger SubItemType DaggerBackstabber = new SubItemType(3, Dagger, "backstabber", "+3", ""); SubItemType DaggerFlica = new SubItemType(5, Dagger, "flicka", "'Flicka'", ""); // Gem SubItemType GemRed = new SubItemType(1, Gem, "red", "Red Gem", ""); SubItemType GemBlue = new SubItemType(2, Gem, "blue", "Blue Gem", ""); // Rings - SubItemType RingProtection2 = new SubItemType(2, Ring, "protection2", "Ring of Protection +2", ""); // level 11, (x=27,y=16) - SubItemType RingProtection3 = new SubItemType(3, Ring, "protection3", "Ring of Protection +3", ""); // level 4, (x=6, y=24) + SubItemType RingProtection2 = new SubItemType(2, Ring, "protection2", "Protection +2", ""); // level 11, (x=27,y=16) + SubItemType RingProtection3 = new SubItemType(3, Ring, "protection3", "Protection +3", ""); // level 4, (x=6, y=24) // Axe SubItemType AxeDrowCleaver = new SubItemType(3, Axe, "drow_cleaver", "'Drow Cleaver'", "", ""); //------------- // --- Wall --- //------------- // All levels Wall empty = new Wall(0L, WallType.Empty, Arrays.asList(GameSupportType.Eob1)); Wall wall1 = new Wall(1L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); Wall wall2 = new Wall(2L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); Wall emptyMonsterBlock = new Wall(25L, WallType.SquarePart, null, "eob_blocker", "eob_blocker"); // Block monsters to move trough Wall teleport = new Wall(52L, WallType.SquarePart, null, "eob_teleporter", "eob_teleporter"); Wall wallWithDoor = new Wall(58L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); // Side look Wall wallWithNet = new Wall(59L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); // Side look // Sewers levels Wall sewersDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal", "\t:addPullChain()"); Wall sewersDoor = new Wall(8L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal"); Wall sewersDoorOpened = new Wall(12L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal", "\t:setDoorState(\"open\")"); Wall sewersDoorPortcullisWithButton = new Wall(13L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_portcullis", "eob_sewers_door_portcullis", "\t:addPullChain()"); Wall sewersDoorPortcullisThrowableThrough = new Wall(18L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_portcullis_throwable", "eob_portcullis_throwable"); Wall sewersLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_ladder_up", "eob_ladder_up"); // Ladder Wall sewersLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_ladder_down", "eob_ladder_down"); // Ladder Wall sewersEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_ceiling_shaft", "eob_sewers_ceiling_shaft"); Wall sewersEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_ceiling_shaft", "eob_sewers_ceiling_shaft"); Wall sewersPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_pressure_plate", "eob_sewers_pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall sewersWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_alcove", "eob_sewers_alcove"); Wall sewersDoorStacked = new Wall(30L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal_force", "eob_sewers_door_metal_stacked"); Wall sewersDoorPortcullisStacked = new Wall(31L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_portcullis", "eob_sewers_door_portcullis_stacked"); Wall sewersWallWithEyeKeyHole = new Wall(32L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_eye", "eob_sewers_lock_eye"); Wall sewersWallWithJewelKeyHole = new Wall(35L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_gem", "eob_sewers_lock_gem"); Wall sewersWallWithSecretButtonLarge = new Wall(39L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_secret_button", "eob_sewers_secret_button_large"); // Brick Wall sewersWallWithKeyHoleButton = new Wall(41L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_iron", "eob_sewers_lock_iron"); // Key hole -> button Wall sewersWallWithDrainage = new Wall(43L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage"); Wall sewersWallWithDrainageBent1 = new Wall(44L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage_bent"); // Is it the same as 62??? Wall sewersWallWithButtonSmall = new Wall(50L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_secret_button_small", "eob_sewers_secret_button_small"); Wall sewersWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_long", "eob_sewers_wall_text_long"); Wall sewersWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lock_silver", "eob_lock_silver"); Wall sewersWallWithKeyHole2_ = new Wall(54L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lock_golden", "eob_lock_golden"); Wall sewersWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lever", "eob_lever"); Wall sewersWallWithText2_ = new Wall(57L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_long", "eob_sewers_wall_text_rats"); // Read able text (Rats ->) Wall sewersWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_wall_button", "eob_severs_wall_button"); Wall sewersWallWithButtonPressed = new Wall(61L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_switch", "eob_sewers_switch", "\t:setLeverState(\"activated\")"); Wall sewersWallWithDrainageBent2 = new Wall(62L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage_bent"); // Is it the same as 44??? Wall sewersWallWithPipe = new Wall(63L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_pipe", "eob_sewers_wall_pipe"); Wall sewersWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(1, 2, 3), "eob_sewers_illusion_wall_rune", "eob_sewers_illusion_wall_rune"); Wall sewersWallWithRune = new Wall(65L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_rune1", "eob_sewers_wall_text_rune"); // Rune on the wall Wall sewersWallWithDaggerKeyHole = new Wall(66L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_alcove_dagger", "eob_sewers_alcove_dagger"); // Dagger is used as key Wall sewersWallIllusionWithRune = new Wall(67L, WallType.Wall, Wall.levels(1, 2, 3), "eob_sewers_illusion_wall_rune", "eob_sewers_illusion_wall_rune"); Wall sewersCaveIn = new Wall(69L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_cave_in", "eob_sewers_cave_in"); // Ruins levels Wall ruinsDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone", "eob_ruins_door_stone", "\t:addPullChain()"); Wall ruinsDoor = new Wall(8L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone", "eob_ruins_door_stone"); Wall ruinsLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_stairs_up", "eob_ruins_stairs_up"); Wall ruinsLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_stairs_down", "eob_ruins_stairs_down"); Wall ruinsEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_ceiling_shaft", "eob_ruins_ceiling_shaft"); Wall ruinsEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_pit", "eob_ruins_pit"); Wall ruinsPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_pressure_plate", "eob_ruins_pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall ruinsWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_alcove", "eob_ruins_alcove"); Wall ruinsDoorStacked = new Wall(30L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone_stacked", "eob_ruins_door_stone_stacked"); Wall ruinsWallWithStatueLever = new Wall(32L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_statue_lever", "eob_ruins_statue_lever"); Wall ruinsWallWithSmallStatue = new Wall(34L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_small_statue", "eob_ruins_small_statue"); Wall ruinsWallWithChain = new Wall(36L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_chain_lever", "eob_ruins_chain_lever"); // Chain on the wall -> Type of the lever Wall ruinsWallWithFiringMechanism = new Wall(38L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_dart_firing_pad", "eob_ruins_dart_firing_pad"); // Level 6: Darts Wall ruinsWallWithSecretButtonTiny = new Wall(39L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_secret_button_tiny", "eob_ruins_secret_button_tiny"); Wall ruinsNet = new Wall(40L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_net", "eob_ruins_net"); Wall ruinsNetTorn = new Wall(41L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_net", "eob_ruins_net_torn", "\t:setDoorState(\"open\")"); // NetTorn (4 level) Wall ruinsWallPortalLevelNecklace = new Wall(43L, WallType.SolidPart, Wall.levels(5), "eob_ruins_portal_necklace", "eob_ruins_portal_necklace"); // Level 5 - Stone Necklace Wall ruinsWallPortalLevelScepter = new Wall(45L, WallType.SolidPart, Wall.levels(6), "eob_ruins_portal_scepter", "eob_ruins_portal_scepter"); // Level 6 - Stone Scepter Wall ruinsWallPortalLevelAmulet = new Wall(46L, WallType.SolidPart, Wall.levels(4), "eob_ruins_portal_amulet", "eob_ruins_portal_amulet"); // Level 4 - Stone Amulet Wall ruinsWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_wall_text", "eob_ruins_wall_text"); Wall ruinsWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_statue_lock", "eob_ruins_statue_lock"); Wall ruinsWallWithKeyHole2 = new Wall(54L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_ornate_lock", "eob_ruins_ornate_lock"); Wall ruinsWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_lever", "eob_ruins_lever"); Wall ruinsWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_wall_button", "eob_ruins_wall_button"); Wall ruinsWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall", "eob_ruins_illusion_wall"); Wall ruinsWallIllusionWithStatue = new Wall(66L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall_statue", "eob_ruins_illusion_wall_statue"); Wall ruinsWallIllusionWithRune = new Wall(67L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall_rune", "eob_ruins_illusion_wall_rune"); // Drow levels Wall drowDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(7, 8, 9), "prison_door_metal", "door", "\t:addPullChain()"); Wall drowDoor = new Wall(8L, WallType.DoorPart, Wall.levels(7, 8, 9), "prison_door_metal", "door"); Wall drowLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_stairs_up", "stairs_up"); Wall drowLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_stairs_down", "stairs_down"); Wall drowEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_ceiling_shaft", "ceiling_shaft"); Wall drowEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_pit", "pit"); Wall drowPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall drowWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_alcove", "wall_alcove"); Wall drowWallWithFiringMechanism2 = new Wall(32L, WallType.SolidPart, Wall.levels(7, 8, 9), "daemon_head", "firing_mechanism"); // Level 7: Fireball Wall drowWallWithText2 = new Wall(33L, WallType.SolidPart, Wall.levels(7, 8, 9), "dungeon_wall_text_long", "wall_text"); // It is written, the key lies on the other side. Wall drowWallWithGemKeyHole = new Wall(36L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock_prison", "wall_gem_lock"); // Gem is used as key Wall drowWallWithSecretButtonTiny = new Wall(39L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_secret_button_small", "secret_button_tiny"); Wall drowWallPortalLevelCross = new Wall(40L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Cross Wall drowWallPortalLevelNecklace = new Wall(41L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Necklace Wall drowWallPortalLevelDaggerL7 = new Wall(43L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Dagger Wall drowWallPortalLevelDaggerL9 = new Wall(43L, WallType.SolidPart, Wall.levels(9), "temple_glass_wall_2", "portal"); // Level 9 - missing Stone Dagger Wall drowWallPortalLevelAmulet = new Wall(44L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Amulet Wall drowWallPortalLevelScepter = new Wall(45L, WallType.SolidPart, Wall.levels(8), "temple_glass_wall_2", "portal"); // Level 8 - missing Stone Scepter Wall drowWallPortalLevelGem = new Wall(46L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Gem Wall drowWallThrowable = new Wall(47L, WallType.Wall, Wall.levels(7, 8, 9), "prison_secret_door", "wall_throwable"); Wall drowWallWithFiringMechanismFireball = new Wall(48L, WallType.SolidPart, Wall.levels(7), "daemon_head", "firing_mechanism"); // Level 7: Fireball Wall drowWallWithFiringMechanismDartsL9 = new Wall(48L, WallType.SolidPart, Wall.levels(9), "daemon_head", "firing_mechanism"); // Level 9: Darts Wall drowWallWithFiringMechanismDartsL8 = new Wall(49L, WallType.SolidPart, Wall.levels(8), "daemon_head", "firing_mechanism"); // Level 7: Darts Wall drowWallWithFiringMechanismMagicMissile = new Wall(49L, WallType.SolidPart, Wall.levels(9), "daemon_head", "firing_mechanism2"); // Level 9: MagicMissile Wall drowWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_wall_text_long", "wall_text"); Wall drowWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock", "wall_spider_lock"); Wall drowWallWithKeyHole2 = new Wall(54L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock_ornate", "wall_lock_ornate"); Wall drowWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(7, 8, 9), "lever", "wall_lever"); Wall drowWallIllusionWithSpider = new Wall(57L, WallType.Wall, Wall.levels(7, 8, 9), "temple_secret_door", "wall_illusion_with_spider"); Wall drowWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(7, 8, 9), "wall_button", "wall_button"); Wall drowWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(7, 8, 9), "prison_secret_door", "wall_illusion"); // Hive levels Wall hiveDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(10, 11), "dungeon_door_metal", "door", "\t:addPullChain()"); Wall hiveDoor = new Wall(8L, WallType.DoorPart, Wall.levels(10, 11), "prison_door_metal", "door"); Wall hiveLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_stairs_up", "stairs_up"); Wall hiveLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_stairs_down", "stairs_down"); Wall hiveEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_ceiling_shaft", "ceiling_shaft"); Wall hiveEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_pit", "pit"); Wall hivePressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall hiveWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_alcove", "wall_alcove"); Wall hiveWallWithSecretButtonSmall = new Wall(31L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_secret_button_small", "secret_button_small"); Wall hiveWallWithSecretButtonTiny = new Wall(33L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_secret_button_small", "secret_button_tiny"); Wall hiveWallPortalLevelCross = new Wall(36L, WallType.SolidPart, Wall.levels(11), "temple_glass_wall_2", "portal"); // Level 11 - missing Stone Cross Wall hiveWallPortalLevelOrb = new Wall(37L, WallType.SolidPart, Wall.levels(11), "temple_glass_wall_2", "portal"); // Level 11 - missing Stone Orb Wall hiveWallPortalLevelScepter = new Wall(38L, WallType.SolidPart, Wall.levels(10), "temple_glass_wall_2", "portal"); // Level 10 - missing Stone Scepter Wall hiveWallPortalLevelRing = new Wall(39L, WallType.SolidPart, Wall.levels(10), "temple_glass_wall_2", "portal"); // Level 10 - missing Stone Ring Wall hiveWallWithText = new Wall(41L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_wall_text_long", "wall_text"); Wall hiveWallWithKeyHole = new Wall(42L, WallType.SolidPart, Wall.levels(10, 11), "lock", "wall_lock"); Wall hiveWallWithLeverUp = new Wall(43L, WallType.SolidPart, Wall.levels(10, 11), "lever", "wall_lever"); Wall hiveWallWithLeverDown = new Wall(44L, WallType.SolidPart, Wall.levels(10, 11), "lever", "wall_lever", "\t:setLeverState(\"activated\")"); Wall hiveWallWithButton = new Wall(45L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_button"); Wall hiveWallWithSwitch = new Wall(46L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_switch"); // Can be pressed or released Wall hiveWallWithStar = new Wall(48L, WallType.SolidPart, Wall.levels(10, 11), "daemon_head", "wall_star"); // Level 11: Celestial star Wall hiveWallWithRift = new Wall(49L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_ivy_1", "hive_wall_rift"); Wall hiveWallWithManacles = new Wall(50L, WallType.SolidPart, Wall.levels(10, 11), "prison_bench", "prison_manacles"); Wall hiveWallWithButton2 = new Wall(60L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_button"); // Sanctum levels Wall sanctumDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(12), "temple_door_metal", "door", "\t:addPullChain()"); Wall sanctumDoor = new Wall(8L, WallType.DoorPart, Wall.levels(12), "temple_door_metal", "door"); Wall sanctumPedestal = new Wall(22L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal"); Wall sanctumPedestalWithEye = new Wall(26L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal_eye"); Wall sanctumPedestalWithEyeDetector = new Wall(27L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal_eye"); Wall sanctumPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(12), "temple_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall sanctumWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(12), "temple_alcove", "wall_alcove"); Wall sanctumWallWithFiringMechanism = new Wall(30L, WallType.SolidPart, Wall.levels(12), "daemon_head", "firing_mechanism"); // Level 12: Fireball Wall sanctumWallWithSecretButtonSmall = new Wall(31L, WallType.SolidPart, Wall.levels(12), "temple_secret_button_small", "secret_button_small"); Wall sanctumWallWithSecretButtonTiny = new Wall(33L, WallType.SolidPart, Wall.levels(12), "temple_secret_button_small", "secret_button_tiny"); Wall sanctumWallPortalLevelOrb = new Wall(37L, WallType.SolidPart, Wall.levels(12), "temple_glass_wall_2", "portal"); // Level 12 - missing Stone Orb Wall sanctumWallWithLamp = new Wall(38L, WallType.SolidPart, Wall.levels(12), "torch_holder", "wall_lamp"); Wall sanctumSpikeTrap = new Wall(39L, WallType.SquarePart, Wall.levels(12), "temple_floor_drainage", "spike_trap"); Wall sanctumWallWithText = new Wall(41L, WallType.SolidPart, Wall.levels(12), "temple_wall_text_long", "wall_text"); Wall sanctumWallWithKeyHole = new Wall(42L, WallType.SolidPart, Wall.levels(12), "lock", "wall_skull_lock"); Wall sanctumWallWithLampSmoke = new Wall(43L, WallType.SolidPart, Wall.levels(12), "torch_holder", "wall_lamp_smoke"); Wall sanctumWallWithButton = new Wall(45L, WallType.SolidPart, Wall.levels(12), "wall_button", "wall_button"); Wall sanctumWallWithButton2 = new Wall(60L, WallType.SolidPart, Wall.levels(12), "wall_button", "wall_button"); } }
true
true
public static void init() { //-------------- // --- Items --- //-------------- ItemType Axe = new ItemType(0x00, "axe", "Axe", "hand_axe"); ItemType Longsword = new ItemType(0x01, "long_sword", "Long Sword", "long_sword"); ItemType Dart = new ItemType(0x04, "dart", "Dart", "shuriken"); ItemType Dagger = new ItemType(0x05, "dagger", "Dagger", "dagger"); ItemType DwarvenPotion = new ItemType(0x06, "dwarven_potion", "Dwarven potion", "potion_healing"); ItemType Bow = new ItemType(0x07, "bow", "Bow", "short_bow"); ItemType Spear = new ItemType(0x09, "spear", "Spear", "legionary_spear"); ItemType Mace = new ItemType(0x0B, "mace", "Mace", "knoffer"); ItemType Sling = new ItemType(0x0E, "sling", "Sling", "sling"); ItemType Dart2 = new ItemType(0x0F, "dart", "Dart", "shuriken"); ItemType Arrow = new ItemType(0x10, "arrow", "Arrow", "arrow"); ItemType Rock = new ItemType(0x12, "rock", "Rock", "rock"); ItemType Chainmail = new ItemType(0x14, "chainmail", "Chainmail", "ring_mail"); ItemType DwarvenHelmet = new ItemType(0x15, "dwarven_helmet", "Dwarven Helmet", "full_helmet"); ItemType LeatherArmor = new ItemType(0x16, "leather_armor", "Leather Armor", "leather_brigandine"); ItemType Shield = new ItemType(0x1B, "shield", "Shield", "round_shield"); ItemType LockPicks = new ItemType(0x1C, "lock_picks", "Lock picks", "machine_part_south"); ItemType Rations = new ItemType(0x1F, "rations", "Rations", "pitroot_bread"); ItemType LeatherBoots = new ItemType(0x20, "leather_boots", "Leather boots", "leather_boots"); ItemType Bones = new ItemType(0x21, "bones", "Bones", "remains_of_toorum"); ItemType MageScroll = new ItemType(0x22, "mage_scroll", "Mage scroll", "scroll"); ItemType ClericScroll = new ItemType(0x23, "cleric_scroll", "Cleric scroll", "scroll"); ItemType TextScroll = new ItemType(0x24, "scroll", "Text scroll", "scroll"); ItemType Stone = new ItemType(0x25, "stone", "Stone", "rock"); ItemType Key = new ItemType(0x26, "key", "Key", "brass_key"); // Different keys ItemType Potion = new ItemType(0x27, "potion", "Potion", "potion_healing"); ItemType Gem = new ItemType(0x28, "gem", "Gem", "blue_gem"); // Gems of different colors (red and blue) ItemType Robe = new ItemType(0x29, "robe", "Robe", "peasant_tunic"); ItemType MedallionOfAdornment = new ItemType(0x2c, "medallion_of_adornment", "Medallion of Adornment", "spirit_mirror_pendant"); ItemType Ring = new ItemType(0x2a, "ring", "Ring", "hardstone_bracelet"); // There are no rings in Grimrock, we need to replace them with bracelets ItemType Ring2 = new ItemType(0x2f, "ring2", "Ring", "bracelet_tirin"); // This one has no power (found in lv 4, x=11,y=29) ItemType Wand = new ItemType(0x30, "wand", "Wand", "whitewood_wand"); //----------------- // --- SubItems --- //----------------- // Text scroll SubItemType TextScroll1 = new SubItemType(47, TextScroll, "text1", "", "Unknown text"); SubItemType TextScroll2 = new SubItemType(48, TextScroll, "text2", "", "Unknown text"); SubItemType TextScroll3 = new SubItemType(49, TextScroll, "text3", "", "Unknown text"); SubItemType TextScroll4 = new SubItemType(50, TextScroll, "text4", "", "Unknown text"); // Cleric scroll SubItemType ClericScrollBless = new SubItemType(1, ClericScroll, "bless", "Bless", "1L"); SubItemType ClericScrollCureLightWnds = new SubItemType(2, ClericScroll, "cure_light_wnds", "Cure Light Wounds", "1L"); SubItemType ClericScrollCauseLightWnds = new SubItemType(3, ClericScroll, "cause_light_wnds", "Cause Light Wounds", "1L"); SubItemType ClericScrollDetectMagic = new SubItemType(4, ClericScroll, "detect_magic", "Detect Magic", "1L"); SubItemType ClericScrollProtectEvil = new SubItemType(5, ClericScroll, "protect_evil", "Protect-Evil", "1L"); SubItemType ClericScrollAid = new SubItemType(6, ClericScroll, "aid", "Aid", "2L"); SubItemType ClericScrollFlameBlade = new SubItemType(7, ClericScroll, "flame_blade", "Flame Blade", "2L"); SubItemType ClericScrollHoldPerson = new SubItemType(8, ClericScroll, "hold_person", "Hold Person", "2L"); SubItemType ClericScrollSlowPoison = new SubItemType(9, ClericScroll, "slow_poison", "Slow Poison", "2L"); SubItemType ClericScrollCreateFood = new SubItemType(10, ClericScroll, "create_food", "Create Food", "3L"); SubItemType ClericScrollDispelMagic = new SubItemType(11, ClericScroll, "dispel_magic", "Dispel Magic", "3L"); SubItemType ClericScrollMagicalVestment = new SubItemType(12, ClericScroll, "magical_vestment", "Magical Vestment", "3L"); SubItemType ClericScrollPrayer = new SubItemType(13, ClericScroll, "prayer", "Prayer", "3L"); SubItemType ClericScrollRemoveParalysis = new SubItemType(14, ClericScroll, "remove_paralysis", "Remove Paralysis", "3L"); SubItemType ClericScrollCureSeriousWnds = new SubItemType(15, ClericScroll, "cure_serious_wnds", "Cure Serious Wounds", "4L"); SubItemType ClericScrollCauseSeriousWnds = new SubItemType(16, ClericScroll, "cause_serious_wnds", "Cause Serious Wounds", "4L"); SubItemType ClericScrollNeutralPoison = new SubItemType(17, ClericScroll, "neutral_poison", "Neutral-Poison", "4L"); SubItemType ClericScrollProtectEvil10 = new SubItemType(18, ClericScroll, "protect_evil10", "Protect-Evil 10'", "4L"); SubItemType ClericScrollCureCriticalWnds = new SubItemType(20, ClericScroll, "cure_critical_wnds", "Cure Critical Wounds", "5L"); SubItemType ClericScrollCauseCriticalWnds = new SubItemType(21, ClericScroll, "cause_critical_wnds", "Cause Critical Wounds", "5L"); SubItemType ClericScrollFlameStrike = new SubItemType(22, ClericScroll, "flame_strike", "Flame Strike", "5L"); SubItemType ClericScrollRaiseDead = new SubItemType(23, ClericScroll, "raise_dead", "Raise Dead", "5L"); // Mage scroll SubItemType MageScrollArmor = new SubItemType(1, MageScroll, "armor", "Armor", "1L"); SubItemType MageScrollBurningHands = new SubItemType(2, MageScroll, "burning_hands", "Burning Hands", "1L"); SubItemType MageScrollDetectMagic = new SubItemType(3, MageScroll, "detect_magic", "Detect Magic", "1L"); SubItemType MageScrollMagicMissile = new SubItemType(4, MageScroll, "magic_missile", "Magic Missile", "1L"); SubItemType MageScrollReadMagic = new SubItemType(5, MageScroll, "read_magic", "Read Magic", "1L"); SubItemType MageScrollShield = new SubItemType(6, MageScroll, "shield", "Shield", "1L"); SubItemType MageScrollShockingGrasp = new SubItemType(7, MageScroll, "shocking_grasp", "Shocking Grasp", "1L"); SubItemType MageScrollInvisibility = new SubItemType(8, MageScroll, "invisibility", "Invisibility", "2L"); SubItemType MageScrollKnock = new SubItemType(9, MageScroll, "knock", "Knock", "2L"); SubItemType MageScrollMsAcidArrow = new SubItemType(10, MageScroll, "ms_acid_arrow", "M's Acid Arrow", "2L"); SubItemType MageScrollStinkingCloud = new SubItemType(11, MageScroll, "stinking_cloud", "Stinking Cloud", "2L"); SubItemType MageScrollDispelMagic = new SubItemType(12, MageScroll, "dispel_magic", "Dispel Magic", "3L"); SubItemType MageScrollFireball = new SubItemType(13, MageScroll, "fireball", "Fireball", "3L"); SubItemType MageScrollFlameArrow = new SubItemType(14, MageScroll, "flame_arrow", "Flame Arrow", "3L"); SubItemType MageScrollHaste = new SubItemType(15, MageScroll, "haste", "Haste", "3L"); SubItemType MageScrollHoldPerson = new SubItemType(16, MageScroll, "hold_person", "Hold Person", "3L"); SubItemType MageScrollInvisibility10 = new SubItemType(17, MageScroll, "invisibility 10'", "Invisibility 10'", "3L"); SubItemType MageScrollLightningBolt = new SubItemType(18, MageScroll, "lightning_bolt", "Lightning Bolt", "3L"); SubItemType MageScrollVampiricTouch = new SubItemType(19, MageScroll, "vampiric_touch", "Vampiric Touch", "3L"); SubItemType MageScrollFear = new SubItemType(20, MageScroll, "fear", "Fear", "4L"); SubItemType MageScrollIceStorm = new SubItemType(21, MageScroll, "ice_storm", "Ice Storm", "4L"); SubItemType MageScrollStoneSkin = new SubItemType(22, MageScroll, "stone_skin", "Stone Skin", "4L"); SubItemType MageScrollCloudKill = new SubItemType(23, MageScroll, "cloud_kill", "Cloud Kill", "5L"); SubItemType MageScrollConeOfCold = new SubItemType(24, MageScroll, "cone_of_cold", "Cone of Cold", "5L"); SubItemType MageScrollHoldMonster = new SubItemType(25, MageScroll, "hold_monster", "Hold Monster", "5L"); // Potion SubItemType PotionGiantStrength = new SubItemType(1, Potion, "giant_strength", "Giant Strength", ""); SubItemType PotionHealing = new SubItemType(2, Potion, "healing", "Healing", ""); SubItemType PotionExtraHealing = new SubItemType(3, Potion, "extra_healing", "Extra Healing", ""); SubItemType PotionPoison = new SubItemType(4, Potion, "poison", "Poison", ""); SubItemType PotionVitality = new SubItemType(5, Potion, "vitality", "Vitality", ""); SubItemType PotionSpeed = new SubItemType(6, Potion, "speed", "Speed", ""); SubItemType PotionInvisibility = new SubItemType(7, Potion, "invisibility", "Invisibility", ""); SubItemType PotionCurePoison = new SubItemType(8, Potion, "cure_poison", "Cure Poison", ""); // Dwarven potion SubItemType DwarvenPotionHealing = new SubItemType(8, Potion, "healing", "Healing", ""); // Key SubItemType KeySilver = new SubItemType(1, Key, "silver", "", ""); SubItemType KeyGold = new SubItemType(2, Key, "gold", "", ""); SubItemType KeyDwarven = new SubItemType(3, Key, "dwarven", "", ""); SubItemType KeySimple = new SubItemType(4, Key, "", "", ""); SubItemType KeySkull = new SubItemType(5, Key, "skull", "", ""); SubItemType KeyDrow = new SubItemType(6, Key, "drow", "", ""); SubItemType KeyJeweled = new SubItemType(7, Key, "jeweled", "", ""); SubItemType KeyRuby = new SubItemType(8, Key, "ruby", "", ""); // Wand SubItemType WandLightningBolt = new SubItemType(1, Wand, "lightning_bolt", "Lightning Bolt", ""); SubItemType WandConeOfCold = new SubItemType(2, Wand, "cone_of_cold", "Cone of Cold", ""); SubItemType WandCureSeriousWounds = new SubItemType(3, Wand, "cure_serious_wnds", "Cure Serious Wounds", ""); SubItemType WandFireball = new SubItemType(4, Wand, "fireball", "Fireball", ""); SubItemType WandSlivias = new SubItemType(5, Wand, "slivias", "Slivias", "Move 1 square away"); SubItemType WandMagicMissile = new SubItemType(6, Wand, "magic_missile", "Magic Missile", ""); SubItemType WandMagicalVestment = new SubItemType(7, Wand, "magical_vestment", "Magical Vestment", ""); // Rations SubItemType RationsBasic = new SubItemType(25, Rations, "", "Rations", ""); SubItemType RationsIron = new SubItemType(50, Rations, "iron", "Iron Rations", ""); // Bones SubItemType HumanBones = new SubItemType(1, Bones, "human", "", ""); SubItemType HalflingBones = new SubItemType(6, Bones, "halfling", "", ""); // Dart SubItemType DartPlus1 = new SubItemType(1, Dart, "plus1", "+1", "", ""); SubItemType DartPlus2 = new SubItemType(2, Dart, "plus2", "+2", "", ""); SubItemType DartPlus3 = new SubItemType(3, Dart, "plus3", "+3", "", ""); SubItemType DartPlus4 = new SubItemType(4, Dart, "plus4", "+4", "", ""); SubItemType DartPlus5 = new SubItemType(5, Dart, "plus5", "+5", "", ""); SubItemType Dart2Plus1 = new SubItemType(1, Dart2, "plus1", "+1", "", ""); SubItemType Dart2Plus2 = new SubItemType(2, Dart2, "plus2", "+2", "", ""); SubItemType Dart2Plus3 = new SubItemType(3, Dart2, "plus3", "+3", "", ""); SubItemType Dart2Plus4 = new SubItemType(4, Dart2, "plus4", "+4", "", ""); SubItemType Dart2Plus5 = new SubItemType(5, Dart2, "plus5", "+5", "", ""); // Stone SubItemType StoneHolySymbol = new SubItemType(1, Stone, "holy_symbol", "", ""); SubItemType StoneNecklace = new SubItemType(2, Stone, "necklace", "", ""); SubItemType StoneOrb = new SubItemType(3, Stone, "orb", "", ""); SubItemType StoneDagger = new SubItemType(4, Stone, "dagger", "", ""); SubItemType StoneMedallion = new SubItemType(5, Stone, "medallion", "", ""); SubItemType StoneScepter = new SubItemType(6, Stone, "scepter", "", ""); // Dagger SubItemType DaggerBackstabber = new SubItemType(3, Dagger, "backstabber", "+3", ""); SubItemType DaggerFlica = new SubItemType(5, Dagger, "flicka", "'Flicka'", ""); // Gem SubItemType GemRed = new SubItemType(1, Gem, "red", "Red Gem", ""); SubItemType GemBlue = new SubItemType(2, Gem, "blue", "Blue Gem", ""); // Rings SubItemType RingProtection2 = new SubItemType(2, Ring, "protection2", "Ring of Protection +2", ""); // level 11, (x=27,y=16) SubItemType RingProtection3 = new SubItemType(3, Ring, "protection3", "Ring of Protection +3", ""); // level 4, (x=6, y=24) // Axe SubItemType AxeDrowCleaver = new SubItemType(3, Axe, "drow_cleaver", "'Drow Cleaver'", "", ""); //------------- // --- Wall --- //------------- // All levels Wall empty = new Wall(0L, WallType.Empty, Arrays.asList(GameSupportType.Eob1)); Wall wall1 = new Wall(1L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); Wall wall2 = new Wall(2L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); Wall emptyMonsterBlock = new Wall(25L, WallType.SquarePart, null, "eob_blocker", "eob_blocker"); // Block monsters to move trough Wall teleport = new Wall(52L, WallType.SquarePart, null, "eob_teleporter", "eob_teleporter"); Wall wallWithDoor = new Wall(58L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); // Side look Wall wallWithNet = new Wall(59L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); // Side look // Sewers levels Wall sewersDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal", "\t:addPullChain()"); Wall sewersDoor = new Wall(8L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal"); Wall sewersDoorOpened = new Wall(12L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal", "\t:setDoorState(\"open\")"); Wall sewersDoorPortcullisWithButton = new Wall(13L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_portcullis", "eob_sewers_door_portcullis", "\t:addPullChain()"); Wall sewersDoorPortcullisThrowableThrough = new Wall(18L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_portcullis_throwable", "eob_portcullis_throwable"); Wall sewersLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_ladder_up", "eob_ladder_up"); // Ladder Wall sewersLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_ladder_down", "eob_ladder_down"); // Ladder Wall sewersEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_ceiling_shaft", "eob_sewers_ceiling_shaft"); Wall sewersEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_ceiling_shaft", "eob_sewers_ceiling_shaft"); Wall sewersPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_pressure_plate", "eob_sewers_pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall sewersWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_alcove", "eob_sewers_alcove"); Wall sewersDoorStacked = new Wall(30L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal_force", "eob_sewers_door_metal_stacked"); Wall sewersDoorPortcullisStacked = new Wall(31L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_portcullis", "eob_sewers_door_portcullis_stacked"); Wall sewersWallWithEyeKeyHole = new Wall(32L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_eye", "eob_sewers_lock_eye"); Wall sewersWallWithJewelKeyHole = new Wall(35L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_gem", "eob_sewers_lock_gem"); Wall sewersWallWithSecretButtonLarge = new Wall(39L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_secret_button", "eob_sewers_secret_button_large"); // Brick Wall sewersWallWithKeyHoleButton = new Wall(41L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_iron", "eob_sewers_lock_iron"); // Key hole -> button Wall sewersWallWithDrainage = new Wall(43L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage"); Wall sewersWallWithDrainageBent1 = new Wall(44L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage_bent"); // Is it the same as 62??? Wall sewersWallWithButtonSmall = new Wall(50L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_secret_button_small", "eob_sewers_secret_button_small"); Wall sewersWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_long", "eob_sewers_wall_text_long"); Wall sewersWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lock_silver", "eob_lock_silver"); Wall sewersWallWithKeyHole2_ = new Wall(54L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lock_golden", "eob_lock_golden"); Wall sewersWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lever", "eob_lever"); Wall sewersWallWithText2_ = new Wall(57L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_long", "eob_sewers_wall_text_rats"); // Read able text (Rats ->) Wall sewersWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_wall_button", "eob_severs_wall_button"); Wall sewersWallWithButtonPressed = new Wall(61L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_switch", "eob_sewers_switch", "\t:setLeverState(\"activated\")"); Wall sewersWallWithDrainageBent2 = new Wall(62L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage_bent"); // Is it the same as 44??? Wall sewersWallWithPipe = new Wall(63L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_pipe", "eob_sewers_wall_pipe"); Wall sewersWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(1, 2, 3), "eob_sewers_illusion_wall_rune", "eob_sewers_illusion_wall_rune"); Wall sewersWallWithRune = new Wall(65L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_rune1", "eob_sewers_wall_text_rune"); // Rune on the wall Wall sewersWallWithDaggerKeyHole = new Wall(66L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_alcove_dagger", "eob_sewers_alcove_dagger"); // Dagger is used as key Wall sewersWallIllusionWithRune = new Wall(67L, WallType.Wall, Wall.levels(1, 2, 3), "eob_sewers_illusion_wall_rune", "eob_sewers_illusion_wall_rune"); Wall sewersCaveIn = new Wall(69L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_cave_in", "eob_sewers_cave_in"); // Ruins levels Wall ruinsDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone", "eob_ruins_door_stone", "\t:addPullChain()"); Wall ruinsDoor = new Wall(8L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone", "eob_ruins_door_stone"); Wall ruinsLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_stairs_up", "eob_ruins_stairs_up"); Wall ruinsLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_stairs_down", "eob_ruins_stairs_down"); Wall ruinsEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_ceiling_shaft", "eob_ruins_ceiling_shaft"); Wall ruinsEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_pit", "eob_ruins_pit"); Wall ruinsPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_pressure_plate", "eob_ruins_pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall ruinsWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_alcove", "eob_ruins_alcove"); Wall ruinsDoorStacked = new Wall(30L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone_stacked", "eob_ruins_door_stone_stacked"); Wall ruinsWallWithStatueLever = new Wall(32L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_statue_lever", "eob_ruins_statue_lever"); Wall ruinsWallWithSmallStatue = new Wall(34L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_small_statue", "eob_ruins_small_statue"); Wall ruinsWallWithChain = new Wall(36L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_chain_lever", "eob_ruins_chain_lever"); // Chain on the wall -> Type of the lever Wall ruinsWallWithFiringMechanism = new Wall(38L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_dart_firing_pad", "eob_ruins_dart_firing_pad"); // Level 6: Darts Wall ruinsWallWithSecretButtonTiny = new Wall(39L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_secret_button_tiny", "eob_ruins_secret_button_tiny"); Wall ruinsNet = new Wall(40L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_net", "eob_ruins_net"); Wall ruinsNetTorn = new Wall(41L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_net", "eob_ruins_net_torn", "\t:setDoorState(\"open\")"); // NetTorn (4 level) Wall ruinsWallPortalLevelNecklace = new Wall(43L, WallType.SolidPart, Wall.levels(5), "eob_ruins_portal_necklace", "eob_ruins_portal_necklace"); // Level 5 - Stone Necklace Wall ruinsWallPortalLevelScepter = new Wall(45L, WallType.SolidPart, Wall.levels(6), "eob_ruins_portal_scepter", "eob_ruins_portal_scepter"); // Level 6 - Stone Scepter Wall ruinsWallPortalLevelAmulet = new Wall(46L, WallType.SolidPart, Wall.levels(4), "eob_ruins_portal_amulet", "eob_ruins_portal_amulet"); // Level 4 - Stone Amulet Wall ruinsWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_wall_text", "eob_ruins_wall_text"); Wall ruinsWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_statue_lock", "eob_ruins_statue_lock"); Wall ruinsWallWithKeyHole2 = new Wall(54L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_ornate_lock", "eob_ruins_ornate_lock"); Wall ruinsWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_lever", "eob_ruins_lever"); Wall ruinsWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_wall_button", "eob_ruins_wall_button"); Wall ruinsWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall", "eob_ruins_illusion_wall"); Wall ruinsWallIllusionWithStatue = new Wall(66L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall_statue", "eob_ruins_illusion_wall_statue"); Wall ruinsWallIllusionWithRune = new Wall(67L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall_rune", "eob_ruins_illusion_wall_rune"); // Drow levels Wall drowDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(7, 8, 9), "prison_door_metal", "door", "\t:addPullChain()"); Wall drowDoor = new Wall(8L, WallType.DoorPart, Wall.levels(7, 8, 9), "prison_door_metal", "door"); Wall drowLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_stairs_up", "stairs_up"); Wall drowLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_stairs_down", "stairs_down"); Wall drowEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_ceiling_shaft", "ceiling_shaft"); Wall drowEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_pit", "pit"); Wall drowPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall drowWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_alcove", "wall_alcove"); Wall drowWallWithFiringMechanism2 = new Wall(32L, WallType.SolidPart, Wall.levels(7, 8, 9), "daemon_head", "firing_mechanism"); // Level 7: Fireball Wall drowWallWithText2 = new Wall(33L, WallType.SolidPart, Wall.levels(7, 8, 9), "dungeon_wall_text_long", "wall_text"); // It is written, the key lies on the other side. Wall drowWallWithGemKeyHole = new Wall(36L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock_prison", "wall_gem_lock"); // Gem is used as key Wall drowWallWithSecretButtonTiny = new Wall(39L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_secret_button_small", "secret_button_tiny"); Wall drowWallPortalLevelCross = new Wall(40L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Cross Wall drowWallPortalLevelNecklace = new Wall(41L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Necklace Wall drowWallPortalLevelDaggerL7 = new Wall(43L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Dagger Wall drowWallPortalLevelDaggerL9 = new Wall(43L, WallType.SolidPart, Wall.levels(9), "temple_glass_wall_2", "portal"); // Level 9 - missing Stone Dagger Wall drowWallPortalLevelAmulet = new Wall(44L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Amulet Wall drowWallPortalLevelScepter = new Wall(45L, WallType.SolidPart, Wall.levels(8), "temple_glass_wall_2", "portal"); // Level 8 - missing Stone Scepter Wall drowWallPortalLevelGem = new Wall(46L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Gem Wall drowWallThrowable = new Wall(47L, WallType.Wall, Wall.levels(7, 8, 9), "prison_secret_door", "wall_throwable"); Wall drowWallWithFiringMechanismFireball = new Wall(48L, WallType.SolidPart, Wall.levels(7), "daemon_head", "firing_mechanism"); // Level 7: Fireball Wall drowWallWithFiringMechanismDartsL9 = new Wall(48L, WallType.SolidPart, Wall.levels(9), "daemon_head", "firing_mechanism"); // Level 9: Darts Wall drowWallWithFiringMechanismDartsL8 = new Wall(49L, WallType.SolidPart, Wall.levels(8), "daemon_head", "firing_mechanism"); // Level 7: Darts Wall drowWallWithFiringMechanismMagicMissile = new Wall(49L, WallType.SolidPart, Wall.levels(9), "daemon_head", "firing_mechanism2"); // Level 9: MagicMissile Wall drowWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_wall_text_long", "wall_text"); Wall drowWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock", "wall_spider_lock"); Wall drowWallWithKeyHole2 = new Wall(54L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock_ornate", "wall_lock_ornate"); Wall drowWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(7, 8, 9), "lever", "wall_lever"); Wall drowWallIllusionWithSpider = new Wall(57L, WallType.Wall, Wall.levels(7, 8, 9), "temple_secret_door", "wall_illusion_with_spider"); Wall drowWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(7, 8, 9), "wall_button", "wall_button"); Wall drowWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(7, 8, 9), "prison_secret_door", "wall_illusion"); // Hive levels Wall hiveDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(10, 11), "dungeon_door_metal", "door", "\t:addPullChain()"); Wall hiveDoor = new Wall(8L, WallType.DoorPart, Wall.levels(10, 11), "prison_door_metal", "door"); Wall hiveLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_stairs_up", "stairs_up"); Wall hiveLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_stairs_down", "stairs_down"); Wall hiveEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_ceiling_shaft", "ceiling_shaft"); Wall hiveEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_pit", "pit"); Wall hivePressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall hiveWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_alcove", "wall_alcove"); Wall hiveWallWithSecretButtonSmall = new Wall(31L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_secret_button_small", "secret_button_small"); Wall hiveWallWithSecretButtonTiny = new Wall(33L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_secret_button_small", "secret_button_tiny"); Wall hiveWallPortalLevelCross = new Wall(36L, WallType.SolidPart, Wall.levels(11), "temple_glass_wall_2", "portal"); // Level 11 - missing Stone Cross Wall hiveWallPortalLevelOrb = new Wall(37L, WallType.SolidPart, Wall.levels(11), "temple_glass_wall_2", "portal"); // Level 11 - missing Stone Orb Wall hiveWallPortalLevelScepter = new Wall(38L, WallType.SolidPart, Wall.levels(10), "temple_glass_wall_2", "portal"); // Level 10 - missing Stone Scepter Wall hiveWallPortalLevelRing = new Wall(39L, WallType.SolidPart, Wall.levels(10), "temple_glass_wall_2", "portal"); // Level 10 - missing Stone Ring Wall hiveWallWithText = new Wall(41L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_wall_text_long", "wall_text"); Wall hiveWallWithKeyHole = new Wall(42L, WallType.SolidPart, Wall.levels(10, 11), "lock", "wall_lock"); Wall hiveWallWithLeverUp = new Wall(43L, WallType.SolidPart, Wall.levels(10, 11), "lever", "wall_lever"); Wall hiveWallWithLeverDown = new Wall(44L, WallType.SolidPart, Wall.levels(10, 11), "lever", "wall_lever", "\t:setLeverState(\"activated\")"); Wall hiveWallWithButton = new Wall(45L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_button"); Wall hiveWallWithSwitch = new Wall(46L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_switch"); // Can be pressed or released Wall hiveWallWithStar = new Wall(48L, WallType.SolidPart, Wall.levels(10, 11), "daemon_head", "wall_star"); // Level 11: Celestial star Wall hiveWallWithRift = new Wall(49L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_ivy_1", "hive_wall_rift"); Wall hiveWallWithManacles = new Wall(50L, WallType.SolidPart, Wall.levels(10, 11), "prison_bench", "prison_manacles"); Wall hiveWallWithButton2 = new Wall(60L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_button"); // Sanctum levels Wall sanctumDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(12), "temple_door_metal", "door", "\t:addPullChain()"); Wall sanctumDoor = new Wall(8L, WallType.DoorPart, Wall.levels(12), "temple_door_metal", "door"); Wall sanctumPedestal = new Wall(22L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal"); Wall sanctumPedestalWithEye = new Wall(26L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal_eye"); Wall sanctumPedestalWithEyeDetector = new Wall(27L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal_eye"); Wall sanctumPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(12), "temple_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall sanctumWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(12), "temple_alcove", "wall_alcove"); Wall sanctumWallWithFiringMechanism = new Wall(30L, WallType.SolidPart, Wall.levels(12), "daemon_head", "firing_mechanism"); // Level 12: Fireball Wall sanctumWallWithSecretButtonSmall = new Wall(31L, WallType.SolidPart, Wall.levels(12), "temple_secret_button_small", "secret_button_small"); Wall sanctumWallWithSecretButtonTiny = new Wall(33L, WallType.SolidPart, Wall.levels(12), "temple_secret_button_small", "secret_button_tiny"); Wall sanctumWallPortalLevelOrb = new Wall(37L, WallType.SolidPart, Wall.levels(12), "temple_glass_wall_2", "portal"); // Level 12 - missing Stone Orb Wall sanctumWallWithLamp = new Wall(38L, WallType.SolidPart, Wall.levels(12), "torch_holder", "wall_lamp"); Wall sanctumSpikeTrap = new Wall(39L, WallType.SquarePart, Wall.levels(12), "temple_floor_drainage", "spike_trap"); Wall sanctumWallWithText = new Wall(41L, WallType.SolidPart, Wall.levels(12), "temple_wall_text_long", "wall_text"); Wall sanctumWallWithKeyHole = new Wall(42L, WallType.SolidPart, Wall.levels(12), "lock", "wall_skull_lock"); Wall sanctumWallWithLampSmoke = new Wall(43L, WallType.SolidPart, Wall.levels(12), "torch_holder", "wall_lamp_smoke"); Wall sanctumWallWithButton = new Wall(45L, WallType.SolidPart, Wall.levels(12), "wall_button", "wall_button"); Wall sanctumWallWithButton2 = new Wall(60L, WallType.SolidPart, Wall.levels(12), "wall_button", "wall_button"); }
public static void init() { //-------------- // --- Items --- //-------------- ItemType Axe = new ItemType(0x00, "axe", "Axe", "hand_axe"); ItemType Longsword = new ItemType(0x01, "long_sword", "Long Sword", "long_sword"); ItemType Dart = new ItemType(0x04, "dart", "Dart", "shuriken"); ItemType Dagger = new ItemType(0x05, "dagger", "Dagger", "dagger"); ItemType DwarvenPotion = new ItemType(0x06, "dwarven_potion", "Dwarven potion", "potion_healing"); ItemType Bow = new ItemType(0x07, "bow", "Bow", "short_bow"); ItemType Spear = new ItemType(0x09, "spear", "Spear", "legionary_spear"); ItemType Mace = new ItemType(0x0B, "mace", "Mace", "knoffer"); ItemType Sling = new ItemType(0x0E, "sling", "Sling", "sling"); ItemType Dart2 = new ItemType(0x0F, "dart", "Dart", "shuriken"); ItemType Arrow = new ItemType(0x10, "arrow", "Arrow", "arrow"); ItemType Rock = new ItemType(0x12, "rock", "Rock", "rock"); ItemType Chainmail = new ItemType(0x14, "chainmail", "Chainmail", "ring_mail"); ItemType DwarvenHelmet = new ItemType(0x15, "dwarven_helmet", "Dwarven Helmet", "full_helmet"); ItemType LeatherArmor = new ItemType(0x16, "leather_armor", "Leather Armor", "leather_brigandine"); ItemType Shield = new ItemType(0x1B, "shield", "Shield", "round_shield"); ItemType LockPicks = new ItemType(0x1C, "lock_picks", "Lock picks", "machine_part_south"); ItemType Rations = new ItemType(0x1F, "rations", "Rations", "pitroot_bread"); ItemType LeatherBoots = new ItemType(0x20, "leather_boots", "Leather boots", "leather_boots"); ItemType Bones = new ItemType(0x21, "bones", "Bones", "remains_of_toorum"); ItemType MageScroll = new ItemType(0x22, "mage_scroll", "Mage scroll", "scroll"); ItemType ClericScroll = new ItemType(0x23, "cleric_scroll", "Cleric scroll", "scroll"); ItemType TextScroll = new ItemType(0x24, "scroll", "Text scroll", "scroll"); ItemType Stone = new ItemType(0x25, "stone", "Stone", "rock"); ItemType Key = new ItemType(0x26, "key", "Key", "brass_key"); // Different keys ItemType Potion = new ItemType(0x27, "potion", "Potion", "potion_healing"); ItemType Gem = new ItemType(0x28, "gem", "Gem", "blue_gem"); // Gems of different colors (red and blue) ItemType Robe = new ItemType(0x29, "robe", "Robe", "peasant_tunic"); ItemType MedallionOfAdornment = new ItemType(0x2c, "medallion_of_adornment", "Medallion of Adornment", "spirit_mirror_pendant"); ItemType Ring = new ItemType(0x2a, "ring", "Ring", "hardstone_bracelet"); // There are no rings in Grimrock, we need to replace them with bracelets ItemType Ring2 = new ItemType(0x2f, "ring2", "Ring", "bracelet_tirin"); // This one has no power (found in lv 4, x=11,y=29) ItemType Wand = new ItemType(0x30, "wand", "Wand", "whitewood_wand"); //----------------- // --- SubItems --- //----------------- // Text scroll SubItemType TextScroll1 = new SubItemType(47, TextScroll, "text1", "", "Unknown text"); SubItemType TextScroll2 = new SubItemType(48, TextScroll, "text2", "", "Unknown text"); SubItemType TextScroll3 = new SubItemType(49, TextScroll, "text3", "", "Unknown text"); SubItemType TextScroll4 = new SubItemType(50, TextScroll, "text4", "", "Unknown text"); // Cleric scroll SubItemType ClericScrollBless = new SubItemType(1, ClericScroll, "bless", "Bless", "1L"); SubItemType ClericScrollCureLightWnds = new SubItemType(2, ClericScroll, "cure_light_wnds", "Cure Light Wounds", "1L"); SubItemType ClericScrollCauseLightWnds = new SubItemType(3, ClericScroll, "cause_light_wnds", "Cause Light Wounds", "1L"); SubItemType ClericScrollDetectMagic = new SubItemType(4, ClericScroll, "detect_magic", "Detect Magic", "1L"); SubItemType ClericScrollProtectEvil = new SubItemType(5, ClericScroll, "protect_evil", "Protect-Evil", "1L"); SubItemType ClericScrollAid = new SubItemType(6, ClericScroll, "aid", "Aid", "2L"); SubItemType ClericScrollFlameBlade = new SubItemType(7, ClericScroll, "flame_blade", "Flame Blade", "2L"); SubItemType ClericScrollHoldPerson = new SubItemType(8, ClericScroll, "hold_person", "Hold Person", "2L"); SubItemType ClericScrollSlowPoison = new SubItemType(9, ClericScroll, "slow_poison", "Slow Poison", "2L"); SubItemType ClericScrollCreateFood = new SubItemType(10, ClericScroll, "create_food", "Create Food", "3L"); SubItemType ClericScrollDispelMagic = new SubItemType(11, ClericScroll, "dispel_magic", "Dispel Magic", "3L"); SubItemType ClericScrollMagicalVestment = new SubItemType(12, ClericScroll, "magical_vestment", "Magical Vestment", "3L"); SubItemType ClericScrollPrayer = new SubItemType(13, ClericScroll, "prayer", "Prayer", "3L"); SubItemType ClericScrollRemoveParalysis = new SubItemType(14, ClericScroll, "remove_paralysis", "Remove Paralysis", "3L"); SubItemType ClericScrollCureSeriousWnds = new SubItemType(15, ClericScroll, "cure_serious_wnds", "Cure Serious Wounds", "4L"); SubItemType ClericScrollCauseSeriousWnds = new SubItemType(16, ClericScroll, "cause_serious_wnds", "Cause Serious Wounds", "4L"); SubItemType ClericScrollNeutralPoison = new SubItemType(17, ClericScroll, "neutral_poison", "Neutral-Poison", "4L"); SubItemType ClericScrollProtectEvil10 = new SubItemType(18, ClericScroll, "protect_evil10", "Protect-Evil 10'", "4L"); SubItemType ClericScrollCureCriticalWnds = new SubItemType(20, ClericScroll, "cure_critical_wnds", "Cure Critical Wounds", "5L"); SubItemType ClericScrollCauseCriticalWnds = new SubItemType(21, ClericScroll, "cause_critical_wnds", "Cause Critical Wounds", "5L"); SubItemType ClericScrollFlameStrike = new SubItemType(22, ClericScroll, "flame_strike", "Flame Strike", "5L"); SubItemType ClericScrollRaiseDead = new SubItemType(23, ClericScroll, "raise_dead", "Raise Dead", "5L"); // Mage scroll SubItemType MageScrollArmor = new SubItemType(1, MageScroll, "armor", "Armor", "1L"); SubItemType MageScrollBurningHands = new SubItemType(2, MageScroll, "burning_hands", "Burning Hands", "1L"); SubItemType MageScrollDetectMagic = new SubItemType(3, MageScroll, "detect_magic", "Detect Magic", "1L"); SubItemType MageScrollMagicMissile = new SubItemType(4, MageScroll, "magic_missile", "Magic Missile", "1L"); SubItemType MageScrollReadMagic = new SubItemType(5, MageScroll, "read_magic", "Read Magic", "1L"); SubItemType MageScrollShield = new SubItemType(6, MageScroll, "shield", "Shield", "1L"); SubItemType MageScrollShockingGrasp = new SubItemType(7, MageScroll, "shocking_grasp", "Shocking Grasp", "1L"); SubItemType MageScrollInvisibility = new SubItemType(8, MageScroll, "invisibility", "Invisibility", "2L"); SubItemType MageScrollKnock = new SubItemType(9, MageScroll, "knock", "Knock", "2L"); SubItemType MageScrollMsAcidArrow = new SubItemType(10, MageScroll, "ms_acid_arrow", "M's Acid Arrow", "2L"); SubItemType MageScrollStinkingCloud = new SubItemType(11, MageScroll, "stinking_cloud", "Stinking Cloud", "2L"); SubItemType MageScrollDispelMagic = new SubItemType(12, MageScroll, "dispel_magic", "Dispel Magic", "3L"); SubItemType MageScrollFireball = new SubItemType(13, MageScroll, "fireball", "Fireball", "3L"); SubItemType MageScrollFlameArrow = new SubItemType(14, MageScroll, "flame_arrow", "Flame Arrow", "3L"); SubItemType MageScrollHaste = new SubItemType(15, MageScroll, "haste", "Haste", "3L"); SubItemType MageScrollHoldPerson = new SubItemType(16, MageScroll, "hold_person", "Hold Person", "3L"); SubItemType MageScrollInvisibility10 = new SubItemType(17, MageScroll, "invisibility 10'", "Invisibility 10'", "3L"); SubItemType MageScrollLightningBolt = new SubItemType(18, MageScroll, "lightning_bolt", "Lightning Bolt", "3L"); SubItemType MageScrollVampiricTouch = new SubItemType(19, MageScroll, "vampiric_touch", "Vampiric Touch", "3L"); SubItemType MageScrollFear = new SubItemType(20, MageScroll, "fear", "Fear", "4L"); SubItemType MageScrollIceStorm = new SubItemType(21, MageScroll, "ice_storm", "Ice Storm", "4L"); SubItemType MageScrollStoneSkin = new SubItemType(22, MageScroll, "stone_skin", "Stone Skin", "4L"); SubItemType MageScrollCloudKill = new SubItemType(23, MageScroll, "cloud_kill", "Cloud Kill", "5L"); SubItemType MageScrollConeOfCold = new SubItemType(24, MageScroll, "cone_of_cold", "Cone of Cold", "5L"); SubItemType MageScrollHoldMonster = new SubItemType(25, MageScroll, "hold_monster", "Hold Monster", "5L"); // Potion SubItemType PotionGiantStrength = new SubItemType(1, Potion, "giant_strength", "Giant Strength", ""); SubItemType PotionHealing = new SubItemType(2, Potion, "healing", "Healing", ""); SubItemType PotionExtraHealing = new SubItemType(3, Potion, "extra_healing", "Extra Healing", ""); SubItemType PotionPoison = new SubItemType(4, Potion, "poison", "Poison", ""); SubItemType PotionVitality = new SubItemType(5, Potion, "vitality", "Vitality", ""); SubItemType PotionSpeed = new SubItemType(6, Potion, "speed", "Speed", ""); SubItemType PotionInvisibility = new SubItemType(7, Potion, "invisibility", "Invisibility", ""); SubItemType PotionCurePoison = new SubItemType(8, Potion, "cure_poison", "Cure Poison", ""); // Dwarven potion SubItemType DwarvenPotionHealing = new SubItemType(8, Potion, "healing", "Healing", ""); // Key SubItemType KeySilver = new SubItemType(1, Key, "silver", "", ""); SubItemType KeyGold = new SubItemType(2, Key, "gold", "", ""); SubItemType KeyDwarven = new SubItemType(3, Key, "dwarven", "", ""); SubItemType KeySimple = new SubItemType(4, Key, "", "", ""); SubItemType KeySkull = new SubItemType(5, Key, "skull", "", ""); SubItemType KeyDrow = new SubItemType(6, Key, "drow", "", ""); SubItemType KeyJeweled = new SubItemType(7, Key, "jeweled", "", ""); SubItemType KeyRuby = new SubItemType(8, Key, "ruby", "", ""); // Wand SubItemType WandLightningBolt = new SubItemType(1, Wand, "lightning_bolt", "Lightning Bolt", ""); SubItemType WandConeOfCold = new SubItemType(2, Wand, "cone_of_cold", "Cone of Cold", ""); SubItemType WandCureSeriousWounds = new SubItemType(3, Wand, "cure_serious_wnds", "Cure Serious Wounds", ""); SubItemType WandFireball = new SubItemType(4, Wand, "fireball", "Fireball", ""); SubItemType WandSlivias = new SubItemType(5, Wand, "slivias", "Slivias", "Move 1 square away"); SubItemType WandMagicMissile = new SubItemType(6, Wand, "magic_missile", "Magic Missile", ""); SubItemType WandMagicalVestment = new SubItemType(7, Wand, "magical_vestment", "Magical Vestment", ""); // Rations SubItemType RationsBasic = new SubItemType(25, Rations, "", "Rations", ""); SubItemType RationsIron = new SubItemType(50, Rations, "iron", "Iron Rations", ""); // Bones SubItemType HumanBones = new SubItemType(1, Bones, "human", "", ""); SubItemType HalflingBones = new SubItemType(6, Bones, "halfling", "", ""); // Dart SubItemType DartPlus1 = new SubItemType(1, Dart, "plus1", "+1", "", ""); SubItemType DartPlus2 = new SubItemType(2, Dart, "plus2", "+2", "", ""); SubItemType DartPlus3 = new SubItemType(3, Dart, "plus3", "+3", "", ""); SubItemType DartPlus4 = new SubItemType(4, Dart, "plus4", "+4", "", ""); SubItemType DartPlus5 = new SubItemType(5, Dart, "plus5", "+5", "", ""); SubItemType Dart2Plus1 = new SubItemType(1, Dart2, "plus1", "+1", "", ""); SubItemType Dart2Plus2 = new SubItemType(2, Dart2, "plus2", "+2", "", ""); SubItemType Dart2Plus3 = new SubItemType(3, Dart2, "plus3", "+3", "", ""); SubItemType Dart2Plus4 = new SubItemType(4, Dart2, "plus4", "+4", "", ""); SubItemType Dart2Plus5 = new SubItemType(5, Dart2, "plus5", "+5", "", ""); // Stone SubItemType StoneHolySymbol = new SubItemType(1, Stone, "holy_symbol", "", ""); SubItemType StoneNecklace = new SubItemType(2, Stone, "necklace", "", ""); SubItemType StoneOrb = new SubItemType(3, Stone, "orb", "", ""); SubItemType StoneDagger = new SubItemType(4, Stone, "dagger", "", ""); SubItemType StoneMedallion = new SubItemType(5, Stone, "medallion", "", ""); SubItemType StoneScepter = new SubItemType(6, Stone, "scepter", "", ""); // Dagger SubItemType DaggerBackstabber = new SubItemType(3, Dagger, "backstabber", "+3", ""); SubItemType DaggerFlica = new SubItemType(5, Dagger, "flicka", "'Flicka'", ""); // Gem SubItemType GemRed = new SubItemType(1, Gem, "red", "Red Gem", ""); SubItemType GemBlue = new SubItemType(2, Gem, "blue", "Blue Gem", ""); // Rings SubItemType RingProtection2 = new SubItemType(2, Ring, "protection2", "Protection +2", ""); // level 11, (x=27,y=16) SubItemType RingProtection3 = new SubItemType(3, Ring, "protection3", "Protection +3", ""); // level 4, (x=6, y=24) // Axe SubItemType AxeDrowCleaver = new SubItemType(3, Axe, "drow_cleaver", "'Drow Cleaver'", "", ""); //------------- // --- Wall --- //------------- // All levels Wall empty = new Wall(0L, WallType.Empty, Arrays.asList(GameSupportType.Eob1)); Wall wall1 = new Wall(1L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); Wall wall2 = new Wall(2L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); Wall emptyMonsterBlock = new Wall(25L, WallType.SquarePart, null, "eob_blocker", "eob_blocker"); // Block monsters to move trough Wall teleport = new Wall(52L, WallType.SquarePart, null, "eob_teleporter", "eob_teleporter"); Wall wallWithDoor = new Wall(58L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); // Side look Wall wallWithNet = new Wall(59L, WallType.SolidPart, Arrays.asList(GameSupportType.Eob1)); // Side look // Sewers levels Wall sewersDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal", "\t:addPullChain()"); Wall sewersDoor = new Wall(8L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal"); Wall sewersDoorOpened = new Wall(12L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal", "eob_sewers_door_metal", "\t:setDoorState(\"open\")"); Wall sewersDoorPortcullisWithButton = new Wall(13L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_portcullis", "eob_sewers_door_portcullis", "\t:addPullChain()"); Wall sewersDoorPortcullisThrowableThrough = new Wall(18L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_portcullis_throwable", "eob_portcullis_throwable"); Wall sewersLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_ladder_up", "eob_ladder_up"); // Ladder Wall sewersLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_ladder_down", "eob_ladder_down"); // Ladder Wall sewersEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_ceiling_shaft", "eob_sewers_ceiling_shaft"); Wall sewersEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_ceiling_shaft", "eob_sewers_ceiling_shaft"); Wall sewersPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_pressure_plate", "eob_sewers_pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall sewersWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_alcove", "eob_sewers_alcove"); Wall sewersDoorStacked = new Wall(30L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_metal_force", "eob_sewers_door_metal_stacked"); Wall sewersDoorPortcullisStacked = new Wall(31L, WallType.DoorPart, Wall.levels(1, 2, 3), "eob_sewers_door_portcullis", "eob_sewers_door_portcullis_stacked"); Wall sewersWallWithEyeKeyHole = new Wall(32L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_eye", "eob_sewers_lock_eye"); Wall sewersWallWithJewelKeyHole = new Wall(35L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_gem", "eob_sewers_lock_gem"); Wall sewersWallWithSecretButtonLarge = new Wall(39L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_secret_button", "eob_sewers_secret_button_large"); // Brick Wall sewersWallWithKeyHoleButton = new Wall(41L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_lock_iron", "eob_sewers_lock_iron"); // Key hole -> button Wall sewersWallWithDrainage = new Wall(43L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage"); Wall sewersWallWithDrainageBent1 = new Wall(44L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage_bent"); // Is it the same as 62??? Wall sewersWallWithButtonSmall = new Wall(50L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_secret_button_small", "eob_sewers_secret_button_small"); Wall sewersWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_long", "eob_sewers_wall_text_long"); Wall sewersWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lock_silver", "eob_lock_silver"); Wall sewersWallWithKeyHole2_ = new Wall(54L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lock_golden", "eob_lock_golden"); Wall sewersWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_lever", "eob_lever"); Wall sewersWallWithText2_ = new Wall(57L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_long", "eob_sewers_wall_text_rats"); // Read able text (Rats ->) Wall sewersWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_wall_button", "eob_severs_wall_button"); Wall sewersWallWithButtonPressed = new Wall(61L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_switch", "eob_sewers_switch", "\t:setLeverState(\"activated\")"); Wall sewersWallWithDrainageBent2 = new Wall(62L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_drainage", "eob_sewers_wall_drainage_bent"); // Is it the same as 44??? Wall sewersWallWithPipe = new Wall(63L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_pipe", "eob_sewers_wall_pipe"); Wall sewersWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(1, 2, 3), "eob_sewers_illusion_wall_rune", "eob_sewers_illusion_wall_rune"); Wall sewersWallWithRune = new Wall(65L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_wall_text_rune1", "eob_sewers_wall_text_rune"); // Rune on the wall Wall sewersWallWithDaggerKeyHole = new Wall(66L, WallType.SolidPart, Wall.levels(1, 2, 3), "eob_sewers_alcove_dagger", "eob_sewers_alcove_dagger"); // Dagger is used as key Wall sewersWallIllusionWithRune = new Wall(67L, WallType.Wall, Wall.levels(1, 2, 3), "eob_sewers_illusion_wall_rune", "eob_sewers_illusion_wall_rune"); Wall sewersCaveIn = new Wall(69L, WallType.SquarePart, Wall.levels(1, 2, 3), "eob_sewers_cave_in", "eob_sewers_cave_in"); // Ruins levels Wall ruinsDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone", "eob_ruins_door_stone", "\t:addPullChain()"); Wall ruinsDoor = new Wall(8L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone", "eob_ruins_door_stone"); Wall ruinsLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_stairs_up", "eob_ruins_stairs_up"); Wall ruinsLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_stairs_down", "eob_ruins_stairs_down"); Wall ruinsEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_ceiling_shaft", "eob_ruins_ceiling_shaft"); Wall ruinsEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_pit", "eob_ruins_pit"); Wall ruinsPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(4, 5, 6), "eob_ruins_pressure_plate", "eob_ruins_pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall ruinsWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_alcove", "eob_ruins_alcove"); Wall ruinsDoorStacked = new Wall(30L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_door_stone_stacked", "eob_ruins_door_stone_stacked"); Wall ruinsWallWithStatueLever = new Wall(32L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_statue_lever", "eob_ruins_statue_lever"); Wall ruinsWallWithSmallStatue = new Wall(34L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_small_statue", "eob_ruins_small_statue"); Wall ruinsWallWithChain = new Wall(36L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_chain_lever", "eob_ruins_chain_lever"); // Chain on the wall -> Type of the lever Wall ruinsWallWithFiringMechanism = new Wall(38L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_dart_firing_pad", "eob_ruins_dart_firing_pad"); // Level 6: Darts Wall ruinsWallWithSecretButtonTiny = new Wall(39L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_secret_button_tiny", "eob_ruins_secret_button_tiny"); Wall ruinsNet = new Wall(40L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_net", "eob_ruins_net"); Wall ruinsNetTorn = new Wall(41L, WallType.DoorPart, Wall.levels(4, 5, 6), "eob_ruins_net", "eob_ruins_net_torn", "\t:setDoorState(\"open\")"); // NetTorn (4 level) Wall ruinsWallPortalLevelNecklace = new Wall(43L, WallType.SolidPart, Wall.levels(5), "eob_ruins_portal_necklace", "eob_ruins_portal_necklace"); // Level 5 - Stone Necklace Wall ruinsWallPortalLevelScepter = new Wall(45L, WallType.SolidPart, Wall.levels(6), "eob_ruins_portal_scepter", "eob_ruins_portal_scepter"); // Level 6 - Stone Scepter Wall ruinsWallPortalLevelAmulet = new Wall(46L, WallType.SolidPart, Wall.levels(4), "eob_ruins_portal_amulet", "eob_ruins_portal_amulet"); // Level 4 - Stone Amulet Wall ruinsWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_wall_text", "eob_ruins_wall_text"); Wall ruinsWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_statue_lock", "eob_ruins_statue_lock"); Wall ruinsWallWithKeyHole2 = new Wall(54L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_ornate_lock", "eob_ruins_ornate_lock"); Wall ruinsWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_lever", "eob_ruins_lever"); Wall ruinsWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(4, 5, 6), "eob_ruins_wall_button", "eob_ruins_wall_button"); Wall ruinsWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall", "eob_ruins_illusion_wall"); Wall ruinsWallIllusionWithStatue = new Wall(66L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall_statue", "eob_ruins_illusion_wall_statue"); Wall ruinsWallIllusionWithRune = new Wall(67L, WallType.Wall, Wall.levels(4, 5, 6), "eob_ruins_illusion_wall_rune", "eob_ruins_illusion_wall_rune"); // Drow levels Wall drowDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(7, 8, 9), "prison_door_metal", "door", "\t:addPullChain()"); Wall drowDoor = new Wall(8L, WallType.DoorPart, Wall.levels(7, 8, 9), "prison_door_metal", "door"); Wall drowLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_stairs_up", "stairs_up"); Wall drowLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_stairs_down", "stairs_down"); Wall drowEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_ceiling_shaft", "ceiling_shaft"); Wall drowEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_pit", "pit"); Wall drowPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(7, 8, 9), "prison_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall drowWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_alcove", "wall_alcove"); Wall drowWallWithFiringMechanism2 = new Wall(32L, WallType.SolidPart, Wall.levels(7, 8, 9), "daemon_head", "firing_mechanism"); // Level 7: Fireball Wall drowWallWithText2 = new Wall(33L, WallType.SolidPart, Wall.levels(7, 8, 9), "dungeon_wall_text_long", "wall_text"); // It is written, the key lies on the other side. Wall drowWallWithGemKeyHole = new Wall(36L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock_prison", "wall_gem_lock"); // Gem is used as key Wall drowWallWithSecretButtonTiny = new Wall(39L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_secret_button_small", "secret_button_tiny"); Wall drowWallPortalLevelCross = new Wall(40L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Cross Wall drowWallPortalLevelNecklace = new Wall(41L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Necklace Wall drowWallPortalLevelDaggerL7 = new Wall(43L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Dagger Wall drowWallPortalLevelDaggerL9 = new Wall(43L, WallType.SolidPart, Wall.levels(9), "temple_glass_wall_2", "portal"); // Level 9 - missing Stone Dagger Wall drowWallPortalLevelAmulet = new Wall(44L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Stone Amulet Wall drowWallPortalLevelScepter = new Wall(45L, WallType.SolidPart, Wall.levels(8), "temple_glass_wall_2", "portal"); // Level 8 - missing Stone Scepter Wall drowWallPortalLevelGem = new Wall(46L, WallType.SolidPart, Wall.levels(7), "temple_glass_wall_2", "portal"); // Level 7 - missing Gem Wall drowWallThrowable = new Wall(47L, WallType.Wall, Wall.levels(7, 8, 9), "prison_secret_door", "wall_throwable"); Wall drowWallWithFiringMechanismFireball = new Wall(48L, WallType.SolidPart, Wall.levels(7), "daemon_head", "firing_mechanism"); // Level 7: Fireball Wall drowWallWithFiringMechanismDartsL9 = new Wall(48L, WallType.SolidPart, Wall.levels(9), "daemon_head", "firing_mechanism"); // Level 9: Darts Wall drowWallWithFiringMechanismDartsL8 = new Wall(49L, WallType.SolidPart, Wall.levels(8), "daemon_head", "firing_mechanism"); // Level 7: Darts Wall drowWallWithFiringMechanismMagicMissile = new Wall(49L, WallType.SolidPart, Wall.levels(9), "daemon_head", "firing_mechanism2"); // Level 9: MagicMissile Wall drowWallWithText = new Wall(51L, WallType.SolidPart, Wall.levels(7, 8, 9), "prison_wall_text_long", "wall_text"); Wall drowWallWithKeyHole = new Wall(53L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock", "wall_spider_lock"); Wall drowWallWithKeyHole2 = new Wall(54L, WallType.SolidPart, Wall.levels(7, 8, 9), "lock_ornate", "wall_lock_ornate"); Wall drowWallWithLever = new Wall(55L, WallType.SolidPart, Wall.levels(7, 8, 9), "lever", "wall_lever"); Wall drowWallIllusionWithSpider = new Wall(57L, WallType.Wall, Wall.levels(7, 8, 9), "temple_secret_door", "wall_illusion_with_spider"); Wall drowWallWithButton = new Wall(60L, WallType.SolidPart, Wall.levels(7, 8, 9), "wall_button", "wall_button"); Wall drowWallIllusion = new Wall(64L, WallType.Wall, Wall.levels(7, 8, 9), "prison_secret_door", "wall_illusion"); // Hive levels Wall hiveDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(10, 11), "dungeon_door_metal", "door", "\t:addPullChain()"); Wall hiveDoor = new Wall(8L, WallType.DoorPart, Wall.levels(10, 11), "prison_door_metal", "door"); Wall hiveLevelUp = new Wall(23L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_stairs_up", "stairs_up"); Wall hiveLevelDown = new Wall(24L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_stairs_down", "stairs_down"); Wall hiveEmptyCeilingShaft = new Wall(26L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_ceiling_shaft", "ceiling_shaft"); Wall hiveEmptyPit = new Wall(27L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_pit", "pit"); Wall hivePressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(10, 11), "dungeon_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall hiveWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_alcove", "wall_alcove"); Wall hiveWallWithSecretButtonSmall = new Wall(31L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_secret_button_small", "secret_button_small"); Wall hiveWallWithSecretButtonTiny = new Wall(33L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_secret_button_small", "secret_button_tiny"); Wall hiveWallPortalLevelCross = new Wall(36L, WallType.SolidPart, Wall.levels(11), "temple_glass_wall_2", "portal"); // Level 11 - missing Stone Cross Wall hiveWallPortalLevelOrb = new Wall(37L, WallType.SolidPart, Wall.levels(11), "temple_glass_wall_2", "portal"); // Level 11 - missing Stone Orb Wall hiveWallPortalLevelScepter = new Wall(38L, WallType.SolidPart, Wall.levels(10), "temple_glass_wall_2", "portal"); // Level 10 - missing Stone Scepter Wall hiveWallPortalLevelRing = new Wall(39L, WallType.SolidPart, Wall.levels(10), "temple_glass_wall_2", "portal"); // Level 10 - missing Stone Ring Wall hiveWallWithText = new Wall(41L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_wall_text_long", "wall_text"); Wall hiveWallWithKeyHole = new Wall(42L, WallType.SolidPart, Wall.levels(10, 11), "lock", "wall_lock"); Wall hiveWallWithLeverUp = new Wall(43L, WallType.SolidPart, Wall.levels(10, 11), "lever", "wall_lever"); Wall hiveWallWithLeverDown = new Wall(44L, WallType.SolidPart, Wall.levels(10, 11), "lever", "wall_lever", "\t:setLeverState(\"activated\")"); Wall hiveWallWithButton = new Wall(45L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_button"); Wall hiveWallWithSwitch = new Wall(46L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_switch"); // Can be pressed or released Wall hiveWallWithStar = new Wall(48L, WallType.SolidPart, Wall.levels(10, 11), "daemon_head", "wall_star"); // Level 11: Celestial star Wall hiveWallWithRift = new Wall(49L, WallType.SolidPart, Wall.levels(10, 11), "dungeon_ivy_1", "hive_wall_rift"); Wall hiveWallWithManacles = new Wall(50L, WallType.SolidPart, Wall.levels(10, 11), "prison_bench", "prison_manacles"); Wall hiveWallWithButton2 = new Wall(60L, WallType.SolidPart, Wall.levels(10, 11), "wall_button", "wall_button"); // Sanctum levels Wall sanctumDoorWithButton = new Wall(3L, WallType.DoorPart, Wall.levels(12), "temple_door_metal", "door", "\t:addPullChain()"); Wall sanctumDoor = new Wall(8L, WallType.DoorPart, Wall.levels(12), "temple_door_metal", "door"); Wall sanctumPedestal = new Wall(22L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal"); Wall sanctumPedestalWithEye = new Wall(26L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal_eye"); Wall sanctumPedestalWithEyeDetector = new Wall(27L, WallType.SquarePart, Wall.levels(12), "altar", "pedestal_eye"); Wall sanctumPressurePlate = new Wall(28L, WallType.SquarePart, Wall.levels(12), "temple_pressure_plate", "pressure_plate", "\t:setTriggeredByParty(true)\n\t:setTriggeredByMonster(true)\n\t:setTriggeredByItem(true)"); Wall sanctumWallWithAlcove = new Wall(29L, WallType.SolidPart, Wall.levels(12), "temple_alcove", "wall_alcove"); Wall sanctumWallWithFiringMechanism = new Wall(30L, WallType.SolidPart, Wall.levels(12), "daemon_head", "firing_mechanism"); // Level 12: Fireball Wall sanctumWallWithSecretButtonSmall = new Wall(31L, WallType.SolidPart, Wall.levels(12), "temple_secret_button_small", "secret_button_small"); Wall sanctumWallWithSecretButtonTiny = new Wall(33L, WallType.SolidPart, Wall.levels(12), "temple_secret_button_small", "secret_button_tiny"); Wall sanctumWallPortalLevelOrb = new Wall(37L, WallType.SolidPart, Wall.levels(12), "temple_glass_wall_2", "portal"); // Level 12 - missing Stone Orb Wall sanctumWallWithLamp = new Wall(38L, WallType.SolidPart, Wall.levels(12), "torch_holder", "wall_lamp"); Wall sanctumSpikeTrap = new Wall(39L, WallType.SquarePart, Wall.levels(12), "temple_floor_drainage", "spike_trap"); Wall sanctumWallWithText = new Wall(41L, WallType.SolidPart, Wall.levels(12), "temple_wall_text_long", "wall_text"); Wall sanctumWallWithKeyHole = new Wall(42L, WallType.SolidPart, Wall.levels(12), "lock", "wall_skull_lock"); Wall sanctumWallWithLampSmoke = new Wall(43L, WallType.SolidPart, Wall.levels(12), "torch_holder", "wall_lamp_smoke"); Wall sanctumWallWithButton = new Wall(45L, WallType.SolidPart, Wall.levels(12), "wall_button", "wall_button"); Wall sanctumWallWithButton2 = new Wall(60L, WallType.SolidPart, Wall.levels(12), "wall_button", "wall_button"); }
diff --git a/src/uk/me/parabola/util/MultiHashMap.java b/src/uk/me/parabola/util/MultiHashMap.java index 301a1f82..564b1388 100644 --- a/src/uk/me/parabola/util/MultiHashMap.java +++ b/src/uk/me/parabola/util/MultiHashMap.java @@ -1,59 +1,59 @@ package uk.me.parabola.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; public class MultiHashMap<K,V> extends HashMap<K,List<V>> { /** * the empty list to be returned when there is key without values. */ private final List<V> emptyList = Collections.unmodifiableList(new ArrayList<V>(0)); /** * Returns the list of values associated with the given key. * * @param key the key to get the values for. * @return a list of values for the given keys or the empty list of no such * value exist. */ public List<V> get(Object key) { List<V> result = super.get(key); return result == null ? emptyList : result; } public V add(K key, V value ) { List<V> values = super.get(key); if (values == null ) { values = new LinkedList<V>(); super.put( key, values ); } boolean results = values.add(value); return ( results ? value : null ); } public V remove(K key, V value ) { List<V> values = super.get(key); if (values == null ) return null; values.remove(value); if (values.isEmpty()) - super.remove(values); + super.remove(key); return value; } }
true
true
public V remove(K key, V value ) { List<V> values = super.get(key); if (values == null ) return null; values.remove(value); if (values.isEmpty()) super.remove(values); return value; }
public V remove(K key, V value ) { List<V> values = super.get(key); if (values == null ) return null; values.remove(value); if (values.isEmpty()) super.remove(key); return value; }
diff --git a/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java b/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java index 035c2610..7f87eea4 100644 --- a/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java +++ b/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java @@ -1,1645 +1,1645 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * DrFTPD is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * DrFTPD; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA */ package net.sf.drftpd.master.command.plugins; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.StringTokenizer; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; import javax.net.ssl.HandshakeCompletedEvent; import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import net.sf.drftpd.NoAvailableSlaveException; import net.sf.drftpd.NoSFVEntryException; import net.sf.drftpd.ObjectNotFoundException; import net.sf.drftpd.SlaveUnavailableException; import net.sf.drftpd.event.TransferEvent; import net.sf.drftpd.master.BaseFtpConnection; import net.sf.drftpd.master.FtpRequest; import net.sf.drftpd.master.command.CommandManager; import net.sf.drftpd.master.command.CommandManagerFactory; import net.sf.drftpd.master.config.ZipscriptConfig; import org.apache.log4j.Logger; import org.drftpd.ActiveConnection; import org.drftpd.Bytes; import org.drftpd.Checksum; import org.drftpd.PassiveConnection; import org.drftpd.SFVFile; import org.drftpd.SSLGetContext; import org.drftpd.commands.CommandHandler; import org.drftpd.commands.CommandHandlerFactory; import org.drftpd.commands.Reply; import org.drftpd.commands.ReplyException; import org.drftpd.commands.ReplySlaveUnavailableException; import org.drftpd.commands.UnhandledCommandException; import org.drftpd.commands.UserManagement; import org.drftpd.master.RemoteSlave; import org.drftpd.master.RemoteTransfer; import org.drftpd.remotefile.LinkedRemoteFile; import org.drftpd.remotefile.LinkedRemoteFileInterface; import org.drftpd.remotefile.ListUtils; import org.drftpd.remotefile.StaticRemoteFile; import org.drftpd.slave.ConnectInfo; import org.drftpd.slave.Connection; import org.drftpd.slave.RemoteIOException; import org.drftpd.slave.Transfer; import org.drftpd.slave.TransferFailedException; import org.drftpd.slave.TransferStatus; import org.drftpd.usermanager.UserFileException; import org.tanesha.replacer.ReplacerEnvironment; import org.drftpd.SFVFile.SFVStatus; /** * @author mog * @author zubov * @version $Id$ */ public class DataConnectionHandler implements CommandHandler, CommandHandlerFactory, Cloneable, HandshakeCompletedListener { private static final Logger logger = Logger.getLogger(DataConnectionHandler.class); private SSLContext _ctx; private boolean _encryptedDataChannel; private boolean _SSLHandshakeClientMode = false; protected boolean _isPasv = false; protected boolean _isPort = false; /** * Holds the address that getDataSocket() should connect to in PORT mode. */ private InetSocketAddress _portAddress; protected boolean _preTransfer = false; private RemoteSlave _preTransferRSlave; private long _resumePosition = 0; private RemoteSlave _rslave; /** * ServerSocket for PASV mode. */ private PassiveConnection _passiveConnection; private RemoteTransfer _transfer; private LinkedRemoteFileInterface _transferFile; private char _type = 'A'; private boolean _handshakeCompleted; public DataConnectionHandler() { super(); _handshakeCompleted = false; try { _ctx = SSLGetContext.getSSLContext(); } catch (FileNotFoundException e) { _ctx = null; logger.warn("Couldn't load SSLContext, SSL/TLS disabled"); } catch (Exception e) { _ctx = null; logger.warn("Couldn't load SSLContext, SSL/TLS disabled", e); } } private Reply doAUTH(BaseFtpConnection conn) { if (_ctx == null) { return new Reply(500, "TLS not configured"); } Socket s = conn.getControlSocket(); //reply success conn.getControlWriter().write(new Reply(234, conn.getRequest().getCommandLine() + " successful").toString()); conn.getControlWriter().flush(); SSLSocket s2 = null; try { s2 = (SSLSocket) _ctx.getSocketFactory().createSocket(s, s.getInetAddress().getHostAddress(), s.getPort(), true); conn.setControlSocket(s2); s2.setUseClientMode(false); s2.addHandshakeCompletedListener(this); s2.startHandshake(); while(!_handshakeCompleted) { synchronized(this) { try { wait(10000); } catch (InterruptedException e) { s2.close(); conn.stop("Took too long to negotiate SSL"); return new Reply(400, "Took too long to negotiate SSL"); } } } // reset for possible auth later _handshakeCompleted = false; } catch (IOException e) { logger.warn("", e); if (s2 != null) { try { s2.close(); } catch (IOException e2){ logger.debug("error closing SSLSocket connection"); } } conn.stop(e.getMessage()); return null; } s2 = null; return null; } /** * <code>MODE &lt;SP&gt; <mode-code> &lt;CRLF&gt;</code><br> * * The argument is a single Telnet character code specifying the data * transfer modes described in the Section on Transmission Modes. */ private Reply doMODE(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } if (request.getArgument().equalsIgnoreCase("S")) { return Reply.RESPONSE_200_COMMAND_OK; } return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } /** * <code>PASV &lt;CRLF&gt;</code><br> * * This command requests the server-DTP to "listen" on a data port (which is * not its default data port) and to wait for a connection rather than * initiate one upon receipt of a transfer command. The response to this * command includes the host and port address this server is listening on. */ private Reply doPASVandCPSV(BaseFtpConnection conn) { if (!_preTransfer) { return new Reply(500, "You need to use a client supporting PRET (PRE Transfer) to use PASV"); } //reset(); _preTransfer = false; if (isPort() == true) { throw new RuntimeException(); } if (conn.getRequest().getCommand().equals("CPSV")) { _SSLHandshakeClientMode=true; } InetSocketAddress address = null; if (_preTransferRSlave == null) { try { _passiveConnection = new PassiveConnection(_encryptedDataChannel ? _ctx : null, conn.getGlobalContext().getPortRange(), false); try { address = new InetSocketAddress(conn.getGlobalContext() .getConfig().getPasvAddress(), _passiveConnection .getLocalPort()); } catch (NullPointerException e) { address = new InetSocketAddress(conn.getControlSocket() .getLocalAddress(), _passiveConnection.getLocalPort()); } _isPasv = true; } catch (Exception ex) { logger.warn("", ex); return new Reply(550, ex.getMessage()); } } else { try { String index = _preTransferRSlave.issueListenToSlave(_encryptedDataChannel, _SSLHandshakeClientMode); ConnectInfo ci = _preTransferRSlave.fetchTransferResponseFromIndex(index); _transfer = _preTransferRSlave.getTransfer(ci.getTransferIndex()); address = new InetSocketAddress(_preTransferRSlave.getIP(),_transfer.getAddress().getPort()); _isPasv = true; } catch (SlaveUnavailableException e) { reset(); return Reply.RESPONSE_530_SLAVE_UNAVAILABLE; } catch (RemoteIOException e) { reset(); _preTransferRSlave.setOffline( "Slave could not listen for a connection"); logger.error("Slave could not listen for a connection", e); return new Reply(500, "Slave could not listen for a connection"); } } if (conn.getRequest().getCommand().equals("CPSV")) { // can only reset it if the transfer was setup with CPSV _SSLHandshakeClientMode = false; } String addrStr = address.getAddress().getHostAddress().replace('.', ',') + ',' + (address.getPort() >> 8) + ',' + (address.getPort() & 0xFF); return new Reply(227, "Entering Passive Mode (" + addrStr + ")."); } private Reply doPBSZ(BaseFtpConnection conn) throws UnhandledCommandException { String cmd = conn.getRequest().getArgument(); if ((cmd == null) || !cmd.equals("0")) { return Reply.RESPONSE_501_SYNTAX_ERROR; } return Reply.RESPONSE_200_COMMAND_OK; } /** * <code>PORT &lt;SP&gt; <host-port> &lt;CRLF&gt;</code><br> * * The argument is a HOST-PORT specification for the data port to be used in * data connection. There are defaults for both the user and server data * ports, and under normal circumstances this command and its reply are not * needed. If this command is used, the argument is the concatenation of a * 32-bit internet host address and a 16-bit TCP port address. This address * information is broken into 8-bit fields and the value of each field is * transmitted as a decimal number (in character string representation). The * fields are separated by commas. A port command would be: * * PORT h1,h2,h3,h4,p1,p2 * * where h1 is the high order 8 bits of the internet host address. */ private Reply doPORT(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); reset(); InetAddress clientAddr = null; // argument check if (!request.hasArgument()) { //Syntax error in parameters or arguments return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(request.getArgument(), ","); if (st.countTokens() != 6) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // get data server String dataSrvName = st.nextToken() + '.' + st.nextToken() + '.' + st.nextToken() + '.' + st.nextToken(); try { clientAddr = InetAddress.getByName(dataSrvName); } catch (UnknownHostException ex) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String portHostAddress = clientAddr.getHostAddress(); String clientHostAddress = conn.getControlSocket().getInetAddress() .getHostAddress(); if ((portHostAddress.startsWith("192.168.") && !clientHostAddress.startsWith("192.168.")) || (portHostAddress.startsWith("10.") && !clientHostAddress.startsWith("10."))) { Reply response = new Reply(501); response.addComment("==YOU'RE BEHIND A NAT ROUTER=="); response.addComment( "Configure the firewall settings of your FTP client"); response.addComment(" to use your real IP: " + conn.getControlSocket().getInetAddress().getHostAddress()); response.addComment("And set up port forwarding in your router."); response.addComment( "Or you can just use a PRET capable client, see"); response.addComment(" http://drftpd.org/ for PRET capable clients"); return response; } int clientPort; // get data server port try { int hi = Integer.parseInt(st.nextToken()); int lo = Integer.parseInt(st.nextToken()); clientPort = (hi << 8) | lo; } catch (NumberFormatException ex) { reset(); return Reply.RESPONSE_501_SYNTAX_ERROR; //out.write(ftpStatus.getResponse(552, request, user, null)); } _isPort = true; _portAddress = new InetSocketAddress(clientAddr, clientPort); if (portHostAddress.startsWith("127.")) { return new Reply(200, "Ok, but distributed transfers won't work with local addresses"); } //Notify the user that this is not his IP.. Good for NAT users that // aren't aware that their IP has changed. if (!clientAddr.equals(conn.getControlSocket().getInetAddress())) { return new Reply(200, "FXP allowed. If you're not FXPing then set your IP to " + conn.getControlSocket().getInetAddress().getHostAddress() + " (usually in firewall settings)"); } return Reply.RESPONSE_200_COMMAND_OK; } private Reply doPRET(BaseFtpConnection conn) { reset(); FtpRequest request = conn.getRequest(); FtpRequest ghostRequest = new FtpRequest(request.getArgument()); String cmd = ghostRequest.getCommand(); if (cmd.equals("LIST") || cmd.equals("NLST") || cmd.equals("MLSD")) { _preTransferRSlave = null; _preTransfer = true; return new Reply(200, "OK, will use master for upcoming transfer"); } else if (cmd.equals("RETR")) { try { LinkedRemoteFileInterface downFile = conn.getCurrentDirectory() .lookupFile(ghostRequest.getArgument()); _preTransferRSlave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(downFile.getAvailableSlaves(), Transfer.TRANSFER_SENDING_DOWNLOAD, conn, downFile); _preTransfer = true; return new Reply(200, "OK, will use " + _preTransferRSlave.getName() + " for upcoming transfer"); } catch (NoAvailableSlaveException e) { return Reply.RESPONSE_530_SLAVE_UNAVAILABLE; } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } else if (cmd.equals("STOR")) { LinkedRemoteFile.NonExistingFile nef = conn.getCurrentDirectory() .lookupNonExistingFile(ghostRequest.getArgument()); if (nef.exists()) { return Reply.RESPONSE_530_ACCESS_DENIED; } if (!ListUtils.isLegalFileName(nef.getPath())) { return Reply.RESPONSE_530_ACCESS_DENIED; } try { _preTransferRSlave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(conn.getGlobalContext() .getSlaveManager() .getAvailableSlaves(), Transfer.TRANSFER_RECEIVING_UPLOAD, conn, nef.getFile()); _preTransfer = true; return new Reply(200, "OK, will use " + _preTransferRSlave.getName() + " for upcoming transfer"); } catch (NoAvailableSlaveException e) { return Reply.RESPONSE_530_SLAVE_UNAVAILABLE; } } else { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } } private Reply doSSCN(BaseFtpConnection conn) { if (_ctx == null) { return new Reply(500, "TLS not configured"); } if (!(conn.getControlSocket() instanceof SSLSocket)) { return new Reply(500, "You are not on a secure channel"); } if (!_encryptedDataChannel) { return new Reply(500, "SSCN only works for encrypted transfers"); } if (conn.getRequest().hasArgument()) { if (conn.getRequest().getArgument().equalsIgnoreCase("ON")) { _SSLHandshakeClientMode = true; } if (conn.getRequest().getArgument().equalsIgnoreCase("OFF")) { _SSLHandshakeClientMode = false; } } return new Reply(220, "SSCN:" + (_SSLHandshakeClientMode ? "CLIENT" : "SERVER") + " METHOD"); } private Reply doPROT(BaseFtpConnection conn) throws UnhandledCommandException { if (_ctx == null) { return new Reply(500, "TLS not configured"); } if (!(conn.getControlSocket() instanceof SSLSocket)) { return new Reply(500, "You are not on a secure channel"); } FtpRequest req = conn.getRequest(); if (!req.hasArgument()) { //clear _encryptedDataChannel = false; return Reply.RESPONSE_200_COMMAND_OK; } if (!req.hasArgument() || (req.getArgument().length() != 1)) { return Reply.RESPONSE_501_SYNTAX_ERROR; } switch (Character.toUpperCase(req.getArgument().charAt(0))) { case 'C': //clear _encryptedDataChannel = false; return Reply.RESPONSE_200_COMMAND_OK; case 'P': //private _encryptedDataChannel = true; return Reply.RESPONSE_200_COMMAND_OK; default: return Reply.RESPONSE_501_SYNTAX_ERROR; } } /** * <code>REST &lt;SP&gt; <marker> &lt;CRLF&gt;</code><br> * * The argument field represents the server marker at which file transfer is * to be restarted. This command does not cause file transfer but skips over * the file to the specified data checkpoint. This command shall be * immediately followed by the appropriate FTP service command which shall * cause file transfer to resume. */ private Reply doREST(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { reset(); return Reply.RESPONSE_501_SYNTAX_ERROR; } String skipNum = request.getArgument(); try { _resumePosition = Long.parseLong(skipNum); } catch (NumberFormatException ex) { reset(); return Reply.RESPONSE_501_SYNTAX_ERROR; } if (_resumePosition < 0) { _resumePosition = 0; reset(); return Reply.RESPONSE_501_SYNTAX_ERROR; } return Reply.RESPONSE_350_PENDING_FURTHER_INFORMATION; } private Reply doSITE_RESCAN(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); boolean forceRescan = (request.hasArgument() && request.getArgument().equalsIgnoreCase("force")); LinkedRemoteFileInterface directory = conn.getCurrentDirectory(); SFVFile sfv; try { sfv = conn.getCurrentDirectory().lookupSFVFile(); } catch (Exception e) { return new Reply(200, "Error getting SFV File: " + e.getMessage()); } PrintWriter out = conn.getControlWriter(); for (Iterator i = sfv.getEntries().entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String fileName = (String) entry.getKey(); Long checkSum = (Long) entry.getValue(); LinkedRemoteFileInterface file; try { file = directory.lookupFile(fileName); } catch (FileNotFoundException ex) { out.write("200- SFV: " + Checksum.formatChecksum(checkSum.longValue()) + " SLAVE: " + fileName + " MISSING" + BaseFtpConnection.NEWLINE); continue; } String status; long fileCheckSum = 0; try { if (forceRescan) { fileCheckSum = file.getCheckSumFromSlave(); } else { fileCheckSum = file.getCheckSum(); } } catch (NoAvailableSlaveException e1) { out.println("200- " + fileName + "SFV: " + Checksum.formatChecksum(checkSum.longValue()) + " SLAVE: OFFLINE"); continue; } catch (IOException ex) { out.print("200- " + fileName + " SFV: " + Checksum.formatChecksum(checkSum.longValue()) + " SLAVE: IO error: " + ex.getMessage()); continue; } if (fileCheckSum == 0L) { status = "FAILED - failed to checksum file"; } else if (checkSum.longValue() == fileCheckSum) { status = "OK"; } else { status = "FAILED - checksum mismatch"; } out.println("200- " + fileName + " SFV: " + Checksum.formatChecksum(checkSum.longValue()) + " SLAVE: " + Checksum.formatChecksum(checkSum.longValue()) + " " + status); continue; } return Reply.RESPONSE_200_COMMAND_OK; } private Reply doSITE_XDUPE(BaseFtpConnection conn) { return Reply.RESPONSE_502_COMMAND_NOT_IMPLEMENTED; // resetState(); // // if (!request.hasArgument()) { // if (this.xdupe == 0) { // out.println("200 Extended dupe mode is disabled."); // } else { // out.println( // "200 Extended dupe mode " + this.xdupe + " is enabled."); // } // return; // } // // short myXdupe; // try { // myXdupe = Short.parseShort(request.getArgument()); // } catch (NumberFormatException ex) { // out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR); // return; // } // // if (myXdupe > 0 || myXdupe < 4) { // out.print( // FtpResponse.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM); // return; // } // this.xdupe = myXdupe; // out.println("200 Activated extended dupe mode " + myXdupe + "."); } /** * <code>STRU &lt;SP&gt; &lt;structure-code&gt; &lt;CRLF&gt;</code><br> * * The argument is a single Telnet character code specifying file structure. */ private Reply doSTRU(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } if (request.getArgument().equalsIgnoreCase("F")) { return Reply.RESPONSE_200_COMMAND_OK; } return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } /** * <code>SYST &lt;CRLF&gt;</code><br> * * This command is used to find out the type of operating system at the * server. */ private Reply doSYST(BaseFtpConnection conn) { /* * String systemName = System.getProperty("os.name"); if(systemName == * null) { systemName = "UNKNOWN"; } else { systemName = * systemName.toUpperCase(); systemName = systemName.replace(' ', '-'); } * String args[] = {systemName}; */ return Reply.RESPONSE_215_SYSTEM_TYPE; //String args[] = { "UNIX" }; //out.write(ftpStatus.getResponse(215, request, user, args)); } /** * <code>TYPE &lt;SP&gt; &lt;type-code&gt; &lt;CRLF&gt;</code><br> * * The argument specifies the representation type. */ private Reply doTYPE(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // get type from argument if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set it if (setType(request.getArgument().charAt(0))) { return Reply.RESPONSE_200_COMMAND_OK; } return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } public Reply execute(BaseFtpConnection conn) throws ReplyException { String cmd = conn.getRequest().getCommand(); logger.info(cmd); if ("MODE".equals(cmd)) { return doMODE(conn); } if ("PASV".equals(cmd) || "CPSV".equals(cmd)) { return doPASVandCPSV(conn); } if ("PORT".equals(cmd)) { return doPORT(conn); } if ("PRET".equals(cmd)) { return doPRET(conn); } if ("REST".equals(cmd)) { return doREST(conn); } if ("RETR".equals(cmd) || "STOR".equals(cmd) || "APPE".equals(cmd)) { return transfer(conn); } if ("SITE RESCAN".equals(cmd)) { return doSITE_RESCAN(conn); } if ("SITE XDUPE".equals(cmd)) { return doSITE_XDUPE(conn); } if ("STRU".equals(cmd)) { return doSTRU(conn); } if ("SYST".equals(cmd)) { return doSYST(conn); } if ("TYPE".equals(cmd)) { return doTYPE(conn); } if ("AUTH".equals(cmd)) { return doAUTH(conn); } if ("PROT".equals(cmd)) { return doPROT(conn); } if ("PBSZ".equals(cmd)) { return doPBSZ(conn); } if ("SSCN".equals(cmd)) { return doSSCN(conn); } throw UnhandledCommandException.create(DataConnectionHandler.class, conn.getRequest()); } /** * Get the data socket. * * Used by LIST and NLST and MLST. */ public Socket getDataSocket() throws IOException { Socket dataSocket; // get socket depending on the selection if (isPort()) { try { ActiveConnection ac = new ActiveConnection(_encryptedDataChannel ? _ctx : null, _portAddress, false); dataSocket = ac.connect(); } catch (IOException ex) { logger.warn("Error opening data socket", ex); dataSocket = null; throw ex; } } else if (isPasv()) { try { dataSocket = _passiveConnection.connect(); } finally { if (_passiveConnection != null) { _passiveConnection.abort(); _passiveConnection = null; } } } else { throw new IllegalStateException("Neither PASV nor PORT"); } // Already done since we are using ActiveConnection and PasvConnection /* dataSocket.setSoTimeout(Connection.TIMEOUT); // 15 seconds timeout if (dataSocket instanceof SSLSocket) { SSLSocket ssldatasocket = (SSLSocket) dataSocket; ssldatasocket.setUseClientMode(false); ssldatasocket.startHandshake(); }*/ return dataSocket; } public String[] getFeatReplies() { if (_ctx != null) { return new String[] { "PRET", "AUTH SSL", "PBSZ", "CPSV" , "SSCN"}; } return new String[] { "PRET" }; } public String getHelp(String cmd) { ResourceBundle bundle = ResourceBundle.getBundle(DataConnectionHandler.class.getName()); if ("".equals(cmd)) return bundle.getString("help.general")+"\n"; else if("rescan".equals(cmd)) return bundle.getString("help.rescan")+"\n"; else return ""; } public RemoteSlave getTranferSlave() { return _rslave; } public synchronized RemoteTransfer getTransfer() throws ObjectNotFoundException { if (_transfer == null) throw new ObjectNotFoundException(); return _transfer; } public LinkedRemoteFileInterface getTransferFile() { if(_transferFile == null) throw new NullPointerException(); return _transferFile; } /** * Get the user data type. */ public char getType() { return _type; } public CommandHandler initialize(BaseFtpConnection conn, CommandManager initializer) { try { return (DataConnectionHandler) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public boolean isEncryptedDataChannel() { return _encryptedDataChannel; } /** * Guarantes pre transfer is set up correctly. */ public boolean isPasv() { return _isPasv; } public boolean isPort() { return _isPort; } public boolean isPreTransfer() { return _preTransfer || isPasv(); } public synchronized boolean isTransfering() { return _transfer != null; } public void load(CommandManagerFactory initializer) { } protected synchronized void reset() { _rslave = null; if (_transfer != null) { try { _transfer.abort("reset"); } catch (Throwable t) { logger.debug("reset failed to abort transfer on the slave", t); } } _transfer = null; if (_transferFile != null) { if (_transferFile.getXfertime() == -1) { // if transfer failed on STOR _transferFile.setXfertime(0); } _transferFile = null; } _preTransfer = false; _preTransferRSlave = null; if (_passiveConnection != null) { //isPasv() && _preTransferRSlave == null _passiveConnection.abort(); } _isPasv = false; _passiveConnection = null; _isPort = false; _resumePosition = 0; } /** * Set the data type. Supported types are A (ascii) and I (binary). * * @return true if success */ private boolean setType(char type) { type = Character.toUpperCase(type); if ((type != 'A') && (type != 'I')) { return false; } _type = type; return true; } /** * <code>STOU &lt;CRLF&gt;</code><br> * * This command behaves like STOR except that the resultant file is to be * created in the current directory under a name unique to that directory. * The 250 Transfer Started response must include the name generated. */ //TODO STOU /* * public void doSTOU(FtpRequest request, PrintWriter out) { * // reset state variables resetState(); * // get filenames String fileName = * user.getVirtualDirectory().getAbsoluteName("ftp.dat"); String * physicalName = user.getVirtualDirectory().getPhysicalName(fileName); File * requestedFile = new File(physicalName); requestedFile = * IoUtils.getUniqueFile(requestedFile); fileName = * user.getVirtualDirectory().getVirtualName(requestedFile.getAbsolutePath()); * String args[] = {fileName}; * // check permission * if(!user.getVirtualDirectory().hasCreatePermission(fileName, false)) { * out.write(ftpStatus.getResponse(550, request, user, null)); return; } * // now transfer file data out.print(FtpResponse.RESPONSE_150_OK); * InputStream is = null; OutputStream os = null; try { Socket dataSoc = * mDataConnection.getDataSocket(); if (dataSoc == null) { * out.write(ftpStatus.getResponse(550, request, user, args)); return; } * * * is = dataSoc.getInputStream(); os = user.getOutputStream( new * FileOutputStream(requestedFile) ); * * StreamConnector msc = new StreamConnector(is, os); * msc.setMaxTransferRate(user.getMaxUploadRate()); msc.setObserver(this); * msc.connect(); * * if(msc.hasException()) { out.write(ftpStatus.getResponse(451, request, * user, null)); return; } else { * mConfig.getStatistics().setUpload(requestedFile, user, * msc.getTransferredSize()); } * * out.write(ftpStatus.getResponse(226, request, user, null)); * mDataConnection.reset(); out.write(ftpStatus.getResponse(250, request, * user, args)); } catch(IOException ex) { * out.write(ftpStatus.getResponse(425, request, user, null)); } finally { * IoUtils.close(is); IoUtils.close(os); mDataConnection.reset(); } } */ /** * <code>RETR &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command causes the server-DTP to transfer a copy of the file, * specified in the pathname, to the server- or user-DTP at the other end of * the data connection. The status and contents of the file at the server * site shall be unaffected. * * RETR 125, 150 (110) 226, 250 425, 426, 451 450, 550 500, 501, 421, 530 * <p> * <code>STOR &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command causes the server-DTP to accept the data transferred via the * data connection and to store the data as a file at the server site. If * the file specified in the pathname exists at the server site, then its * contents shall be replaced by the data being transferred. A new file is * created at the server site if the file specified in the pathname does not * already exist. * * STOR 125, 150 (110) 226, 250 425, 426, 451, 551, 552 532, 450, 452, 553 * 500, 501, 421, 530 * * ''zipscript?? renames bad uploads to .bad, how do we handle this with * resumes? */ //TODO add APPE support private Reply transfer(BaseFtpConnection conn) throws ReplyException { if (!_encryptedDataChannel && conn.getGlobalContext().getConfig().checkPermission("denydatauncrypted", conn.getUserNull())) { reset(); return new Reply(530, "USE SECURE DATA CONNECTION"); } try { FtpRequest request = conn.getRequest(); char direction = conn.getDirection(); String cmd = conn.getRequest().getCommand(); boolean isStor = cmd.equals("STOR"); boolean isRetr = cmd.equals("RETR"); boolean isAppe = cmd.equals("APPE"); boolean isStou = cmd.equals("STOU"); String eventType = isRetr ? "RETR" : "STOR"; if (isAppe || isStou) { throw UnhandledCommandException.create(DataConnectionHandler.class, conn.getRequest()); } // argument check if (!request.hasArgument()) { // reset(); already done in finally block return Reply.RESPONSE_501_SYNTAX_ERROR; } // Checks maxsim up/down // _simup OR _simdown = 0, exempt int count = conn.transferCounter(direction); int comparison = (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) ? conn.getUserNull().getMaxSimUp() : conn.getUserNull().getMaxSimDown(); - if (count != 0 && count > comparison) { + if (comparison != 0 && count > comparison) { if (isStor) { logger.debug(conn.getUserNull() + " reached the max simultaneous uploads slots. Cancelling transfer."); return new Reply(550, "You dont have more uploads slots"); } else if (isRetr) { logger.debug(conn.getUserNull() + " reached the max simultaneous downloads slots. Cancelling transfer."); return new Reply(550, "You dont have more download slots"); } } // get filenames LinkedRemoteFileInterface targetDir; String targetFileName; if (isRetr) { try { _transferFile = conn.getCurrentDirectory().lookupFile(request.getArgument()); if (!_transferFile.isFile()) { // reset(); already done in finally block return new Reply(550, "Not a plain file"); } targetDir = _transferFile.getParentFileNull(); targetFileName = _transferFile.getName(); } catch (FileNotFoundException ex) { // reset(); already done in finally block return new Reply(550, ex.getMessage()); } } else if (isStor) { LinkedRemoteFile.NonExistingFile ret = conn.getCurrentDirectory() .lookupNonExistingFile(conn.getGlobalContext() .getConfig() .getFileName(request.getArgument())); targetDir = ret.getFile(); targetFileName = ret.getPath(); if (ret.exists()) { // target exists, this could be overwrite or resume //TODO overwrite & resume files. // reset(); already done in finally block return new Reply(550, "Requested action not taken. File exists."); //_transferFile = targetDir; //targetDir = _transferFile.getParent(); //if(_transfereFile.getOwner().equals(getUser().getUsername())) // { // // allow overwrite/resume //} //if(directory.isDirectory()) { // return FtpReply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; //} } if (!ListUtils.isLegalFileName(targetFileName) || !conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) { // reset(); already done in finally block return new Reply(553, "Requested action not taken. File name not allowed."); } //do our zipscript sfv checks String checkName = targetFileName.toLowerCase(); ZipscriptConfig zsCfg = conn.getGlobalContext().getZsConfig(); boolean SfvFirstEnforcedPath = zsCfg.checkSfvFirstEnforcedPath(targetDir, conn.getUserNull()); try { SFVFile sfv = conn.getCurrentDirectory().lookupSFVFile(); if (checkName.endsWith(".sfv") && !zsCfg.multiSfvAllowed()) { return new Reply(533, "Requested action not taken. Multiple SFV files not allowed."); } if (SfvFirstEnforcedPath && !zsCfg.checkAllowedExtension(checkName)) { // filename not explicitly permitted, check for sfv entry boolean allow = false; if (zsCfg.restrictSfvEnabled()) { for (Iterator iter = sfv.getNames().iterator(); iter.hasNext();) { String name = (String) iter.next(); if (name.toLowerCase().equals(checkName)) { allow = true; break; } } if (!allow) { return new Reply(533, "Requested action not taken. File not found in sfv."); } } } } catch (FileNotFoundException e1) { // no sfv found in dir if ( !zsCfg.checkAllowedExtension(checkName) && SfvFirstEnforcedPath ) { // filename not explicitly permitted // ForceSfvFirst is on, and file is in an enforced path. return new Reply(533, "Requested action not taken. You must upload sfv first."); } } catch (IOException e1) { //error reading sfv, do nothing } catch (NoAvailableSlaveException e1) { //sfv not online, do nothing } } else { // reset(); already done in finally block throw UnhandledCommandException.create( DataConnectionHandler.class, request); } // check access if (!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) { // reset(); already done in finally block return new Reply(550, request.getArgument() + ": No such file"); } switch (direction) { case Transfer.TRANSFER_SENDING_DOWNLOAD: if (!conn.getGlobalContext().getConfig().checkPathPermission("download", conn.getUserNull(), targetDir)) { // reset(); already done in finally block return Reply.RESPONSE_530_ACCESS_DENIED; } break; case Transfer.TRANSFER_RECEIVING_UPLOAD: if (!conn.getGlobalContext().getConfig().checkPathPermission("upload", conn.getUserNull(), targetDir)) { // reset(); already done in finally block return Reply.RESPONSE_530_ACCESS_DENIED; } break; default: // reset(); already done in finally block throw UnhandledCommandException.create(DataConnectionHandler.class, request); } //check credits if (isRetr) { if ((conn.getUserNull().getKeyedMap().getObjectFloat( UserManagement.RATIO) != 0) && (conn.getGlobalContext().getConfig() .getCreditLossRatio(_transferFile, conn.getUserNull()) != 0) && (conn.getUserNull().getCredits() < _transferFile .length())) { // reset(); already done in finally block return new Reply(550, "Not enough credits."); } } //setup _rslave //if (isCpsv) if (isPasv()) { // isPasv() means we're setup correctly // if (!_preTransfer || _preTransferRSlave == null) // return FtpReply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; //check pretransfer if (isRetr && !_transferFile.getSlaves().contains(_preTransferRSlave)) { // reset(); already done in finally block return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } _rslave = _preTransferRSlave; //_preTransferRSlave = null; //_preTransfer = false; //code above to be handled by reset() } else { try { if (direction == Transfer.TRANSFER_SENDING_DOWNLOAD) { _rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(_transferFile.getAvailableSlaves(), Transfer.TRANSFER_SENDING_DOWNLOAD, conn, _transferFile); } else if (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) { _rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(conn.getGlobalContext() .getSlaveManager() .getAvailableSlaves(), Transfer.TRANSFER_RECEIVING_UPLOAD, conn, targetDir); } else { // reset(); already done in finally block throw new RuntimeException(); } } catch (NoAvailableSlaveException ex) { //TODO Might not be good to 450 reply always //from rfc: 450 Requested file action not taken. File unavailable (e.g., file busy). // reset(); already done in finally block throw new ReplySlaveUnavailableException(ex, 450); } } if (isStor) { //setup upload if (_rslave == null) { // reset(); already done in finally block throw new NullPointerException(); } List rslaves = Collections.singletonList(_rslave); StaticRemoteFile uploadFile = new StaticRemoteFile(rslaves, targetFileName, conn.getUserNull().getName(), conn.getUserNull().getGroup(), 0L, System.currentTimeMillis(), 0L); synchronized (this) { - _transferFile.setXfertime(-1); // used for new files to be + uploadFile.setXfertime(-1); // used for new files to be // uploaded, see getXfertime() _transferFile = targetDir.addFile(uploadFile); } } // setup _transfer if (isPort()) { try { String index = _rslave.issueConnectToSlave(_portAddress .getAddress().getHostAddress(), _portAddress .getPort(), _encryptedDataChannel, _SSLHandshakeClientMode); ConnectInfo ci = _rslave.fetchTransferResponseFromIndex(index); synchronized (this) { _transfer = _rslave.getTransfer(ci.getTransferIndex()); } } catch (Exception ex) { logger.fatal("rslave=" + _rslave, ex); // reset(); already done in finally block return new Reply(450, ex.getClass().getName() + " from slave: " + ex.getMessage()); } } else if (isPasv()) { //_transfer is already set up by doPASV() } else { // reset(); already done in finally block return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } { PrintWriter out = conn.getControlWriter(); out.write(new Reply(150, "File status okay; about to open data connection " + (isRetr ? "from " : "to ") + _rslave.getName() + ".").toString()); out.flush(); } TransferStatus status = null; //transfer try { //TODO ABORtable transfers if (isRetr) { _transfer.sendFile(_transferFile.getPath(), getType(), _resumePosition); while (true) { status = _transfer.getTransferStatus(); if (status.isFinished()) { break; } try { Thread.sleep(100); } catch (InterruptedException e1) { } } } else if (isStor) { _transfer.receiveFile(_transferFile.getPath(), getType(), _resumePosition); while (true) { status = _transfer.getTransferStatus(); _transferFile.setLength(status.getTransfered()); if (status.isFinished()) { break; } try { Thread.sleep(100); } catch (InterruptedException e1) { } } } else { throw new RuntimeException(); } } catch (IOException ex) { logger.debug("", ex); if (ex instanceof TransferFailedException) { // the below chunk makes no sense, we don't process it anywhere /* status = ((TransferFailedException) ex).getStatus(); conn.getGlobalContext() .dispatchFtpEvent(new TransferEvent(conn, eventType, _transferFile, conn.getClientAddress(), _rslave, _transfer.getAddress().getAddress(), _type, false)); */ if (isRetr) { conn.getUserNull().updateCredits(-status.getTransfered()); } } Reply reply = null; if (isStor) { _transferFile.delete(); logger.error("IOException during transfer, deleting file", ex); reply = new Reply(426, "Transfer failed, deleting file"); } else { logger.error("IOException during transfer", ex); reply = new Reply(426, ex.getMessage()); } reply.addComment(ex.getMessage()); // reset(); already done in finally block return reply; } catch (SlaveUnavailableException e) { logger.debug("", e); Reply reply = null; if (isStor) { _transferFile.delete(); logger.error("Slave went offline during transfer, deleting file", e); reply = new Reply(426, "Slave went offline during transfer, deleting file"); } else { logger.error("Slave went offline during transfer", e); reply = new Reply(426, "Slave went offline during transfer"); } reply.addComment(e.getLocalizedMessage()); // reset(); already done in finally block return reply; } // TransferThread transferThread = new TransferThread(rslave, // transfer); // System.err.println("Calling interruptibleSleepUntilFinished"); // try { // transferThread.interruptibleSleepUntilFinished(); // } catch (Throwable e1) { // e1.printStackTrace(); // } // System.err.println("Finished"); ReplacerEnvironment env = new ReplacerEnvironment(); env.add("bytes", Bytes.formatBytes(status.getTransfered())); env.add("speed", Bytes.formatBytes(status.getXferSpeed()) + "/s"); env.add("seconds", "" + ((float)status.getElapsed() / 1000F)); env.add("checksum", Checksum.formatChecksum(status.getChecksum())); Reply response = new Reply(226, conn.jprintf(DataConnectionHandler.class, "transfer.complete", env)); synchronized (conn.getGlobalContext()) { // need to synchronize // here so only one // TransferEvent can be sent at a time if (isStor) { if (_resumePosition == 0) { _transferFile.setCheckSum(status.getChecksum()); } else { // try { // checksum = _transferFile.getCheckSumFromSlave(); // } catch (NoAvailableSlaveException e) { // response.addComment( // "No available slaves when getting checksum from // slave: " // + e.getMessage()); // logger.warn("", e); // checksum = 0; // } catch (IOException e) { // response.addComment( // "IO error getting checksum from slave: " // + e.getMessage()); // logger.warn("", e); // checksum = 0; // } } _transferFile.setLastModified(System.currentTimeMillis()); _transferFile.setLength(status.getTransfered()); _transferFile.setXfertime(status.getElapsed()); } boolean zipscript = zipscript(isRetr, isStor, status .getChecksum(), response, targetFileName, targetDir); if (zipscript) { // transferstatistics if (isRetr) { float ratio = conn.getGlobalContext().getConfig() .getCreditLossRatio(_transferFile, conn.getUserNull()); if (ratio != 0) { conn.getUserNull().updateCredits( (long) (-status.getTransfered() * ratio)); } if (!conn.getGlobalContext().getConfig() .checkPathPermission("nostatsdn", conn.getUserNull(), conn.getCurrentDirectory())) { conn.getUserNull().updateDownloadedBytes( status.getTransfered()); conn.getUserNull().updateDownloadedTime( status.getElapsed()); conn.getUserNull().updateDownloadedFiles(1); } } else { conn.getUserNull().updateCredits( (long) (status.getTransfered() * conn .getGlobalContext().getConfig() .getCreditCheckRatio(_transferFile, conn.getUserNull()))); if (!conn.getGlobalContext().getConfig() .checkPathPermission("nostatsup", conn.getUserNull(), conn.getCurrentDirectory())) { conn.getUserNull().updateUploadedBytes( status.getTransfered()); conn.getUserNull().updateUploadedTime( status.getElapsed()); conn.getUserNull().updateUploadedFiles(1); } } try { conn.getUserNull().commit(); } catch (UserFileException e) { logger.warn("", e); } } // Dispatch for both STOR and RETR conn.getGlobalContext().dispatchFtpEvent( new TransferEvent(conn, eventType, _transferFile, conn .getClientAddress(), _rslave, _transfer .getAddress().getAddress(), getType())); return response; } } finally { reset(); } } public void unload() { } /** * @param isRetr * @param isStor * @param status * @param response * @param targetFileName * @param targetDir * Returns true if crc check was okay, i.e, if credits should be * altered */ private boolean zipscript(boolean isRetr, boolean isStor, long checksum, Reply response, String targetFileName, LinkedRemoteFileInterface targetDir) { // zipscript logger.debug("Running zipscript on file " + targetFileName + " with CRC of " + checksum); if (isRetr) { //compare checksum from transfer to cached checksum logger.debug("checksum from transfer = " + checksum); if (checksum != 0) { response.addComment("Checksum from transfer: " + Checksum.formatChecksum(checksum)); long cachedChecksum; cachedChecksum = _transferFile.getCheckSumCached(); if (cachedChecksum == 0) { _transferFile.setCheckSum(checksum); } else if (cachedChecksum != checksum) { response.addComment( "WARNING: checksum from transfer didn't match cached checksum"); logger.info("checksum from transfer " + Checksum.formatChecksum(checksum) + "didn't match cached checksum" + Checksum.formatChecksum(cachedChecksum) + " for " + _transferFile.toString() + " from slave " + _rslave.getName(), new Throwable()); } //compare checksum from transfer to checksum from sfv try { long sfvChecksum = _transferFile.getParentFileNull() .lookupSFVFile() .getChecksum(_transferFile.getName()); if (sfvChecksum == checksum) { response.addComment( "checksum from transfer matched checksum in .sfv"); } else { response.addComment( "WARNING: checksum from transfer didn't match checksum in .sfv"); } } catch (NoAvailableSlaveException e1) { response.addComment( "slave with .sfv offline, checksum not verified"); } catch (FileNotFoundException e1) { //continue without verification } catch (NoSFVEntryException e1) { //file not found in .sfv, continue } catch (IOException e1) { logger.info("", e1); response.addComment("IO Error reading sfv file: " + e1.getMessage()); } } else { // slave has disabled download crc //response.addComment("Slave has disabled download checksum"); } } else if (isStor) { if (!targetFileName.toLowerCase().endsWith(".sfv")) { try { long sfvChecksum = targetDir.lookupSFVFile().getChecksum(targetFileName); if (checksum == sfvChecksum) { response.addComment("checksum match: SLAVE/SFV:" + Long.toHexString(checksum)); } else if (checksum == 0) { response.addComment( "checksum match: SLAVE/SFV: DISABLED"); } else { response.addComment("checksum mismatch: SLAVE: " + Long.toHexString(checksum) + " SFV: " + Long.toHexString(sfvChecksum)); response.addComment(" deleting file"); response.setMessage("Checksum mismatch, deleting file"); _transferFile.delete(); // getUser().updateCredits( // - ((long) getUser().getRatio() * transferedBytes)); // getUser().updateUploadedBytes(-transferedBytes); // response.addComment(conn.status()); return false; // don't modify credits // String badtargetFilename = targetFilename + ".bad"; // // try { // LinkedRemoteFile badtargetFile = // targetDir.getFile(badtargetFilename); // badtargetFile.delete(); // response.addComment( // "zipscript - removing " // + badtargetFilename // + " to be replaced with new file"); // } catch (FileNotFoundException e2) { // //good, continue... // response.addComment( // "zipscript - checksum mismatch, renaming to " // + badtargetFilename); // } // targetFile.renameTo(targetDir.getPath() + // badtargetFilename); } } catch (NoAvailableSlaveException e) { response.addComment( "zipscript - SFV unavailable, slave(s) with .sfv file is offline"); } catch (NoSFVEntryException e) { response.addComment("zipscript - no entry in sfv for file"); } catch (IOException e) { response.addComment( "zipscript - SFV unavailable, IO error: " + e.getMessage()); } } } return true; // modify credits, transfer was okay } public synchronized void handshakeCompleted(HandshakeCompletedEvent arg0) { _handshakeCompleted = true; notifyAll(); } }
false
true
private Reply transfer(BaseFtpConnection conn) throws ReplyException { if (!_encryptedDataChannel && conn.getGlobalContext().getConfig().checkPermission("denydatauncrypted", conn.getUserNull())) { reset(); return new Reply(530, "USE SECURE DATA CONNECTION"); } try { FtpRequest request = conn.getRequest(); char direction = conn.getDirection(); String cmd = conn.getRequest().getCommand(); boolean isStor = cmd.equals("STOR"); boolean isRetr = cmd.equals("RETR"); boolean isAppe = cmd.equals("APPE"); boolean isStou = cmd.equals("STOU"); String eventType = isRetr ? "RETR" : "STOR"; if (isAppe || isStou) { throw UnhandledCommandException.create(DataConnectionHandler.class, conn.getRequest()); } // argument check if (!request.hasArgument()) { // reset(); already done in finally block return Reply.RESPONSE_501_SYNTAX_ERROR; } // Checks maxsim up/down // _simup OR _simdown = 0, exempt int count = conn.transferCounter(direction); int comparison = (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) ? conn.getUserNull().getMaxSimUp() : conn.getUserNull().getMaxSimDown(); if (count != 0 && count > comparison) { if (isStor) { logger.debug(conn.getUserNull() + " reached the max simultaneous uploads slots. Cancelling transfer."); return new Reply(550, "You dont have more uploads slots"); } else if (isRetr) { logger.debug(conn.getUserNull() + " reached the max simultaneous downloads slots. Cancelling transfer."); return new Reply(550, "You dont have more download slots"); } } // get filenames LinkedRemoteFileInterface targetDir; String targetFileName; if (isRetr) { try { _transferFile = conn.getCurrentDirectory().lookupFile(request.getArgument()); if (!_transferFile.isFile()) { // reset(); already done in finally block return new Reply(550, "Not a plain file"); } targetDir = _transferFile.getParentFileNull(); targetFileName = _transferFile.getName(); } catch (FileNotFoundException ex) { // reset(); already done in finally block return new Reply(550, ex.getMessage()); } } else if (isStor) { LinkedRemoteFile.NonExistingFile ret = conn.getCurrentDirectory() .lookupNonExistingFile(conn.getGlobalContext() .getConfig() .getFileName(request.getArgument())); targetDir = ret.getFile(); targetFileName = ret.getPath(); if (ret.exists()) { // target exists, this could be overwrite or resume //TODO overwrite & resume files. // reset(); already done in finally block return new Reply(550, "Requested action not taken. File exists."); //_transferFile = targetDir; //targetDir = _transferFile.getParent(); //if(_transfereFile.getOwner().equals(getUser().getUsername())) // { // // allow overwrite/resume //} //if(directory.isDirectory()) { // return FtpReply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; //} } if (!ListUtils.isLegalFileName(targetFileName) || !conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) { // reset(); already done in finally block return new Reply(553, "Requested action not taken. File name not allowed."); } //do our zipscript sfv checks String checkName = targetFileName.toLowerCase(); ZipscriptConfig zsCfg = conn.getGlobalContext().getZsConfig(); boolean SfvFirstEnforcedPath = zsCfg.checkSfvFirstEnforcedPath(targetDir, conn.getUserNull()); try { SFVFile sfv = conn.getCurrentDirectory().lookupSFVFile(); if (checkName.endsWith(".sfv") && !zsCfg.multiSfvAllowed()) { return new Reply(533, "Requested action not taken. Multiple SFV files not allowed."); } if (SfvFirstEnforcedPath && !zsCfg.checkAllowedExtension(checkName)) { // filename not explicitly permitted, check for sfv entry boolean allow = false; if (zsCfg.restrictSfvEnabled()) { for (Iterator iter = sfv.getNames().iterator(); iter.hasNext();) { String name = (String) iter.next(); if (name.toLowerCase().equals(checkName)) { allow = true; break; } } if (!allow) { return new Reply(533, "Requested action not taken. File not found in sfv."); } } } } catch (FileNotFoundException e1) { // no sfv found in dir if ( !zsCfg.checkAllowedExtension(checkName) && SfvFirstEnforcedPath ) { // filename not explicitly permitted // ForceSfvFirst is on, and file is in an enforced path. return new Reply(533, "Requested action not taken. You must upload sfv first."); } } catch (IOException e1) { //error reading sfv, do nothing } catch (NoAvailableSlaveException e1) { //sfv not online, do nothing } } else { // reset(); already done in finally block throw UnhandledCommandException.create( DataConnectionHandler.class, request); } // check access if (!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) { // reset(); already done in finally block return new Reply(550, request.getArgument() + ": No such file"); } switch (direction) { case Transfer.TRANSFER_SENDING_DOWNLOAD: if (!conn.getGlobalContext().getConfig().checkPathPermission("download", conn.getUserNull(), targetDir)) { // reset(); already done in finally block return Reply.RESPONSE_530_ACCESS_DENIED; } break; case Transfer.TRANSFER_RECEIVING_UPLOAD: if (!conn.getGlobalContext().getConfig().checkPathPermission("upload", conn.getUserNull(), targetDir)) { // reset(); already done in finally block return Reply.RESPONSE_530_ACCESS_DENIED; } break; default: // reset(); already done in finally block throw UnhandledCommandException.create(DataConnectionHandler.class, request); } //check credits if (isRetr) { if ((conn.getUserNull().getKeyedMap().getObjectFloat( UserManagement.RATIO) != 0) && (conn.getGlobalContext().getConfig() .getCreditLossRatio(_transferFile, conn.getUserNull()) != 0) && (conn.getUserNull().getCredits() < _transferFile .length())) { // reset(); already done in finally block return new Reply(550, "Not enough credits."); } } //setup _rslave //if (isCpsv) if (isPasv()) { // isPasv() means we're setup correctly // if (!_preTransfer || _preTransferRSlave == null) // return FtpReply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; //check pretransfer if (isRetr && !_transferFile.getSlaves().contains(_preTransferRSlave)) { // reset(); already done in finally block return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } _rslave = _preTransferRSlave; //_preTransferRSlave = null; //_preTransfer = false; //code above to be handled by reset() } else { try { if (direction == Transfer.TRANSFER_SENDING_DOWNLOAD) { _rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(_transferFile.getAvailableSlaves(), Transfer.TRANSFER_SENDING_DOWNLOAD, conn, _transferFile); } else if (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) { _rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(conn.getGlobalContext() .getSlaveManager() .getAvailableSlaves(), Transfer.TRANSFER_RECEIVING_UPLOAD, conn, targetDir); } else { // reset(); already done in finally block throw new RuntimeException(); } } catch (NoAvailableSlaveException ex) { //TODO Might not be good to 450 reply always //from rfc: 450 Requested file action not taken. File unavailable (e.g., file busy). // reset(); already done in finally block throw new ReplySlaveUnavailableException(ex, 450); } } if (isStor) { //setup upload if (_rslave == null) { // reset(); already done in finally block throw new NullPointerException(); } List rslaves = Collections.singletonList(_rslave); StaticRemoteFile uploadFile = new StaticRemoteFile(rslaves, targetFileName, conn.getUserNull().getName(), conn.getUserNull().getGroup(), 0L, System.currentTimeMillis(), 0L); synchronized (this) { _transferFile.setXfertime(-1); // used for new files to be // uploaded, see getXfertime() _transferFile = targetDir.addFile(uploadFile); } } // setup _transfer if (isPort()) { try { String index = _rslave.issueConnectToSlave(_portAddress .getAddress().getHostAddress(), _portAddress .getPort(), _encryptedDataChannel, _SSLHandshakeClientMode); ConnectInfo ci = _rslave.fetchTransferResponseFromIndex(index); synchronized (this) { _transfer = _rslave.getTransfer(ci.getTransferIndex()); } } catch (Exception ex) { logger.fatal("rslave=" + _rslave, ex); // reset(); already done in finally block return new Reply(450, ex.getClass().getName() + " from slave: " + ex.getMessage()); } } else if (isPasv()) { //_transfer is already set up by doPASV() } else { // reset(); already done in finally block return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } { PrintWriter out = conn.getControlWriter(); out.write(new Reply(150, "File status okay; about to open data connection " + (isRetr ? "from " : "to ") + _rslave.getName() + ".").toString()); out.flush(); } TransferStatus status = null; //transfer try { //TODO ABORtable transfers if (isRetr) { _transfer.sendFile(_transferFile.getPath(), getType(), _resumePosition); while (true) { status = _transfer.getTransferStatus(); if (status.isFinished()) { break; } try { Thread.sleep(100); } catch (InterruptedException e1) { } } } else if (isStor) { _transfer.receiveFile(_transferFile.getPath(), getType(), _resumePosition); while (true) { status = _transfer.getTransferStatus(); _transferFile.setLength(status.getTransfered()); if (status.isFinished()) { break; } try { Thread.sleep(100); } catch (InterruptedException e1) { } } } else { throw new RuntimeException(); } } catch (IOException ex) { logger.debug("", ex); if (ex instanceof TransferFailedException) { // the below chunk makes no sense, we don't process it anywhere /* status = ((TransferFailedException) ex).getStatus(); conn.getGlobalContext() .dispatchFtpEvent(new TransferEvent(conn, eventType, _transferFile, conn.getClientAddress(), _rslave, _transfer.getAddress().getAddress(), _type, false)); */ if (isRetr) { conn.getUserNull().updateCredits(-status.getTransfered()); } } Reply reply = null; if (isStor) { _transferFile.delete(); logger.error("IOException during transfer, deleting file", ex); reply = new Reply(426, "Transfer failed, deleting file"); } else { logger.error("IOException during transfer", ex); reply = new Reply(426, ex.getMessage()); } reply.addComment(ex.getMessage()); // reset(); already done in finally block return reply; } catch (SlaveUnavailableException e) { logger.debug("", e); Reply reply = null; if (isStor) { _transferFile.delete(); logger.error("Slave went offline during transfer, deleting file", e); reply = new Reply(426, "Slave went offline during transfer, deleting file"); } else { logger.error("Slave went offline during transfer", e); reply = new Reply(426, "Slave went offline during transfer"); } reply.addComment(e.getLocalizedMessage()); // reset(); already done in finally block return reply; } // TransferThread transferThread = new TransferThread(rslave, // transfer); // System.err.println("Calling interruptibleSleepUntilFinished"); // try { // transferThread.interruptibleSleepUntilFinished(); // } catch (Throwable e1) { // e1.printStackTrace(); // } // System.err.println("Finished"); ReplacerEnvironment env = new ReplacerEnvironment(); env.add("bytes", Bytes.formatBytes(status.getTransfered())); env.add("speed", Bytes.formatBytes(status.getXferSpeed()) + "/s"); env.add("seconds", "" + ((float)status.getElapsed() / 1000F)); env.add("checksum", Checksum.formatChecksum(status.getChecksum())); Reply response = new Reply(226, conn.jprintf(DataConnectionHandler.class, "transfer.complete", env)); synchronized (conn.getGlobalContext()) { // need to synchronize // here so only one // TransferEvent can be sent at a time if (isStor) { if (_resumePosition == 0) { _transferFile.setCheckSum(status.getChecksum()); } else { // try { // checksum = _transferFile.getCheckSumFromSlave(); // } catch (NoAvailableSlaveException e) { // response.addComment( // "No available slaves when getting checksum from // slave: " // + e.getMessage()); // logger.warn("", e); // checksum = 0; // } catch (IOException e) { // response.addComment( // "IO error getting checksum from slave: " // + e.getMessage()); // logger.warn("", e); // checksum = 0; // } } _transferFile.setLastModified(System.currentTimeMillis()); _transferFile.setLength(status.getTransfered()); _transferFile.setXfertime(status.getElapsed()); } boolean zipscript = zipscript(isRetr, isStor, status .getChecksum(), response, targetFileName, targetDir); if (zipscript) { // transferstatistics if (isRetr) { float ratio = conn.getGlobalContext().getConfig() .getCreditLossRatio(_transferFile, conn.getUserNull()); if (ratio != 0) { conn.getUserNull().updateCredits( (long) (-status.getTransfered() * ratio)); } if (!conn.getGlobalContext().getConfig() .checkPathPermission("nostatsdn", conn.getUserNull(), conn.getCurrentDirectory())) { conn.getUserNull().updateDownloadedBytes( status.getTransfered()); conn.getUserNull().updateDownloadedTime( status.getElapsed()); conn.getUserNull().updateDownloadedFiles(1); } } else { conn.getUserNull().updateCredits( (long) (status.getTransfered() * conn .getGlobalContext().getConfig() .getCreditCheckRatio(_transferFile, conn.getUserNull()))); if (!conn.getGlobalContext().getConfig() .checkPathPermission("nostatsup", conn.getUserNull(), conn.getCurrentDirectory())) { conn.getUserNull().updateUploadedBytes( status.getTransfered()); conn.getUserNull().updateUploadedTime( status.getElapsed()); conn.getUserNull().updateUploadedFiles(1); } } try { conn.getUserNull().commit(); } catch (UserFileException e) { logger.warn("", e); } } // Dispatch for both STOR and RETR conn.getGlobalContext().dispatchFtpEvent( new TransferEvent(conn, eventType, _transferFile, conn .getClientAddress(), _rslave, _transfer .getAddress().getAddress(), getType())); return response; } } finally { reset(); } }
private Reply transfer(BaseFtpConnection conn) throws ReplyException { if (!_encryptedDataChannel && conn.getGlobalContext().getConfig().checkPermission("denydatauncrypted", conn.getUserNull())) { reset(); return new Reply(530, "USE SECURE DATA CONNECTION"); } try { FtpRequest request = conn.getRequest(); char direction = conn.getDirection(); String cmd = conn.getRequest().getCommand(); boolean isStor = cmd.equals("STOR"); boolean isRetr = cmd.equals("RETR"); boolean isAppe = cmd.equals("APPE"); boolean isStou = cmd.equals("STOU"); String eventType = isRetr ? "RETR" : "STOR"; if (isAppe || isStou) { throw UnhandledCommandException.create(DataConnectionHandler.class, conn.getRequest()); } // argument check if (!request.hasArgument()) { // reset(); already done in finally block return Reply.RESPONSE_501_SYNTAX_ERROR; } // Checks maxsim up/down // _simup OR _simdown = 0, exempt int count = conn.transferCounter(direction); int comparison = (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) ? conn.getUserNull().getMaxSimUp() : conn.getUserNull().getMaxSimDown(); if (comparison != 0 && count > comparison) { if (isStor) { logger.debug(conn.getUserNull() + " reached the max simultaneous uploads slots. Cancelling transfer."); return new Reply(550, "You dont have more uploads slots"); } else if (isRetr) { logger.debug(conn.getUserNull() + " reached the max simultaneous downloads slots. Cancelling transfer."); return new Reply(550, "You dont have more download slots"); } } // get filenames LinkedRemoteFileInterface targetDir; String targetFileName; if (isRetr) { try { _transferFile = conn.getCurrentDirectory().lookupFile(request.getArgument()); if (!_transferFile.isFile()) { // reset(); already done in finally block return new Reply(550, "Not a plain file"); } targetDir = _transferFile.getParentFileNull(); targetFileName = _transferFile.getName(); } catch (FileNotFoundException ex) { // reset(); already done in finally block return new Reply(550, ex.getMessage()); } } else if (isStor) { LinkedRemoteFile.NonExistingFile ret = conn.getCurrentDirectory() .lookupNonExistingFile(conn.getGlobalContext() .getConfig() .getFileName(request.getArgument())); targetDir = ret.getFile(); targetFileName = ret.getPath(); if (ret.exists()) { // target exists, this could be overwrite or resume //TODO overwrite & resume files. // reset(); already done in finally block return new Reply(550, "Requested action not taken. File exists."); //_transferFile = targetDir; //targetDir = _transferFile.getParent(); //if(_transfereFile.getOwner().equals(getUser().getUsername())) // { // // allow overwrite/resume //} //if(directory.isDirectory()) { // return FtpReply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; //} } if (!ListUtils.isLegalFileName(targetFileName) || !conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) { // reset(); already done in finally block return new Reply(553, "Requested action not taken. File name not allowed."); } //do our zipscript sfv checks String checkName = targetFileName.toLowerCase(); ZipscriptConfig zsCfg = conn.getGlobalContext().getZsConfig(); boolean SfvFirstEnforcedPath = zsCfg.checkSfvFirstEnforcedPath(targetDir, conn.getUserNull()); try { SFVFile sfv = conn.getCurrentDirectory().lookupSFVFile(); if (checkName.endsWith(".sfv") && !zsCfg.multiSfvAllowed()) { return new Reply(533, "Requested action not taken. Multiple SFV files not allowed."); } if (SfvFirstEnforcedPath && !zsCfg.checkAllowedExtension(checkName)) { // filename not explicitly permitted, check for sfv entry boolean allow = false; if (zsCfg.restrictSfvEnabled()) { for (Iterator iter = sfv.getNames().iterator(); iter.hasNext();) { String name = (String) iter.next(); if (name.toLowerCase().equals(checkName)) { allow = true; break; } } if (!allow) { return new Reply(533, "Requested action not taken. File not found in sfv."); } } } } catch (FileNotFoundException e1) { // no sfv found in dir if ( !zsCfg.checkAllowedExtension(checkName) && SfvFirstEnforcedPath ) { // filename not explicitly permitted // ForceSfvFirst is on, and file is in an enforced path. return new Reply(533, "Requested action not taken. You must upload sfv first."); } } catch (IOException e1) { //error reading sfv, do nothing } catch (NoAvailableSlaveException e1) { //sfv not online, do nothing } } else { // reset(); already done in finally block throw UnhandledCommandException.create( DataConnectionHandler.class, request); } // check access if (!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) { // reset(); already done in finally block return new Reply(550, request.getArgument() + ": No such file"); } switch (direction) { case Transfer.TRANSFER_SENDING_DOWNLOAD: if (!conn.getGlobalContext().getConfig().checkPathPermission("download", conn.getUserNull(), targetDir)) { // reset(); already done in finally block return Reply.RESPONSE_530_ACCESS_DENIED; } break; case Transfer.TRANSFER_RECEIVING_UPLOAD: if (!conn.getGlobalContext().getConfig().checkPathPermission("upload", conn.getUserNull(), targetDir)) { // reset(); already done in finally block return Reply.RESPONSE_530_ACCESS_DENIED; } break; default: // reset(); already done in finally block throw UnhandledCommandException.create(DataConnectionHandler.class, request); } //check credits if (isRetr) { if ((conn.getUserNull().getKeyedMap().getObjectFloat( UserManagement.RATIO) != 0) && (conn.getGlobalContext().getConfig() .getCreditLossRatio(_transferFile, conn.getUserNull()) != 0) && (conn.getUserNull().getCredits() < _transferFile .length())) { // reset(); already done in finally block return new Reply(550, "Not enough credits."); } } //setup _rslave //if (isCpsv) if (isPasv()) { // isPasv() means we're setup correctly // if (!_preTransfer || _preTransferRSlave == null) // return FtpReply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; //check pretransfer if (isRetr && !_transferFile.getSlaves().contains(_preTransferRSlave)) { // reset(); already done in finally block return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } _rslave = _preTransferRSlave; //_preTransferRSlave = null; //_preTransfer = false; //code above to be handled by reset() } else { try { if (direction == Transfer.TRANSFER_SENDING_DOWNLOAD) { _rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(_transferFile.getAvailableSlaves(), Transfer.TRANSFER_SENDING_DOWNLOAD, conn, _transferFile); } else if (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) { _rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(conn.getGlobalContext() .getSlaveManager() .getAvailableSlaves(), Transfer.TRANSFER_RECEIVING_UPLOAD, conn, targetDir); } else { // reset(); already done in finally block throw new RuntimeException(); } } catch (NoAvailableSlaveException ex) { //TODO Might not be good to 450 reply always //from rfc: 450 Requested file action not taken. File unavailable (e.g., file busy). // reset(); already done in finally block throw new ReplySlaveUnavailableException(ex, 450); } } if (isStor) { //setup upload if (_rslave == null) { // reset(); already done in finally block throw new NullPointerException(); } List rslaves = Collections.singletonList(_rslave); StaticRemoteFile uploadFile = new StaticRemoteFile(rslaves, targetFileName, conn.getUserNull().getName(), conn.getUserNull().getGroup(), 0L, System.currentTimeMillis(), 0L); synchronized (this) { uploadFile.setXfertime(-1); // used for new files to be // uploaded, see getXfertime() _transferFile = targetDir.addFile(uploadFile); } } // setup _transfer if (isPort()) { try { String index = _rslave.issueConnectToSlave(_portAddress .getAddress().getHostAddress(), _portAddress .getPort(), _encryptedDataChannel, _SSLHandshakeClientMode); ConnectInfo ci = _rslave.fetchTransferResponseFromIndex(index); synchronized (this) { _transfer = _rslave.getTransfer(ci.getTransferIndex()); } } catch (Exception ex) { logger.fatal("rslave=" + _rslave, ex); // reset(); already done in finally block return new Reply(450, ex.getClass().getName() + " from slave: " + ex.getMessage()); } } else if (isPasv()) { //_transfer is already set up by doPASV() } else { // reset(); already done in finally block return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } { PrintWriter out = conn.getControlWriter(); out.write(new Reply(150, "File status okay; about to open data connection " + (isRetr ? "from " : "to ") + _rslave.getName() + ".").toString()); out.flush(); } TransferStatus status = null; //transfer try { //TODO ABORtable transfers if (isRetr) { _transfer.sendFile(_transferFile.getPath(), getType(), _resumePosition); while (true) { status = _transfer.getTransferStatus(); if (status.isFinished()) { break; } try { Thread.sleep(100); } catch (InterruptedException e1) { } } } else if (isStor) { _transfer.receiveFile(_transferFile.getPath(), getType(), _resumePosition); while (true) { status = _transfer.getTransferStatus(); _transferFile.setLength(status.getTransfered()); if (status.isFinished()) { break; } try { Thread.sleep(100); } catch (InterruptedException e1) { } } } else { throw new RuntimeException(); } } catch (IOException ex) { logger.debug("", ex); if (ex instanceof TransferFailedException) { // the below chunk makes no sense, we don't process it anywhere /* status = ((TransferFailedException) ex).getStatus(); conn.getGlobalContext() .dispatchFtpEvent(new TransferEvent(conn, eventType, _transferFile, conn.getClientAddress(), _rslave, _transfer.getAddress().getAddress(), _type, false)); */ if (isRetr) { conn.getUserNull().updateCredits(-status.getTransfered()); } } Reply reply = null; if (isStor) { _transferFile.delete(); logger.error("IOException during transfer, deleting file", ex); reply = new Reply(426, "Transfer failed, deleting file"); } else { logger.error("IOException during transfer", ex); reply = new Reply(426, ex.getMessage()); } reply.addComment(ex.getMessage()); // reset(); already done in finally block return reply; } catch (SlaveUnavailableException e) { logger.debug("", e); Reply reply = null; if (isStor) { _transferFile.delete(); logger.error("Slave went offline during transfer, deleting file", e); reply = new Reply(426, "Slave went offline during transfer, deleting file"); } else { logger.error("Slave went offline during transfer", e); reply = new Reply(426, "Slave went offline during transfer"); } reply.addComment(e.getLocalizedMessage()); // reset(); already done in finally block return reply; } // TransferThread transferThread = new TransferThread(rslave, // transfer); // System.err.println("Calling interruptibleSleepUntilFinished"); // try { // transferThread.interruptibleSleepUntilFinished(); // } catch (Throwable e1) { // e1.printStackTrace(); // } // System.err.println("Finished"); ReplacerEnvironment env = new ReplacerEnvironment(); env.add("bytes", Bytes.formatBytes(status.getTransfered())); env.add("speed", Bytes.formatBytes(status.getXferSpeed()) + "/s"); env.add("seconds", "" + ((float)status.getElapsed() / 1000F)); env.add("checksum", Checksum.formatChecksum(status.getChecksum())); Reply response = new Reply(226, conn.jprintf(DataConnectionHandler.class, "transfer.complete", env)); synchronized (conn.getGlobalContext()) { // need to synchronize // here so only one // TransferEvent can be sent at a time if (isStor) { if (_resumePosition == 0) { _transferFile.setCheckSum(status.getChecksum()); } else { // try { // checksum = _transferFile.getCheckSumFromSlave(); // } catch (NoAvailableSlaveException e) { // response.addComment( // "No available slaves when getting checksum from // slave: " // + e.getMessage()); // logger.warn("", e); // checksum = 0; // } catch (IOException e) { // response.addComment( // "IO error getting checksum from slave: " // + e.getMessage()); // logger.warn("", e); // checksum = 0; // } } _transferFile.setLastModified(System.currentTimeMillis()); _transferFile.setLength(status.getTransfered()); _transferFile.setXfertime(status.getElapsed()); } boolean zipscript = zipscript(isRetr, isStor, status .getChecksum(), response, targetFileName, targetDir); if (zipscript) { // transferstatistics if (isRetr) { float ratio = conn.getGlobalContext().getConfig() .getCreditLossRatio(_transferFile, conn.getUserNull()); if (ratio != 0) { conn.getUserNull().updateCredits( (long) (-status.getTransfered() * ratio)); } if (!conn.getGlobalContext().getConfig() .checkPathPermission("nostatsdn", conn.getUserNull(), conn.getCurrentDirectory())) { conn.getUserNull().updateDownloadedBytes( status.getTransfered()); conn.getUserNull().updateDownloadedTime( status.getElapsed()); conn.getUserNull().updateDownloadedFiles(1); } } else { conn.getUserNull().updateCredits( (long) (status.getTransfered() * conn .getGlobalContext().getConfig() .getCreditCheckRatio(_transferFile, conn.getUserNull()))); if (!conn.getGlobalContext().getConfig() .checkPathPermission("nostatsup", conn.getUserNull(), conn.getCurrentDirectory())) { conn.getUserNull().updateUploadedBytes( status.getTransfered()); conn.getUserNull().updateUploadedTime( status.getElapsed()); conn.getUserNull().updateUploadedFiles(1); } } try { conn.getUserNull().commit(); } catch (UserFileException e) { logger.warn("", e); } } // Dispatch for both STOR and RETR conn.getGlobalContext().dispatchFtpEvent( new TransferEvent(conn, eventType, _transferFile, conn .getClientAddress(), _rslave, _transfer .getAddress().getAddress(), getType())); return response; } } finally { reset(); } }
diff --git a/src/nodebox/client/DraggableNumber.java b/src/nodebox/client/DraggableNumber.java index 158012bd..67ddf225 100644 --- a/src/nodebox/client/DraggableNumber.java +++ b/src/nodebox/client/DraggableNumber.java @@ -1,366 +1,367 @@ package nodebox.client; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.text.NumberFormat; /** * DraggableNumber represents a number that can be edited in a variety of interesting ways: * by dragging, selecting the arrow buttons, or double-clicking to do direct input. */ public class DraggableNumber extends JComponent implements MouseListener, MouseMotionListener, ComponentListener { private static Image draggerLeft, draggerRight, draggerBackground; private static int draggerLeftWidth, draggerRightWidth, draggerHeight; static { try { draggerLeft = ImageIO.read(new File("res/dragger-left.png")); draggerRight = ImageIO.read(new File("res/dragger-right.png")); draggerBackground = ImageIO.read(new File("res/dragger-background.png")); draggerLeftWidth = draggerLeft.getWidth(null); draggerRightWidth = draggerRight.getWidth(null); draggerHeight = draggerBackground.getHeight(null); } catch (IOException e) { throw new RuntimeException(e); } } // todo: could use something like BoundedRangeModel (but then for floats) for checking bounds. private JTextField numberField; private double oldValue, value; private int previousX; private Double minimumValue; private Double maximumValue; /** * Only one <code>ChangeEvent</code> is needed per slider instance since the * event's only (read-only) state is the source property. The source * of events generated here is always "this". The event is lazily * created the first time that an event notification is fired. * * @see #fireStateChanged */ protected transient ChangeEvent changeEvent = null; private NumberFormat numberFormat; public DraggableNumber() { setLayout(null); addMouseListener(this); addMouseMotionListener(this); addComponentListener(this); Dimension d = new Dimension(87, 20); setPreferredSize(d); numberField = new JTextField(); numberField.putClientProperty("JComponent.sizeVariant", "small"); numberField.setFont(Theme.SMALL_BOLD_FONT); numberField.setHorizontalAlignment(JTextField.CENTER); numberField.setVisible(false); numberField.addKeyListener(new EscapeListener()); numberField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commitNumberField(); } }); numberField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { - commitNumberField(); + if (numberField.isVisible()) + commitNumberField(); } }); add(numberField); numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMinimumFractionDigits(2); numberFormat.setMaximumFractionDigits(2); setValue(0); // Set the correct size for the numberField. componentResized(null); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (!enabled) cancelNumberField(); } //// Value ranges //// public Double getMinimumValue() { return minimumValue; } public boolean hasMinimumValue() { return minimumValue == null; } public void setMinimumValue(double minimumValue) { this.minimumValue = minimumValue; } public void clearMinimumValue() { this.minimumValue = null; } public Double getMaximumValue() { return maximumValue; } public boolean hasMaximumValue() { return maximumValue == null; } public void setMaximumValue(double maximumValue) { this.maximumValue = maximumValue; } public void clearMaximumValue() { this.maximumValue = null; } //// Value //// public double getValue() { return value; } public double clampValue(double value) { if (minimumValue != null && value < minimumValue) value = minimumValue; if (maximumValue != null && value > maximumValue) value = maximumValue; return value; } public void setValue(double value) { this.value = clampValue(value); String formattedNumber = numberFormat.format(getValue()); numberField.setText(formattedNumber); repaint(); } public void setValueFromString(String s) throws NumberFormatException { setValue(Double.parseDouble(s)); } public String valueAsString() { return numberFormat.format(value); } //// Number formatting //// public NumberFormat getNumberFormat() { return numberFormat; } public void setNumberFormat(NumberFormat numberFormat) { this.numberFormat = numberFormat; // Refresh the label setValue(getValue()); } private void commitNumberField() { numberField.setVisible(false); String s = numberField.getText(); try { setValueFromString(s); fireStateChanged(); } catch (NumberFormatException e) { Toolkit.getDefaultToolkit().beep(); } } private void cancelNumberField() { numberField.setVisible(false); } //// Component paint //// private Rectangle getLeftButtonRect(Rectangle r) { if (r == null) r = getBounds(); return new Rectangle(0, 0, draggerLeftWidth, draggerHeight); } private Rectangle getRightButtonRect(Rectangle r) { if (r == null) r = getBounds(); return new Rectangle(r.width - draggerRightWidth, r.y, draggerRightWidth, draggerHeight); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Rectangle r = getBounds(); int centerWidth = r.width - draggerLeftWidth - draggerRightWidth; g2.drawImage(draggerLeft, 0, 0, null); g2.drawImage(draggerRight, r.width - draggerRightWidth, 0, null); g2.drawImage(draggerBackground, draggerLeftWidth, 0, centerWidth, draggerHeight, null); g2.setFont(Theme.SMALL_BOLD_FONT); if (isEnabled()) { g2.setColor(Theme.TEXT_NORMAL_COLOR); } else { g2.setColor(Theme.TEXT_DISABLED_COLOR); } SwingUtils.drawCenteredShadowText(g2, valueAsString(), r.width / 2, 14, Theme.DRAGGABLE_NUMBER_HIGLIGHT_COLOR); } //// Component size //// @Override public Dimension getPreferredSize() { // The control is actually 20 pixels high, but setting the height to 30 will leave a nice margin. return new Dimension(120, 30); } //// Component listeners public void componentResized(ComponentEvent e) { numberField.setBounds(draggerLeftWidth, 1, getWidth() - draggerLeftWidth - draggerRightWidth, draggerHeight - 2); } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } //// Mouse listeners //// public void mousePressed(MouseEvent e) { if (!isEnabled()) return; if (e.getButton() == MouseEvent.BUTTON1) { oldValue = getValue(); previousX = e.getX(); } } public void mouseClicked(MouseEvent e) { if (!isEnabled()) return; float dx = 1.0F; if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) > 0) { dx = 10F; } else if ((e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) > 0) { dx = 0.01F; } if (getLeftButtonRect(null).contains(e.getPoint())) { setValue(getValue() - dx); fireStateChanged(); } else if (getRightButtonRect(null).contains(e.getPoint())) { setValue(getValue() + dx); fireStateChanged(); } else if (e.getClickCount() >= 2) { numberField.setText(valueAsString()); numberField.setVisible(true); numberField.requestFocus(); numberField.selectAll(); componentResized(null); repaint(); } } public void mouseReleased(MouseEvent e) { if (!isEnabled()) return; if (oldValue != value) fireStateChanged(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { if (!isEnabled()) return; float deltaX = e.getX() - previousX; if (deltaX == 0F) return; if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) > 0) { deltaX *= 10; } else if ((e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) > 0) { deltaX *= 0.01; } setValue(getValue() + deltaX); previousX = e.getX(); fireStateChanged(); } /** * Adds a ChangeListener to the slider. * * @param l the ChangeListener to add * @see #fireStateChanged * @see #removeChangeListener */ public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } /** * Removes a ChangeListener from the slider. * * @param l the ChangeListener to remove * @see #fireStateChanged * @see #addChangeListener */ public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } /** * Send a ChangeEvent, whose source is this Slider, to * each listener. This method method is called each time * a ChangeEvent is received from the model. * * @see #addChangeListener * @see javax.swing.event.EventListenerList */ protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) { changeEvent = new ChangeEvent(this); } ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new DraggableNumber()); frame.pack(); frame.setVisible(true); } /** * When the escape key is pressed in the numberField, ignore the change and "close" the field. */ private class EscapeListener extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) numberField.setVisible(false); } } }
true
true
public DraggableNumber() { setLayout(null); addMouseListener(this); addMouseMotionListener(this); addComponentListener(this); Dimension d = new Dimension(87, 20); setPreferredSize(d); numberField = new JTextField(); numberField.putClientProperty("JComponent.sizeVariant", "small"); numberField.setFont(Theme.SMALL_BOLD_FONT); numberField.setHorizontalAlignment(JTextField.CENTER); numberField.setVisible(false); numberField.addKeyListener(new EscapeListener()); numberField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commitNumberField(); } }); numberField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { commitNumberField(); } }); add(numberField); numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMinimumFractionDigits(2); numberFormat.setMaximumFractionDigits(2); setValue(0); // Set the correct size for the numberField. componentResized(null); }
public DraggableNumber() { setLayout(null); addMouseListener(this); addMouseMotionListener(this); addComponentListener(this); Dimension d = new Dimension(87, 20); setPreferredSize(d); numberField = new JTextField(); numberField.putClientProperty("JComponent.sizeVariant", "small"); numberField.setFont(Theme.SMALL_BOLD_FONT); numberField.setHorizontalAlignment(JTextField.CENTER); numberField.setVisible(false); numberField.addKeyListener(new EscapeListener()); numberField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commitNumberField(); } }); numberField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { if (numberField.isVisible()) commitNumberField(); } }); add(numberField); numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMinimumFractionDigits(2); numberFormat.setMaximumFractionDigits(2); setValue(0); // Set the correct size for the numberField. componentResized(null); }
diff --git a/src/share/classes/com/sun/javafx/runtime/location/SequenceConstant.java b/src/share/classes/com/sun/javafx/runtime/location/SequenceConstant.java index 2f0c887c8..bad3dbe20 100755 --- a/src/share/classes/com/sun/javafx/runtime/location/SequenceConstant.java +++ b/src/share/classes/com/sun/javafx/runtime/location/SequenceConstant.java @@ -1,122 +1,122 @@ /* * Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.javafx.runtime.location; import java.util.Iterator; import com.sun.javafx.runtime.sequence.Sequence; import com.sun.javafx.runtime.sequence.SequencePredicate; import com.sun.javafx.runtime.TypeInfo; /** * SequenceConstant * * @author Brian Goetz */ public class SequenceConstant<T> extends AbstractConstantLocation<Sequence<? extends T>> implements SequenceLocation<T> { private final TypeInfo<T, ?> typeInfo; private Sequence<? extends T> $value; public static<T> SequenceLocation<T> make(TypeInfo<T, ?> typeInfo, Sequence<? extends T> value) { return new SequenceConstant<T>(typeInfo, value); } protected SequenceConstant(TypeInfo<T, ?> typeInfo, Sequence<? extends T> value) { this.typeInfo = typeInfo; - this.$value = value; + this.$value = (value != null)? value : typeInfo.emptySequence; } public Sequence<? extends T> getAsSequence() { return $value; } public TypeInfo<T, ?> getElementType() { return typeInfo; } public Sequence<? extends T> get() { return $value; } public Sequence<? extends T> setAsSequence(Sequence<? extends T> value) { throw new UnsupportedOperationException(); } public void addSequenceChangeListener(ChangeListener<T> listener) { } public void removeSequenceChangeListener(ChangeListener<T> listener) { } public T get(int position) { return $value.get(position); } public Sequence<? extends T> getSlice(int startPos, int endPos) { return $value.getSlice(startPos, endPos); } public Sequence<? extends T> replaceSlice(int startPos, int endPos, Sequence<? extends T> newValues) { throw new UnsupportedOperationException(); } public void deleteSlice(int startPos, int endPos) { throw new UnsupportedOperationException(); } public void deleteAll() { throw new UnsupportedOperationException(); } public void deleteValue(T value) { throw new UnsupportedOperationException(); } public void delete(SequencePredicate<T> tSequencePredicate) { throw new UnsupportedOperationException(); } public void delete(int position) { throw new UnsupportedOperationException(); } public T set(int position, T value) { throw new UnsupportedOperationException(); } public void insert(T value) { throw new UnsupportedOperationException(); } public void insert(Sequence<? extends T> values) { throw new UnsupportedOperationException(); } public void insertBefore(T value, int position) { throw new UnsupportedOperationException(); } public void insertBefore(Sequence<? extends T> values, int position) { throw new UnsupportedOperationException(); } }
true
true
protected SequenceConstant(TypeInfo<T, ?> typeInfo, Sequence<? extends T> value) { this.typeInfo = typeInfo; this.$value = value; }
protected SequenceConstant(TypeInfo<T, ?> typeInfo, Sequence<? extends T> value) { this.typeInfo = typeInfo; this.$value = (value != null)? value : typeInfo.emptySequence; }
diff --git a/modules/cpr/src/main/java/org/atmosphere/websocket/WebSocket.java b/modules/cpr/src/main/java/org/atmosphere/websocket/WebSocket.java index 31c83edc0..8ac7e43dc 100644 --- a/modules/cpr/src/main/java/org/atmosphere/websocket/WebSocket.java +++ b/modules/cpr/src/main/java/org/atmosphere/websocket/WebSocket.java @@ -1,248 +1,248 @@ /* * Copyright 2012 Jeanfrancois Arcand * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.websocket; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.cpr.AsyncIOInterceptor; import org.atmosphere.cpr.AsyncIOWriter; import org.atmosphere.cpr.AsyncIOWriterAdapter; import org.atmosphere.cpr.AtmosphereConfig; import org.atmosphere.cpr.AtmosphereInterceptorWriter; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResourceEventListener; import org.atmosphere.cpr.AtmosphereResourceImpl; import org.atmosphere.cpr.AtmosphereResponse; import org.atmosphere.util.ByteArrayAsyncWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean; /** * Represent a portable WebSocket implementation which can be used to write message. * * @author Jeanfrancois Arcand */ public abstract class WebSocket extends AtmosphereInterceptorWriter { protected static final Logger logger = LoggerFactory.getLogger(WebSocket.class); public final static String WEBSOCKET_INITIATED = WebSocket.class.getName() + ".initiated"; public final static String WEBSOCKET_SUSPEND = WebSocket.class.getName() + ".suspend"; public final static String WEBSOCKET_RESUME = WebSocket.class.getName() + ".resume"; public final static String WEBSOCKET_ACCEPT_DONE = WebSocket.class.getName() + ".acceptDone"; private AtmosphereResource r; protected long lastWrite = 0; protected final boolean binaryWrite; private final ByteArrayAsyncWriter buffer = new ByteArrayAsyncWriter(); private final AtomicBoolean firstWrite = new AtomicBoolean(false); public WebSocket(AtmosphereConfig config) { String s = config.getInitParameter(ApplicationConfig.WEBSOCKET_BINARY_WRITE); if (s != null && Boolean.parseBoolean(s)) { binaryWrite = true; } else { binaryWrite = false; } } public WebSocket() { binaryWrite = false; } /** * Associate an {@link AtmosphereResource} to this WebSocket * * @param r an {@link AtmosphereResource} to this WebSocket * @return this */ public WebSocket resource(AtmosphereResource r) { // Make sure we carry what was set at the onOpen stage. if (this.r != null && r != null) { // TODO: This is all over the place and quite ugly (the cast). Need to fix this in 1.1 AtmosphereResourceImpl.class.cast(r).cloneState(this.r); } this.r = r; return this; } /** * Return the an {@link AtmosphereResource} used by this WebSocket, or null if the WebSocket has been closed * before the WebSocket message has been processed. * * @return {@link AtmosphereResource} */ public AtmosphereResource resource() { return r; } /** * The last time, in milliseconds, a write operation occurred. * * @return this */ public long lastWriteTimeStampInMilliseconds() { return lastWrite == -1 ? System.currentTimeMillis() : lastWrite; } protected byte[] transform(byte[] b, int offset, int length) throws IOException { AtmosphereResponse response = r.getResponse(); AsyncIOWriter a = response.getAsyncIOWriter(); try { response.asyncIOWriter(buffer); invokeInterceptor(response, b, offset, length); return buffer.stream().toByteArray(); } finally { buffer.close(null); response.asyncIOWriter(a); } } /** * {@inheritDoc} */ @Override public WebSocket write(AtmosphereResponse r, String data) throws IOException { firstWrite.set(true); if (!isOpen()) throw new IOException("Connection remotely closed"); logger.trace("WebSocket.write()"); boolean transform = filters.size() > 0; if (binaryWrite) { byte[] b = data.getBytes(resource().getResponse().getCharacterEncoding()); if (transform) { b = transform(b, 0, b.length); } if (b != null) { write(b, 0, b.length); } } else { if (transform) { byte[] b = data.getBytes(resource().getResponse().getCharacterEncoding()); data = new String(transform(b, 0, b.length), r.getCharacterEncoding()); } if (data != null) { write(data); } } lastWrite = System.currentTimeMillis(); return this; } /** * {@inheritDoc} */ @Override public WebSocket write(AtmosphereResponse r, byte[] data) throws IOException { return write(r, data, 0, data.length); } /** * {@inheritDoc} */ @Override public WebSocket write(AtmosphereResponse r, byte[] b, int offset, int length) throws IOException { firstWrite.set(true); if (!isOpen()) throw new IOException("Connection remotely closed"); logger.trace("WebSocket.write()"); boolean transform = filters.size() > 0; if (binaryWrite) { if (transform) { b = transform(b, offset, length); } if (b != null) { write(b, 0, length); } } else { String data = null; if (transform) { - data = new String(transform(b, 0, length), r.getCharacterEncoding()); + data = new String(transform(b, offset, length), r.getCharacterEncoding()); } else { - data = new String(b, 0, length, r.getCharacterEncoding()); + data = new String(b, offset, length, r.getCharacterEncoding()); } if (data != null) { write(data); } } lastWrite = System.currentTimeMillis(); return this; } /** * {@inheritDoc} */ @Override public WebSocket writeError(AtmosphereResponse r, int errorCode, String message) throws IOException { if (!firstWrite.get()) { logger.debug("The WebSocket handshake succeeded but the dispatched URI failed {}:{}. " + "The WebSocket connection is still open and client can continue sending messages.", message, errorCode); } else { logger.debug("{} {}", errorCode, message); } return this; } /** * {@inheritDoc} */ @Override public WebSocket redirect(AtmosphereResponse r, String location) throws IOException { logger.error("WebSocket Redirect not supported"); return this; } /** * {@inheritDoc} */ @Override public void close(AtmosphereResponse r) throws IOException { logger.trace("WebSocket.close()"); close(); } /** * {@inheritDoc} */ @Override public WebSocket flush(AtmosphereResponse r) throws IOException { return this; } /** * Is the underlying WebSocket open. * * @return */ abstract public boolean isOpen(); abstract public void write(String s) throws IOException; abstract public void write(byte[] b, int offset, int length) throws IOException; abstract public void close(); }
false
true
public WebSocket write(AtmosphereResponse r, byte[] b, int offset, int length) throws IOException { firstWrite.set(true); if (!isOpen()) throw new IOException("Connection remotely closed"); logger.trace("WebSocket.write()"); boolean transform = filters.size() > 0; if (binaryWrite) { if (transform) { b = transform(b, offset, length); } if (b != null) { write(b, 0, length); } } else { String data = null; if (transform) { data = new String(transform(b, 0, length), r.getCharacterEncoding()); } else { data = new String(b, 0, length, r.getCharacterEncoding()); } if (data != null) { write(data); } } lastWrite = System.currentTimeMillis(); return this; }
public WebSocket write(AtmosphereResponse r, byte[] b, int offset, int length) throws IOException { firstWrite.set(true); if (!isOpen()) throw new IOException("Connection remotely closed"); logger.trace("WebSocket.write()"); boolean transform = filters.size() > 0; if (binaryWrite) { if (transform) { b = transform(b, offset, length); } if (b != null) { write(b, 0, length); } } else { String data = null; if (transform) { data = new String(transform(b, offset, length), r.getCharacterEncoding()); } else { data = new String(b, offset, length, r.getCharacterEncoding()); } if (data != null) { write(data); } } lastWrite = System.currentTimeMillis(); return this; }
diff --git a/app/forms/MovieForm.java b/app/forms/MovieForm.java index 219ecc1..1dc5056 100644 --- a/app/forms/MovieForm.java +++ b/app/forms/MovieForm.java @@ -1,150 +1,151 @@ package forms; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import models.Dvd; import models.EMovieAttributeType; import models.Movie; import models.MovieAttibute; import play.data.validation.Constraints.Required; /** * This is used when the user adds or edits a new movie * * @author tuxburner * */ public class MovieForm { public Long movieId; @Required public String title; @Required public Integer year; public Integer runtime; public String plot; public String posterUrl; public String backDropUrl; public List<String> genres = new ArrayList<String>(); public List<String> actors = new ArrayList<String>(); public String director; /** * This describes in which series the movie is for example Alien, Terminator, * Indiana Jones are Series of movies */ public String series; public Boolean hasBackdrop; public Boolean hasPoster; /** * Transforms a {@link Dvd} to a {@link DvdForm} for editing the dvd in the * frontend * * @param dvd * @return */ public static MovieForm movieToForm(final Movie movie) { final MovieForm movieForm = new MovieForm(); + movieForm.movieId = movie.id; movieForm.title = movie.title; movieForm.year = movie.year; movieForm.runtime = movie.runtime; movieForm.plot = movie.description; movieForm.hasBackdrop = movie.hasBackdrop; movieForm.hasPoster = movie.hasPoster; final Set<MovieAttibute> attributes = movie.attributes; for (final MovieAttibute dvdAttibute : attributes) { if (EMovieAttributeType.GENRE.equals(dvdAttibute.attributeType)) { movieForm.genres.add(dvdAttibute.value); } if (EMovieAttributeType.ACTOR.equals(dvdAttibute.attributeType)) { movieForm.actors.add(dvdAttibute.value); } if (EMovieAttributeType.DIRECTOR.equals(dvdAttibute.attributeType)) { movieForm.director = dvdAttibute.value; } } Collections.sort(movieForm.actors); Collections.sort(movieForm.genres); return movieForm; } /** * Gathers all attributes for the given type from the db and checks if the dvd * * @param attributeType * @return */ public List<MovieFormAttribute> getDvdAttributes(final EMovieAttributeType attributeType, final Map<Integer, String> formVals) { final List<MovieFormAttribute> result = new ArrayList<MovieFormAttribute>(); // merge wit the attributes from the database final List<MovieAttibute> genres = MovieAttibute.getAllByType(attributeType); final Set<String> newGenreMatchedWithDb = new HashSet<String>(); for (final MovieAttibute movieAttibute : genres) { final String value = movieAttibute.value; boolean selected = false; for (final String formAttrs : formVals.values()) { if (value.equals(formAttrs)) { newGenreMatchedWithDb.add(formAttrs); selected = true; break; } } result.add(new MovieFormAttribute(selected, value)); } // add all attributes which where not in the database :) for (final String genre : formVals.values()) { if (newGenreMatchedWithDb.contains(genre) == false) { result.add(new MovieFormAttribute(true, genre)); } } return result; } /** * This returns the values as a , seperated string * * @param values * @return */ public final String getDvdFormAttributesAsString(final List<String> values) { String returnVal = ""; String sep = ""; for (final String value : values) { returnVal += sep + value; sep = ","; } return returnVal; } }
true
true
public static MovieForm movieToForm(final Movie movie) { final MovieForm movieForm = new MovieForm(); movieForm.title = movie.title; movieForm.year = movie.year; movieForm.runtime = movie.runtime; movieForm.plot = movie.description; movieForm.hasBackdrop = movie.hasBackdrop; movieForm.hasPoster = movie.hasPoster; final Set<MovieAttibute> attributes = movie.attributes; for (final MovieAttibute dvdAttibute : attributes) { if (EMovieAttributeType.GENRE.equals(dvdAttibute.attributeType)) { movieForm.genres.add(dvdAttibute.value); } if (EMovieAttributeType.ACTOR.equals(dvdAttibute.attributeType)) { movieForm.actors.add(dvdAttibute.value); } if (EMovieAttributeType.DIRECTOR.equals(dvdAttibute.attributeType)) { movieForm.director = dvdAttibute.value; } } Collections.sort(movieForm.actors); Collections.sort(movieForm.genres); return movieForm; }
public static MovieForm movieToForm(final Movie movie) { final MovieForm movieForm = new MovieForm(); movieForm.movieId = movie.id; movieForm.title = movie.title; movieForm.year = movie.year; movieForm.runtime = movie.runtime; movieForm.plot = movie.description; movieForm.hasBackdrop = movie.hasBackdrop; movieForm.hasPoster = movie.hasPoster; final Set<MovieAttibute> attributes = movie.attributes; for (final MovieAttibute dvdAttibute : attributes) { if (EMovieAttributeType.GENRE.equals(dvdAttibute.attributeType)) { movieForm.genres.add(dvdAttibute.value); } if (EMovieAttributeType.ACTOR.equals(dvdAttibute.attributeType)) { movieForm.actors.add(dvdAttibute.value); } if (EMovieAttributeType.DIRECTOR.equals(dvdAttibute.attributeType)) { movieForm.director = dvdAttibute.value; } } Collections.sort(movieForm.actors); Collections.sort(movieForm.genres); return movieForm; }
diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java index 4924bc6543..8f27d2a1e3 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java +++ b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java @@ -1,158 +1,158 @@ /** * Copyright 2011 Microsoft Corporation * * 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.microsoft.windowsazure.serviceruntime; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * */ class XmlRoleEnvironmentDataDeserializer implements RoleEnvironmentDataDeserializer { public XmlRoleEnvironmentDataDeserializer() { } @Override public RoleEnvironmentData deserialize(InputStream stream) { try { JAXBContext context = JAXBContext.newInstance(RoleEnvironmentInfo.class.getPackage().getName()); Unmarshaller unmarshaller = context.createUnmarshaller(); @SuppressWarnings("unchecked") RoleEnvironmentInfo environmentInfo = ((JAXBElement<RoleEnvironmentInfo>) unmarshaller.unmarshal(stream)) .getValue(); Map<String, String> configurationSettings = translateConfigurationSettings(environmentInfo); Map<String, LocalResource> localResources = translateLocalResources(environmentInfo); RoleInstance currentInstance = translateCurrentInstance(environmentInfo); Map<String, Role> roles = translateRoles(environmentInfo, currentInstance, environmentInfo .getCurrentInstance().getRoleName()); return new RoleEnvironmentData(environmentInfo.getDeployment().getId(), configurationSettings, localResources, currentInstance, roles, environmentInfo.getDeployment().isEmulated()); } catch (JAXBException e) { throw new RuntimeException(e); } } private Map<String, String> translateConfigurationSettings(RoleEnvironmentInfo environmentInfo) { Map<String, String> configurationSettings = new HashMap<String, String>(); for (ConfigurationSettingInfo settingInfo : environmentInfo.getCurrentInstance().getConfigurationSettings() .getConfigurationSetting()) { configurationSettings.put(settingInfo.getName(), settingInfo.getValue()); } return configurationSettings; } private Map<String, LocalResource> translateLocalResources(RoleEnvironmentInfo environmentInfo) { Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); for (LocalResourceInfo resourceInfo : environmentInfo.getCurrentInstance().getLocalResources() .getLocalResource()) { localResources.put(resourceInfo.getName(), new LocalResource(resourceInfo.getSizeInMB(), resourceInfo.getName(), resourceInfo.getPath())); } return localResources; } private Map<String, Role> translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance, String currentRole) { Map<String, Role> roles = new HashMap<String, Role>(); for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) { Map<String, RoleInstance> instances = translateRoleInstances(roleInfo.getInstances()); - if (roleInfo.getName() == currentRole) { + if (roleInfo.getName().equals(currentRole)) { instances.put(currentInstance.getId(), currentInstance); } Role role = new Role(roleInfo.getName(), instances); for (RoleInstance instance : role.getInstances().values()) { instance.setRole(role); } roles.put(roleInfo.getName(), role); } if (!roles.containsKey(currentRole)) { Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>(); instances.put(currentInstance.getId(), currentInstance); Role singleRole = new Role(currentRole, instances); currentInstance.setRole(singleRole); roles.put(currentRole, singleRole); } return roles; } private Map<String, RoleInstance> translateRoleInstances(RoleInstancesInfo instancesInfo) { Map<String, RoleInstance> roleInstances = new HashMap<String, RoleInstance>(); for (RoleInstanceInfo instanceInfo : instancesInfo.getInstance()) { RoleInstance instance = new RoleInstance(instanceInfo.getId(), instanceInfo.getFaultDomain(), instanceInfo.getUpdateDomain(), translateRoleInstanceEndpoints(instanceInfo.getEndpoints())); for (RoleInstanceEndpoint endpoint : instance.getInstanceEndpoints().values()) { endpoint.setRoleInstance(instance); } roleInstances.put(instance.getId(), instance); } return roleInstances; } private Map<String, RoleInstanceEndpoint> translateRoleInstanceEndpoints(EndpointsInfo endpointsInfo) { Map<String, RoleInstanceEndpoint> endpoints = new HashMap<String, RoleInstanceEndpoint>(); for (EndpointInfo endpointInfo : endpointsInfo.getEndpoint()) { RoleInstanceEndpoint endpoint = new RoleInstanceEndpoint(endpointInfo.getProtocol().toString(), new InetSocketAddress(endpointInfo.getAddress(), endpointInfo.getPort())); endpoints.put(endpointInfo.getName(), endpoint); } return endpoints; } private RoleInstance translateCurrentInstance(RoleEnvironmentInfo environmentInfo) { CurrentRoleInstanceInfo currentInstanceInfo = environmentInfo.getCurrentInstance(); RoleInstance currentInstance = new RoleInstance(currentInstanceInfo.getId(), currentInstanceInfo.getFaultDomain(), currentInstanceInfo.getUpdateDomain(), translateRoleInstanceEndpoints(environmentInfo.getCurrentInstance().getEndpoints())); for (RoleInstanceEndpoint endpoint : currentInstance.getInstanceEndpoints().values()) { endpoint.setRoleInstance(currentInstance); } return currentInstance; } }
true
true
private Map<String, Role> translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance, String currentRole) { Map<String, Role> roles = new HashMap<String, Role>(); for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) { Map<String, RoleInstance> instances = translateRoleInstances(roleInfo.getInstances()); if (roleInfo.getName() == currentRole) { instances.put(currentInstance.getId(), currentInstance); } Role role = new Role(roleInfo.getName(), instances); for (RoleInstance instance : role.getInstances().values()) { instance.setRole(role); } roles.put(roleInfo.getName(), role); } if (!roles.containsKey(currentRole)) { Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>(); instances.put(currentInstance.getId(), currentInstance); Role singleRole = new Role(currentRole, instances); currentInstance.setRole(singleRole); roles.put(currentRole, singleRole); } return roles; }
private Map<String, Role> translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance, String currentRole) { Map<String, Role> roles = new HashMap<String, Role>(); for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) { Map<String, RoleInstance> instances = translateRoleInstances(roleInfo.getInstances()); if (roleInfo.getName().equals(currentRole)) { instances.put(currentInstance.getId(), currentInstance); } Role role = new Role(roleInfo.getName(), instances); for (RoleInstance instance : role.getInstances().values()) { instance.setRole(role); } roles.put(roleInfo.getName(), role); } if (!roles.containsKey(currentRole)) { Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>(); instances.put(currentInstance.getId(), currentInstance); Role singleRole = new Role(currentRole, instances); currentInstance.setRole(singleRole); roles.put(currentRole, singleRole); } return roles; }
diff --git a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/SipServletTestCase.java b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/SipServletTestCase.java index 373a223c5..923ed6944 100644 --- a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/SipServletTestCase.java +++ b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/SipServletTestCase.java @@ -1,106 +1,105 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip; import java.io.File; import java.io.InputStream; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.TestCase; /** * This class is responsible for reading up the properties configuration file * and starting/stopping tomcat. It delegates to the test case inheriting from it * the deployment of the context and the location of the dar configuration file * since it should map to the test case. */ public abstract class SipServletTestCase extends TestCase { private static Log logger = LogFactory.getLog(SipServletTestCase.class); protected String tomcatBasePath; protected String projectHome; protected SipEmbedded tomcat; protected boolean autoDeployOnStartup = true; public SipServletTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); //Reading properties Properties properties = new Properties(); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( "org/mobicents/servlet/sip/testsuite/testsuite.properties"); try{ properties.load(inputStream); } catch (NullPointerException e) { inputStream = getClass().getResourceAsStream( "org/mobicents/servlet/sip/testsuite/testsuite.properties"); properties.load(inputStream); } // First try to use the env variables - useful for shell scripting tomcatBasePath = System.getenv("CATALINA_HOME"); projectHome = System.getenv("SIP_SERVLETS_HOME"); // Otherwise use the properties if(this.tomcatBasePath == null || this.tomcatBasePath.length() <= 0) this.tomcatBasePath = properties.getProperty("tomcat.home"); if(this.projectHome == null || this.projectHome.length() <= 0) this.projectHome = properties.getProperty("project.home"); logger.info("Tomcat base Path is : " + tomcatBasePath); logger.info("Project Home is : " + projectHome); //starting tomcat tomcat = new SipEmbedded(); tomcat.setPath(tomcatBasePath); tomcat.setLoggingFilePath( - "file:"+ File.separatorChar + File.separatorChar + -// File.separatorChar + + "file:"+ File.separatorChar + File.separatorChar + File.separatorChar + projectHome + File.separatorChar + "sip-servlets-test-suite" + File.separatorChar + "testsuite" + File.separatorChar + "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar); String darConfigurationFile = getDarConfigurationFile(); tomcat.setDarConfigurationFilePath(darConfigurationFile); tomcat.startTomcat(); if(autoDeployOnStartup) { deployApplication(); } } @Override protected void tearDown() throws Exception { tomcat.stopTomcat(); super.tearDown(); } /** * Delegates the choice of the application to deploy to the test case */ protected abstract void deployApplication(); /** * Delegates the choice of the default application router * configuration file to use to the test case */ protected abstract String getDarConfigurationFile(); }
true
true
protected void setUp() throws Exception { super.setUp(); //Reading properties Properties properties = new Properties(); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( "org/mobicents/servlet/sip/testsuite/testsuite.properties"); try{ properties.load(inputStream); } catch (NullPointerException e) { inputStream = getClass().getResourceAsStream( "org/mobicents/servlet/sip/testsuite/testsuite.properties"); properties.load(inputStream); } // First try to use the env variables - useful for shell scripting tomcatBasePath = System.getenv("CATALINA_HOME"); projectHome = System.getenv("SIP_SERVLETS_HOME"); // Otherwise use the properties if(this.tomcatBasePath == null || this.tomcatBasePath.length() <= 0) this.tomcatBasePath = properties.getProperty("tomcat.home"); if(this.projectHome == null || this.projectHome.length() <= 0) this.projectHome = properties.getProperty("project.home"); logger.info("Tomcat base Path is : " + tomcatBasePath); logger.info("Project Home is : " + projectHome); //starting tomcat tomcat = new SipEmbedded(); tomcat.setPath(tomcatBasePath); tomcat.setLoggingFilePath( "file:"+ File.separatorChar + File.separatorChar + // File.separatorChar + projectHome + File.separatorChar + "sip-servlets-test-suite" + File.separatorChar + "testsuite" + File.separatorChar + "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar); String darConfigurationFile = getDarConfigurationFile(); tomcat.setDarConfigurationFilePath(darConfigurationFile); tomcat.startTomcat(); if(autoDeployOnStartup) { deployApplication(); } }
protected void setUp() throws Exception { super.setUp(); //Reading properties Properties properties = new Properties(); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( "org/mobicents/servlet/sip/testsuite/testsuite.properties"); try{ properties.load(inputStream); } catch (NullPointerException e) { inputStream = getClass().getResourceAsStream( "org/mobicents/servlet/sip/testsuite/testsuite.properties"); properties.load(inputStream); } // First try to use the env variables - useful for shell scripting tomcatBasePath = System.getenv("CATALINA_HOME"); projectHome = System.getenv("SIP_SERVLETS_HOME"); // Otherwise use the properties if(this.tomcatBasePath == null || this.tomcatBasePath.length() <= 0) this.tomcatBasePath = properties.getProperty("tomcat.home"); if(this.projectHome == null || this.projectHome.length() <= 0) this.projectHome = properties.getProperty("project.home"); logger.info("Tomcat base Path is : " + tomcatBasePath); logger.info("Project Home is : " + projectHome); //starting tomcat tomcat = new SipEmbedded(); tomcat.setPath(tomcatBasePath); tomcat.setLoggingFilePath( "file:"+ File.separatorChar + File.separatorChar + File.separatorChar + projectHome + File.separatorChar + "sip-servlets-test-suite" + File.separatorChar + "testsuite" + File.separatorChar + "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar); String darConfigurationFile = getDarConfigurationFile(); tomcat.setDarConfigurationFilePath(darConfigurationFile); tomcat.startTomcat(); if(autoDeployOnStartup) { deployApplication(); } }
diff --git a/src/net/java/sip/communicator/impl/gui/lookandfeel/SIPCommMenuBarUI.java b/src/net/java/sip/communicator/impl/gui/lookandfeel/SIPCommMenuBarUI.java index 7741bd464..d0ab3a46c 100644 --- a/src/net/java/sip/communicator/impl/gui/lookandfeel/SIPCommMenuBarUI.java +++ b/src/net/java/sip/communicator/impl/gui/lookandfeel/SIPCommMenuBarUI.java @@ -1,34 +1,33 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.lookandfeel; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; /** * @author Yana Stamcheva */ public class SIPCommMenuBarUI extends BasicMenuBarUI { /** * Creates a new SIPCommMenuUI instance. */ public static ComponentUI createUI(JComponent x) { return new SIPCommMenuBarUI(); } protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); - LookAndFeel.installBorder(menuBar, null); } }
true
true
protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); LookAndFeel.installBorder(menuBar, null); }
protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); }
diff --git a/org.lh.dmlj.schema.editor/src/org/lh/dmlj/schema/editor/wizard/export/ExportWizard.java b/org.lh.dmlj.schema.editor/src/org/lh/dmlj/schema/editor/wizard/export/ExportWizard.java index d2e18b7..77175ff 100644 --- a/org.lh.dmlj.schema.editor/src/org/lh/dmlj/schema/editor/wizard/export/ExportWizard.java +++ b/org.lh.dmlj.schema.editor/src/org/lh/dmlj/schema/editor/wizard/export/ExportWizard.java @@ -1,134 +1,134 @@ package org.lh.dmlj.schema.editor.wizard.export; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IExportWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.lh.dmlj.schema.Schema; import org.lh.dmlj.schema.editor.template.SchemaTemplate; public class ExportWizard extends Wizard implements IExportWizard { private OutputFileSelectionPage outputFileSelectionPage; private SchemaSelectionPage schemaSelectionPage; private IStructuredSelection selection; private static String rtrim(String line) { StringBuilder p = new StringBuilder(line); while (p.length() > 0 && p.charAt(p.length() - 1) == ' ') { p.setLength(p.length() - 1); } return p.toString(); } public ExportWizard() { super(); setWindowTitle("Export"); } @Override public void addPages() { schemaSelectionPage = new SchemaSelectionPage(selection); addPage(schemaSelectionPage); outputFileSelectionPage = new OutputFileSelectionPage(); addPage(outputFileSelectionPage); } @Override public void init(IWorkbench workbench, IStructuredSelection selection) { this.selection = selection; } @Override public boolean performFinish() { Schema schema = schemaSelectionPage.getSchema(); File file = outputFileSelectionPage.getFile(); if (file.exists()) { String title = "Overwrite file ?"; String message = "File '" + file.getAbsolutePath() + "' exists. Do you want to overwrite it ?"; String[] buttons = { "Yes", "No" }; MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttons, 1); if (dialog.open() == 1) { return false; } } // generate the schema syntax (no busy cursor needed since this is lightning fast) try { SchemaTemplate template = new SchemaTemplate(); List<Object> args = new ArrayList<Object>(); args.add(schema); args.add(Boolean.TRUE); // full syntax String syntax = template.generate(args); // remove trailing spaces... PrintWriter out = new PrintWriter(new FileWriter(file)); BufferedReader in = new BufferedReader(new StringReader(syntax)); for (String line = in.readLine(); line != null; line = in.readLine()) { out.println(rtrim(line)); } out.flush(); out.close(); in.close(); } catch (Throwable t) { String title = "Error"; String p = t.getMessage() != null ? " (" + t.getMessage() + ")": ""; String message = "An error occurred: " + t.getClass().getSimpleName() + p + ". See log."; String[] buttons = { "OK" }; MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttons, 1); dialog.open(); return false; } // open the generated syntax file in a text editor: try { // replace backward slashes into forward ones... StringBuilder p = new StringBuilder(file.getAbsolutePath()); for (int i = 0; i < p.length(); i++) { if (p.charAt(i) == '\\') { p.setCharAt(i, '/'); } } - URI uri = new URI("file:///" + p.toString()); - IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), + URI uri = new URI("file", p.toString(), null); // make sure the file name is encoded + IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), uri, "org.eclipse.ui.DefaultTextEditor", true); } catch (Throwable t) { // something went wrong while opening the file in a text editor, provide the user // with some feedback... MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", "Cannot open syntax file '" + file.getAbsolutePath() + "'."); // and print a stack trace... t.printStackTrace(); } return true; } }
true
true
public boolean performFinish() { Schema schema = schemaSelectionPage.getSchema(); File file = outputFileSelectionPage.getFile(); if (file.exists()) { String title = "Overwrite file ?"; String message = "File '" + file.getAbsolutePath() + "' exists. Do you want to overwrite it ?"; String[] buttons = { "Yes", "No" }; MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttons, 1); if (dialog.open() == 1) { return false; } } // generate the schema syntax (no busy cursor needed since this is lightning fast) try { SchemaTemplate template = new SchemaTemplate(); List<Object> args = new ArrayList<Object>(); args.add(schema); args.add(Boolean.TRUE); // full syntax String syntax = template.generate(args); // remove trailing spaces... PrintWriter out = new PrintWriter(new FileWriter(file)); BufferedReader in = new BufferedReader(new StringReader(syntax)); for (String line = in.readLine(); line != null; line = in.readLine()) { out.println(rtrim(line)); } out.flush(); out.close(); in.close(); } catch (Throwable t) { String title = "Error"; String p = t.getMessage() != null ? " (" + t.getMessage() + ")": ""; String message = "An error occurred: " + t.getClass().getSimpleName() + p + ". See log."; String[] buttons = { "OK" }; MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttons, 1); dialog.open(); return false; } // open the generated syntax file in a text editor: try { // replace backward slashes into forward ones... StringBuilder p = new StringBuilder(file.getAbsolutePath()); for (int i = 0; i < p.length(); i++) { if (p.charAt(i) == '\\') { p.setCharAt(i, '/'); } } URI uri = new URI("file:///" + p.toString()); IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), uri, "org.eclipse.ui.DefaultTextEditor", true); } catch (Throwable t) { // something went wrong while opening the file in a text editor, provide the user // with some feedback... MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", "Cannot open syntax file '" + file.getAbsolutePath() + "'."); // and print a stack trace... t.printStackTrace(); } return true; }
public boolean performFinish() { Schema schema = schemaSelectionPage.getSchema(); File file = outputFileSelectionPage.getFile(); if (file.exists()) { String title = "Overwrite file ?"; String message = "File '" + file.getAbsolutePath() + "' exists. Do you want to overwrite it ?"; String[] buttons = { "Yes", "No" }; MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttons, 1); if (dialog.open() == 1) { return false; } } // generate the schema syntax (no busy cursor needed since this is lightning fast) try { SchemaTemplate template = new SchemaTemplate(); List<Object> args = new ArrayList<Object>(); args.add(schema); args.add(Boolean.TRUE); // full syntax String syntax = template.generate(args); // remove trailing spaces... PrintWriter out = new PrintWriter(new FileWriter(file)); BufferedReader in = new BufferedReader(new StringReader(syntax)); for (String line = in.readLine(); line != null; line = in.readLine()) { out.println(rtrim(line)); } out.flush(); out.close(); in.close(); } catch (Throwable t) { String title = "Error"; String p = t.getMessage() != null ? " (" + t.getMessage() + ")": ""; String message = "An error occurred: " + t.getClass().getSimpleName() + p + ". See log."; String[] buttons = { "OK" }; MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttons, 1); dialog.open(); return false; } // open the generated syntax file in a text editor: try { // replace backward slashes into forward ones... StringBuilder p = new StringBuilder(file.getAbsolutePath()); for (int i = 0; i < p.length(); i++) { if (p.charAt(i) == '\\') { p.setCharAt(i, '/'); } } URI uri = new URI("file", p.toString(), null); // make sure the file name is encoded IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), uri, "org.eclipse.ui.DefaultTextEditor", true); } catch (Throwable t) { // something went wrong while opening the file in a text editor, provide the user // with some feedback... MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", "Cannot open syntax file '" + file.getAbsolutePath() + "'."); // and print a stack trace... t.printStackTrace(); } return true; }
diff --git a/src/assemblernator/LinkerModule.java b/src/assemblernator/LinkerModule.java index 469bda1..760a613 100644 --- a/src/assemblernator/LinkerModule.java +++ b/src/assemblernator/LinkerModule.java @@ -1,527 +1,527 @@ package assemblernator; import static assemblernator.ErrorReporting.makeError; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import assemblernator.ErrorReporting.ErrorHandler; import simulanator.ScanWrap; /** * * @author Eric * @date May 12, 2012; 3:59:15 PM */ public class LinkerModule implements Comparable<LinkerModule>{ /** Contains all the link records. */ public Map<String, Integer> linkRecord = new HashMap<String, Integer>(); /** Contains all the mod and text records. */ public List<TextModRecord> textMod = new ArrayList<TextModRecord>(); /**Contains all the errors. */ public List<TextRecord> errorText = new ArrayList<TextRecord>(); /**Header record string */ String headerRecord = ""; /**End record string */ String endRecord = ""; /**Link record String */ public String linkerRecord = ""; /** Name of program. */ public String progName; /** Program load address. */ public int loadAddr; /** Length of program. */ public int prgTotalLen; /** Start address of the program */ public int execStart; /** Date the object file was made */ public String date; /** Version that was used to make outputfile */ public int version; /** Total number of records */ public int endRec; /** Total number of link records */ public int endLink; /** Total number of text records */ public int endText; /** Total number of mod records */ public int endMod; /** the offset amount from program address. */ public int offset; /** Success failure boolean */ public boolean success = false; /** End reached */ public boolean done = true; /** * * @author Eric * @date May 20, 2012; 11:42:52 PM */ public static class TextModRecord { /**Text Records*/ public TextRecord text = new TextRecord(); /**Mod Records*/ public List<ModRecord> mods = new ArrayList<ModRecord>(); } /** * @author Eric * @date May 13, 2012; 6:07:31 PM */ public static class TextRecord { /** Program assigned LC for text record */ public int assignedLC; /** Assembled instruction */ public String instrData; /** Flag for high order bits */ public char flagHigh; /** Flag for low order bits */ public char flagLow; /** Number of modifications for high order bits */ public int modHigh; /** Number of modifications for low order bits */ public int modLow; /** Text record String */ public String textRecord = ""; /** Mod record String */ public String modRecord = ""; } /** * @author Eric * @date May 13, 2012; 6:07:53 PM */ public static class ModRecord { /** 4 hex nybbles */ public int hex; /** H, L, or S */ public char HLS; /** The middle of modifications records*/ public List<MiddleMod> midMod = new ArrayList<MiddleMod>(); } /** * @author Eric * @date May 17, 2012; 5:50:57 PM */ public static class MiddleMod { /** Plus or minus sign */ public char plusMin; /** Flag A or E or N */ public char addrType; /** The linkers label for mods */ public String linkerLabel; } /** * * @param in * the outputFile containing all the records * @param error errorhandler for constructor */ public LinkerModule(InputStream in, ErrorHandler error) { // scan wrap Scanner read = new Scanner(in); ScanWrap reader = new ScanWrap(read, error); //String used for name String ender = ""; String temp = ""; String errorMessage = ""; //Number of records int mod = 0; int link = 0; int text = 0; //value checking boolean isValid = true; boolean add = true; //checks for an H String check = reader.readString(ScanWrap.notcolon, "loaderNoHeader"); if (!reader.go("disreguard")) return; //Runs through header record if (check.equalsIgnoreCase("H")) { this.progName = reader.readString(ScanWrap.notcolon, "loaderNoName"); if (!reader.go("disreguard")) return; this.headerRecord = "H:" + this.progName+ ":"; this.loadAddr = reader.readInt(ScanWrap.hex4, "loaderHNoAddr", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.loadAddr); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.loadAddr+ ":"; this.prgTotalLen = reader .readInt(ScanWrap.hex4, "loaderHNoPrL", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.prgTotalLen); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.prgTotalLen + ":"; this.execStart = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.execStart); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.execStart+ ":"; this.date = reader.readString(ScanWrap.datep, "loaderHNoDate"); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +this.date+ ":"; this.version = reader.readInt(ScanWrap.dec4, "loaderHNoVer", 10); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +this.version+ ":"; temp = reader.readString(ScanWrap.notcolon, "loaderHNoLLMM"); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +temp+ ":"; // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); if (!reader.go("disreguard")) return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); this.headerRecord = this.headerRecord + ":" + ender + ":"; } }else{ error.reportError(makeError("loaderNoHeader"),0,0); return; } //checks for L or T record check = reader.readString(ScanWrap.notcolon, ""); if (!reader.go("disreguard")) return; //loops to get all the L and T records from object file while (check.equals("L") || check.equals("T")) { TextModRecord theRecordsForTextMod = new TextModRecord(); String entryLabel = ""; int entryAddr = 0; //gets all information from linker record if (check.equals("L")) { link++; entryLabel = reader.readString(ScanWrap.notcolon, ""); if (!reader.go("disreguard")) return; this.linkerRecord = this.linkerRecord + ":" + "L:" + entryLabel + ":"; entryAddr = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(entryAddr); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.linkerRecord = this.linkerRecord + ":"+ entryAddr + ":"; // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); this.linkerRecord = this.linkerRecord + ":"+ ender + "\nLabel does not match Program Name \n"; }else{ this.linkerRecord = this.linkerRecord + ":"+ ender + "\n"; } linkRecord.put(entryLabel, entryAddr); check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) return; //gets all information out of Text record } else if (check.equals("T")) { text++; theRecordsForTextMod.text.assignedLC = reader.readInt(ScanWrap.hex4, "textLC", 16); theRecordsForTextMod.text.textRecord = "T:" + theRecordsForTextMod.text.assignedLC + ":"; if (!reader.go("disreguard")){ errorMessage = "800: Text record missing valid program assigned location."; add = false; } //error checking isValid = OperandChecker.isValidMem(theRecordsForTextMod.text.assignedLC); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; add = false; } theRecordsForTextMod.text.instrData = reader.readString(ScanWrap.notcolon, "textData"); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.instrData+ ":"; if (!reader.go("disreguard")) { errorMessage = "801: Text record missing valid assembled instruction/data."; add = false; } theRecordsForTextMod.text.flagHigh = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.flagHigh + ":"; if (!reader.go("disreguard")) { errorMessage = "802: Text record missing valid status flag."; add = false; } if(!(theRecordsForTextMod.text.flagHigh == 'A' || theRecordsForTextMod.text.flagHigh == 'R' || theRecordsForTextMod.text.flagHigh == 'E' || theRecordsForTextMod.text.flagHigh == 'C')){ errorMessage = "802: Text record missing valid status flag."; add = false; } theRecordsForTextMod.text.flagLow = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.flagLow + ":"; if (!reader.go("disreguard")) { errorMessage = "802: Text record missing valid status flag."; add = false; } if(!(theRecordsForTextMod.text.flagLow == 'A' || theRecordsForTextMod.text.flagLow == 'R' || theRecordsForTextMod.text.flagLow == 'E' || theRecordsForTextMod.text.flagLow == 'C')){ errorMessage = "802: Text record missing valid status flag."; add = false; } theRecordsForTextMod.text.modHigh = reader.readInt(ScanWrap.notcolon, "textMod", 16); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.modHigh + ":"; if (!reader.go("disreguard")) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } //check for mod high if(theRecordsForTextMod.text.modHigh>16 || theRecordsForTextMod.text.modHigh<0) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } theRecordsForTextMod.text.modLow = reader.readInt(ScanWrap.notcolon, "textMod", 16); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.modLow + ":"; if (!reader.go("disreguard")) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } //check for mod low if(theRecordsForTextMod.text.modLow>16 || theRecordsForTextMod.text.modLow<0) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + ender + ":\n" + errorMessage; errorMessage = ""; // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) return; //gets all mod records for a text record while (check.equals("M")) { ModRecord modification = new ModRecord(); mod++; modification.hex = reader.readInt(ScanWrap.hex4, "modHex", 16); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord + "M:" + modification.hex + ":"; if (!reader.go("disreguard")) { errorMessage = "804: Modification record missing 4 hex nybbles."; add = false; } //error checking isValid = OperandChecker.isValidMem(modification.hex); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; add = false; } boolean run = true; String loop = ""; boolean firstRun = true; while (run) { MiddleMod midtemp = new MiddleMod(); if(firstRun){ midtemp.plusMin = reader.readString(ScanWrap.notcolon, "modPm").charAt(0); firstRun=false; }else{ midtemp.plusMin = loop.charAt(0); } theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.plusMin + ":"; if (!reader.go("disreguard")) { errorMessage = "805: Modification record missing plus or minus sign."; add = false; } //error checking isValid = OperandChecker.isValidPlusMin(midtemp.plusMin); if(!isValid){ errorMessage = "812: Modification records must contain plus or minus sign."; add = false; } midtemp.addrType = reader.readString(ScanWrap.notcolon, "modFlag").charAt(0); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.addrType + ":"; if (!reader.go("disreguard")) { errorMessage = "806: Modification record missing correct flag R, E, or N."; add = false; } if(!(midtemp.addrType == 'E' || midtemp.addrType == 'R' || midtemp.addrType == 'N')){ errorMessage = "806: Modification record missing correct flag R, E, or N."; add = false; } midtemp.linkerLabel = reader.readString( ScanWrap.notcolon, "modLink"); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.linkerLabel + ":"; if (!reader.go("disreguard")) { errorMessage = "807: Modification record missing valid label for address."; add = false; } loop = reader.readString(ScanWrap.notcolon, "modHLS"); if (!reader.go("disreguard")) { errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } if (loop.equals("")) { run = false; } modification.midMod.add(midtemp); } loop = reader.readString(ScanWrap.notcolon, "modHLS"); if (!reader.go("disreguard")) { errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } modification.HLS = loop.charAt(0); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ modification.HLS + ":"; if(!(modification.HLS == 'H' || modification.HLS == 'L' || modification.HLS == 'S')){ errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ ender + ":\n" + errorMessage; // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } theRecordsForTextMod.mods.add(modification); check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) { errorMessage = "809: Invalid Record. Records must start with valid record character."; add = false; } }// end of mod record if(add){ textMod.add(theRecordsForTextMod); }else{ errorText.add(theRecordsForTextMod.text); add = true; } }// end of text record }//end of while loop checking for linking records and text records //checks for an end record if (check.equals("E")) { this.endRec = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = "E:" + this.endRec + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endRec); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endLink = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endLink + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endLink); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endText = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endText + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endText); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endMod = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endMod + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endMod); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095.";; } ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); this.endRecord = this.endRecord + ":" + ender +":\n" + errorMessage; //error checking - if (!reader.go("disreguard")) - return; +// if (!reader.go("disreguard")) +// return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } }else{ error.reportError(makeError("loaderNoEnd"),0,0); return; } //warnings for amount of mod text and link records if(link != this.endLink){ error.reportWarning(makeError("linkMatch"), 0, 0); }else if(text != this.endText){ error.reportWarning(makeError("textMatch"), 0, 0); }else if(mod != this.endMod){ error.reportWarning(makeError("modMatch"), 0, 0); }else if((link+text+mod+2) != this.endRec){ error.reportWarning(makeError("totalMatch"), 0, 0); } //program ran successful. Checks for more in file this.success = true; if (read.hasNext()) { this.done = false; } } /** * Compares loadAddr of the LinkerModules */ @Override public int compareTo(LinkerModule cmp) { if(this.loadAddr > cmp.loadAddr){ return 1; }else if(this.loadAddr < cmp.loadAddr){ return -1; }else{ return 0; } } }
true
true
public LinkerModule(InputStream in, ErrorHandler error) { // scan wrap Scanner read = new Scanner(in); ScanWrap reader = new ScanWrap(read, error); //String used for name String ender = ""; String temp = ""; String errorMessage = ""; //Number of records int mod = 0; int link = 0; int text = 0; //value checking boolean isValid = true; boolean add = true; //checks for an H String check = reader.readString(ScanWrap.notcolon, "loaderNoHeader"); if (!reader.go("disreguard")) return; //Runs through header record if (check.equalsIgnoreCase("H")) { this.progName = reader.readString(ScanWrap.notcolon, "loaderNoName"); if (!reader.go("disreguard")) return; this.headerRecord = "H:" + this.progName+ ":"; this.loadAddr = reader.readInt(ScanWrap.hex4, "loaderHNoAddr", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.loadAddr); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.loadAddr+ ":"; this.prgTotalLen = reader .readInt(ScanWrap.hex4, "loaderHNoPrL", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.prgTotalLen); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.prgTotalLen + ":"; this.execStart = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.execStart); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.execStart+ ":"; this.date = reader.readString(ScanWrap.datep, "loaderHNoDate"); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +this.date+ ":"; this.version = reader.readInt(ScanWrap.dec4, "loaderHNoVer", 10); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +this.version+ ":"; temp = reader.readString(ScanWrap.notcolon, "loaderHNoLLMM"); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +temp+ ":"; // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); if (!reader.go("disreguard")) return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); this.headerRecord = this.headerRecord + ":" + ender + ":"; } }else{ error.reportError(makeError("loaderNoHeader"),0,0); return; } //checks for L or T record check = reader.readString(ScanWrap.notcolon, ""); if (!reader.go("disreguard")) return; //loops to get all the L and T records from object file while (check.equals("L") || check.equals("T")) { TextModRecord theRecordsForTextMod = new TextModRecord(); String entryLabel = ""; int entryAddr = 0; //gets all information from linker record if (check.equals("L")) { link++; entryLabel = reader.readString(ScanWrap.notcolon, ""); if (!reader.go("disreguard")) return; this.linkerRecord = this.linkerRecord + ":" + "L:" + entryLabel + ":"; entryAddr = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(entryAddr); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.linkerRecord = this.linkerRecord + ":"+ entryAddr + ":"; // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); this.linkerRecord = this.linkerRecord + ":"+ ender + "\nLabel does not match Program Name \n"; }else{ this.linkerRecord = this.linkerRecord + ":"+ ender + "\n"; } linkRecord.put(entryLabel, entryAddr); check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) return; //gets all information out of Text record } else if (check.equals("T")) { text++; theRecordsForTextMod.text.assignedLC = reader.readInt(ScanWrap.hex4, "textLC", 16); theRecordsForTextMod.text.textRecord = "T:" + theRecordsForTextMod.text.assignedLC + ":"; if (!reader.go("disreguard")){ errorMessage = "800: Text record missing valid program assigned location."; add = false; } //error checking isValid = OperandChecker.isValidMem(theRecordsForTextMod.text.assignedLC); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; add = false; } theRecordsForTextMod.text.instrData = reader.readString(ScanWrap.notcolon, "textData"); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.instrData+ ":"; if (!reader.go("disreguard")) { errorMessage = "801: Text record missing valid assembled instruction/data."; add = false; } theRecordsForTextMod.text.flagHigh = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.flagHigh + ":"; if (!reader.go("disreguard")) { errorMessage = "802: Text record missing valid status flag."; add = false; } if(!(theRecordsForTextMod.text.flagHigh == 'A' || theRecordsForTextMod.text.flagHigh == 'R' || theRecordsForTextMod.text.flagHigh == 'E' || theRecordsForTextMod.text.flagHigh == 'C')){ errorMessage = "802: Text record missing valid status flag."; add = false; } theRecordsForTextMod.text.flagLow = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.flagLow + ":"; if (!reader.go("disreguard")) { errorMessage = "802: Text record missing valid status flag."; add = false; } if(!(theRecordsForTextMod.text.flagLow == 'A' || theRecordsForTextMod.text.flagLow == 'R' || theRecordsForTextMod.text.flagLow == 'E' || theRecordsForTextMod.text.flagLow == 'C')){ errorMessage = "802: Text record missing valid status flag."; add = false; } theRecordsForTextMod.text.modHigh = reader.readInt(ScanWrap.notcolon, "textMod", 16); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.modHigh + ":"; if (!reader.go("disreguard")) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } //check for mod high if(theRecordsForTextMod.text.modHigh>16 || theRecordsForTextMod.text.modHigh<0) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } theRecordsForTextMod.text.modLow = reader.readInt(ScanWrap.notcolon, "textMod", 16); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.modLow + ":"; if (!reader.go("disreguard")) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } //check for mod low if(theRecordsForTextMod.text.modLow>16 || theRecordsForTextMod.text.modLow<0) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + ender + ":\n" + errorMessage; errorMessage = ""; // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) return; //gets all mod records for a text record while (check.equals("M")) { ModRecord modification = new ModRecord(); mod++; modification.hex = reader.readInt(ScanWrap.hex4, "modHex", 16); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord + "M:" + modification.hex + ":"; if (!reader.go("disreguard")) { errorMessage = "804: Modification record missing 4 hex nybbles."; add = false; } //error checking isValid = OperandChecker.isValidMem(modification.hex); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; add = false; } boolean run = true; String loop = ""; boolean firstRun = true; while (run) { MiddleMod midtemp = new MiddleMod(); if(firstRun){ midtemp.plusMin = reader.readString(ScanWrap.notcolon, "modPm").charAt(0); firstRun=false; }else{ midtemp.plusMin = loop.charAt(0); } theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.plusMin + ":"; if (!reader.go("disreguard")) { errorMessage = "805: Modification record missing plus or minus sign."; add = false; } //error checking isValid = OperandChecker.isValidPlusMin(midtemp.plusMin); if(!isValid){ errorMessage = "812: Modification records must contain plus or minus sign."; add = false; } midtemp.addrType = reader.readString(ScanWrap.notcolon, "modFlag").charAt(0); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.addrType + ":"; if (!reader.go("disreguard")) { errorMessage = "806: Modification record missing correct flag R, E, or N."; add = false; } if(!(midtemp.addrType == 'E' || midtemp.addrType == 'R' || midtemp.addrType == 'N')){ errorMessage = "806: Modification record missing correct flag R, E, or N."; add = false; } midtemp.linkerLabel = reader.readString( ScanWrap.notcolon, "modLink"); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.linkerLabel + ":"; if (!reader.go("disreguard")) { errorMessage = "807: Modification record missing valid label for address."; add = false; } loop = reader.readString(ScanWrap.notcolon, "modHLS"); if (!reader.go("disreguard")) { errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } if (loop.equals("")) { run = false; } modification.midMod.add(midtemp); } loop = reader.readString(ScanWrap.notcolon, "modHLS"); if (!reader.go("disreguard")) { errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } modification.HLS = loop.charAt(0); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ modification.HLS + ":"; if(!(modification.HLS == 'H' || modification.HLS == 'L' || modification.HLS == 'S')){ errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ ender + ":\n" + errorMessage; // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } theRecordsForTextMod.mods.add(modification); check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) { errorMessage = "809: Invalid Record. Records must start with valid record character."; add = false; } }// end of mod record if(add){ textMod.add(theRecordsForTextMod); }else{ errorText.add(theRecordsForTextMod.text); add = true; } }// end of text record }//end of while loop checking for linking records and text records //checks for an end record if (check.equals("E")) { this.endRec = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = "E:" + this.endRec + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endRec); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endLink = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endLink + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endLink); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endText = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endText + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endText); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endMod = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endMod + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endMod); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095.";; } ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); this.endRecord = this.endRecord + ":" + ender +":\n" + errorMessage; //error checking if (!reader.go("disreguard")) return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } }else{ error.reportError(makeError("loaderNoEnd"),0,0); return; } //warnings for amount of mod text and link records if(link != this.endLink){ error.reportWarning(makeError("linkMatch"), 0, 0); }else if(text != this.endText){ error.reportWarning(makeError("textMatch"), 0, 0); }else if(mod != this.endMod){ error.reportWarning(makeError("modMatch"), 0, 0); }else if((link+text+mod+2) != this.endRec){ error.reportWarning(makeError("totalMatch"), 0, 0); } //program ran successful. Checks for more in file this.success = true; if (read.hasNext()) { this.done = false; } }
public LinkerModule(InputStream in, ErrorHandler error) { // scan wrap Scanner read = new Scanner(in); ScanWrap reader = new ScanWrap(read, error); //String used for name String ender = ""; String temp = ""; String errorMessage = ""; //Number of records int mod = 0; int link = 0; int text = 0; //value checking boolean isValid = true; boolean add = true; //checks for an H String check = reader.readString(ScanWrap.notcolon, "loaderNoHeader"); if (!reader.go("disreguard")) return; //Runs through header record if (check.equalsIgnoreCase("H")) { this.progName = reader.readString(ScanWrap.notcolon, "loaderNoName"); if (!reader.go("disreguard")) return; this.headerRecord = "H:" + this.progName+ ":"; this.loadAddr = reader.readInt(ScanWrap.hex4, "loaderHNoAddr", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.loadAddr); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.loadAddr+ ":"; this.prgTotalLen = reader .readInt(ScanWrap.hex4, "loaderHNoPrL", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.prgTotalLen); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.prgTotalLen + ":"; this.execStart = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(this.execStart); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.headerRecord = this.headerRecord + ":" +this.execStart+ ":"; this.date = reader.readString(ScanWrap.datep, "loaderHNoDate"); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +this.date+ ":"; this.version = reader.readInt(ScanWrap.dec4, "loaderHNoVer", 10); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +this.version+ ":"; temp = reader.readString(ScanWrap.notcolon, "loaderHNoLLMM"); if (!reader.go("disreguard")) return; this.headerRecord = this.headerRecord + ":" +temp+ ":"; // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); if (!reader.go("disreguard")) return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); this.headerRecord = this.headerRecord + ":" + ender + ":"; } }else{ error.reportError(makeError("loaderNoHeader"),0,0); return; } //checks for L or T record check = reader.readString(ScanWrap.notcolon, ""); if (!reader.go("disreguard")) return; //loops to get all the L and T records from object file while (check.equals("L") || check.equals("T")) { TextModRecord theRecordsForTextMod = new TextModRecord(); String entryLabel = ""; int entryAddr = 0; //gets all information from linker record if (check.equals("L")) { link++; entryLabel = reader.readString(ScanWrap.notcolon, ""); if (!reader.go("disreguard")) return; this.linkerRecord = this.linkerRecord + ":" + "L:" + entryLabel + ":"; entryAddr = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16); if (!reader.go("disreguard")) return; //error checking isValid = OperandChecker.isValidMem(entryAddr); if(!isValid){ error.reportError(makeError("invalidValue"),0,0); return; } this.linkerRecord = this.linkerRecord + ":"+ entryAddr + ":"; // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); this.linkerRecord = this.linkerRecord + ":"+ ender + "\nLabel does not match Program Name \n"; }else{ this.linkerRecord = this.linkerRecord + ":"+ ender + "\n"; } linkRecord.put(entryLabel, entryAddr); check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) return; //gets all information out of Text record } else if (check.equals("T")) { text++; theRecordsForTextMod.text.assignedLC = reader.readInt(ScanWrap.hex4, "textLC", 16); theRecordsForTextMod.text.textRecord = "T:" + theRecordsForTextMod.text.assignedLC + ":"; if (!reader.go("disreguard")){ errorMessage = "800: Text record missing valid program assigned location."; add = false; } //error checking isValid = OperandChecker.isValidMem(theRecordsForTextMod.text.assignedLC); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; add = false; } theRecordsForTextMod.text.instrData = reader.readString(ScanWrap.notcolon, "textData"); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.instrData+ ":"; if (!reader.go("disreguard")) { errorMessage = "801: Text record missing valid assembled instruction/data."; add = false; } theRecordsForTextMod.text.flagHigh = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.flagHigh + ":"; if (!reader.go("disreguard")) { errorMessage = "802: Text record missing valid status flag."; add = false; } if(!(theRecordsForTextMod.text.flagHigh == 'A' || theRecordsForTextMod.text.flagHigh == 'R' || theRecordsForTextMod.text.flagHigh == 'E' || theRecordsForTextMod.text.flagHigh == 'C')){ errorMessage = "802: Text record missing valid status flag."; add = false; } theRecordsForTextMod.text.flagLow = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.flagLow + ":"; if (!reader.go("disreguard")) { errorMessage = "802: Text record missing valid status flag."; add = false; } if(!(theRecordsForTextMod.text.flagLow == 'A' || theRecordsForTextMod.text.flagLow == 'R' || theRecordsForTextMod.text.flagLow == 'E' || theRecordsForTextMod.text.flagLow == 'C')){ errorMessage = "802: Text record missing valid status flag."; add = false; } theRecordsForTextMod.text.modHigh = reader.readInt(ScanWrap.notcolon, "textMod", 16); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.modHigh + ":"; if (!reader.go("disreguard")) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } //check for mod high if(theRecordsForTextMod.text.modHigh>16 || theRecordsForTextMod.text.modHigh<0) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } theRecordsForTextMod.text.modLow = reader.readInt(ScanWrap.notcolon, "textMod", 16); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + theRecordsForTextMod.text.modLow + ":"; if (!reader.go("disreguard")) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } //check for mod low if(theRecordsForTextMod.text.modLow>16 || theRecordsForTextMod.text.modLow<0) { errorMessage = "803: Text record missing valid number of modifications."; add = false; } // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); theRecordsForTextMod.text.textRecord = theRecordsForTextMod.text.textRecord + ":" + ender + ":\n" + errorMessage; errorMessage = ""; // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) return; //gets all mod records for a text record while (check.equals("M")) { ModRecord modification = new ModRecord(); mod++; modification.hex = reader.readInt(ScanWrap.hex4, "modHex", 16); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord + "M:" + modification.hex + ":"; if (!reader.go("disreguard")) { errorMessage = "804: Modification record missing 4 hex nybbles."; add = false; } //error checking isValid = OperandChecker.isValidMem(modification.hex); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; add = false; } boolean run = true; String loop = ""; boolean firstRun = true; while (run) { MiddleMod midtemp = new MiddleMod(); if(firstRun){ midtemp.plusMin = reader.readString(ScanWrap.notcolon, "modPm").charAt(0); firstRun=false; }else{ midtemp.plusMin = loop.charAt(0); } theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.plusMin + ":"; if (!reader.go("disreguard")) { errorMessage = "805: Modification record missing plus or minus sign."; add = false; } //error checking isValid = OperandChecker.isValidPlusMin(midtemp.plusMin); if(!isValid){ errorMessage = "812: Modification records must contain plus or minus sign."; add = false; } midtemp.addrType = reader.readString(ScanWrap.notcolon, "modFlag").charAt(0); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.addrType + ":"; if (!reader.go("disreguard")) { errorMessage = "806: Modification record missing correct flag R, E, or N."; add = false; } if(!(midtemp.addrType == 'E' || midtemp.addrType == 'R' || midtemp.addrType == 'N')){ errorMessage = "806: Modification record missing correct flag R, E, or N."; add = false; } midtemp.linkerLabel = reader.readString( ScanWrap.notcolon, "modLink"); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ midtemp.linkerLabel + ":"; if (!reader.go("disreguard")) { errorMessage = "807: Modification record missing valid label for address."; add = false; } loop = reader.readString(ScanWrap.notcolon, "modHLS"); if (!reader.go("disreguard")) { errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } if (loop.equals("")) { run = false; } modification.midMod.add(midtemp); } loop = reader.readString(ScanWrap.notcolon, "modHLS"); if (!reader.go("disreguard")) { errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } modification.HLS = loop.charAt(0); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ modification.HLS + ":"; if(!(modification.HLS == 'H' || modification.HLS == 'L' || modification.HLS == 'S')){ errorMessage = "808: Modification record missing correct char H, L, or S."; add = false; } // some kind of error checking ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); theRecordsForTextMod.text.modRecord = theRecordsForTextMod.text.modRecord +":"+ ender + ":\n" + errorMessage; // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } theRecordsForTextMod.mods.add(modification); check = reader.readString(ScanWrap.notcolon, "invalidRecord"); if (!reader.go("disreguard")) { errorMessage = "809: Invalid Record. Records must start with valid record character."; add = false; } }// end of mod record if(add){ textMod.add(theRecordsForTextMod); }else{ errorText.add(theRecordsForTextMod.text); add = true; } }// end of text record }//end of while loop checking for linking records and text records //checks for an end record if (check.equals("E")) { this.endRec = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = "E:" + this.endRec + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endRec); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endLink = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endLink + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endLink); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endText = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endText + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endText); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; } this.endMod = reader.readInt(ScanWrap.hex4, "endRecords", 16); this.endRecord = this.endRecord + ":" + this.endMod + ":"; if (!reader.go("disreguard")) errorMessage = "811: Invalid value. Records values must be from 0 - 4095."; //error checking isValid = OperandChecker.isValidMem(this.endMod); if(!isValid){ errorMessage = "811: Invalid value. Records values must be from 0 - 4095.";; } ender = reader.readString(ScanWrap.notcolon, "loaderNoName"); this.endRecord = this.endRecord + ":" + ender +":\n" + errorMessage; //error checking // if (!reader.go("disreguard")) // return; if(!ender.equals(this.progName)){ error.reportWarning(makeError("noMatch"), 0, 0); } }else{ error.reportError(makeError("loaderNoEnd"),0,0); return; } //warnings for amount of mod text and link records if(link != this.endLink){ error.reportWarning(makeError("linkMatch"), 0, 0); }else if(text != this.endText){ error.reportWarning(makeError("textMatch"), 0, 0); }else if(mod != this.endMod){ error.reportWarning(makeError("modMatch"), 0, 0); }else if((link+text+mod+2) != this.endRec){ error.reportWarning(makeError("totalMatch"), 0, 0); } //program ran successful. Checks for more in file this.success = true; if (read.hasNext()) { this.done = false; } }
diff --git a/src/eu/cassandra/sim/Simulation.java b/src/eu/cassandra/sim/Simulation.java index d29480d..5777269 100644 --- a/src/eu/cassandra/sim/Simulation.java +++ b/src/eu/cassandra/sim/Simulation.java @@ -1,844 +1,844 @@ /* Copyright 2011-2013 The Cassandra Consortium (cassandra-fp7.eu) 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 eu.cassandra.sim; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Set; import java.util.Vector; import java.util.concurrent.PriorityBlockingQueue; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.ServletContext; import org.apache.log4j.Logger; import org.bson.types.ObjectId; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.util.JSON; import eu.cassandra.server.mongo.MongoActivityModels; import eu.cassandra.server.mongo.MongoDistributions; import eu.cassandra.server.mongo.MongoResults; import eu.cassandra.server.mongo.MongoRuns; import eu.cassandra.server.mongo.util.DBConn; import eu.cassandra.sim.entities.Entity; import eu.cassandra.sim.entities.appliances.Appliance; import eu.cassandra.sim.entities.appliances.ConsumptionModel; import eu.cassandra.sim.entities.external.ThermalModule; import eu.cassandra.sim.entities.installations.Installation; import eu.cassandra.sim.entities.people.Activity; import eu.cassandra.sim.entities.people.Person; import eu.cassandra.sim.math.Gaussian; import eu.cassandra.sim.math.GaussianMixtureModels; import eu.cassandra.sim.math.Histogram; import eu.cassandra.sim.math.ProbabilityDistribution; import eu.cassandra.sim.math.Uniform; import eu.cassandra.sim.utilities.Constants; import eu.cassandra.sim.utilities.ORNG; import eu.cassandra.sim.utilities.Utils; /** * The Simulation class can simulate up to 4085 years of simulation. * * @author Kyriakos C. Chatzidimitriou (kyrcha [at] iti [dot] gr) * */ public class Simulation implements Runnable { static Logger logger = Logger.getLogger(Simulation.class); private Vector<Installation> installations; private PriorityBlockingQueue<Event> queue; private int tick; private int endTick; private int mcruns; private double co2; private MongoResults m; private SimulationParams simulationWorld; private PricingPolicy pricing; private PricingPolicy baseline_pricing; private String scenario; private String dbname; private String runName; private String resources_path; private ORNG orng; public Collection<Installation> getInstallations () { return installations; } public Installation getInstallation (int index) { return installations.get(index); } public int getCurrentTick () { return tick; } public int getEndTick () { return endTick; } public Simulation(String ascenario, String adbname, String arunName, String aresources_path, int seed) { scenario = ascenario; dbname = adbname; runName = arunName; resources_path = aresources_path; m = new MongoResults(dbname); m.createIndexes(); if(seed > 0) { orng = new ORNG(seed); } else { orng = new ORNG(); } } public SimulationParams getSimulationWorld () { return simulationWorld; } public void run () { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); try { System.out.println("Run " + dbname + " started @ " + Calendar.getInstance().getTimeInMillis()); calculateExpectedPower(dbname); // System.out.println("EP calculated"); long startTime = System.currentTimeMillis(); int percentage = 0; int mccount = 0; double mcrunsRatio = 1.0/(double)mcruns; for(int i = 0; i < mcruns; i++) { tick = 0; double avgPPowerPerHour = 0; double avgQPowerPerHour = 0; double[] avgPPowerPerHourPerInst = new double[installations.size()]; double[] avgQPowerPerHourPerInst = new double[installations.size()]; double maxPower = 0; // double cycleMaxPower = 0; double avgPower = 0; double energy = 0; double energyOffpeak = 0; double cost = 0; // double billingCycleEnergy = 0; // double billingCycleEnergyOffpeak = 0; while (tick < endTick) { // If it is the beginning of the day create the events if (tick % Constants.MIN_IN_DAY == 0) { // System.out.println("Day " + ((tick / Constants.MIN_IN_DAY) + 1)); for (Installation installation: installations) { // System.out.println("Installation: " + installation.getName()); installation.updateDailySchedule(tick, queue, simulationWorld.getResponseType(), orng); } // System.out.println("Daily queue size: " + queue.size() + "(" + // simulationWorld.getSimCalendar().isWeekend(tick) + ")"); } Event top = queue.peek(); while (top != null && top.getTick() == tick) { Event e = queue.poll(); boolean applied = e.apply(); if(applied) { if(e.getAction() == Event.SWITCH_ON) { try { //m.addOpenTick(e.getAppliance().getId(), tick); } catch (Exception exc) { throw exc; } } else if(e.getAction() == Event.SWITCH_OFF){ //m.addCloseTick(e.getAppliance().getId(), tick); } } top = queue.peek(); } /* * Calculate the total power for this simulation step for all the * installations. */ float sumP = 0; float sumQ = 0; int counter = 0; for(Installation installation: installations) { installation.nextStep(tick); double p = installation.getCurrentPowerP(); double q = installation.getCurrentPowerQ(); // if(p> 0.001) System.out.println(p); installation.updateMaxPower(p); installation.updateAvgPower(p/endTick); if(installation.getPricing().isOffpeak(tick)) { installation.updateEnergyOffpeak(p); } else { installation.updateEnergy(p); } installation.updateAppliancesAndActivitiesConsumptions(tick, endTick); m.addTickResultForInstallation(tick, installation.getId(), p * mcrunsRatio, q * mcrunsRatio, MongoResults.COL_INSTRESULTS); sumP += p; sumQ += q; avgPPowerPerHour += p; avgQPowerPerHour += q; avgPPowerPerHourPerInst[counter] += p; avgQPowerPerHourPerInst[counter] += q; String name = installation.getName(); // logger.info("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + power); // System.out.println("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + p); if((tick + 1) % (Constants.MIN_IN_DAY * installation.getPricing().getBillingCycle()) == 0 || installation.getPricing().getType().equalsIgnoreCase("TOUPricing")) { installation.updateCost(tick); } counter++; } if(sumP > maxPower) maxPower = sumP; // if(sumP > cycleMaxPower) cycleMaxPower = sumP; avgPower += sumP/endTick; energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // if(pricing.isOffpeak(tick)) { // energyOffpeak += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } else { // energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } // if((tick + 1) % (Constants.MIN_IN_DAY * pricing.getBillingCycle()) == 0 || pricing.getType().equalsIgnoreCase("TOUPricing")) { // cost = totalInstCost(); //alternate method // billingCycleEnergy = totalInstEnergy(); // billingCycleEnergyOffpeak = totalInstOffpeak(); // cycleMaxPower = 0; // } m.addAggregatedTickResult(tick, sumP * mcrunsRatio, sumQ * mcrunsRatio, MongoResults.COL_AGGRRESULTS); tick++; if(tick % Constants.MIN_IN_HOUR == 0) { m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY); m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour) * mcrunsRatio, (avgQPowerPerHour) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY_EN); avgPPowerPerHour = 0; avgQPowerPerHour = 0; counter = 0; for(Installation installation: installations) { m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY); m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY_EN); avgPPowerPerHourPerInst[counter] = 0; avgQPowerPerHourPerInst[counter] = 0; counter++; } } mccount++; percentage = (int)(0.75 * mccount * 100.0 / (mcruns * endTick)); // System.out.println("Percentage: " + percentage + " - " + mccount); objRun.put("percentage", 25 + percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(Installation installation: installations) { installation.updateCost(tick); // update the rest of the energy m.addKPIs(installation.getId(), installation.getMaxPower() * mcrunsRatio, installation.getAvgPower() * mcrunsRatio, installation.getEnergy() * mcrunsRatio, installation.getCost() * mcrunsRatio, installation.getEnergy() * co2 * mcrunsRatio); installation.addAppliancesKPIs(m, mcrunsRatio, co2); installation.addActivitiesKPIs(m, mcrunsRatio, co2); } cost = totalInstCost(); m.addKPIs(MongoResults.AGGR, maxPower * mcrunsRatio, avgPower * mcrunsRatio, energy * mcrunsRatio, cost * mcrunsRatio, energy * co2 * mcrunsRatio); if(i+1 != mcruns) setup(true); } // Write installation results to csv file String filename = resources_path + "/csvs/" + runName + ".csv"; System.out.println(filename); File csvFile = new File(filename); FileWriter fw = new FileWriter(csvFile); String row = "tick"; for(Installation installation: installations) { row += "," + installation.getName() + "_p"; row += "," + installation.getName() + "_q"; } fw.write(row+"\n"); for(int i = 0; i < endTick; i++) { row = String.valueOf(i); for(Installation installation: installations) { DBObject tickResult = m.getTickResultForInstallation(i, installation.getId(), MongoResults.COL_INSTRESULTS); double p = ((Double)tickResult.get("p")).doubleValue(); double q = ((Double)tickResult.get("q")).doubleValue(); row += "," + p; row += "," + q; } fw.write(row+"\n"); } fw.flush(); fw.close(); // End of file writing // zip file // http://www.mkyong.com/java/how-to-compress-files-in-zip-format/ System.out.println("Zipping..."); byte[] buffer = new byte[1024]; - FileOutputStream fos = new FileOutputStream(runName + ".zip"); + FileOutputStream fos = new FileOutputStream(filename + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(runName + ".csv"); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(filename); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); fos.close(); csvFile.delete(); // End of zip file System.out.println("End of Zipping..."); long endTime = System.currentTimeMillis(); objRun.put("ended", endTime); System.out.println("Updating DB..."); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); System.out.println("End of Updating DB..."); logger.info("Time elapsed for Run " + dbname + ": " + ((endTime - startTime)/(1000.0 * 60)) + " mins"); logger.info("Run " + dbname + " ended @ " + Calendar.getInstance().toString()); } catch(Exception e) { e.printStackTrace(); System.out.println(Utils.stackTraceToString(e.getStackTrace())); // Change the run object in the db to reflect the exception if(objRun != null) { objRun.put("percentage", -1); objRun.put("state", e.getMessage()); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } } } private double totalInstCost() { double cost = 0; for(Installation installation: installations) { cost += installation.getCost(); } return cost; } public void setup(boolean jump) throws Exception { installations = new Vector<Installation>(); /* TODO Change the Simulation Calendar initialization */ logger.info("Simulation setup started: " + dbname); DBObject jsonScenario = (DBObject) JSON.parse(scenario); DBObject scenarioDoc = (DBObject) jsonScenario.get("scenario"); DBObject simParamsDoc = (DBObject) jsonScenario.get("sim_params"); simulationWorld = new SimulationParams(simParamsDoc); // get from scenario for each installation otherwise fallback DBObject pricingDoc = (DBObject) jsonScenario.get("pricing"); DBObject basePricingDoc = (DBObject) jsonScenario.get("baseline_pricing"); if(pricingDoc != null) { pricing = new PricingPolicy(pricingDoc); } else { pricing = new PricingPolicy(); } if(basePricingDoc != null) { baseline_pricing = new PricingPolicy(basePricingDoc); } else { baseline_pricing = new PricingPolicy(); } int numOfDays = ((Integer)simParamsDoc.get("numberOfDays")).intValue(); endTick = Constants.MIN_IN_DAY * numOfDays; mcruns = ((Integer)simParamsDoc.get("mcruns")).intValue(); co2 = Utils.getDouble(simParamsDoc.get("co2")); // Check type of setup String setup = (String)scenarioDoc.get("setup"); if(setup.equalsIgnoreCase("static")) { staticSetup(jsonScenario); } else if(setup.equalsIgnoreCase("dynamic")) { dynamicSetup(jsonScenario, jump); } else { throw new Exception("Problem with setup property!!!"); } logger.info("Simulation setup finished: " + dbname); } public void staticSetup (DBObject jsonScenario) throws Exception { int numOfInstallations = ((Integer)jsonScenario.get("instcount")).intValue(); queue = new PriorityBlockingQueue<Event>(2 * numOfInstallations); for (int i = 1; i <= numOfInstallations; i++) { DBObject instDoc = (DBObject)jsonScenario.get("inst"+i); String id = ((ObjectId)instDoc.get("_id")).toString(); String name = (String)instDoc.get("name"); String description = (String)instDoc.get("description"); String type = (String)instDoc.get("type"); String clustername = (String)instDoc.get("cluster"); PricingPolicy instPricing = pricing; PricingPolicy instBaseline_pricing = baseline_pricing; if(jsonScenario.get("pricing-" + clustername + "-" + id) != null) { DBObject pricingDoc = (DBObject) jsonScenario.get("pricing-" + clustername + "-" + id); instPricing = new PricingPolicy(pricingDoc); } if(jsonScenario.get("baseline_pricing-" + clustername + "-" + id) != null) { DBObject basePricingDoc = (DBObject) jsonScenario.get("baseline_pricing-" + clustername + "-" + id); instBaseline_pricing = new PricingPolicy(basePricingDoc); } Installation inst = new Installation.Builder( id, name, description, type, clustername, instPricing, instBaseline_pricing).build(); // Thermal module if exists DBObject thermalDoc = (DBObject)instDoc.get("thermal"); if(thermalDoc != null && inst.getPricing().getType().equalsIgnoreCase("TOUPricing")) { ThermalModule tm = new ThermalModule(thermalDoc, inst.getPricing().getTOUArray()); inst.setThermalModule(tm); } int appcount = ((Integer)instDoc.get("appcount")).intValue(); // Create the appliances HashMap<String,Appliance> existing = new HashMap<String,Appliance>(); for (int j = 1; j <= appcount; j++) { DBObject applianceDoc = (DBObject)instDoc.get("app"+j); String appid = ((ObjectId)applianceDoc.get("_id")).toString(); String appname = (String)applianceDoc.get("name"); String appdescription = (String)applianceDoc.get("description"); String apptype = (String)applianceDoc.get("type"); double standy = Utils.getDouble(applianceDoc.get("standy_consumption")); boolean base = Utils.getBoolean(applianceDoc.get("base")); DBObject consModDoc = (DBObject)applianceDoc.get("consmod"); ConsumptionModel pconsmod = new ConsumptionModel(consModDoc.get("pmodel").toString(), "p"); ConsumptionModel qconsmod = new ConsumptionModel(consModDoc.get("qmodel").toString(), "q"); Appliance app = new Appliance.Builder( appid, appname, appdescription, apptype, inst, pconsmod, qconsmod, standy, base).build(orng); existing.put(appid, app); inst.addAppliance(app); } DBObject personDoc = (DBObject)instDoc.get("person1"); String personid = ((ObjectId)personDoc.get("_id")).toString(); String personName = (String)personDoc.get("name"); String personDescription = (String)personDoc.get("description"); String personType = (String)personDoc.get("type"); double awareness = Utils.getDouble(personDoc.get("awareness")); double sensitivity = Utils.getDouble(personDoc.get("sensitivity")); Person person = new Person.Builder( personid, personName, personDescription, personType, inst, awareness, sensitivity).build(); inst.addPerson(person); int actcount = ((Integer)personDoc.get("activitycount")).intValue(); for (int j = 1; j <= actcount; j++) { DBObject activityDoc = (DBObject)personDoc.get("activity"+j); String activityName = (String)activityDoc.get("name"); String activityType = (String)activityDoc.get("type"); String actid = ((ObjectId)activityDoc.get("_id")).toString(); int actmodcount = ((Integer)activityDoc.get("actmodcount")).intValue(); Activity act = new Activity.Builder(actid, activityName, "", activityType, simulationWorld).build(); ProbabilityDistribution startDist; ProbabilityDistribution durDist; ProbabilityDistribution timesDist; for (int k = 1; k <= actmodcount; k++) { DBObject actmodDoc = (DBObject)activityDoc.get("actmod"+k); String actmodName = (String)actmodDoc.get("name"); String actmodType = (String)actmodDoc.get("type"); String actmodDayType = (String)actmodDoc.get("day_type"); boolean shiftable = Utils.getBoolean(actmodDoc.get("shiftable")); boolean exclusive = Utils.getEquality(actmodDoc.get("config"), "exclusive", true); DBObject duration = (DBObject)actmodDoc.get("duration"); durDist = json2dist(duration, "duration"); DBObject start = (DBObject)actmodDoc.get("start"); startDist = json2dist(start, "start"); DBObject rep = (DBObject)actmodDoc.get("repetitions"); timesDist = json2dist(rep, "reps"); act.addDuration(actmodDayType, durDist); act.addStartTime(actmodDayType, startDist); act.addTimes(actmodDayType, timesDist); act.addShiftable(actmodDayType, shiftable); act.addConfig(actmodDayType, exclusive); // add appliances BasicDBList containsAppliances = (BasicDBList)actmodDoc.get("containsAppliances"); for(int l = 0; l < containsAppliances.size(); l++) { String containAppId = (String)containsAppliances.get(l); Appliance app = existing.get(containAppId); act.addAppliance(actmodDayType,app,1.0/containsAppliances.size()); } } person.addActivity(act); } installations.add(inst); } } private void calculateExpectedPower(String dbname) { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); System.out.println("Start exp power calc."); int percentage = 0; double[] aggr_exp = new double[Constants.MIN_IN_DAY]; int count = 0; for(Installation installation: installations) { double[] inst_exp = new double[Constants.MIN_IN_DAY]; Person person = installation.getPersons().get(0); for(Activity activity: person.getActivities()) { System.out.println("CEP: " + activity.getName()); double[] act_exp = activity.calcExpPower(); // NumberFormat nf = new DecimalFormat("0.#"); // for (double c : act_exp) { // System.out.print(nf.format(c) + " "); // } // System.out.println(" "); for(int i = 0; i < act_exp.length; i++) { inst_exp[i] += act_exp[i]; m.addExpectedPowerTick(i, activity.getId(), act_exp[i], 0, MongoResults.COL_ACTRESULTS_EXP); } } // For every appliance that is a base load find mean value and add for(Appliance appliance: installation.getAppliances()) { if(appliance.isBase()) { double mean = 0; Double[] cons = appliance.getActiveConsumption(); for(int i = 0; i < cons.length; i++) { mean += cons[i].doubleValue(); } mean /= cons.length; for(int i = 0; i < inst_exp.length; i++) { inst_exp[i] += mean; } } } for(int i = 0; i < inst_exp.length; i++) { aggr_exp[i] += inst_exp[i]; m.addExpectedPowerTick(i, installation.getId(), inst_exp[i], 0, MongoResults.COL_INSTRESULTS_EXP); } count++; percentage = (int)(0.25 * count * 100.0) / (installations.size()); objRun.put("percentage", percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(int i = 0; i < aggr_exp.length; i++) { m.addExpectedPowerTick(i, "aggr", aggr_exp[i], 0, MongoResults.COL_AGGRRESULTS_EXP); System.out.println(aggr_exp[i]); } System.out.println("End exp power calc."); } private String addEntity(Entity e, boolean jump) { BasicDBObject obj = e.toDBObject(); if(!jump) DBConn.getConn(dbname).getCollection(e.getCollection()).insert(obj); ObjectId objId = (ObjectId)obj.get("_id"); return objId.toString(); } public void dynamicSetup(DBObject jsonScenario, boolean jump) throws Exception { DBObject scenario = (DBObject)jsonScenario.get("scenario"); String scenario_id = ((ObjectId)scenario.get("_id")).toString(); DBObject demog = (DBObject)jsonScenario.get("demog"); BasicDBList generators = (BasicDBList) demog.get("generators"); // Initialize simulation variables int numOfInstallations = Utils.getInt(demog.get("numberOfEntities")); //System.out.println(numOfInstallations+""); queue = new PriorityBlockingQueue<Event>(2 * numOfInstallations); for (int i = 1; i <= numOfInstallations; i++) { DBObject instDoc = (DBObject)jsonScenario.get("inst"+1); String id = i+""; String name = ((String)instDoc.get("name")) + i; String description = (String)instDoc.get("description"); String type = (String)instDoc.get("type"); Installation inst = new Installation.Builder( id, name, description, type, null, pricing, baseline_pricing).build(); inst.setParentId(scenario_id); String inst_id = addEntity(inst, jump); inst.setId(inst_id); int appcount = Utils.getInt(instDoc.get("appcount")); // Create the appliances HashMap<String,Appliance> existing = new HashMap<String,Appliance>(); for (int j = 1; j <= appcount; j++) { DBObject applianceDoc = (DBObject)instDoc.get("app"+j); String appid = ((ObjectId)applianceDoc.get("_id")).toString(); String appname = (String)applianceDoc.get("name"); String appdescription = (String)applianceDoc.get("description"); String apptype = (String)applianceDoc.get("type"); double standy = Utils.getDouble(applianceDoc.get("standy_consumption")); boolean base = Utils.getBoolean(applianceDoc.get("base")); DBObject consModDoc = (DBObject)applianceDoc.get("consmod"); ConsumptionModel pconsmod = new ConsumptionModel(consModDoc.get("pmodel").toString(), "p"); ConsumptionModel qconsmod = new ConsumptionModel(consModDoc.get("qmodel").toString(), "q"); Appliance app = new Appliance.Builder( appid, appname, appdescription, apptype, inst, pconsmod, qconsmod, standy, base).build(orng); existing.put(appid, app); } HashMap<String,Double> gens = new HashMap<String,Double>(); for(int k = 0; k < generators.size(); k++) { DBObject generator = (DBObject)generators.get(k); String entityId = (String)generator.get("entity_id"); double prob = Utils.getDouble(generator.get("probability")); gens.put(entityId, new Double(prob)); } Set<String> keys = existing.keySet(); for(String key : keys) { Double prob = gens.get(key); if(prob != null) { double probValue = prob.doubleValue(); if(orng.nextDouble() < probValue) { Appliance selectedApp = existing.get(key); selectedApp.setParentId(inst.getId()); String app_id = addEntity(selectedApp, jump); selectedApp.setId(app_id); inst.addAppliance(selectedApp); ConsumptionModel cm = selectedApp.getPConsumptionModel(); cm.setParentId(app_id); String cm_id = addEntity(cm, jump); cm.setId(cm_id); } } } int personcount = Utils.getInt(instDoc.get("personcount")); // Create the appliances HashMap<String,Person> existingPersons = new HashMap<String,Person>(); for (int j = 1; j <= personcount; j++) { DBObject personDoc = (DBObject)instDoc.get("person"+j); String personid = ((ObjectId)personDoc.get("_id")).toString(); String personName = (String)personDoc.get("name"); String personDescription = (String)personDoc.get("description"); String personType = (String)personDoc.get("type"); double awareness = Utils.getDouble(personDoc.get("awareness")); double sensitivity = Utils.getDouble(personDoc.get("sensitivity")); Person person = new Person.Builder( personid, personName, personDescription, personType, inst, awareness, sensitivity).build(); int actcount = Utils.getInt(personDoc.get("activitycount")); //System.out.println("Act-Count: " + actcount); for (int k = 1; k <= actcount; k++) { DBObject activityDoc = (DBObject)personDoc.get("activity"+k); String activityName = (String)activityDoc.get("name"); String activityType = (String)activityDoc.get("type"); String actid = ((ObjectId)activityDoc.get("_id")).toString(); int actmodcount = Utils.getInt(activityDoc.get("actmodcount")); Activity act = new Activity.Builder(actid, activityName, "", activityType, simulationWorld).build(); ProbabilityDistribution startDist; ProbabilityDistribution durDist; ProbabilityDistribution timesDist; for (int l = 1; l <= actmodcount; l++) { DBObject actmodDoc = (DBObject)activityDoc.get("actmod"+l); act.addModels(actmodDoc); String actmodName = (String)actmodDoc.get("name"); String actmodType = (String)actmodDoc.get("type"); String actmodDayType = (String)actmodDoc.get("day_type"); boolean shiftable = Utils.getBoolean(actmodDoc.get("shiftable")); boolean exclusive = Utils.getEquality(actmodDoc.get("config"), "exclusive", true); DBObject duration = (DBObject)actmodDoc.get("duration"); act.addDurations(duration); durDist = json2dist(duration, "duration"); //System.out.println(durDist.getPrecomputedBin()); DBObject start = (DBObject)actmodDoc.get("start"); act.addStarts(start); startDist = json2dist(start, "start"); //System.out.println(startDist.getPrecomputedBin()); DBObject rep = (DBObject)actmodDoc.get("repetitions"); act.addTimes(rep); timesDist = json2dist(rep, "reps"); //System.out.println(timesDist.getPrecomputedBin()); act.addDuration(actmodDayType, durDist); act.addStartTime(actmodDayType, startDist); act.addTimes(actmodDayType, timesDist); act.addShiftable(actmodDayType, shiftable); act.addConfig(actmodDayType, exclusive); // add appliances BasicDBList containsAppliances = (BasicDBList)actmodDoc.get("containsAppliances"); for(int m = 0; m < containsAppliances.size(); m++) { String containAppId = (String)containsAppliances.get(m); Appliance app = existing.get(containAppId); //act.addAppliance(actmodDayType,app,1.0/containsAppliances.size()); act.addAppliance(actmodDayType,app,1.0); } } person.addActivity(act); } existingPersons.put(personid, person); } double roulette = orng.nextDouble(); double sum = 0; for(int k = 0; k < generators.size(); k++) { DBObject generator = (DBObject)generators.get(k); String entityId = (String)generator.get("entity_id"); if(existingPersons.containsKey(entityId)) { double prob = Utils.getDouble(generator.get("probability")); sum += prob; if(roulette < sum) { Person selectedPerson = existingPersons.get(entityId); selectedPerson.setParentId(inst.getId()); String person_id = addEntity(selectedPerson, jump); selectedPerson.setId(person_id); inst.addPerson(selectedPerson); Vector<Activity> activities = selectedPerson.getActivities(); for(Activity a : activities) { a.setParentId(person_id); String act_id = addEntity(a, jump); a.setId(act_id); Vector<DBObject> models = a.getModels(); Vector<DBObject> starts = a.getStarts(); Vector<DBObject> durations = a.getDurations(); Vector<DBObject> times = a.getTimes(); for(int l = 0; l < models.size(); l++ ) { DBObject m = models.get(l); m.put("act_id", act_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS).insert(m); ObjectId objId = (ObjectId)m.get("_id"); String actmod_id = objId.toString(); DBObject s = starts.get(l); s.put("actmod_id", actmod_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(s); DBObject d = durations.get(l); d.put("actmod_id", actmod_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS).insert(d); DBObject t = times.get(l); t.put("actmod_id", actmod_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS).insert(t); } } break; } } } installations.add(inst); } } public static ProbabilityDistribution json2dist(DBObject distribution, String flag) throws Exception { String distType = (String)distribution.get("distrType"); switch (distType) { case ("Normal Distribution"): BasicDBList normalList = (BasicDBList)distribution.get("parameters"); DBObject normalDoc = (DBObject)normalList.get(0); double mean = Double.parseDouble(normalDoc.get("mean").toString()); double std = Double.parseDouble(normalDoc.get("std").toString()); Gaussian normal = new Gaussian(mean, std); normal.precompute(0, 1439, 1440); return normal; case ("Uniform Distribution"): BasicDBList unifList = (BasicDBList)distribution.get("parameters"); DBObject unifDoc = (DBObject)unifList.get(0); double from = Double.parseDouble(unifDoc.get("start").toString()); double to = Double.parseDouble(unifDoc.get("end").toString()); // System.out.println(from + " " + to); Uniform uniform = null; if(flag.equalsIgnoreCase("start")) { uniform = new Uniform(Math.max(from-1,0), Math.min(to-1, 1439), true); } else { uniform = new Uniform(from, to, false); } return uniform; case ("Gaussian Mixture Models"): BasicDBList mixList = (BasicDBList)distribution.get("parameters"); int length = mixList.size(); double[] w = new double[length]; double[] means = new double[length]; double[] stds = new double[length]; for(int i = 0; i < mixList.size(); i++) { DBObject tuple = (DBObject)mixList.get(i); w[i] = Double.parseDouble(tuple.get("w").toString()); means[i] = Double.parseDouble(tuple.get("mean").toString()); stds[i] = Double.parseDouble(tuple.get("std").toString()); } GaussianMixtureModels gmm = new GaussianMixtureModels(length, w, means, stds); gmm.precompute(0, 1439, 1440); return gmm; case ("Histogram"): BasicDBList hList = (BasicDBList)distribution.get("values"); int l = hList.size(); double[] v = new double[l]; for(int i = 0; i < l; i++) { v[i] = Double.parseDouble(hList.get(i).toString()); } Histogram h = new Histogram(v); return h; default: throw new Exception("Non existing distribution type. Problem in setting up the simulation."); } } }
true
true
public void run () { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); try { System.out.println("Run " + dbname + " started @ " + Calendar.getInstance().getTimeInMillis()); calculateExpectedPower(dbname); // System.out.println("EP calculated"); long startTime = System.currentTimeMillis(); int percentage = 0; int mccount = 0; double mcrunsRatio = 1.0/(double)mcruns; for(int i = 0; i < mcruns; i++) { tick = 0; double avgPPowerPerHour = 0; double avgQPowerPerHour = 0; double[] avgPPowerPerHourPerInst = new double[installations.size()]; double[] avgQPowerPerHourPerInst = new double[installations.size()]; double maxPower = 0; // double cycleMaxPower = 0; double avgPower = 0; double energy = 0; double energyOffpeak = 0; double cost = 0; // double billingCycleEnergy = 0; // double billingCycleEnergyOffpeak = 0; while (tick < endTick) { // If it is the beginning of the day create the events if (tick % Constants.MIN_IN_DAY == 0) { // System.out.println("Day " + ((tick / Constants.MIN_IN_DAY) + 1)); for (Installation installation: installations) { // System.out.println("Installation: " + installation.getName()); installation.updateDailySchedule(tick, queue, simulationWorld.getResponseType(), orng); } // System.out.println("Daily queue size: " + queue.size() + "(" + // simulationWorld.getSimCalendar().isWeekend(tick) + ")"); } Event top = queue.peek(); while (top != null && top.getTick() == tick) { Event e = queue.poll(); boolean applied = e.apply(); if(applied) { if(e.getAction() == Event.SWITCH_ON) { try { //m.addOpenTick(e.getAppliance().getId(), tick); } catch (Exception exc) { throw exc; } } else if(e.getAction() == Event.SWITCH_OFF){ //m.addCloseTick(e.getAppliance().getId(), tick); } } top = queue.peek(); } /* * Calculate the total power for this simulation step for all the * installations. */ float sumP = 0; float sumQ = 0; int counter = 0; for(Installation installation: installations) { installation.nextStep(tick); double p = installation.getCurrentPowerP(); double q = installation.getCurrentPowerQ(); // if(p> 0.001) System.out.println(p); installation.updateMaxPower(p); installation.updateAvgPower(p/endTick); if(installation.getPricing().isOffpeak(tick)) { installation.updateEnergyOffpeak(p); } else { installation.updateEnergy(p); } installation.updateAppliancesAndActivitiesConsumptions(tick, endTick); m.addTickResultForInstallation(tick, installation.getId(), p * mcrunsRatio, q * mcrunsRatio, MongoResults.COL_INSTRESULTS); sumP += p; sumQ += q; avgPPowerPerHour += p; avgQPowerPerHour += q; avgPPowerPerHourPerInst[counter] += p; avgQPowerPerHourPerInst[counter] += q; String name = installation.getName(); // logger.info("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + power); // System.out.println("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + p); if((tick + 1) % (Constants.MIN_IN_DAY * installation.getPricing().getBillingCycle()) == 0 || installation.getPricing().getType().equalsIgnoreCase("TOUPricing")) { installation.updateCost(tick); } counter++; } if(sumP > maxPower) maxPower = sumP; // if(sumP > cycleMaxPower) cycleMaxPower = sumP; avgPower += sumP/endTick; energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // if(pricing.isOffpeak(tick)) { // energyOffpeak += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } else { // energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } // if((tick + 1) % (Constants.MIN_IN_DAY * pricing.getBillingCycle()) == 0 || pricing.getType().equalsIgnoreCase("TOUPricing")) { // cost = totalInstCost(); //alternate method // billingCycleEnergy = totalInstEnergy(); // billingCycleEnergyOffpeak = totalInstOffpeak(); // cycleMaxPower = 0; // } m.addAggregatedTickResult(tick, sumP * mcrunsRatio, sumQ * mcrunsRatio, MongoResults.COL_AGGRRESULTS); tick++; if(tick % Constants.MIN_IN_HOUR == 0) { m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY); m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour) * mcrunsRatio, (avgQPowerPerHour) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY_EN); avgPPowerPerHour = 0; avgQPowerPerHour = 0; counter = 0; for(Installation installation: installations) { m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY); m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY_EN); avgPPowerPerHourPerInst[counter] = 0; avgQPowerPerHourPerInst[counter] = 0; counter++; } } mccount++; percentage = (int)(0.75 * mccount * 100.0 / (mcruns * endTick)); // System.out.println("Percentage: " + percentage + " - " + mccount); objRun.put("percentage", 25 + percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(Installation installation: installations) { installation.updateCost(tick); // update the rest of the energy m.addKPIs(installation.getId(), installation.getMaxPower() * mcrunsRatio, installation.getAvgPower() * mcrunsRatio, installation.getEnergy() * mcrunsRatio, installation.getCost() * mcrunsRatio, installation.getEnergy() * co2 * mcrunsRatio); installation.addAppliancesKPIs(m, mcrunsRatio, co2); installation.addActivitiesKPIs(m, mcrunsRatio, co2); } cost = totalInstCost(); m.addKPIs(MongoResults.AGGR, maxPower * mcrunsRatio, avgPower * mcrunsRatio, energy * mcrunsRatio, cost * mcrunsRatio, energy * co2 * mcrunsRatio); if(i+1 != mcruns) setup(true); } // Write installation results to csv file String filename = resources_path + "/csvs/" + runName + ".csv"; System.out.println(filename); File csvFile = new File(filename); FileWriter fw = new FileWriter(csvFile); String row = "tick"; for(Installation installation: installations) { row += "," + installation.getName() + "_p"; row += "," + installation.getName() + "_q"; } fw.write(row+"\n"); for(int i = 0; i < endTick; i++) { row = String.valueOf(i); for(Installation installation: installations) { DBObject tickResult = m.getTickResultForInstallation(i, installation.getId(), MongoResults.COL_INSTRESULTS); double p = ((Double)tickResult.get("p")).doubleValue(); double q = ((Double)tickResult.get("q")).doubleValue(); row += "," + p; row += "," + q; } fw.write(row+"\n"); } fw.flush(); fw.close(); // End of file writing // zip file // http://www.mkyong.com/java/how-to-compress-files-in-zip-format/ System.out.println("Zipping..."); byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(runName + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(runName + ".csv"); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(filename); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); fos.close(); csvFile.delete(); // End of zip file System.out.println("End of Zipping..."); long endTime = System.currentTimeMillis(); objRun.put("ended", endTime); System.out.println("Updating DB..."); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); System.out.println("End of Updating DB..."); logger.info("Time elapsed for Run " + dbname + ": " + ((endTime - startTime)/(1000.0 * 60)) + " mins"); logger.info("Run " + dbname + " ended @ " + Calendar.getInstance().toString()); } catch(Exception e) { e.printStackTrace(); System.out.println(Utils.stackTraceToString(e.getStackTrace())); // Change the run object in the db to reflect the exception if(objRun != null) { objRun.put("percentage", -1); objRun.put("state", e.getMessage()); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } } }
public void run () { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); try { System.out.println("Run " + dbname + " started @ " + Calendar.getInstance().getTimeInMillis()); calculateExpectedPower(dbname); // System.out.println("EP calculated"); long startTime = System.currentTimeMillis(); int percentage = 0; int mccount = 0; double mcrunsRatio = 1.0/(double)mcruns; for(int i = 0; i < mcruns; i++) { tick = 0; double avgPPowerPerHour = 0; double avgQPowerPerHour = 0; double[] avgPPowerPerHourPerInst = new double[installations.size()]; double[] avgQPowerPerHourPerInst = new double[installations.size()]; double maxPower = 0; // double cycleMaxPower = 0; double avgPower = 0; double energy = 0; double energyOffpeak = 0; double cost = 0; // double billingCycleEnergy = 0; // double billingCycleEnergyOffpeak = 0; while (tick < endTick) { // If it is the beginning of the day create the events if (tick % Constants.MIN_IN_DAY == 0) { // System.out.println("Day " + ((tick / Constants.MIN_IN_DAY) + 1)); for (Installation installation: installations) { // System.out.println("Installation: " + installation.getName()); installation.updateDailySchedule(tick, queue, simulationWorld.getResponseType(), orng); } // System.out.println("Daily queue size: " + queue.size() + "(" + // simulationWorld.getSimCalendar().isWeekend(tick) + ")"); } Event top = queue.peek(); while (top != null && top.getTick() == tick) { Event e = queue.poll(); boolean applied = e.apply(); if(applied) { if(e.getAction() == Event.SWITCH_ON) { try { //m.addOpenTick(e.getAppliance().getId(), tick); } catch (Exception exc) { throw exc; } } else if(e.getAction() == Event.SWITCH_OFF){ //m.addCloseTick(e.getAppliance().getId(), tick); } } top = queue.peek(); } /* * Calculate the total power for this simulation step for all the * installations. */ float sumP = 0; float sumQ = 0; int counter = 0; for(Installation installation: installations) { installation.nextStep(tick); double p = installation.getCurrentPowerP(); double q = installation.getCurrentPowerQ(); // if(p> 0.001) System.out.println(p); installation.updateMaxPower(p); installation.updateAvgPower(p/endTick); if(installation.getPricing().isOffpeak(tick)) { installation.updateEnergyOffpeak(p); } else { installation.updateEnergy(p); } installation.updateAppliancesAndActivitiesConsumptions(tick, endTick); m.addTickResultForInstallation(tick, installation.getId(), p * mcrunsRatio, q * mcrunsRatio, MongoResults.COL_INSTRESULTS); sumP += p; sumQ += q; avgPPowerPerHour += p; avgQPowerPerHour += q; avgPPowerPerHourPerInst[counter] += p; avgQPowerPerHourPerInst[counter] += q; String name = installation.getName(); // logger.info("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + power); // System.out.println("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + p); if((tick + 1) % (Constants.MIN_IN_DAY * installation.getPricing().getBillingCycle()) == 0 || installation.getPricing().getType().equalsIgnoreCase("TOUPricing")) { installation.updateCost(tick); } counter++; } if(sumP > maxPower) maxPower = sumP; // if(sumP > cycleMaxPower) cycleMaxPower = sumP; avgPower += sumP/endTick; energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // if(pricing.isOffpeak(tick)) { // energyOffpeak += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } else { // energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } // if((tick + 1) % (Constants.MIN_IN_DAY * pricing.getBillingCycle()) == 0 || pricing.getType().equalsIgnoreCase("TOUPricing")) { // cost = totalInstCost(); //alternate method // billingCycleEnergy = totalInstEnergy(); // billingCycleEnergyOffpeak = totalInstOffpeak(); // cycleMaxPower = 0; // } m.addAggregatedTickResult(tick, sumP * mcrunsRatio, sumQ * mcrunsRatio, MongoResults.COL_AGGRRESULTS); tick++; if(tick % Constants.MIN_IN_HOUR == 0) { m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY); m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour) * mcrunsRatio, (avgQPowerPerHour) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY_EN); avgPPowerPerHour = 0; avgQPowerPerHour = 0; counter = 0; for(Installation installation: installations) { m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY); m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY_EN); avgPPowerPerHourPerInst[counter] = 0; avgQPowerPerHourPerInst[counter] = 0; counter++; } } mccount++; percentage = (int)(0.75 * mccount * 100.0 / (mcruns * endTick)); // System.out.println("Percentage: " + percentage + " - " + mccount); objRun.put("percentage", 25 + percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(Installation installation: installations) { installation.updateCost(tick); // update the rest of the energy m.addKPIs(installation.getId(), installation.getMaxPower() * mcrunsRatio, installation.getAvgPower() * mcrunsRatio, installation.getEnergy() * mcrunsRatio, installation.getCost() * mcrunsRatio, installation.getEnergy() * co2 * mcrunsRatio); installation.addAppliancesKPIs(m, mcrunsRatio, co2); installation.addActivitiesKPIs(m, mcrunsRatio, co2); } cost = totalInstCost(); m.addKPIs(MongoResults.AGGR, maxPower * mcrunsRatio, avgPower * mcrunsRatio, energy * mcrunsRatio, cost * mcrunsRatio, energy * co2 * mcrunsRatio); if(i+1 != mcruns) setup(true); } // Write installation results to csv file String filename = resources_path + "/csvs/" + runName + ".csv"; System.out.println(filename); File csvFile = new File(filename); FileWriter fw = new FileWriter(csvFile); String row = "tick"; for(Installation installation: installations) { row += "," + installation.getName() + "_p"; row += "," + installation.getName() + "_q"; } fw.write(row+"\n"); for(int i = 0; i < endTick; i++) { row = String.valueOf(i); for(Installation installation: installations) { DBObject tickResult = m.getTickResultForInstallation(i, installation.getId(), MongoResults.COL_INSTRESULTS); double p = ((Double)tickResult.get("p")).doubleValue(); double q = ((Double)tickResult.get("q")).doubleValue(); row += "," + p; row += "," + q; } fw.write(row+"\n"); } fw.flush(); fw.close(); // End of file writing // zip file // http://www.mkyong.com/java/how-to-compress-files-in-zip-format/ System.out.println("Zipping..."); byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(filename + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(runName + ".csv"); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(filename); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); fos.close(); csvFile.delete(); // End of zip file System.out.println("End of Zipping..."); long endTime = System.currentTimeMillis(); objRun.put("ended", endTime); System.out.println("Updating DB..."); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); System.out.println("End of Updating DB..."); logger.info("Time elapsed for Run " + dbname + ": " + ((endTime - startTime)/(1000.0 * 60)) + " mins"); logger.info("Run " + dbname + " ended @ " + Calendar.getInstance().toString()); } catch(Exception e) { e.printStackTrace(); System.out.println(Utils.stackTraceToString(e.getStackTrace())); // Change the run object in the db to reflect the exception if(objRun != null) { objRun.put("percentage", -1); objRun.put("state", e.getMessage()); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } } }
diff --git a/src/test/java/gr/zapantis/rockpaperscissors/RockPaperScissorsGameTest.java b/src/test/java/gr/zapantis/rockpaperscissors/RockPaperScissorsGameTest.java index de7ed6b..666774e 100644 --- a/src/test/java/gr/zapantis/rockpaperscissors/RockPaperScissorsGameTest.java +++ b/src/test/java/gr/zapantis/rockpaperscissors/RockPaperScissorsGameTest.java @@ -1,15 +1,15 @@ package gr.zapantis.rockpaperscissors; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class RockPaperScissorsGameTest { @Test public void createGame() { - RockPaperScissorsGameTest rockPaperScissorsGameTest = new RockPaperScissorsGameTest(); - assertNotNull(rockPaperScissorsGameTest); + RockPaperScissorsGame rockPaperScissorsGame = new RockPaperScissorsGame(); + assertNotNull(rockPaperScissorsGame); } }
true
true
public void createGame() { RockPaperScissorsGameTest rockPaperScissorsGameTest = new RockPaperScissorsGameTest(); assertNotNull(rockPaperScissorsGameTest); }
public void createGame() { RockPaperScissorsGame rockPaperScissorsGame = new RockPaperScissorsGame(); assertNotNull(rockPaperScissorsGame); }
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java index 64b38c0e..a177b311 100644 --- a/src/com/android/launcher2/LauncherModel.java +++ b/src/com/android/launcher2/LauncherModel.java @@ -1,1816 +1,1820 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import com.android.launcher.R; import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons private final boolean mAppsCanBeOnExternalStorage; private int mBatchSize; // 0 is all apps at once private int mAllAppsLoadDelay; // milliseconds between batches private final LauncherApplication mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private LoaderTask mLoaderTask; private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); static { sWorkerThread.start(); } private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); // We start off with everything not loaded. After that, we assume that // our monitoring of the package manager provides all updates and we never // need to do a requery. These are only ever touched from the loader thread. private boolean mWorkspaceLoaded; private boolean mAllAppsLoaded; private WeakReference<Callbacks> mCallbacks; // < only access in worker thread > private AllAppsList mAllAppsList; // sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by // LauncherModel to their ids static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>(); // sItems is passed to bindItems, which expects a list of all folders and shortcuts created by // LauncherModel that are directly on the home screen (however, no widgets or shortcuts // within folders). static final ArrayList<ItemInfo> sItems = new ArrayList<ItemInfo>(); // sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() static final ArrayList<LauncherAppWidgetInfo> sAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); // sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>(); // </ only access in worker thread > private IconCache mIconCache; private Bitmap mDefaultIcon; private static int mCellCountX; private static int mCellCountY; public interface Callbacks { public boolean setLoadOnResume(); public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsAdded(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent); public void bindPackagesUpdated(); public boolean isAllAppsVisible(); } LauncherModel(LauncherApplication app, IconCache iconCache) { mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated(); mApp = app; mAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( mIconCache.getFullResDefaultActivityIcon(), app); mAllAppsLoadDelay = app.getResources().getInteger(R.integer.config_allAppsBatchLoadDelay); mBatchSize = app.getResources().getInteger(R.integer.config_allAppsBatchSize); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screen, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screen, cellX, cellY); } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, final ItemInfo item, final long container, final int screen, final int cellX, final int cellY) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false); final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screen); sWorker.post(new Runnable() { public void run() { cr.update(uri, values, null, null); ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " + "doesn't match original"); } // Items are added/removed from the corresponding FolderInfo elsewhere, such // as in Workspace.onDrop. Here, we just add/remove them from the list of items // that are on the desktop, as appropriate if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (!sItems.contains(modelItem)) { sItems.add(modelItem); } } else { sItems.remove(modelItem); } } }); } /** * Resize an item in the DB to a new <spanX, spanY, cellX, cellY> */ static void resizeItemInDatabase(Context context, final ItemInfo item, final int cellX, final int cellY, final int spanX, final int spanY) { item.spanX = spanX; item.spanY = spanY; item.cellX = cellX; item.cellY = cellY; final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false); final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.SPANX, spanX); values.put(LauncherSettings.Favorites.SPANY, spanY); values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); sWorker.post(new Runnable() { public void run() { cr.update(uri, values, null, null); ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " + "doesn't match original"); } } }); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screen = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, long container, int screen, int cellX, int cellY, final boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Launcher l = (Launcher) context; LauncherApplication app = (LauncherApplication) l.getApplication(); item.id = app.getLauncherProvider().generateNewId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, cellX, cellY); sWorker.post(new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); sItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.put(item.id, (FolderInfo) item); if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { sItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { sItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.add((LauncherAppWidgetInfo) item); break; } } }); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( int cellId, int screen, int localCellX, int localCellY, int spanX, int spanY) { return ((cellId & 0xFF) << 24) | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); sWorker.post(new Runnable() { public void run() { cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); final ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " + "doesn't match original"); } } }); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); sWorker.post(new Runnable() { public void run() { cr.delete(uriToDelete, null, null); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.remove(item.id); sItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sItemsIdMap.remove(item.id); } }); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); sWorker.post(new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); sItemsIdMap.remove(info.id); sFolders.remove(info.id); sItems.remove(info); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); for (ItemInfo childInfo : info.contents) { sItemsIdMap.remove(childInfo.id); } } }); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps. // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything // next time. mAllAppsLoaded = false; startLoaderFromBackground(); } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(mApp, false); } } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldTask.stopLocked(); } mLoaderTask = new LoaderTask(context, isLaunching); sWorker.post(mLoaderTask); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mLoadAndBindStepFinished; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } private void loadAndBindWorkspace() { // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); if (mStopped) { return; } mWorkspaceLoaded = true; } // Bind the workspace bindWorkspace(); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } public void run() { // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) { if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { return true; } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (occupied[item.screen][x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + item.screen + ":" + x + "," + y + ") occupied by " + occupied[item.screen][x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { occupied[item.screen][x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); sItems.clear(); sAppWidgets.clear(); sFolders.clear(); sItemsIdMap.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); final ItemInfo occupied[][][] = new ItemInfo[Launcher.SCREEN_COUNT][mCellCountX][mCellCountY]; try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: sItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sFolders, container); folderInfo.add(info); break; } sItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. updateSavedIcon(context, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: sItems.add(folderInfo); break; } sItemsIdMap.put(folderInfo.id, folderInfo); sFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < Launcher.SCREEN_COUNT; s++) { if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied[s][x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = sItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(sItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(sFolders); } } }); // Wait until the queue goes empty. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = sAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); if (mStopped) { return; } mAllAppsLoaded = true; } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)mAllAppsList.data.clone(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sItems.size()); } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp; final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mAllAppsList.updatePackage(context, packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mAllAppsList.removePackage(packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } if (removed != null) { final boolean permanent = mOp != OP_UNAVAILABLE; final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsRemoved(removedFinal, permanent); } } }); } mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(); } } }); } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { - return sCollator.compare(a.title.toString(), b.title.toString()); + int result = sCollator.compare(a.title.toString(), b.title.toString()); + if (result == 0) { + result = a.componentName.compareTo(b.componentName); + } + return result; } }; public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR = new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return sCollator.compare(a.label.toString(), b.label.toString()); } }; public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(ResolveInfo a, ResolveInfo b) { String labelA, labelB; if (mLabelCache.containsKey(a)) labelA = mLabelCache.get(a); else labelA = a.loadLabel(mPackageManager).toString(); if (mLabelCache.containsKey(b)) labelB = mLabelCache.get(b); else labelB = b.loadLabel(mPackageManager).toString(); return sCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) labelA = mLabelCache.get(a); else labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); if (mLabelCache.containsKey(b)) labelB = mLabelCache.get(b); else labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); return sCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
true
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screen = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, long container, int screen, int cellX, int cellY, final boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Launcher l = (Launcher) context; LauncherApplication app = (LauncherApplication) l.getApplication(); item.id = app.getLauncherProvider().generateNewId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, cellX, cellY); sWorker.post(new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); sItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.put(item.id, (FolderInfo) item); if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { sItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { sItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.add((LauncherAppWidgetInfo) item); break; } } }); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( int cellId, int screen, int localCellX, int localCellY, int spanX, int spanY) { return ((cellId & 0xFF) << 24) | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); sWorker.post(new Runnable() { public void run() { cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); final ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " + "doesn't match original"); } } }); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); sWorker.post(new Runnable() { public void run() { cr.delete(uriToDelete, null, null); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.remove(item.id); sItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sItemsIdMap.remove(item.id); } }); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); sWorker.post(new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); sItemsIdMap.remove(info.id); sFolders.remove(info.id); sItems.remove(info); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); for (ItemInfo childInfo : info.contents) { sItemsIdMap.remove(childInfo.id); } } }); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps. // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything // next time. mAllAppsLoaded = false; startLoaderFromBackground(); } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(mApp, false); } } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldTask.stopLocked(); } mLoaderTask = new LoaderTask(context, isLaunching); sWorker.post(mLoaderTask); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mLoadAndBindStepFinished; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } private void loadAndBindWorkspace() { // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); if (mStopped) { return; } mWorkspaceLoaded = true; } // Bind the workspace bindWorkspace(); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } public void run() { // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) { if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { return true; } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (occupied[item.screen][x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + item.screen + ":" + x + "," + y + ") occupied by " + occupied[item.screen][x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { occupied[item.screen][x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); sItems.clear(); sAppWidgets.clear(); sFolders.clear(); sItemsIdMap.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); final ItemInfo occupied[][][] = new ItemInfo[Launcher.SCREEN_COUNT][mCellCountX][mCellCountY]; try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: sItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sFolders, container); folderInfo.add(info); break; } sItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. updateSavedIcon(context, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: sItems.add(folderInfo); break; } sItemsIdMap.put(folderInfo.id, folderInfo); sFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < Launcher.SCREEN_COUNT; s++) { if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied[s][x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = sItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(sItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(sFolders); } } }); // Wait until the queue goes empty. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = sAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); if (mStopped) { return; } mAllAppsLoaded = true; } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)mAllAppsList.data.clone(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sItems.size()); } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp; final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mAllAppsList.updatePackage(context, packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mAllAppsList.removePackage(packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } if (removed != null) { final boolean permanent = mOp != OP_UNAVAILABLE; final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsRemoved(removedFinal, permanent); } } }); } mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(); } } }); } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR = new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return sCollator.compare(a.label.toString(), b.label.toString()); } }; public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(ResolveInfo a, ResolveInfo b) { String labelA, labelB; if (mLabelCache.containsKey(a)) labelA = mLabelCache.get(a); else labelA = a.loadLabel(mPackageManager).toString(); if (mLabelCache.containsKey(b)) labelB = mLabelCache.get(b); else labelB = b.loadLabel(mPackageManager).toString(); return sCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) labelA = mLabelCache.get(a); else labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); if (mLabelCache.containsKey(b)) labelB = mLabelCache.get(b); else labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); return sCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screen = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, long container, int screen, int cellX, int cellY, final boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Launcher l = (Launcher) context; LauncherApplication app = (LauncherApplication) l.getApplication(); item.id = app.getLauncherProvider().generateNewId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, cellX, cellY); sWorker.post(new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); sItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.put(item.id, (FolderInfo) item); if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { sItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { sItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.add((LauncherAppWidgetInfo) item); break; } } }); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( int cellId, int screen, int localCellX, int localCellY, int spanX, int spanY) { return ((cellId & 0xFF) << 24) | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); sWorker.post(new Runnable() { public void run() { cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); final ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " + "doesn't match original"); } } }); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); sWorker.post(new Runnable() { public void run() { cr.delete(uriToDelete, null, null); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.remove(item.id); sItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sItemsIdMap.remove(item.id); } }); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); sWorker.post(new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); sItemsIdMap.remove(info.id); sFolders.remove(info.id); sItems.remove(info); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); for (ItemInfo childInfo : info.contents) { sItemsIdMap.remove(childInfo.id); } } }); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps. // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything // next time. mAllAppsLoaded = false; startLoaderFromBackground(); } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(mApp, false); } } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldTask.stopLocked(); } mLoaderTask = new LoaderTask(context, isLaunching); sWorker.post(mLoaderTask); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mLoadAndBindStepFinished; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } private void loadAndBindWorkspace() { // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); if (mStopped) { return; } mWorkspaceLoaded = true; } // Bind the workspace bindWorkspace(); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } public void run() { // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) { if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { return true; } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (occupied[item.screen][x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + item.screen + ":" + x + "," + y + ") occupied by " + occupied[item.screen][x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { occupied[item.screen][x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); sItems.clear(); sAppWidgets.clear(); sFolders.clear(); sItemsIdMap.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); final ItemInfo occupied[][][] = new ItemInfo[Launcher.SCREEN_COUNT][mCellCountX][mCellCountY]; try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: sItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sFolders, container); folderInfo.add(info); break; } sItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. updateSavedIcon(context, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: sItems.add(folderInfo); break; } sItemsIdMap.put(folderInfo.id, folderInfo); sFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < Launcher.SCREEN_COUNT; s++) { if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied[s][x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = sItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(sItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(sFolders); } } }); // Wait until the queue goes empty. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = sAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); if (mStopped) { return; } mAllAppsLoaded = true; } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)mAllAppsList.data.clone(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sItems.size()); } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp; final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mAllAppsList.updatePackage(context, packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mAllAppsList.removePackage(packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } if (removed != null) { final boolean permanent = mOp != OP_UNAVAILABLE; final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsRemoved(removedFinal, permanent); } } }); } mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(); } } }); } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = sCollator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR = new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return sCollator.compare(a.label.toString(), b.label.toString()); } }; public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(ResolveInfo a, ResolveInfo b) { String labelA, labelB; if (mLabelCache.containsKey(a)) labelA = mLabelCache.get(a); else labelA = a.loadLabel(mPackageManager).toString(); if (mLabelCache.containsKey(b)) labelB = mLabelCache.get(b); else labelB = b.loadLabel(mPackageManager).toString(); return sCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) labelA = mLabelCache.get(a); else labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); if (mLabelCache.containsKey(b)) labelB = mLabelCache.get(b); else labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); return sCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
diff --git a/core/typechecker/src/main/java/org/overture/typecheck/visitors/TypeCheckerImportsVisitor.java b/core/typechecker/src/main/java/org/overture/typecheck/visitors/TypeCheckerImportsVisitor.java index 4fbf128222..e4f97f3223 100644 --- a/core/typechecker/src/main/java/org/overture/typecheck/visitors/TypeCheckerImportsVisitor.java +++ b/core/typechecker/src/main/java/org/overture/typecheck/visitors/TypeCheckerImportsVisitor.java @@ -1,132 +1,133 @@ package org.overture.typecheck.visitors; import java.util.List; import java.util.Vector; import org.overture.ast.analysis.QuestionAnswerAdaptor; import org.overture.ast.definitions.PDefinition; import org.overture.ast.definitions.assistants.PDefinitionAssistantTC; import org.overture.ast.definitions.assistants.PDefinitionListAssistantTC; import org.overture.ast.factory.AstFactory; import org.overture.ast.modules.AAllImport; import org.overture.ast.modules.AFunctionValueImport; import org.overture.ast.modules.AModuleModules; import org.overture.ast.modules.AOperationValueImport; import org.overture.ast.modules.ATypeImport; import org.overture.ast.modules.SValueImport; import org.overture.ast.types.PType; import org.overture.ast.types.SInvariantType; import org.overture.ast.types.assistants.PTypeAssistantTC; import org.overture.typecheck.FlatCheckedEnvironment; import org.overture.typecheck.TypeCheckInfo; import org.overture.typecheck.TypeCheckerErrors; import org.overture.typecheck.TypeComparator; import org.overturetool.vdmj.lex.LexNameToken; import org.overturetool.vdmj.typechecker.NameScope; public class TypeCheckerImportsVisitor extends QuestionAnswerAdaptor<TypeCheckInfo, PType> { /** * */ private static final long serialVersionUID = -6883311293059829368L; final private QuestionAnswerAdaptor<TypeCheckInfo, PType> rootVisitor; public TypeCheckerImportsVisitor(TypeCheckVisitor typeCheckVisitor) { this.rootVisitor = typeCheckVisitor; } @Override public PType caseAAllImport(AAllImport node, TypeCheckInfo question) { return null; // Implicitly OK. } @Override public PType caseATypeImport(ATypeImport node, TypeCheckInfo question) { if (node.getDef() != null && node.getFrom() != null) { PDefinition def = node.getDef(); LexNameToken name = node.getName(); AModuleModules from = node.getFrom(); def.setType((SInvariantType)PTypeAssistantTC.typeResolve(PDefinitionAssistantTC.getType(def),null,rootVisitor,question)); PDefinition expdef = PDefinitionListAssistantTC.findType(from.getExportdefs(),name, null); if (expdef != null) { PType exptype = PTypeAssistantTC.typeResolve(expdef.getType(),null,rootVisitor,question); if (!TypeComparator.compatible(def.getType(), exptype)) { TypeCheckerErrors.report(3192, "Type import of " + name + " does not match export from " + from.getName(),node.getLocation(),node); TypeCheckerErrors.detail2("Import", def.getType().toString() //TODO: .toDetailedString() , "Export", exptype.toString()); //TODO: .toDetailedString()); } } } return null; } @Override public PType defaultSValueImport(SValueImport node, TypeCheckInfo question) { PType type = node.getImportType(); AModuleModules from = node.getFrom(); LexNameToken name = node.getName(); if (type != null && from != null) { type = PTypeAssistantTC.typeResolve(type, null, rootVisitor, question); PDefinition expdef = PDefinitionListAssistantTC.findName(from.getExportdefs(), name, NameScope.NAMES); if (expdef != null) { PType exptype = PTypeAssistantTC.typeResolve(expdef.getType(), null, rootVisitor, question); if (!TypeComparator.compatible(type, exptype)) { TypeCheckerErrors.report(3194, "Type of value import " + name + " does not match export from " + from.getName(),node.getLocation(),node); TypeCheckerErrors.detail2("Import", type.toString(), //TODO: .toDetailedString(), "Export", exptype.toString()); //TODO: .toDetailedString()); } } } return null; } @Override public PType caseAFunctionValueImport(AFunctionValueImport node, TypeCheckInfo question) { //TODO: This might need to be made in another way if (node.getTypeParams().size() == 0) { defaultSValueImport(node, question); } else { List<PDefinition> defs = new Vector<PDefinition>(); for (LexNameToken pname: node.getTypeParams()) { + LexNameToken pnameClone = pname.clone(); PDefinition p = - AstFactory.newALocalDefinition(pname.location, pname, NameScope.NAMES, AstFactory.newAParameterType(pname)); + AstFactory.newALocalDefinition(pname.location, pnameClone, NameScope.NAMES, AstFactory.newAParameterType(pnameClone)); PDefinitionAssistantTC.markUsed(p); defs.add(p); } FlatCheckedEnvironment params = new FlatCheckedEnvironment( defs, question.env, NameScope.NAMES); defaultSValueImport(node, new TypeCheckInfo(params,question.scope,question.qualifiers)); } return null; } @Override public PType caseAOperationValueImport(AOperationValueImport node, TypeCheckInfo question) { return defaultSValueImport(node, question); } }
false
true
public PType caseAFunctionValueImport(AFunctionValueImport node, TypeCheckInfo question) { //TODO: This might need to be made in another way if (node.getTypeParams().size() == 0) { defaultSValueImport(node, question); } else { List<PDefinition> defs = new Vector<PDefinition>(); for (LexNameToken pname: node.getTypeParams()) { PDefinition p = AstFactory.newALocalDefinition(pname.location, pname, NameScope.NAMES, AstFactory.newAParameterType(pname)); PDefinitionAssistantTC.markUsed(p); defs.add(p); } FlatCheckedEnvironment params = new FlatCheckedEnvironment( defs, question.env, NameScope.NAMES); defaultSValueImport(node, new TypeCheckInfo(params,question.scope,question.qualifiers)); } return null; }
public PType caseAFunctionValueImport(AFunctionValueImport node, TypeCheckInfo question) { //TODO: This might need to be made in another way if (node.getTypeParams().size() == 0) { defaultSValueImport(node, question); } else { List<PDefinition> defs = new Vector<PDefinition>(); for (LexNameToken pname: node.getTypeParams()) { LexNameToken pnameClone = pname.clone(); PDefinition p = AstFactory.newALocalDefinition(pname.location, pnameClone, NameScope.NAMES, AstFactory.newAParameterType(pnameClone)); PDefinitionAssistantTC.markUsed(p); defs.add(p); } FlatCheckedEnvironment params = new FlatCheckedEnvironment( defs, question.env, NameScope.NAMES); defaultSValueImport(node, new TypeCheckInfo(params,question.scope,question.qualifiers)); } return null; }
diff --git a/wflow-core/src/main/java/org/joget/apps/app/dao/FormDefinitionDaoImpl.java b/wflow-core/src/main/java/org/joget/apps/app/dao/FormDefinitionDaoImpl.java index 9bc0e661..cf915f36 100755 --- a/wflow-core/src/main/java/org/joget/apps/app/dao/FormDefinitionDaoImpl.java +++ b/wflow-core/src/main/java/org/joget/apps/app/dao/FormDefinitionDaoImpl.java @@ -1,152 +1,152 @@ package org.joget.apps.app.dao; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.joget.apps.app.model.AppDefinition; import org.joget.apps.app.model.FormDefinition; import org.joget.apps.form.model.FormColumnCache; import org.joget.commons.util.LogUtil; import org.springframework.orm.hibernate3.HibernateCallback; /** * DAO to load/store FormDefinition objects */ public class FormDefinitionDaoImpl extends AbstractAppVersionedObjectDao<FormDefinition> implements FormDefinitionDao { public static final String ENTITY_NAME = "FormDefinition"; private FormColumnCache formColumnCache; public FormColumnCache getFormColumnCache() { return formColumnCache; } public void setFormColumnCache(FormColumnCache formColumnCache) { this.formColumnCache = formColumnCache; } @Override public String getEntityName() { return ENTITY_NAME; } /** * Retrieves FormDefinitions mapped to a table name. * @param tableName * @return */ @Override public Collection<FormDefinition> loadFormDefinitionByTableName(String tableName) { // load the form definitions String condition = " WHERE e.tableName=?"; Object[] params = {tableName}; Collection<FormDefinition> results = find(getEntityName(), condition, params, null, null, 0, -1); return results; } public Collection<FormDefinition> getFormDefinitionList(String filterString, AppDefinition appDefinition, String sort, Boolean desc, Integer start, Integer rows) { String conditions = ""; List params = new ArrayList(); if (filterString == null) { filterString = ""; } conditions = "and (id like ? or name like ? or tableName like ?)"; params.add("%" + filterString + "%"); params.add("%" + filterString + "%"); params.add("%" + filterString + "%"); return this.find(conditions, params.toArray(), appDefinition, sort, desc, start, rows); } public Long getFormDefinitionListCount(String filterString, AppDefinition appDefinition) { String conditions = ""; List params = new ArrayList(); if (filterString == null) { filterString = ""; } conditions = "and (id like ? or name like ? or tableName like ?)"; params.add("%" + filterString + "%"); params.add("%" + filterString + "%"); params.add("%" + filterString + "%"); return this.count(conditions, params.toArray(), appDefinition); } @Override public FormDefinition loadById(String id, AppDefinition appDefinition) { return super.loadById(id, appDefinition); } @Override public boolean add(FormDefinition object) { object.setDateCreated(new Date()); object.setDateModified(new Date()); return super.add(object); } @Override public boolean update(FormDefinition object) { // clear from cache formColumnCache.remove(object.getTableName()); // update object object.setDateModified(new Date()); return super.update(object); } @Override public boolean delete(String id, AppDefinition appDef) { boolean result = false; try { - FormDefinition obj = loadById(id, appDef); + FormDefinition obj = super.loadById(id, appDef); // detach from app if (obj != null) { Collection<FormDefinition> list = appDef.getFormDefinitionList(); for (FormDefinition object : list) { if (obj.getId().equals(object.getId())) { list.remove(obj); break; } } obj.setAppDefinition(null); // delete obj super.delete(getEntityName(), obj); result = true; // clear from cache formColumnCache.remove(obj.getTableName()); } } catch (Exception e) { LogUtil.error(getClass().getName(), e, ""); } return result; } public Collection<String> getTableNameList(AppDefinition appDefinition) { final AppDefinition appDef = appDefinition; Collection<String> result = (Collection<String>) this.findHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { String query = "SELECT DISTINCT e.tableName FROM " + getEntityName() + " e where e.appId = ? and e.appVersion = ?"; Query q = session.createQuery(query); q.setParameter(0, appDef.getAppId()); q.setParameter(1, appDef.getVersion()); return q.list(); } }); return result; } }
true
true
public boolean delete(String id, AppDefinition appDef) { boolean result = false; try { FormDefinition obj = loadById(id, appDef); // detach from app if (obj != null) { Collection<FormDefinition> list = appDef.getFormDefinitionList(); for (FormDefinition object : list) { if (obj.getId().equals(object.getId())) { list.remove(obj); break; } } obj.setAppDefinition(null); // delete obj super.delete(getEntityName(), obj); result = true; // clear from cache formColumnCache.remove(obj.getTableName()); } } catch (Exception e) { LogUtil.error(getClass().getName(), e, ""); } return result; }
public boolean delete(String id, AppDefinition appDef) { boolean result = false; try { FormDefinition obj = super.loadById(id, appDef); // detach from app if (obj != null) { Collection<FormDefinition> list = appDef.getFormDefinitionList(); for (FormDefinition object : list) { if (obj.getId().equals(object.getId())) { list.remove(obj); break; } } obj.setAppDefinition(null); // delete obj super.delete(getEntityName(), obj); result = true; // clear from cache formColumnCache.remove(obj.getTableName()); } } catch (Exception e) { LogUtil.error(getClass().getName(), e, ""); } return result; }
diff --git a/search-impl/impl/src/java/org/sakaiproject/search/indexer/impl/ConcurrentSearchIndexBuilderWorkerImpl.java b/search-impl/impl/src/java/org/sakaiproject/search/indexer/impl/ConcurrentSearchIndexBuilderWorkerImpl.java index d5b45746..459c7fcb 100644 --- a/search-impl/impl/src/java/org/sakaiproject/search/indexer/impl/ConcurrentSearchIndexBuilderWorkerImpl.java +++ b/search-impl/impl/src/java/org/sakaiproject/search/indexer/impl/ConcurrentSearchIndexBuilderWorkerImpl.java @@ -1,466 +1,466 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.search.indexer.impl; import java.util.Observable; import java.util.Observer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.api.ComponentManager; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.db.api.SqlService; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.search.api.SearchService; import org.sakaiproject.search.indexer.api.IndexWorker; import org.sakaiproject.search.indexer.api.IndexWorkerDocumentListener; import org.sakaiproject.search.journal.api.ManagementOperation; import org.sakaiproject.search.journal.impl.JournalSettings; import org.sakaiproject.user.api.UserDirectoryService; /** * A management operation to perform indexing to the journal * * @author ieb */ public class ConcurrentSearchIndexBuilderWorkerImpl implements ManagementOperation, IndexWorkerDocumentListener { private static final Log log = LogFactory .getLog(ConcurrentSearchIndexBuilderWorkerImpl.class); private boolean enabled = false; /** * dependency */ private UserDirectoryService userDirectoryService; /** * dependency */ private SearchService searchService; /** * dependency */ private IndexWorker indexWorker; /** * dependency */ private ComponentManager componentManager; /** * Dependency */ private ServerConfigurationService serverConfigurationService; /** * we need to watch local events to guage activity */ private EventTrackingService eventTrackingService; /** * Setting A load factor 1 is full load, 100 is normal The load factor * controlls the backoff of the indexer threads. If the load Factor is high, * the search threads back off more. */ private long loadFactor = 1000L; /** * Has been started once at least */ private boolean started = false; /** * threads should run */ private boolean runThreads = false; /** * The last time an index run was performed on this node */ private long lastIndexRun = System.currentTimeMillis(); /** * The time the last event was seen */ private long lastEvent; private ThreadLocal<String> nowIndexing = new ThreadLocal<String>(); private JournalSettings journalSettings; private SqlService sqlService; private SecurityService securityService; public void destroy() { } public void init() { if (started && !runThreads) { log.warn("JVM Shutdown in progress, will not startup"); return; } if (componentManager.hasBeenClosed()) { log.warn("Component manager Shutdown in progress, will not startup"); return; } enabled = searchService.isEnabled() && "true".equals(serverConfigurationService.getString("search.indexqueue", "true")); started = true; runThreads = true; if ( !enabled ) { return; } eventTrackingService.addLocalObserver(new Observer() { public void update(Observable arg0, Object arg1) { lastEvent = System.currentTimeMillis(); } }); } /** * @see java.lang.Runnable#run() */ public void runOnce() { if (!enabled) { return; } if (componentManager.hasBeenClosed()) { log.info("Component Manager has been closed"); return; } nowIndexing.set("-"); if (journalSettings.getSoakTest() && (searchService.getPendingDocs() == 0)) { log.error("SOAK TEST---SOAK TEST---SOAK TEST. Index Rebuild Started"); searchService.rebuildInstance(); } log.debug("Run Processing Thread"); int totalDocs = searchService.getPendingDocs(); long now = System.currentTimeMillis(); long interval = now - lastEvent; boolean process = false; boolean createIndex = false; if (totalDocs > 200) { loadFactor = 10L; } else { loadFactor = 1000L; } if (totalDocs == 0) { process = false; } else if (totalDocs < 20 && interval > (20 * loadFactor)) { process = true; } else if (totalDocs >= 20 && totalDocs < 50 && interval > (10 * loadFactor)) { process = true; } else if (totalDocs >= 50 && totalDocs < 90 && interval > (5 * loadFactor)) { process = true; } else if (totalDocs > ((90 * loadFactor) / 1000)) { process = true; } // should this node consider taking the lock ? long lastIndexInterval = (System.currentTimeMillis() - lastIndexRun); long lastIndexMetric = lastIndexInterval * totalDocs; // if we have 1000 docs, then indexing should happen // after 10 seconds break // 1000*10000 10000000 // 500 docs/ 20 seconds // log.debug("Activity " + (lastIndexMetric > (10000L * loadFactor)) + " " + (lastIndexInterval > (60L * loadFactor)) + " " + createIndex); if (true) { log.debug("===" + process + "=============PROCESSING "); if (process) { lastIndexRun = System.currentTimeMillis(); int batchSize = 100; if (totalDocs > 100000) { - batchSize = 100000; + batchSize = 10000; } else if (totalDocs > 1000) { batchSize = 500; } else if (totalDocs > 500) { batchSize = 200; } securityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); try { indexWorker.process(batchSize); } finally { securityService.popAdvisor(); } lastIndexRun = System.currentTimeMillis(); } } } /** * @see org.sakaiproject.search.indexer.api.IndexWorkerDocumentListener#indexDocumentEnd(org.sakaiproject.search.indexer.api.IndexWorker, * java.lang.String) */ public void indexDocumentEnd(IndexWorker worker, String ref) { nowIndexing.set("-"); } /** * @see org.sakaiproject.search.indexer.api.IndexWorkerDocumentListener#indexDocumentStart(org.sakaiproject.search.indexer.api.IndexWorker, * java.lang.String) */ public void indexDocumentStart(IndexWorker worker, String ref) { nowIndexing.set(ref); } /** * @return the componentManager */ public ComponentManager getComponentManager() { return componentManager; } /** * @param componentManager * the componentManager to set */ public void setComponentManager(ComponentManager componentManager) { this.componentManager = componentManager; } /** * @return the eventTrackingService */ public EventTrackingService getEventTrackingService() { return eventTrackingService; } /** * @param eventTrackingService * the eventTrackingService to set */ public void setEventTrackingService(EventTrackingService eventTrackingService) { this.eventTrackingService = eventTrackingService; } /** * @return the indexWorker */ public IndexWorker getIndexWorker() { return indexWorker; } /** * @param indexWorker * the indexWorker to set */ public void setIndexWorker(IndexWorker indexWorker) { this.indexWorker = indexWorker; } /** * @return the loadFactor */ public long getLoadFactor() { return loadFactor; } /** * @param loadFactor * the loadFactor to set */ public void setLoadFactor(long loadFactor) { this.loadFactor = loadFactor; } /** * @return the searchService */ public SearchService getSearchService() { return searchService; } /** * @param searchService * the searchService to set */ public void setSearchService(SearchService searchService) { this.searchService = searchService; } /** * @return the userDirectoryService */ public UserDirectoryService getUserDirectoryService() { return userDirectoryService; } /** * @param userDirectoryService * the userDirectoryService to set */ public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } /** * * @param serverConfigurationService */ public void setServerConfigurationService( ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } /** * @return the journalSettings */ public JournalSettings getJournalSettings() { return journalSettings; } /** * @param journalSettings * the journalSettings to set */ public void setJournalSettings(JournalSettings journalSettings) { this.journalSettings = journalSettings; } /** * @return the sqlService */ public SqlService getSqlService() { return sqlService; } /** * @param sqlService the sqlService to set */ public void setSqlService(SqlService sqlService) { this.sqlService = sqlService; } /** * @return the securityService */ public SecurityService getSecurityService() { return securityService; } /** * @param securityService the securityService to set */ public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } }
true
true
public void runOnce() { if (!enabled) { return; } if (componentManager.hasBeenClosed()) { log.info("Component Manager has been closed"); return; } nowIndexing.set("-"); if (journalSettings.getSoakTest() && (searchService.getPendingDocs() == 0)) { log.error("SOAK TEST---SOAK TEST---SOAK TEST. Index Rebuild Started"); searchService.rebuildInstance(); } log.debug("Run Processing Thread"); int totalDocs = searchService.getPendingDocs(); long now = System.currentTimeMillis(); long interval = now - lastEvent; boolean process = false; boolean createIndex = false; if (totalDocs > 200) { loadFactor = 10L; } else { loadFactor = 1000L; } if (totalDocs == 0) { process = false; } else if (totalDocs < 20 && interval > (20 * loadFactor)) { process = true; } else if (totalDocs >= 20 && totalDocs < 50 && interval > (10 * loadFactor)) { process = true; } else if (totalDocs >= 50 && totalDocs < 90 && interval > (5 * loadFactor)) { process = true; } else if (totalDocs > ((90 * loadFactor) / 1000)) { process = true; } // should this node consider taking the lock ? long lastIndexInterval = (System.currentTimeMillis() - lastIndexRun); long lastIndexMetric = lastIndexInterval * totalDocs; // if we have 1000 docs, then indexing should happen // after 10 seconds break // 1000*10000 10000000 // 500 docs/ 20 seconds // log.debug("Activity " + (lastIndexMetric > (10000L * loadFactor)) + " " + (lastIndexInterval > (60L * loadFactor)) + " " + createIndex); if (true) { log.debug("===" + process + "=============PROCESSING "); if (process) { lastIndexRun = System.currentTimeMillis(); int batchSize = 100; if (totalDocs > 100000) { batchSize = 100000; } else if (totalDocs > 1000) { batchSize = 500; } else if (totalDocs > 500) { batchSize = 200; } securityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); try { indexWorker.process(batchSize); } finally { securityService.popAdvisor(); } lastIndexRun = System.currentTimeMillis(); } } }
public void runOnce() { if (!enabled) { return; } if (componentManager.hasBeenClosed()) { log.info("Component Manager has been closed"); return; } nowIndexing.set("-"); if (journalSettings.getSoakTest() && (searchService.getPendingDocs() == 0)) { log.error("SOAK TEST---SOAK TEST---SOAK TEST. Index Rebuild Started"); searchService.rebuildInstance(); } log.debug("Run Processing Thread"); int totalDocs = searchService.getPendingDocs(); long now = System.currentTimeMillis(); long interval = now - lastEvent; boolean process = false; boolean createIndex = false; if (totalDocs > 200) { loadFactor = 10L; } else { loadFactor = 1000L; } if (totalDocs == 0) { process = false; } else if (totalDocs < 20 && interval > (20 * loadFactor)) { process = true; } else if (totalDocs >= 20 && totalDocs < 50 && interval > (10 * loadFactor)) { process = true; } else if (totalDocs >= 50 && totalDocs < 90 && interval > (5 * loadFactor)) { process = true; } else if (totalDocs > ((90 * loadFactor) / 1000)) { process = true; } // should this node consider taking the lock ? long lastIndexInterval = (System.currentTimeMillis() - lastIndexRun); long lastIndexMetric = lastIndexInterval * totalDocs; // if we have 1000 docs, then indexing should happen // after 10 seconds break // 1000*10000 10000000 // 500 docs/ 20 seconds // log.debug("Activity " + (lastIndexMetric > (10000L * loadFactor)) + " " + (lastIndexInterval > (60L * loadFactor)) + " " + createIndex); if (true) { log.debug("===" + process + "=============PROCESSING "); if (process) { lastIndexRun = System.currentTimeMillis(); int batchSize = 100; if (totalDocs > 100000) { batchSize = 10000; } else if (totalDocs > 1000) { batchSize = 500; } else if (totalDocs > 500) { batchSize = 200; } securityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); try { indexWorker.process(batchSize); } finally { securityService.popAdvisor(); } lastIndexRun = System.currentTimeMillis(); } } }
diff --git a/src/com/xabber/android/data/notification/NotificationManager.java b/src/com/xabber/android/data/notification/NotificationManager.java index b1e6df89..7c79c1e7 100644 --- a/src/com/xabber/android/data/notification/NotificationManager.java +++ b/src/com/xabber/android/data/notification/NotificationManager.java @@ -1,653 +1,653 @@ /** * Copyright (c) 2013, Redsolution LTD. All rights reserved. * * This file is part of Xabber project; you can redistribute it and/or * modify it under the terms of the GNU General Public License, Version 3. * * Xabber is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.xabber.android.data.notification; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.media.AudioManager; import android.net.Uri; import android.os.Handler; import android.os.Vibrator; import android.widget.RemoteViews; import com.xabber.android.data.Application; import com.xabber.android.data.LogManager; import com.xabber.android.data.OnCloseListener; import com.xabber.android.data.OnInitializedListener; import com.xabber.android.data.OnLoadListener; import com.xabber.android.data.SettingsManager; import com.xabber.android.data.account.AccountItem; import com.xabber.android.data.account.AccountManager; import com.xabber.android.data.account.ArchiveMode; import com.xabber.android.data.account.OnAccountArchiveModeChangedListener; import com.xabber.android.data.account.OnAccountChangedListener; import com.xabber.android.data.account.OnAccountRemovedListener; import com.xabber.android.data.connection.ConnectionState; import com.xabber.android.data.extension.avatar.AvatarManager; import com.xabber.android.data.extension.muc.MUCManager; import com.xabber.android.data.message.MessageItem; import com.xabber.android.data.message.MessageManager; import com.xabber.android.data.message.chat.ChatManager; import com.xabber.android.data.message.phrase.PhraseManager; import com.xabber.android.data.roster.RosterManager; import com.xabber.android.ui.ChatViewer; import com.xabber.android.ui.ClearNotifications; import com.xabber.android.ui.ContactList; import com.xabber.android.ui.ReconnectionActivity; import com.xabber.android.utils.Emoticons; import com.xabber.android.utils.StringUtils; import com.xabber.androiddev.R; /** * Manage notifications about message, subscription and authentication. * * @author alexander.ivanov */ public class NotificationManager implements OnInitializedListener, OnAccountChangedListener, OnCloseListener, OnLoadListener, Runnable, OnAccountRemovedListener, OnAccountArchiveModeChangedListener { public static final int PERSISTENT_NOTIFICATION_ID = 1; private static final int CHAT_NOTIFICATION_ID = 2; private static final int BASE_NOTIFICATION_PROVIDER_ID = 0x10; private static final long VIBRATION_DURATION = 500; private static final int MAX_NOTIFICATION_TEXT = 80; private final long startTime; private final Application application; private final android.app.NotificationManager notificationManager; private final Notification persistentNotification; private final PendingIntent clearNotifications; private final Handler handler; /** * Runnable to start vibration. */ private final Runnable startVibro; /** * Runnable to force stop vibration. */ private final Runnable stopVibro; /** * List of providers for notifications. */ private final List<NotificationProvider<? extends NotificationItem>> providers; /** * List of */ private final List<MessageNotification> messageNotifications; private final static NotificationManager instance; static { instance = new NotificationManager(); Application.getInstance().addManager(instance); } public static NotificationManager getInstance() { return instance; } private NotificationManager() { this.application = Application.getInstance(); notificationManager = (android.app.NotificationManager) application .getSystemService(Context.NOTIFICATION_SERVICE); persistentNotification = new Notification(); handler = new Handler(); providers = new ArrayList<NotificationProvider<? extends NotificationItem>>(); messageNotifications = new ArrayList<MessageNotification>(); startTime = System.currentTimeMillis(); clearNotifications = PendingIntent.getActivity(application, 0, ClearNotifications.createIntent(application), 0); stopVibro = new Runnable() { @Override public void run() { handler.removeCallbacks(startVibro); handler.removeCallbacks(stopVibro); ((Vibrator) NotificationManager.this.application .getSystemService(Context.VIBRATOR_SERVICE)).cancel(); } }; startVibro = new Runnable() { @Override public void run() { handler.removeCallbacks(startVibro); handler.removeCallbacks(stopVibro); ((Vibrator) NotificationManager.this.application .getSystemService(Context.VIBRATOR_SERVICE)).cancel(); ((Vibrator) NotificationManager.this.application .getSystemService(Context.VIBRATOR_SERVICE)) .vibrate(VIBRATION_DURATION); handler.postDelayed(stopVibro, VIBRATION_DURATION); } }; } @Override public void onLoad() { final Collection<MessageNotification> messageNotifications = new ArrayList<MessageNotification>(); Cursor cursor = NotificationTable.getInstance().list(); try { if (cursor.moveToFirst()) { do { messageNotifications.add(new MessageNotification( NotificationTable.getAccount(cursor), NotificationTable.getUser(cursor), NotificationTable.getText(cursor), NotificationTable.getTimeStamp(cursor), NotificationTable.getCount(cursor))); } while (cursor.moveToNext()); } } finally { cursor.close(); } Application.getInstance().runOnUiThread(new Runnable() { @Override public void run() { onLoaded(messageNotifications); } }); } private void onLoaded(Collection<MessageNotification> messageNotifications) { this.messageNotifications.addAll(messageNotifications); for (MessageNotification messageNotification : messageNotifications) MessageManager.getInstance().openChat( messageNotification.getAccount(), messageNotification.getUser()); } @Override public void onInitialized() { application.addUIListener(OnAccountChangedListener.class, this); updateMessageNotification(null); } /** * Register new provider for notifications. * * @param provider */ public void registerNotificationProvider( NotificationProvider<? extends NotificationItem> provider) { providers.add(provider); } /** * Update notifications for specified provider. * * @param <T> * @param provider * @param notify * Ticker to be shown. Can be <code>null</code>. */ public <T extends NotificationItem> void updateNotifications( NotificationProvider<T> provider, T notify) { int id = providers.indexOf(provider); if (id == -1) throw new IllegalStateException( "registerNotificationProvider() must be called from onLoaded() method."); else id += BASE_NOTIFICATION_PROVIDER_ID; Iterator<? extends NotificationItem> iterator = provider .getNotifications().iterator(); if (!iterator.hasNext()) { notificationManager.cancel(id); } else { NotificationItem top; String ticker; if (notify == null) { top = iterator.next(); ticker = null; } else { top = notify; ticker = top.getTitle(); } Intent intent = top.getIntent(); Notification notification = new Notification(provider.getIcon(), ticker, System.currentTimeMillis()); if (!provider.canClearNotifications()) notification.flags |= Notification.FLAG_NO_CLEAR; notification.setLatestEventInfo(application, top.getTitle(), top .getText(), PendingIntent.getActivity(application, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); if (ticker != null) setNotificationDefaults(notification, SettingsManager.eventsVibro(), provider.getSound(), provider.getStreamType()); notification.deleteIntent = clearNotifications; notify(id, notification); } } /** * Sound, vibration and lightning flags. * * @param notification * @param streamType */ private void setNotificationDefaults(Notification notification, boolean vibro, Uri sound, int streamType) { notification.audioStreamType = streamType; notification.defaults = 0; notification.sound = sound; if (vibro) { if (SettingsManager.eventsIgnoreSystemVibro()) handler.post(startVibro); else notification.defaults |= Notification.DEFAULT_VIBRATE; } if (SettingsManager.eventsLightning()) { notification.defaults |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS; } } /** * Chat was changed: * <ul> * <li>incoming message</li> * <li>chat was opened</li> * <li>account was changed</li> * </ul> * * Update chat and persistent notifications. * * @param ticker * message to be shown. * @return */ private void updateMessageNotification(MessageItem ticker) { Collection<String> accountList = AccountManager.getInstance() .getAccounts(); int accountCount = accountList.size(); boolean started = application.isInitialized(); int waiting = 0; int connecting = 0; int connected = 0; for (String account : accountList) { ConnectionState state = AccountManager.getInstance() .getAccount(account).getState(); if (RosterManager.getInstance().isRosterReceived(account)) connected++; else if (state == ConnectionState.connecting || state == ConnectionState.authentication) connecting++; else if (state == ConnectionState.waiting) waiting++; } String accountQuantity; String connectionState; if (connected > 0) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_connected, connected); connectionState = String.format(connectionFormat, connected, accountCount, accountQuantity); } else if (connecting > 0) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_connecting, connecting); connectionState = String.format(connectionFormat, connecting, accountCount, accountQuantity); } else if (waiting > 0 && started) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_waiting, waiting); connectionState = String.format(connectionFormat, waiting, accountCount, accountQuantity); } else { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity_offline, accountCount); connectionState = application.getString( R.string.connection_state_offline, accountCount, accountQuantity); } final Intent persistentIntent; if (waiting > 0 && started) persistentIntent = ReconnectionActivity.createIntent(application); else persistentIntent = ContactList.createPersistentIntent(application); if (messageNotifications.isEmpty()) { notificationManager.cancel(CHAT_NOTIFICATION_ID); } else { int messageCount = 0; for (MessageNotification messageNotification : messageNotifications) messageCount += messageNotification.getCount(); MessageNotification message = messageNotifications .get(messageNotifications.size() - 1); RemoteViews chatViews = new RemoteViews( application.getPackageName(), R.layout.chat_notification); Intent chatIntent = ChatViewer.createClearTopIntent(application, message.getAccount(), message.getUser()); if (MUCManager.getInstance().hasRoom(message.getAccount(), message.getUser())) chatViews.setImageViewBitmap(R.id.icon, AvatarManager .getInstance().getRoomBitmap(message.getUser())); else chatViews.setImageViewBitmap(R.id.icon, AvatarManager .getInstance().getUserBitmap(message.getUser())); chatViews.setTextViewText(R.id.title, RosterManager.getInstance() .getName(message.getAccount(), message.getUser())); String text; if (ChatManager.getInstance().isShowText(message.getAccount(), message.getUser())) text = trimText(message.getText()); else text = ""; chatViews.setTextViewText(R.id.text2, Emoticons.getSmiledText(application, text)); chatViews.setTextViewText(R.id.time, StringUtils.getSmartTimeText(message.getTimestamp())); String messageText = StringUtils.getQuantityString( application.getResources(), R.array.chat_message_quantity, messageCount); String contactText = StringUtils.getQuantityString( application.getResources(), R.array.chat_contact_quantity, messageNotifications.size()); String status = application.getString(R.string.chat_status, messageCount, messageText, messageNotifications.size(), contactText); chatViews.setTextViewText(R.id.text, status); Notification notification = new Notification(); - if (Application.SDK_INT >= 14) { + if (Application.SDK_INT >= 14 && SettingsManager.eventsPersistent()) { // Ongoing icons are in the left side, so hide this one. notification.icon = R.drawable.ic_placeholder; notification.when = Long.MIN_VALUE; } else { // Ongoing icons are in the right side, so show this one. updateNotification(notification, ticker); notification.icon = connected > 0 ? R.drawable.ic_stat_message : R.drawable.ic_stat_message_offline; notification.when = System.currentTimeMillis(); } notification.contentView = chatViews; notification.contentIntent = PendingIntent.getActivity(application, 0, chatIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.deleteIntent = clearNotifications; try { notify(CHAT_NOTIFICATION_ID, notification); } catch (RuntimeException e) { LogManager.exception(this, e); // Try to remove avatar in order to avoid // OutOfMemoryError on the Android system side. chatViews.setImageViewResource(R.id.icon, R.drawable.ic_placeholder); notify(CHAT_NOTIFICATION_ID, notification); } } persistentNotification.icon = R.drawable.ic_stat_normal; persistentNotification.setLatestEventInfo(application, application .getString(R.string.application_name), connectionState, PendingIntent.getActivity(application, 0, persistentIntent, PendingIntent.FLAG_UPDATE_CURRENT)); persistentNotification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; persistentNotification.defaults = 0; persistentNotification.sound = null; persistentNotification.tickerText = null; - if (Application.SDK_INT >= 14) { + if (Application.SDK_INT >= 14 && SettingsManager.eventsPersistent()) { // Ongoing icons are in the left side, so always use it. persistentNotification.when = startTime; if (messageNotifications.isEmpty()) { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_normal : R.drawable.ic_stat_offline; } else { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_message : R.drawable.ic_stat_message_offline; } updateNotification(persistentNotification, ticker); } else { // Ongoing icons are in the right side, so hide it if necessary. if (messageNotifications.isEmpty()) { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_normal : R.drawable.ic_stat_offline; persistentNotification.when = startTime; // Show ticker for the messages in active chat. updateNotification(persistentNotification, ticker); } else { persistentNotification.icon = R.drawable.ic_placeholder; persistentNotification.when = Application.SDK_INT >= 9 ? -Long.MAX_VALUE : Long.MAX_VALUE; } } if (SettingsManager.eventsPersistent()) { notify(PERSISTENT_NOTIFICATION_ID, persistentNotification); } else { notificationManager.cancel(PERSISTENT_NOTIFICATION_ID); } } private void notify(int id, Notification notification) { LogManager.i(this, "Notification: " + id + ", ticker: " + notification.tickerText + ", sound: " + notification.sound + ", vibro: " + (notification.defaults & Notification.DEFAULT_VIBRATE) + ", light: " + (notification.defaults & Notification.DEFAULT_LIGHTS)); try { notificationManager.notify(id, notification); } catch (SecurityException e) { } } /** * Update notification according to ticker. * * @param notification * @param ticker */ private void updateNotification(Notification notification, MessageItem ticker) { if (ticker == null) return; if (ticker.getChat().getFirstNotification() || !SettingsManager.eventsFirstOnly()) setNotificationDefaults( notification, ChatManager.getInstance().isMakeVibro( ticker.getChat().getAccount(), ticker.getChat().getUser()), PhraseManager.getInstance().getSound( ticker.getChat().getAccount(), ticker.getChat().getUser(), ticker.getText()), AudioManager.STREAM_NOTIFICATION); if (ChatManager.getInstance().isShowText(ticker.getChat().getAccount(), ticker.getChat().getUser())) notification.tickerText = trimText(ticker.getText()); } private MessageNotification getMessageNotification(String account, String user) { for (MessageNotification messageNotification : messageNotifications) if (messageNotification.equals(account, user)) return messageNotification; return null; } /** * Shows ticker with the message and updates message notification. * * @param messageItem * @param addNotification * Whether notification should be stored. */ public void onMessageNotification(MessageItem messageItem, boolean addNotification) { if (addNotification) { MessageNotification messageNotification = getMessageNotification( messageItem.getChat().getAccount(), messageItem.getChat() .getUser()); if (messageNotification == null) messageNotification = new MessageNotification(messageItem .getChat().getAccount(), messageItem.getChat() .getUser(), null, null, 0); else messageNotifications.remove(messageNotification); messageNotification.addMessage(messageItem.getText()); messageNotifications.add(messageNotification); final String account = messageNotification.getAccount(); final String user = messageNotification.getUser(); final String text = messageNotification.getText(); final Date timestamp = messageNotification.getTimestamp(); final int count = messageNotification.getCount(); if (AccountManager.getInstance().getArchiveMode(account) != ArchiveMode.dontStore) Application.getInstance().runInBackground(new Runnable() { @Override public void run() { NotificationTable.getInstance().write(account, user, text, timestamp, count); } }); } updateMessageNotification(messageItem); } /** * Updates message notification. */ public void onMessageNotification() { updateMessageNotification(null); } public int getNotificationMessageCount(String account, String user) { MessageNotification messageNotification = getMessageNotification( account, user); if (messageNotification == null) return 0; return messageNotification.getCount(); } public void removeMessageNotification(final String account, final String user) { MessageNotification messageNotification = getMessageNotification( account, user); if (messageNotification == null) return; messageNotifications.remove(messageNotification); Application.getInstance().runInBackground(new Runnable() { @Override public void run() { NotificationTable.getInstance().remove(account, user); } }); updateMessageNotification(null); } /** * Called when notifications was cleared by user. */ public void onClearNotifications() { for (NotificationProvider<? extends NotificationItem> provider : providers) if (provider.canClearNotifications()) provider.clearNotifications(); messageNotifications.clear(); Application.getInstance().runInBackground(new Runnable() { @Override public void run() { NotificationTable.getInstance().clear(); } }); updateMessageNotification(null); } @Override public void onAccountArchiveModeChanged(AccountItem accountItem) { final String account = accountItem.getAccount(); if (AccountManager.getInstance().getArchiveMode(account) != ArchiveMode.dontStore) return; Application.getInstance().runInBackground(new Runnable() { @Override public void run() { NotificationTable.getInstance().removeAccount(account); } }); } @Override public void onAccountsChanged(Collection<String> accounts) { handler.post(this); } @Override public void onAccountRemoved(AccountItem accountItem) { for (NotificationProvider<? extends NotificationItem> notificationProvider : providers) if (notificationProvider instanceof AccountNotificationProvider) { ((AccountNotificationProvider<? extends NotificationItem>) notificationProvider) .clearAccountNotifications(accountItem.getAccount()); updateNotifications(notificationProvider, null); } } @Override public void run() { handler.removeCallbacks(this); updateMessageNotification(null); } public Notification getPersistentNotification() { return persistentNotification; } @Override public void onClose() { notificationManager.cancelAll(); } /** * @param text * @return Trimmed text. */ private static String trimText(String text) { if (text.length() > MAX_NOTIFICATION_TEXT) return text.substring(0, MAX_NOTIFICATION_TEXT - 3) + "..."; else return text; } }
false
true
private void updateMessageNotification(MessageItem ticker) { Collection<String> accountList = AccountManager.getInstance() .getAccounts(); int accountCount = accountList.size(); boolean started = application.isInitialized(); int waiting = 0; int connecting = 0; int connected = 0; for (String account : accountList) { ConnectionState state = AccountManager.getInstance() .getAccount(account).getState(); if (RosterManager.getInstance().isRosterReceived(account)) connected++; else if (state == ConnectionState.connecting || state == ConnectionState.authentication) connecting++; else if (state == ConnectionState.waiting) waiting++; } String accountQuantity; String connectionState; if (connected > 0) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_connected, connected); connectionState = String.format(connectionFormat, connected, accountCount, accountQuantity); } else if (connecting > 0) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_connecting, connecting); connectionState = String.format(connectionFormat, connecting, accountCount, accountQuantity); } else if (waiting > 0 && started) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_waiting, waiting); connectionState = String.format(connectionFormat, waiting, accountCount, accountQuantity); } else { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity_offline, accountCount); connectionState = application.getString( R.string.connection_state_offline, accountCount, accountQuantity); } final Intent persistentIntent; if (waiting > 0 && started) persistentIntent = ReconnectionActivity.createIntent(application); else persistentIntent = ContactList.createPersistentIntent(application); if (messageNotifications.isEmpty()) { notificationManager.cancel(CHAT_NOTIFICATION_ID); } else { int messageCount = 0; for (MessageNotification messageNotification : messageNotifications) messageCount += messageNotification.getCount(); MessageNotification message = messageNotifications .get(messageNotifications.size() - 1); RemoteViews chatViews = new RemoteViews( application.getPackageName(), R.layout.chat_notification); Intent chatIntent = ChatViewer.createClearTopIntent(application, message.getAccount(), message.getUser()); if (MUCManager.getInstance().hasRoom(message.getAccount(), message.getUser())) chatViews.setImageViewBitmap(R.id.icon, AvatarManager .getInstance().getRoomBitmap(message.getUser())); else chatViews.setImageViewBitmap(R.id.icon, AvatarManager .getInstance().getUserBitmap(message.getUser())); chatViews.setTextViewText(R.id.title, RosterManager.getInstance() .getName(message.getAccount(), message.getUser())); String text; if (ChatManager.getInstance().isShowText(message.getAccount(), message.getUser())) text = trimText(message.getText()); else text = ""; chatViews.setTextViewText(R.id.text2, Emoticons.getSmiledText(application, text)); chatViews.setTextViewText(R.id.time, StringUtils.getSmartTimeText(message.getTimestamp())); String messageText = StringUtils.getQuantityString( application.getResources(), R.array.chat_message_quantity, messageCount); String contactText = StringUtils.getQuantityString( application.getResources(), R.array.chat_contact_quantity, messageNotifications.size()); String status = application.getString(R.string.chat_status, messageCount, messageText, messageNotifications.size(), contactText); chatViews.setTextViewText(R.id.text, status); Notification notification = new Notification(); if (Application.SDK_INT >= 14) { // Ongoing icons are in the left side, so hide this one. notification.icon = R.drawable.ic_placeholder; notification.when = Long.MIN_VALUE; } else { // Ongoing icons are in the right side, so show this one. updateNotification(notification, ticker); notification.icon = connected > 0 ? R.drawable.ic_stat_message : R.drawable.ic_stat_message_offline; notification.when = System.currentTimeMillis(); } notification.contentView = chatViews; notification.contentIntent = PendingIntent.getActivity(application, 0, chatIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.deleteIntent = clearNotifications; try { notify(CHAT_NOTIFICATION_ID, notification); } catch (RuntimeException e) { LogManager.exception(this, e); // Try to remove avatar in order to avoid // OutOfMemoryError on the Android system side. chatViews.setImageViewResource(R.id.icon, R.drawable.ic_placeholder); notify(CHAT_NOTIFICATION_ID, notification); } } persistentNotification.icon = R.drawable.ic_stat_normal; persistentNotification.setLatestEventInfo(application, application .getString(R.string.application_name), connectionState, PendingIntent.getActivity(application, 0, persistentIntent, PendingIntent.FLAG_UPDATE_CURRENT)); persistentNotification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; persistentNotification.defaults = 0; persistentNotification.sound = null; persistentNotification.tickerText = null; if (Application.SDK_INT >= 14) { // Ongoing icons are in the left side, so always use it. persistentNotification.when = startTime; if (messageNotifications.isEmpty()) { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_normal : R.drawable.ic_stat_offline; } else { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_message : R.drawable.ic_stat_message_offline; } updateNotification(persistentNotification, ticker); } else { // Ongoing icons are in the right side, so hide it if necessary. if (messageNotifications.isEmpty()) { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_normal : R.drawable.ic_stat_offline; persistentNotification.when = startTime; // Show ticker for the messages in active chat. updateNotification(persistentNotification, ticker); } else { persistentNotification.icon = R.drawable.ic_placeholder; persistentNotification.when = Application.SDK_INT >= 9 ? -Long.MAX_VALUE : Long.MAX_VALUE; } } if (SettingsManager.eventsPersistent()) { notify(PERSISTENT_NOTIFICATION_ID, persistentNotification); } else { notificationManager.cancel(PERSISTENT_NOTIFICATION_ID); } }
private void updateMessageNotification(MessageItem ticker) { Collection<String> accountList = AccountManager.getInstance() .getAccounts(); int accountCount = accountList.size(); boolean started = application.isInitialized(); int waiting = 0; int connecting = 0; int connected = 0; for (String account : accountList) { ConnectionState state = AccountManager.getInstance() .getAccount(account).getState(); if (RosterManager.getInstance().isRosterReceived(account)) connected++; else if (state == ConnectionState.connecting || state == ConnectionState.authentication) connecting++; else if (state == ConnectionState.waiting) waiting++; } String accountQuantity; String connectionState; if (connected > 0) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_connected, connected); connectionState = String.format(connectionFormat, connected, accountCount, accountQuantity); } else if (connecting > 0) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_connecting, connecting); connectionState = String.format(connectionFormat, connecting, accountCount, accountQuantity); } else if (waiting > 0 && started) { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity, accountCount); String connectionFormat = StringUtils.getQuantityString( application.getResources(), R.array.connection_state_waiting, waiting); connectionState = String.format(connectionFormat, waiting, accountCount, accountQuantity); } else { accountQuantity = StringUtils.getQuantityString( application.getResources(), R.array.account_quantity_offline, accountCount); connectionState = application.getString( R.string.connection_state_offline, accountCount, accountQuantity); } final Intent persistentIntent; if (waiting > 0 && started) persistentIntent = ReconnectionActivity.createIntent(application); else persistentIntent = ContactList.createPersistentIntent(application); if (messageNotifications.isEmpty()) { notificationManager.cancel(CHAT_NOTIFICATION_ID); } else { int messageCount = 0; for (MessageNotification messageNotification : messageNotifications) messageCount += messageNotification.getCount(); MessageNotification message = messageNotifications .get(messageNotifications.size() - 1); RemoteViews chatViews = new RemoteViews( application.getPackageName(), R.layout.chat_notification); Intent chatIntent = ChatViewer.createClearTopIntent(application, message.getAccount(), message.getUser()); if (MUCManager.getInstance().hasRoom(message.getAccount(), message.getUser())) chatViews.setImageViewBitmap(R.id.icon, AvatarManager .getInstance().getRoomBitmap(message.getUser())); else chatViews.setImageViewBitmap(R.id.icon, AvatarManager .getInstance().getUserBitmap(message.getUser())); chatViews.setTextViewText(R.id.title, RosterManager.getInstance() .getName(message.getAccount(), message.getUser())); String text; if (ChatManager.getInstance().isShowText(message.getAccount(), message.getUser())) text = trimText(message.getText()); else text = ""; chatViews.setTextViewText(R.id.text2, Emoticons.getSmiledText(application, text)); chatViews.setTextViewText(R.id.time, StringUtils.getSmartTimeText(message.getTimestamp())); String messageText = StringUtils.getQuantityString( application.getResources(), R.array.chat_message_quantity, messageCount); String contactText = StringUtils.getQuantityString( application.getResources(), R.array.chat_contact_quantity, messageNotifications.size()); String status = application.getString(R.string.chat_status, messageCount, messageText, messageNotifications.size(), contactText); chatViews.setTextViewText(R.id.text, status); Notification notification = new Notification(); if (Application.SDK_INT >= 14 && SettingsManager.eventsPersistent()) { // Ongoing icons are in the left side, so hide this one. notification.icon = R.drawable.ic_placeholder; notification.when = Long.MIN_VALUE; } else { // Ongoing icons are in the right side, so show this one. updateNotification(notification, ticker); notification.icon = connected > 0 ? R.drawable.ic_stat_message : R.drawable.ic_stat_message_offline; notification.when = System.currentTimeMillis(); } notification.contentView = chatViews; notification.contentIntent = PendingIntent.getActivity(application, 0, chatIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.deleteIntent = clearNotifications; try { notify(CHAT_NOTIFICATION_ID, notification); } catch (RuntimeException e) { LogManager.exception(this, e); // Try to remove avatar in order to avoid // OutOfMemoryError on the Android system side. chatViews.setImageViewResource(R.id.icon, R.drawable.ic_placeholder); notify(CHAT_NOTIFICATION_ID, notification); } } persistentNotification.icon = R.drawable.ic_stat_normal; persistentNotification.setLatestEventInfo(application, application .getString(R.string.application_name), connectionState, PendingIntent.getActivity(application, 0, persistentIntent, PendingIntent.FLAG_UPDATE_CURRENT)); persistentNotification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; persistentNotification.defaults = 0; persistentNotification.sound = null; persistentNotification.tickerText = null; if (Application.SDK_INT >= 14 && SettingsManager.eventsPersistent()) { // Ongoing icons are in the left side, so always use it. persistentNotification.when = startTime; if (messageNotifications.isEmpty()) { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_normal : R.drawable.ic_stat_offline; } else { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_message : R.drawable.ic_stat_message_offline; } updateNotification(persistentNotification, ticker); } else { // Ongoing icons are in the right side, so hide it if necessary. if (messageNotifications.isEmpty()) { persistentNotification.icon = connected > 0 ? R.drawable.ic_stat_normal : R.drawable.ic_stat_offline; persistentNotification.when = startTime; // Show ticker for the messages in active chat. updateNotification(persistentNotification, ticker); } else { persistentNotification.icon = R.drawable.ic_placeholder; persistentNotification.when = Application.SDK_INT >= 9 ? -Long.MAX_VALUE : Long.MAX_VALUE; } } if (SettingsManager.eventsPersistent()) { notify(PERSISTENT_NOTIFICATION_ID, persistentNotification); } else { notificationManager.cancel(PERSISTENT_NOTIFICATION_ID); } }
diff --git a/src/com/jidesoft/plaf/UIDefaultsLookup.java b/src/com/jidesoft/plaf/UIDefaultsLookup.java index 1efaa6e9..9cda51ba 100644 --- a/src/com/jidesoft/plaf/UIDefaultsLookup.java +++ b/src/com/jidesoft/plaf/UIDefaultsLookup.java @@ -1,378 +1,383 @@ /* * @(#)UIManagerLookup.java 4/5/2007 * * Copyright 2002 - 2007 JIDE Software Inc. All rights reserved. */ package com.jidesoft.plaf; import com.jidesoft.converter.ObjectConverterManager; import sun.reflect.Reflection; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * This class simply uses UIManager's get method to lookup the UIDefaults. We used this everywhere in our code so that * we have one central place to find out which UIDefaults we are using. Another good thing is you can use {@link * #setTrace(boolean)} and {@link #setDebug(boolean)} to turn on the trace so that it will print out which UIDefaults we * are trying to get. */ public class UIDefaultsLookup { private static boolean _debug = false; private static boolean _trace = false; /** * Sets the debug mode. If debug mode is on, we will print out any UIDefaults that the value is null. * * @param debug true or false. */ public static void setDebug(boolean debug) { _debug = debug; } /** * Sets the trace mode. If trace mode is on, we will print out any UIDefaults we are trying to get and its current * value. * * @param trace true or false. */ public static void setTrace(boolean trace) { _trace = trace; } public static void put(UIDefaults table, String key, Object value) { Object v = table.get(key); if (v == null || !(v instanceof Map)) { v = new HashMap<ClassLoader, Object>(); table.put(key, v); } ((Map) v).put(value.getClass().getClassLoader(), value); } // Returns the invoker's class loader, or null if none. // NOTE: This must always be invoked when there is exactly one intervening // frame from the core libraries on the stack between this method's // invocation and the desired invoker. static ClassLoader getCallerClassLoader() { // NOTE use of more generic Reflection.getCallerClass() Class caller = Reflection.getCallerClass(3); // This can be null if the VM is requesting it if (caller == null) { return null; } // Circumvent security check since this is package-private return caller.getClassLoader(); } public static Object get(Object key) { Object value = UIManager.get(key); log(value, key, null); if (value instanceof Map && "Theme.painter".equals(key)) { Map map = (Map) value; try { ClassLoader classLoader = getCallerClassLoader(); Object o = map.get(classLoader); while (o == null && classLoader.getParent() != null) { classLoader = classLoader.getParent(); o = map.get(classLoader); } if (o == null && map.size() >= 1) { Collection<Object> classLoaders = map.values(); for (Object cl : classLoaders) { if (cl != null) { o = cl; break; } } } return o; } catch (Exception e) { - return map.get(LookAndFeelFactory.getUIManagerClassLoader()); + if (map.size() == 1) { + return map.values().iterator().next(); + } + else { + return map.get(LookAndFeelFactory.getUIManagerClassLoader()); + } } } return value; } public static Object get(Object key, Locale l) { Object value = UIManager.get(key, l); log(value, key, l); return value; } private static void log(Object value, Object key, Locale l) { if (_debug && value == null) { System.out.println("\"" + key + (l == null ? "" : l.toString()) + " \" ==> null ------------------------"); } else if (_trace) { if (value == null) { System.out.println("\"" + key + (l == null ? "" : l.toString()) + " \" ==> null ------------------------"); } else { System.out.println("\"" + key + (l == null ? "" : l.toString()) + " \" ==> " + value.getClass().getName() + "(" + ObjectConverterManager.toString(value) + ")"); } } } /** * If the value of <code>key</code> is a <code>Font</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is a <code>Font</code>, return the <code>Font</code> object; otherwise * return <code>null</code> */ public static Font getFont(Object key) { Object value = get(key); return (value instanceof Font) ? (Font) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is a <code>Font</code> return it, otherwise * return <code>null</code>. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is a <code>Font</code>, return the * <code>Font</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static Font getFont(Object key, Locale l) { Object value = get(key, l); return (value instanceof Font) ? (Font) value : null; } /** * If the value of <code>key</code> is a <code>Color</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is a <code>Color</code>, return the <code>Color</code> object; * otherwise return <code>null</code> */ public static Color getColor(Object key) { Object value = get(key); return (value instanceof Color) ? (Color) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is a <code>Color</code> return it, otherwise * return <code>null</code>. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is a <code>Color</code>, return the * <code>Color</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static Color getColor(Object key, Locale l) { Object value = get(key, l); return (value instanceof Color) ? (Color) value : null; } /** * If the value of <code>key</code> is an <code>Icon</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is an <code>Icon</code>, return the <code>Icon</code> object; otherwise * return <code>null</code> */ public static Icon getIcon(Object key) { Object value = get(key); return (value instanceof Icon) ? (Icon) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is an <code>Icon</code> return it, otherwise * return <code>null</code>. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is an <code>Icon</code>, return the * <code>Icon</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static Icon getIcon(Object key, Locale l) { Object value = get(key, l); return (value instanceof Icon) ? (Icon) value : null; } /** * If the value of <code>key</code> is a <code>Border</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is a <code>Border</code>, return the <code>Border</code> object; * otherwise return <code>null</code> */ public static Border getBorder(Object key) { Object value = get(key); return (value instanceof Border) ? (Border) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is a <code>Border</code> return it, otherwise * return <code>null</code>. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is a <code>Border</code>, return the * <code>Border</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static Border getBorder(Object key, Locale l) { Object value = get(key, l); return (value instanceof Border) ? (Border) value : null; } /** * If the value of <code>key</code> is a <code>String</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is a <code>String</code>, return the <code>String</code> object; * otherwise return <code>null</code> */ public static String getString(Object key) { Object value = get(key); return (value instanceof String) ? (String) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is a <code>String</code> return it, otherwise * return <code>null</code>. * * @param key the desired key * @param l the desired <code>Locale</code> * @return if the value for <code>key</code> for the given <code>Locale</code> is a <code>String</code>, return the * <code>String</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static String getString(Object key, Locale l) { Object value = get(key, l); return (value instanceof String) ? (String) value : null; } /** * If the value of <code>key</code> is an <code>Integer</code> return its integer value, otherwise return 0. * * @param key the desired key * @return if the value for <code>key</code> is an <code>Integer</code>, return its value, otherwise return 0 */ public static int getInt(Object key) { Object value = get(key); return (value instanceof Integer) ? (Integer) value : 0; } /** * If the value of <code>key</code> for the given <code>Locale</code> is an <code>Integer</code> return its integer * value, otherwise return 0. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is an <code>Integer</code>, return its value, * otherwise return 0 * @since 1.9.5.04 */ public static int getInt(Object key, Locale l) { Object value = get(key, l); return (value instanceof Integer) ? (Integer) value : 0; } /** * If the value of <code>key</code> is boolean, return the boolean value, otherwise return false. * * @param key an <code>Object</code> specifying the key for the desired boolean value * @return if the value of <code>key</code> is boolean, return the boolean value, otherwise return false. * @since 1.9.5.04 */ public static boolean getBoolean(Object key) { Object value = get(key); return (value instanceof Boolean) ? (Boolean) value : false; } /** * If the value of <code>key</code> for the given <code>Locale</code> is boolean, return the boolean value, * otherwise return false. * * @param key an <code>Object</code> specifying the key for the desired boolean value * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is boolean, return the boolean value, otherwise * return false. * @since 1.9.5.04 */ public static boolean getBoolean(Object key, Locale l) { Object value = get(key, l); return (value instanceof Boolean) ? (Boolean) value : false; } /** * If the value of <code>key</code> is an <code>Insets</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is an <code>Insets</code>, return the <code>Insets</code> object; * otherwise return <code>null</code> */ public static Insets getInsets(Object key) { Object value = get(key); return (value instanceof Insets) ? (Insets) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is an <code>Insets</code> return it, otherwise * return <code>null</code>. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is an <code>Insets</code>, return the * <code>Insets</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static Insets getInsets(Object key, Locale l) { Object value = get(key, l); return (value instanceof Insets) ? (Insets) value : null; } /** * If the value of <code>key</code> is a <code>Dimension</code> return it, otherwise return <code>null</code>. * * @param key the desired key * @return if the value for <code>key</code> is a <code>Dimension</code>, return the <code>Dimension</code> object; * otherwise return <code>null</code> */ public static Dimension getDimension(Object key) { Object value = get(key); return (value instanceof Dimension) ? (Dimension) value : null; } /** * If the value of <code>key</code> for the given <code>Locale</code> is a <code>Dimension</code> return it, * otherwise return <code>null</code>. * * @param key the desired key * @param l the desired locale * @return if the value for <code>key</code> and <code>Locale</code> is a <code>Dimension</code>, return the * <code>Dimension</code> object; otherwise return <code>null</code> * @since 1.9.5.04 */ public static Dimension getDimension(Object key, Locale l) { Object value = get(key, l); return (value instanceof Dimension) ? (Dimension) value : null; } }
true
true
public static Object get(Object key) { Object value = UIManager.get(key); log(value, key, null); if (value instanceof Map && "Theme.painter".equals(key)) { Map map = (Map) value; try { ClassLoader classLoader = getCallerClassLoader(); Object o = map.get(classLoader); while (o == null && classLoader.getParent() != null) { classLoader = classLoader.getParent(); o = map.get(classLoader); } if (o == null && map.size() >= 1) { Collection<Object> classLoaders = map.values(); for (Object cl : classLoaders) { if (cl != null) { o = cl; break; } } } return o; } catch (Exception e) { return map.get(LookAndFeelFactory.getUIManagerClassLoader()); } } return value; }
public static Object get(Object key) { Object value = UIManager.get(key); log(value, key, null); if (value instanceof Map && "Theme.painter".equals(key)) { Map map = (Map) value; try { ClassLoader classLoader = getCallerClassLoader(); Object o = map.get(classLoader); while (o == null && classLoader.getParent() != null) { classLoader = classLoader.getParent(); o = map.get(classLoader); } if (o == null && map.size() >= 1) { Collection<Object> classLoaders = map.values(); for (Object cl : classLoaders) { if (cl != null) { o = cl; break; } } } return o; } catch (Exception e) { if (map.size() == 1) { return map.values().iterator().next(); } else { return map.get(LookAndFeelFactory.getUIManagerClassLoader()); } } } return value; }
diff --git a/driver-core/src/main/java/com/datastax/driver/core/RetryingCallback.java b/driver-core/src/main/java/com/datastax/driver/core/RetryingCallback.java index 9515e594a..f87a4b789 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/RetryingCallback.java +++ b/driver-core/src/main/java/com/datastax/driver/core/RetryingCallback.java @@ -1,271 +1,271 @@ package com.datastax.driver.core; import java.net.InetAddress; import java.util.Collections; import java.util.Iterator; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import java.util.concurrent.ExecutionException; import com.datastax.driver.core.policies.RetryPolicy; import com.datastax.driver.core.exceptions.*; import org.apache.cassandra.transport.Message; import org.apache.cassandra.transport.messages.ErrorMessage; import org.apache.cassandra.transport.messages.ExecuteMessage; import org.apache.cassandra.transport.messages.PrepareMessage; import org.apache.cassandra.transport.messages.QueryMessage; import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.cassandra.exceptions.UnavailableException; import org.apache.cassandra.exceptions.PreparedQueryNotFoundException; import org.apache.cassandra.exceptions.ReadTimeoutException; import org.apache.cassandra.exceptions.WriteTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Connection callback that handle retrying another node if the connection fails. * * For queries, this also handle retrying the query if the RetryPolicy say so. */ class RetryingCallback implements Connection.ResponseCallback { private static final Logger logger = LoggerFactory.getLogger(RetryingCallback.class); private final Session.Manager manager; private final Connection.ResponseCallback callback; private final Iterator<Host> queryPlan; private volatile Host current; private volatile HostConnectionPool currentPool; private volatile int queryRetries; private volatile ConsistencyLevel retryConsistencyLevel; private volatile Map<InetAddress, String> errors; public RetryingCallback(Session.Manager manager, Connection.ResponseCallback callback, Query query) { this.manager = manager; this.callback = callback; this.queryPlan = manager.loadBalancer.newQueryPlan(query); } public void sendRequest() { while (queryPlan.hasNext()) { Host host = queryPlan.next(); if (query(host)) return; } callback.onException(null, new NoHostAvailableException(errors == null ? Collections.<InetAddress, String>emptyMap() : errors)); } private boolean query(Host host) { currentPool = manager.pools.get(host); if (currentPool == null || currentPool.isShutdown()) return false; Connection connection = null; try { // Note: this is not perfectly correct to use getConnectTimeoutMillis(), but // until we provide a more fancy to control query timeouts, it's not a bad solution either connection = currentPool.borrowConnection(manager.configuration().getConnectionsConfiguration().getSocketOptions().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS); current = host; connection.write(this); return true; } catch (ConnectionException e) { // If we have any problem with the connection, move to the next node. currentPool.returnConnection(connection); logError(host.getAddress(), e.getMessage()); return false; } catch (BusyConnectionException e) { // The pool shoudln't have give us a busy connection unless we've maxed up the pool, so move on to the next host. currentPool.returnConnection(connection); logError(host.getAddress(), e.getMessage()); return false; } catch (TimeoutException e) { // We timeout, log it but move to the next node. currentPool.returnConnection(connection); logError(host.getAddress(), "Timeout while trying to acquire available connection"); currentPool.returnConnection(connection); return false; } catch (RuntimeException e) { currentPool.returnConnection(connection); logger.error("Unexpected error while querying " + host.getAddress(), e); logError(host.getAddress(), e.getMessage()); return false; } } private void logError(InetAddress address, String msg) { logger.debug("Error querying {}, trying next host (error is: {})", address, msg); if (errors == null) errors = new HashMap<InetAddress, String>(); errors.put(address, msg); } private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { final Host h = current; this.retryConsistencyLevel = newConsistencyLevel; // We should not retry on the current thread as this will be an IO thread. manager.executor().execute(new Runnable() { public void run() { if (retryCurrent) { if (query(h)) return; } sendRequest(); } }); } public Message.Request request() { Message.Request request = callback.request(); if (retryConsistencyLevel != null) { org.apache.cassandra.db.ConsistencyLevel cl = ConsistencyLevel.toCassandraCL(retryConsistencyLevel); if (request instanceof QueryMessage) { QueryMessage qm = (QueryMessage)request; if (qm.consistency != cl) request = new QueryMessage(qm.query, cl); } else if (request instanceof ExecuteMessage) { ExecuteMessage em = (ExecuteMessage)request; if (em.consistency != cl) request = new ExecuteMessage(em.statementId, em.values, cl); } } return request; } public void onSet(Connection connection, Message.Response response) { if (currentPool == null) { // This should not happen but is probably not reason to fail completely logger.error("No current pool set; this should not happen"); } else { currentPool.returnConnection(connection); } try { switch (response.type) { case RESULT: callback.onSet(connection, response); break; case ERROR: ErrorMessage err = (ErrorMessage)response; RetryPolicy.RetryDecision retry = null; RetryPolicy retryPolicy = manager.configuration().getPolicies().getRetryPolicy(); switch (err.error.code()) { case READ_TIMEOUT: assert err.error instanceof ReadTimeoutException; ReadTimeoutException rte = (ReadTimeoutException)err.error; ConsistencyLevel rcl = ConsistencyLevel.from(rte.consistency); - retry = retryPolicy.onReadTimeout(rcl, rte.received, rte.blockFor, rte.dataPresent, queryRetries); + retry = retryPolicy.onReadTimeout(rcl, rte.blockFor, rte.received, rte.dataPresent, queryRetries); break; case WRITE_TIMEOUT: assert err.error instanceof WriteTimeoutException; WriteTimeoutException wte = (WriteTimeoutException)err.error; ConsistencyLevel wcl = ConsistencyLevel.from(wte.consistency); - retry = retryPolicy.onWriteTimeout(wcl, WriteType.from(wte.writeType), wte.received, wte.blockFor, queryRetries); + retry = retryPolicy.onWriteTimeout(wcl, WriteType.from(wte.writeType), wte.blockFor, wte.received, queryRetries); break; case UNAVAILABLE: assert err.error instanceof UnavailableException; UnavailableException ue = (UnavailableException)err.error; ConsistencyLevel ucl = ConsistencyLevel.from(ue.consistency); retry = retryPolicy.onUnavailable(ucl, ue.required, ue.alive, queryRetries); break; case OVERLOADED: // Try another node retry(false, null); return; case IS_BOOTSTRAPPING: // Try another node logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address); retry(false, null); return; case UNPREPARED: assert err.error instanceof PreparedQueryNotFoundException; PreparedQueryNotFoundException pqnf = (PreparedQueryNotFoundException)err.error; String toPrepare = manager.cluster.manager.preparedQueries.get(pqnf.id); if (toPrepare == null) { // This shouldn't happen String msg = String.format("Tried to execute unknown prepared query %s", pqnf.id); logger.error(msg); callback.onException(connection, new DriverInternalError(msg)); return; } try { Message.Response prepareResponse = connection.write(new PrepareMessage(toPrepare)).get(); // TODO check return ? retry = RetryPolicy.RetryDecision.retry(null); } catch (InterruptedException e) { logError(connection.address, "Interrupted while preparing query to execute"); retry(false, null); return; } catch (ExecutionException e) { logError(connection.address, "Unexpected problem while preparing query to execute: " + e.getCause().getMessage()); retry(false, null); return; } catch (ConnectionException e) { logger.debug("Connection exception while preparing missing statement", e); logError(e.address, e.getMessage()); retry(false, null); return; } } if (retry == null) callback.onSet(connection, response); else { switch (retry.getType()) { case RETRY: ++queryRetries; retry(true, retry.getRetryConsistencyLevel()); break; case RETHROW: callback.onSet(connection, response); break; case IGNORE: callback.onSet(connection, new ResultMessage.Void()); break; } } break; default: callback.onSet(connection, response); break; } } catch (Exception e) { callback.onException(connection, e); } } public void onException(Connection connection, Exception exception) { if (connection != null) { if (currentPool == null) { // This should not happen but is probably not reason to fail completely logger.error("No current pool set; this should not happen"); } else { currentPool.returnConnection(connection); } } if (exception instanceof ConnectionException) { ConnectionException ce = (ConnectionException)exception; logError(ce.address, ce.getMessage()); retry(false, null); return; } callback.onException(connection, exception); } }
false
true
public void onSet(Connection connection, Message.Response response) { if (currentPool == null) { // This should not happen but is probably not reason to fail completely logger.error("No current pool set; this should not happen"); } else { currentPool.returnConnection(connection); } try { switch (response.type) { case RESULT: callback.onSet(connection, response); break; case ERROR: ErrorMessage err = (ErrorMessage)response; RetryPolicy.RetryDecision retry = null; RetryPolicy retryPolicy = manager.configuration().getPolicies().getRetryPolicy(); switch (err.error.code()) { case READ_TIMEOUT: assert err.error instanceof ReadTimeoutException; ReadTimeoutException rte = (ReadTimeoutException)err.error; ConsistencyLevel rcl = ConsistencyLevel.from(rte.consistency); retry = retryPolicy.onReadTimeout(rcl, rte.received, rte.blockFor, rte.dataPresent, queryRetries); break; case WRITE_TIMEOUT: assert err.error instanceof WriteTimeoutException; WriteTimeoutException wte = (WriteTimeoutException)err.error; ConsistencyLevel wcl = ConsistencyLevel.from(wte.consistency); retry = retryPolicy.onWriteTimeout(wcl, WriteType.from(wte.writeType), wte.received, wte.blockFor, queryRetries); break; case UNAVAILABLE: assert err.error instanceof UnavailableException; UnavailableException ue = (UnavailableException)err.error; ConsistencyLevel ucl = ConsistencyLevel.from(ue.consistency); retry = retryPolicy.onUnavailable(ucl, ue.required, ue.alive, queryRetries); break; case OVERLOADED: // Try another node retry(false, null); return; case IS_BOOTSTRAPPING: // Try another node logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address); retry(false, null); return; case UNPREPARED: assert err.error instanceof PreparedQueryNotFoundException; PreparedQueryNotFoundException pqnf = (PreparedQueryNotFoundException)err.error; String toPrepare = manager.cluster.manager.preparedQueries.get(pqnf.id); if (toPrepare == null) { // This shouldn't happen String msg = String.format("Tried to execute unknown prepared query %s", pqnf.id); logger.error(msg); callback.onException(connection, new DriverInternalError(msg)); return; } try { Message.Response prepareResponse = connection.write(new PrepareMessage(toPrepare)).get(); // TODO check return ? retry = RetryPolicy.RetryDecision.retry(null); } catch (InterruptedException e) { logError(connection.address, "Interrupted while preparing query to execute"); retry(false, null); return; } catch (ExecutionException e) { logError(connection.address, "Unexpected problem while preparing query to execute: " + e.getCause().getMessage()); retry(false, null); return; } catch (ConnectionException e) { logger.debug("Connection exception while preparing missing statement", e); logError(e.address, e.getMessage()); retry(false, null); return; } } if (retry == null) callback.onSet(connection, response); else { switch (retry.getType()) { case RETRY: ++queryRetries; retry(true, retry.getRetryConsistencyLevel()); break; case RETHROW: callback.onSet(connection, response); break; case IGNORE: callback.onSet(connection, new ResultMessage.Void()); break; } } break; default: callback.onSet(connection, response); break; } } catch (Exception e) { callback.onException(connection, e); } }
public void onSet(Connection connection, Message.Response response) { if (currentPool == null) { // This should not happen but is probably not reason to fail completely logger.error("No current pool set; this should not happen"); } else { currentPool.returnConnection(connection); } try { switch (response.type) { case RESULT: callback.onSet(connection, response); break; case ERROR: ErrorMessage err = (ErrorMessage)response; RetryPolicy.RetryDecision retry = null; RetryPolicy retryPolicy = manager.configuration().getPolicies().getRetryPolicy(); switch (err.error.code()) { case READ_TIMEOUT: assert err.error instanceof ReadTimeoutException; ReadTimeoutException rte = (ReadTimeoutException)err.error; ConsistencyLevel rcl = ConsistencyLevel.from(rte.consistency); retry = retryPolicy.onReadTimeout(rcl, rte.blockFor, rte.received, rte.dataPresent, queryRetries); break; case WRITE_TIMEOUT: assert err.error instanceof WriteTimeoutException; WriteTimeoutException wte = (WriteTimeoutException)err.error; ConsistencyLevel wcl = ConsistencyLevel.from(wte.consistency); retry = retryPolicy.onWriteTimeout(wcl, WriteType.from(wte.writeType), wte.blockFor, wte.received, queryRetries); break; case UNAVAILABLE: assert err.error instanceof UnavailableException; UnavailableException ue = (UnavailableException)err.error; ConsistencyLevel ucl = ConsistencyLevel.from(ue.consistency); retry = retryPolicy.onUnavailable(ucl, ue.required, ue.alive, queryRetries); break; case OVERLOADED: // Try another node retry(false, null); return; case IS_BOOTSTRAPPING: // Try another node logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address); retry(false, null); return; case UNPREPARED: assert err.error instanceof PreparedQueryNotFoundException; PreparedQueryNotFoundException pqnf = (PreparedQueryNotFoundException)err.error; String toPrepare = manager.cluster.manager.preparedQueries.get(pqnf.id); if (toPrepare == null) { // This shouldn't happen String msg = String.format("Tried to execute unknown prepared query %s", pqnf.id); logger.error(msg); callback.onException(connection, new DriverInternalError(msg)); return; } try { Message.Response prepareResponse = connection.write(new PrepareMessage(toPrepare)).get(); // TODO check return ? retry = RetryPolicy.RetryDecision.retry(null); } catch (InterruptedException e) { logError(connection.address, "Interrupted while preparing query to execute"); retry(false, null); return; } catch (ExecutionException e) { logError(connection.address, "Unexpected problem while preparing query to execute: " + e.getCause().getMessage()); retry(false, null); return; } catch (ConnectionException e) { logger.debug("Connection exception while preparing missing statement", e); logError(e.address, e.getMessage()); retry(false, null); return; } } if (retry == null) callback.onSet(connection, response); else { switch (retry.getType()) { case RETRY: ++queryRetries; retry(true, retry.getRetryConsistencyLevel()); break; case RETHROW: callback.onSet(connection, response); break; case IGNORE: callback.onSet(connection, new ResultMessage.Void()); break; } } break; default: callback.onSet(connection, response); break; } } catch (Exception e) { callback.onException(connection, e); } }
diff --git a/src/java/com/mozilla/hadoop/Backup.java b/src/java/com/mozilla/hadoop/Backup.java index 8225999..d852b33 100644 --- a/src/java/com/mozilla/hadoop/Backup.java +++ b/src/java/com/mozilla/hadoop/Backup.java @@ -1,447 +1,447 @@ /** * Copyright 2010 Mozilla Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mozilla.hadoop; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * Backup is a distcp alternative. It was created specifically for copying HBase table directories while * the source cluster may still be running. Backup tends to be more immune to errors than distcp when running * in this type of scenario as it favors swallowing exceptions and incrementing counters as opposed to failing. * * The MapReduce output is used to list files that have failed so that list could be used for investigation purposes * and potentially distcp at a later time. * * @author Xavier Stevens * */ public class Backup implements Tool { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(Backup.class); private static final String NAME = "Backup"; private Configuration conf; public static class BackupMapper extends Mapper<LongWritable, Text, Text, NullWritable> { public enum ReportStats { DIRECTORY_GET_PATHS_FAILED, BYTES_EXPECTED, BYTES_COPIED, BYTES_OUTPUTFS, COPY_FILE_FNF_FAILURE, COPY_FILE_FAILED, NOT_MODIFIED }; private FileSystem inputFs; private FileSystem outputFs; private String outputRootPath; private Pattern filePattern; /* (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#setup(org.apache.hadoop.mapreduce.Mapper.Context) */ public void setup(Context context) { Configuration conf = context.getConfiguration(); try { String backupInputPath = conf.get("backup.input.path"); if (!backupInputPath.endsWith(Path.SEPARATOR)) { backupInputPath += Path.SEPARATOR; } filePattern = Pattern.compile(backupInputPath + "(.+)"); inputFs = FileSystem.get(new Path(backupInputPath).toUri(), context.getConfiguration()); outputRootPath = conf.get("backup.output.path"); if (!outputRootPath.endsWith(Path.SEPARATOR)) { outputRootPath += Path.SEPARATOR; } outputFs = FileSystem.get(new Path(outputRootPath).toUri(), conf); } catch (IOException e) { throw new RuntimeException("Could not get FileSystem", e); } } /* (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#cleanup(org.apache.hadoop.mapreduce.Mapper.Context) */ public void cleanup(Context context) { checkAndClose(inputFs); } /** * Copy the file at inputPath to the destination cluster using the same directory structure * @param inputPath * @param context * @throws InterruptedException * @throws IOException */ private void copyFile(Path inputPath, Context context) throws InterruptedException, IOException { FSDataInputStream dis = null; FSDataOutputStream dos = null; String commonPath = null; Matcher m = filePattern.matcher(inputPath.toString()); if (m.find()) { if (m.groupCount() == 1) { commonPath = m.group(1); } } else { throw new RuntimeException("Regex match on common path failed"); } Path fullOutputPath = new Path(outputRootPath + commonPath); try { outputFs.mkdirs(fullOutputPath.getParent()); long inputFileSize = inputFs.getFileStatus(inputPath).getLen(); if (outputFs.exists(fullOutputPath) && inputFs.getFileStatus(inputPath).getLen() == outputFs.getFileStatus(fullOutputPath).getLen()) { context.getCounter(ReportStats.NOT_MODIFIED).increment(1L); } else { context.getCounter(ReportStats.BYTES_EXPECTED).increment(inputFileSize); dis = inputFs.open(inputPath); dos = outputFs.create(fullOutputPath, true); LOG.info("Writing " + inputPath.toString() + " to " + fullOutputPath); - String statusStr = inputPath.toString() + ": copying [ %s / %s ]"; + String statusStr = inputPath.toString() + ": copying [ %d / %d ]"; long totalBytesWritten = 0L; - Object[] statusFormatArgs = new Object[] { StringUtils.humanReadableInt(totalBytesWritten), StringUtils.humanReadableInt(inputFileSize) }; + Object[] statusFormatArgs = new Object[] { totalBytesWritten, inputFileSize }; byte[] buffer = new byte[65536]; int bytesRead = 0; int writeCount = 0; while ((bytesRead = dis.read(buffer)) >= 0) { dos.write(buffer, 0, bytesRead); totalBytesWritten += bytesRead; if (writeCount % 10 == 0) { context.progress(); writeCount = 0; // output copy status - statusFormatArgs[0] = StringUtils.humanReadableInt(totalBytesWritten); + statusFormatArgs[0] = totalBytesWritten; context.setStatus(String.format(statusStr, statusFormatArgs)); } writeCount++; } context.getCounter(ReportStats.BYTES_COPIED).increment(totalBytesWritten); } } catch (FileNotFoundException e) { LOG.error("Source file is missing", e); context.getCounter(ReportStats.COPY_FILE_FNF_FAILURE).increment(1L); } catch (Exception e) { LOG.error("Error copying file", e); context.getCounter(ReportStats.COPY_FILE_FAILED).increment(1L); context.write(new Text(inputPath.toString()), NullWritable.get()); } finally { checkAndClose(dis); checkAndClose(dos); } context.getCounter(ReportStats.BYTES_OUTPUTFS).increment(outputFs.getFileStatus(fullOutputPath).getLen()); } /* (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN, org.apache.hadoop.mapreduce.Mapper.Context) */ public void map(LongWritable key, Text value, Context context) throws InterruptedException, IOException { Path inputPath = new Path(value.toString()); List<Path> inputPaths = null; try { inputPaths = Backup.getAllPaths(inputFs, inputPath); if (inputPaths != null && inputPaths.size() > 0) { for (Path p : inputPaths) { copyFile(p, context); } } } catch (Exception e) { LOG.error("Directory getPaths failed", e); context.getCounter(ReportStats.DIRECTORY_GET_PATHS_FAILED).increment(1L); context.write(new Text(value.toString()), NullWritable.get()); return; } } } /** * Check the handle and close it * @param c */ private static void checkAndClose(java.io.Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.error("Error closing stream", e); } } } /** * Load a list of paths from a file * @param fs * @param inputPath * @return * @throws IOException */ public static List<Path> loadPaths(FileSystem fs, Path inputPath) throws IOException { List<Path> retPaths = new ArrayList<Path>(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(fs.open(inputPath))); String line = null; while ((line = reader.readLine()) != null) { retPaths.add(new Path(line)); } } catch (IOException e) { LOG.error("Exception in loadPaths for inputPath: " + inputPath.toString()); } finally { checkAndClose(reader); } return retPaths; } /** * Walk recursively to get all file paths up to a max depth * @param fs * @param inputPath * @param depth * @param maxDepth * @return * @throws IOException */ public static List<Path> getPaths(FileSystem fs, Path inputPath, int depth, int maxDepth) throws IOException { List<Path> retPaths = new ArrayList<Path>(); for (FileStatus status : fs.listStatus(inputPath)) { if (status.isDir() && (maxDepth == -1 || depth < maxDepth)) { retPaths.addAll(getPaths(fs, status.getPath(), depth + 1, maxDepth)); } else { retPaths.add(status.getPath()); } } return retPaths; } /** * Walk recursively to get all file paths * @param fs * @param inputPath * @param endTimeMillis * @return * @throws IOException */ public static List<Path> getAllPaths(FileSystem fs, Path inputPath) throws IOException { return getPaths(fs, inputPath, 0, -1); } /** * Get the input source files to be used as input for the backup mappers * @param inputFs * @param inputPath * @param outputFs * @return * @throws IOException */ public Path[] createInputSources(List<Path> paths, FileSystem outputFs) throws IOException { int suggestedMapRedTasks = conf.getInt("mapred.map.tasks", 1); Path[] inputSources = new Path[suggestedMapRedTasks]; for (int i=0; i < inputSources.length; i++) { inputSources[i] = new Path(NAME + "-inputsource" + i + ".txt"); } List<BufferedWriter> writers = new ArrayList<BufferedWriter>(); int idx = 0; try { for (Path source : inputSources) { writers.add(new BufferedWriter(new OutputStreamWriter(outputFs.create(source)))); } for (Path p : paths) { writers.get(idx).write(p.toString()); writers.get(idx).newLine(); idx++; if (idx >= inputSources.length) { idx = 0; } } } finally { for (BufferedWriter writer : writers) { checkAndClose(writer); } } return inputSources; } /** * @param args * @return * @throws IOException * @throws ParseException */ public Job initJob(String[] args) throws IOException, ParseException { Path inputPath = null; Path loadPath = null; String outputPath = null; boolean useSpecifiedPaths = false; for (int idx=0; idx < args.length; idx++) { if ("-f".equals(args[idx])) { useSpecifiedPaths = true; loadPath = new Path(args[++idx]); } else if (idx == args.length -1) { outputPath = args[idx]; } else { inputPath = new Path(args[idx]); } } Path mrOutputPath = new Path(NAME + "-results"); conf.setBoolean("mapred.map.tasks.speculative.execution", false); conf.set("backup.input.path", inputPath.toString()); conf.set("backup.output.path", outputPath); FileSystem inputFs = null; FileSystem outputFs = null; Path[] inputSources = null; try { inputFs = FileSystem.get(inputPath.toUri(), new Configuration()); outputFs = FileSystem.get(getConf()); if (useSpecifiedPaths) { inputSources = createInputSources(loadPaths(outputFs, loadPath), outputFs); } else { inputSources = createInputSources(getPaths(inputFs, inputPath, 0, 2), outputFs); } } finally { checkAndClose(inputFs); checkAndClose(outputFs); } Job job = new Job(getConf()); job.setJobName(NAME); job.setJarByClass(Backup.class); job.setMapperClass(BackupMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setNumReduceTasks(0); job.setInputFormatClass(TextInputFormat.class); for (Path source : inputSources) { System.out.println("Adding input path: " + source.toString()); FileInputFormat.addInputPath(job, source); } FileOutputFormat.setOutputPath(job, mrOutputPath); return job; } /** * @return */ private static int printUsage() { System.out.println("Usage: " + NAME + " [generic-options] [-f <file-list-path>] <input-path> <output-path>"); System.out.println(); GenericOptionsParser.printGenericCommandUsage(System.out); return -1; } /* (non-Javadoc) * @see org.apache.hadoop.util.Tool#run(java.lang.String[]) */ public int run(String[] args) throws Exception { if (args.length < 2) { return printUsage(); } int rc = -1; Job job = initJob(args); job.waitForCompletion(true); if (job.isSuccessful()) { rc = 0; FileSystem hdfs = null; try { hdfs = FileSystem.get(job.getConfiguration()); hdfs.delete(new Path(NAME + "-inputsource*.txt"), false); } finally { checkAndClose(hdfs); } } return rc; } /* (non-Javadoc) * @see org.apache.hadoop.conf.Configurable#getConf() */ public Configuration getConf() { return this.conf; } /* (non-Javadoc) * @see org.apache.hadoop.conf.Configurable#setConf(org.apache.hadoop.conf.Configuration) */ public void setConf(Configuration conf) { this.conf = conf; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new Backup(), args); System.exit(res); } }
false
true
private void copyFile(Path inputPath, Context context) throws InterruptedException, IOException { FSDataInputStream dis = null; FSDataOutputStream dos = null; String commonPath = null; Matcher m = filePattern.matcher(inputPath.toString()); if (m.find()) { if (m.groupCount() == 1) { commonPath = m.group(1); } } else { throw new RuntimeException("Regex match on common path failed"); } Path fullOutputPath = new Path(outputRootPath + commonPath); try { outputFs.mkdirs(fullOutputPath.getParent()); long inputFileSize = inputFs.getFileStatus(inputPath).getLen(); if (outputFs.exists(fullOutputPath) && inputFs.getFileStatus(inputPath).getLen() == outputFs.getFileStatus(fullOutputPath).getLen()) { context.getCounter(ReportStats.NOT_MODIFIED).increment(1L); } else { context.getCounter(ReportStats.BYTES_EXPECTED).increment(inputFileSize); dis = inputFs.open(inputPath); dos = outputFs.create(fullOutputPath, true); LOG.info("Writing " + inputPath.toString() + " to " + fullOutputPath); String statusStr = inputPath.toString() + ": copying [ %s / %s ]"; long totalBytesWritten = 0L; Object[] statusFormatArgs = new Object[] { StringUtils.humanReadableInt(totalBytesWritten), StringUtils.humanReadableInt(inputFileSize) }; byte[] buffer = new byte[65536]; int bytesRead = 0; int writeCount = 0; while ((bytesRead = dis.read(buffer)) >= 0) { dos.write(buffer, 0, bytesRead); totalBytesWritten += bytesRead; if (writeCount % 10 == 0) { context.progress(); writeCount = 0; // output copy status statusFormatArgs[0] = StringUtils.humanReadableInt(totalBytesWritten); context.setStatus(String.format(statusStr, statusFormatArgs)); } writeCount++; } context.getCounter(ReportStats.BYTES_COPIED).increment(totalBytesWritten); } } catch (FileNotFoundException e) { LOG.error("Source file is missing", e); context.getCounter(ReportStats.COPY_FILE_FNF_FAILURE).increment(1L); } catch (Exception e) { LOG.error("Error copying file", e); context.getCounter(ReportStats.COPY_FILE_FAILED).increment(1L); context.write(new Text(inputPath.toString()), NullWritable.get()); } finally { checkAndClose(dis); checkAndClose(dos); } context.getCounter(ReportStats.BYTES_OUTPUTFS).increment(outputFs.getFileStatus(fullOutputPath).getLen()); }
private void copyFile(Path inputPath, Context context) throws InterruptedException, IOException { FSDataInputStream dis = null; FSDataOutputStream dos = null; String commonPath = null; Matcher m = filePattern.matcher(inputPath.toString()); if (m.find()) { if (m.groupCount() == 1) { commonPath = m.group(1); } } else { throw new RuntimeException("Regex match on common path failed"); } Path fullOutputPath = new Path(outputRootPath + commonPath); try { outputFs.mkdirs(fullOutputPath.getParent()); long inputFileSize = inputFs.getFileStatus(inputPath).getLen(); if (outputFs.exists(fullOutputPath) && inputFs.getFileStatus(inputPath).getLen() == outputFs.getFileStatus(fullOutputPath).getLen()) { context.getCounter(ReportStats.NOT_MODIFIED).increment(1L); } else { context.getCounter(ReportStats.BYTES_EXPECTED).increment(inputFileSize); dis = inputFs.open(inputPath); dos = outputFs.create(fullOutputPath, true); LOG.info("Writing " + inputPath.toString() + " to " + fullOutputPath); String statusStr = inputPath.toString() + ": copying [ %d / %d ]"; long totalBytesWritten = 0L; Object[] statusFormatArgs = new Object[] { totalBytesWritten, inputFileSize }; byte[] buffer = new byte[65536]; int bytesRead = 0; int writeCount = 0; while ((bytesRead = dis.read(buffer)) >= 0) { dos.write(buffer, 0, bytesRead); totalBytesWritten += bytesRead; if (writeCount % 10 == 0) { context.progress(); writeCount = 0; // output copy status statusFormatArgs[0] = totalBytesWritten; context.setStatus(String.format(statusStr, statusFormatArgs)); } writeCount++; } context.getCounter(ReportStats.BYTES_COPIED).increment(totalBytesWritten); } } catch (FileNotFoundException e) { LOG.error("Source file is missing", e); context.getCounter(ReportStats.COPY_FILE_FNF_FAILURE).increment(1L); } catch (Exception e) { LOG.error("Error copying file", e); context.getCounter(ReportStats.COPY_FILE_FAILED).increment(1L); context.write(new Text(inputPath.toString()), NullWritable.get()); } finally { checkAndClose(dis); checkAndClose(dos); } context.getCounter(ReportStats.BYTES_OUTPUTFS).increment(outputFs.getFileStatus(fullOutputPath).getLen()); }
diff --git a/workloadSuite/GenerateReplayScript.java b/workloadSuite/GenerateReplayScript.java index f856e1a..8b31624 100644 --- a/workloadSuite/GenerateReplayScript.java +++ b/workloadSuite/GenerateReplayScript.java @@ -1,465 +1,465 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.File; import java.io.InputStreamReader; import java.util.HashMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.text.SimpleDateFormat; public class GenerateReplayScript { /* * Workload file format constants for field indices */ static final int INTER_JOB_SLEEP_TIME = 2; static final int INPUT_DATA_SIZE = 3; static final int SHUFFLE_DATA_SIZE = 4; static final int OUTPUT_DATA_SIZE = 5; /* * * Parses a tab separated file into an ArrayList<ArrayList<String>> * */ public static long parseFileArrayList(String path, ArrayList<ArrayList<String>> data ) throws Exception { long maxInput = 0; BufferedReader input = new BufferedReader(new FileReader(path)); String s; String[] array; int rowIndex = 0; int columnIndex = 0; while (true) { if (!input.ready()) break; s = input.readLine(); array = s.split("\t"); try { columnIndex = 0; while (columnIndex < array.length) { if (columnIndex == 0) { data.add(rowIndex,new ArrayList<String>()); } String value = array[columnIndex]; data.get(rowIndex).add(value); if (Long.parseLong(array[INPUT_DATA_SIZE]) > maxInput) { maxInput = Long.parseLong(array[INPUT_DATA_SIZE]); } columnIndex++; } rowIndex++; } catch (Exception e) { } } return maxInput; } /* * * Prints the necessary shell scripts * */ public static void printOutput(ArrayList<ArrayList<String>> workloadData, int clusterSizeRaw, int clusterSizeWorkload, int inputPartitionSize, int inputPartitionCount, String scriptDirPath, String hdfsInputDir, String hdfsOutputPrefix, long totalDataPerReduce, String workloadOutputDir, String hadoopCommand, String pathToWorkGenJar, String pathToWorkGenConf) throws Exception { if (workloadData.size() > 0) { long maxInput = 0; String toWrite = ""; FileWriter runAllJobs = new FileWriter(scriptDirPath + "/run-jobs-all.sh"); toWrite = "#!/bin/bash\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "rm -r " + workloadOutputDir + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "mkdir " + workloadOutputDir + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); System.out.println(); System.out.println(workloadData.size() + " jobs in the workload."); System.out.println("Generating scripts ... please wait ... "); System.out.println(); int written = 0; for (int i=0; i<workloadData.size(); i++) { long sleep = Long.parseLong(workloadData.get(i).get(INTER_JOB_SLEEP_TIME)); long input = Long.parseLong(workloadData.get(i).get(INPUT_DATA_SIZE)); long shuffle = Long.parseLong(workloadData.get(i).get(SHUFFLE_DATA_SIZE)); long output = Long.parseLong(workloadData.get(i).get(OUTPUT_DATA_SIZE)); // Logic to scale sleep time such that smaller cluster = fewer jobs // Currently not done // // sleep = sleep * clusterSizeRaw / clusterSizeWorkload; input = input * clusterSizeWorkload / clusterSizeRaw; shuffle = shuffle * clusterSizeWorkload / clusterSizeRaw; output = output * clusterSizeWorkload / clusterSizeRaw; if (input > maxInput) maxInput = input; + if (input < maxSeqFile(67108864)) input = maxSeqFile(67108864); // 64 MB minimum size - if (input < 67108864) input = 67108864; if (shuffle < 1024 ) shuffle = 1024 ; if (output < 1024 ) output = 1024 ; ArrayList<Integer> inputPartitionSamples = new ArrayList<Integer>(); long inputCopy = input; java.util.Random rng = new java.util.Random(); int tryPartitionSample = rng.nextInt(inputPartitionCount); while (inputCopy > 0) { boolean alreadySampled = true; while (alreadySampled) { if (inputPartitionSamples.size()>=inputPartitionCount) { System.err.println(); System.err.println("ERROR!"); System.err.println("Not enough partitions for input size of " + input + " bytes."); System.err.println("Happened on job number " + i + "."); System.err.println("Input partition size is " + inputPartitionSize + " bytes."); System.err.println("Number of partitions is " + inputPartitionCount + "."); System.err.println("Total data size is " + (((long) inputPartitionSize) * ((long) inputPartitionCount)) + " bytes < " + input + " bytes."); System.err.println("Need to generate a larger input data set."); System.err.println(); throw new Exception("Input data set not large enough. Need to generate a larger data set."); // if exception thrown here, input set not large enough - generate bigger input set } alreadySampled = false; } inputPartitionSamples.add(new Integer(tryPartitionSample)); tryPartitionSample = (tryPartitionSample + 1) % inputPartitionCount; inputCopy -= inputPartitionSize; } FileWriter inputPathFile = new FileWriter(scriptDirPath + "/inputPath-job-" + i + ".txt"); String inputPath = ""; for (int j=0; j<inputPartitionSamples.size(); j++) { inputPath = (hdfsInputDir + "/part-" + String.format("%05d", inputPartitionSamples.get(j))); if (j != (inputPartitionSamples.size()-1)) inputPath += ","; inputPathFile.write(inputPath.toCharArray(), 0, inputPath.length()); } inputPathFile.close(); // write inputPath to separate file to get around ARG_MAX limit for large clusters inputPath = "inputPath-job-" + i + ".txt"; String outputPath = hdfsOutputPrefix + "-" + i; float SIRatio = ((float) shuffle) / ((float) input ); float OSRatio = ((float) output ) / ((float) shuffle); long numReduces = -1; if (totalDataPerReduce > 0) { numReduces = Math.round((shuffle + output) / ((double) totalDataPerReduce)); if (numReduces < 1) numReduces = 1; if (numReduces > clusterSizeWorkload) numReduces = clusterSizeWorkload / 5; toWrite = "" + hadoopCommand + " jar " + pathToWorkGenJar + " org.apache.hadoop.examples.WorkGen -conf " + pathToWorkGenConf + " " + "-r " + numReduces + " " + inputPath + " " + outputPath + " " + SIRatio + " " + OSRatio + " >> " + workloadOutputDir + "/job-" + i + ".txt 2>> " + workloadOutputDir + "/job-" + i + ".txt \n"; } else { toWrite = "" + hadoopCommand + " jar " + pathToWorkGenJar + " org.apache.hadoop.examples.WorkGen -conf " + pathToWorkGenConf + " " + inputPath + " " + outputPath + " " + SIRatio + " " + OSRatio + " >> " + workloadOutputDir + "/job-" + i + ".txt 2>> " + workloadOutputDir + "/job-" + i + ".txt \n"; } FileWriter runFile = new FileWriter(scriptDirPath + "/run-job-" + i + ".sh"); runFile.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "" + hadoopCommand + " dfs -rmr " + outputPath + "\n"; runFile.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputSize " + input + "\n"; runFile.write(toWrite.toCharArray(), 0, toWrite.length()); runFile.close(); // works for linux type systems only Runtime.getRuntime().exec("chmod +x " + scriptDirPath + "/run-job-" + i + ".sh"); toWrite = "./run-job-" + i + ".sh &\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "sleep " + sleep + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); written++; } System.out.println(written + " jobs written ... done."); System.out.println(); toWrite = "# max input " + maxInput + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputPartitionSize " + inputPartitionSize + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputPartitionCount " + inputPartitionCount + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); runAllJobs.close(); // works for linux type systems only Runtime.getRuntime().exec("chmod +x " + scriptDirPath + "/run-jobs-all.sh"); } } /* * * Computes the size of a SequenceFile with the given number * of records. We assume the following 96 byte header: * 4 bytes (magic header prefix) ... key class name: 35 bytes for "org.apache.hadoop.io.BytesWritable" (34 characters + one-byte length) ... value class name: 35 bytes for "org.apache.hadoop.io.BytesWritable" 1 byte boolean (is each record value compressed?) 1 byte boolean (is the file block compressed?) bytes for metadata: in our case, there is no metadata, and we get 4 bytes of zeros 16 bytes of sync * * The SequenceFile writer places a periodic marker after writing a * minimum of 2000 bytes; the marker also falls at a record boundary. * Therefore, unless the serialized record size is a factor of 2000, more * than 2000 bytes will be written between markers. In the code below, we * refer to this distance as the "markerSpacing". * * The SequenceFile writer can be found in: * hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/SequenceFile.java * * There are informative constants at the top of the SequenceFile class, * and the heart of the writer is the append() method of the Writer class. * */ static final int SeqFileHeaderSize = 96; static final int SeqFileRecordSizeUsable = 100; // max_key + max_value static final int SeqFileRecordSizeSerialized = 116; // usable + 4 ints static final int SeqFileMarkerSize = 20; static final double SeqFileMarkerMinSpacing = 2000.0; private static int seqFileSize(int numRecords) { int totalSize = SeqFileHeaderSize; int recordTotal = numRecords * SeqFileRecordSizeSerialized; totalSize += recordTotal; int numRecordsBetweenMarkers = (int) Math.ceil(SeqFileMarkerMinSpacing / (SeqFileRecordSizeSerialized * 1.0)); int markerSpacing = numRecordsBetweenMarkers * SeqFileRecordSizeSerialized; int numMarkers = (int) Math.floor((totalSize * 1.0) / (markerSpacing * 1.0)); totalSize += numMarkers * SeqFileMarkerSize; return totalSize; } /* * * Computes the amount of data a SequenceFile would hold in * an HDFS block of the given size. First, we estimate the number * of records which will fit by inverting seqFileSize(), then we * decrease until we fit within the block. * * To compute the inverse, we start with a simplified form of the equation * computed by seqFileSize(), using X for the number of records: * * totalSize = * header + X * serialized * + markerSize * (header + X * serialized) / markerSpacing * * using some algebra: * * (totalSize - header) * markerSpacing * * = X * serialized * markerSpacing + markerSize * (header + X * serialized) * * * (totalSize - header) * markerSpacing - markerSize * header * * = X * serialized * markerSpacing + markerSize * X * serialized * * = (markerSpacing + markerSize) * X * serialized * * We now have a Right-Hand Side which looks easy to deal with! * * Focusing on the Left-Hand Side, we'd like to avoid multiplying * (totalSize - header) * markerSpacing as it may be a very large number. * We re-write as follows: * * (totalSize - header) * markerSpacing - markerSize * header = * (totalSize - header - markerSize * header / markerSpacing) * markerSpacing * */ public static int maxSeqFile(int blockSize) { // First, compute some values we will need. Same as in seqFileSize() int numRecordsBetweenMarkers = (int) Math.ceil(SeqFileMarkerMinSpacing / (SeqFileRecordSizeSerialized * 1.0)); double markerSpacing = numRecordsBetweenMarkers * SeqFileRecordSizeSerialized * 1.0; // Calculate the Left-Hand Side we wrote in the comment above double est = blockSize - SeqFileHeaderSize - (SeqFileMarkerSize * SeqFileHeaderSize * 1.0) / markerSpacing; est *= markerSpacing; // Now, divide the constants from the Right-Hand Side we found above est /= (markerSpacing + SeqFileMarkerSize * 1.0); est /= (SeqFileRecordSizeSerialized * 1.0); // Can't have a fractional number of records! int numRecords = (int) Math.ceil(est); // Check if we over-estimated while (seqFileSize(numRecords) > blockSize) { numRecords--; } return (numRecords * SeqFileRecordSizeUsable); } /* * * Read in command line arguments etc. * */ public static void main(String args[]) throws Exception { if (args.length < 10) { System.out.println(); System.out.println("Insufficient arguments."); System.out.println(); System.out.println("Usage: "); System.out.println(); System.out.println("java GenerateReplayScript"); System.out.println(" [path to file with workload info]"); System.out.println(" [number of machines in the original production cluster]"); System.out.println(" [number of machines in the cluster on which the workload will be run]"); System.out.println(" [HDFS block size]"); System.out.println(" [number of input partitions]"); System.out.println(" [output directory for the scripts]"); System.out.println(" [HDFS directory for the input data]"); System.out.println(" [amount of data per reduce task in byptes]"); System.out.println(" [directory for the workload output files]"); System.out.println(" [hadoop command on your system]"); System.out.println(" [path to WorkGen.jar]"); System.out.println(" [path to workGenKeyValue_conf.xsl]"); System.out.println(); } else { // variables ArrayList<ArrayList<String>> workloadData = new ArrayList<ArrayList<String>>(); // read command line arguments String fileWorkloadPath = args[0]; int clusterSizeRaw = Integer.parseInt(args[1]); int clusterSizeWorkload = Integer.parseInt(args[2]); int hdfsBlockSize = Integer.parseInt(args[3]); int inputPartitionCount = Integer.parseInt(args[4]); String scriptDirPath = args[5]; String hdfsInputDir = args[6]; String hdfsOutputPrefix = args[7]; long totalDataPerReduce = Long.parseLong(args[8]); String workloadOutputDir = args[9]; String hadoopCommand = args[10]; String pathToWorkGenJar = args[11]; String pathToWorkGenConf = args[12]; // parse data long maxInput = parseFileArrayList(fileWorkloadPath, workloadData); // check if maxInput fits within input data size to be generated long maxInputNeeded = maxInput * clusterSizeWorkload / clusterSizeRaw; int inputPartitionSize = maxSeqFile(hdfsBlockSize); long totalInput = ((long) inputPartitionSize) * ((long) inputPartitionCount); if (maxInputNeeded > totalInput) { System.err.println(); System.err.println("ERROR!"); System.err.println("Not enough partitions for max needed input size of " + maxInputNeeded + " bytes."); System.err.println("HDFS block size is " + hdfsBlockSize + " bytes."); System.err.println("Input partition size is " + inputPartitionSize + " bytes."); System.err.println("Number of partitions is " + inputPartitionCount + "."); System.err.println("Total actual input data size is " + totalInput + " bytes < " + maxInputNeeded + " bytes."); System.err.println("Need to generate a larger input data set."); System.err.println(); throw new Exception("Input data set not large enough. Need to generate a larger data set."); } else { System.err.println(); System.err.println("Max needed input size " + maxInputNeeded + " bytes."); System.err.println("Actual input size is " + totalInput + " bytes >= " + maxInputNeeded + " bytes."); System.err.println("All is good."); System.err.println(); } // make scriptDirPath directory if it doesn't exist File d = new File(scriptDirPath); if (d.exists()) { if (d.isDirectory()) { System.err.println("Warning! About to overwrite existing scripts in: " + scriptDirPath); System.err.print("Ok to continue? [y/n] "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); if (s == null || s.length() < 1 || s.toLowerCase().charAt(0) != 'y') { throw new Exception("Declined overwrite of existing directory"); } } else { throw new Exception(scriptDirPath + " is a file."); } } else { d.mkdirs(); } // print shell scripts printOutput(workloadData, clusterSizeRaw, clusterSizeWorkload, inputPartitionSize, inputPartitionCount, scriptDirPath, hdfsInputDir, hdfsOutputPrefix, totalDataPerReduce, workloadOutputDir, hadoopCommand, pathToWorkGenJar, pathToWorkGenConf); System.out.println("Parameter values for randomwriter_conf.xsl:"); System.out.println("test.randomwrite.total_bytes: " + totalInput); System.out.println("test.randomwrite.bytes_per_map: " + inputPartitionSize); } } }
false
true
public static void printOutput(ArrayList<ArrayList<String>> workloadData, int clusterSizeRaw, int clusterSizeWorkload, int inputPartitionSize, int inputPartitionCount, String scriptDirPath, String hdfsInputDir, String hdfsOutputPrefix, long totalDataPerReduce, String workloadOutputDir, String hadoopCommand, String pathToWorkGenJar, String pathToWorkGenConf) throws Exception { if (workloadData.size() > 0) { long maxInput = 0; String toWrite = ""; FileWriter runAllJobs = new FileWriter(scriptDirPath + "/run-jobs-all.sh"); toWrite = "#!/bin/bash\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "rm -r " + workloadOutputDir + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "mkdir " + workloadOutputDir + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); System.out.println(); System.out.println(workloadData.size() + " jobs in the workload."); System.out.println("Generating scripts ... please wait ... "); System.out.println(); int written = 0; for (int i=0; i<workloadData.size(); i++) { long sleep = Long.parseLong(workloadData.get(i).get(INTER_JOB_SLEEP_TIME)); long input = Long.parseLong(workloadData.get(i).get(INPUT_DATA_SIZE)); long shuffle = Long.parseLong(workloadData.get(i).get(SHUFFLE_DATA_SIZE)); long output = Long.parseLong(workloadData.get(i).get(OUTPUT_DATA_SIZE)); // Logic to scale sleep time such that smaller cluster = fewer jobs // Currently not done // // sleep = sleep * clusterSizeRaw / clusterSizeWorkload; input = input * clusterSizeWorkload / clusterSizeRaw; shuffle = shuffle * clusterSizeWorkload / clusterSizeRaw; output = output * clusterSizeWorkload / clusterSizeRaw; if (input > maxInput) maxInput = input; if (input < 67108864) input = 67108864; if (shuffle < 1024 ) shuffle = 1024 ; if (output < 1024 ) output = 1024 ; ArrayList<Integer> inputPartitionSamples = new ArrayList<Integer>(); long inputCopy = input; java.util.Random rng = new java.util.Random(); int tryPartitionSample = rng.nextInt(inputPartitionCount); while (inputCopy > 0) { boolean alreadySampled = true; while (alreadySampled) { if (inputPartitionSamples.size()>=inputPartitionCount) { System.err.println(); System.err.println("ERROR!"); System.err.println("Not enough partitions for input size of " + input + " bytes."); System.err.println("Happened on job number " + i + "."); System.err.println("Input partition size is " + inputPartitionSize + " bytes."); System.err.println("Number of partitions is " + inputPartitionCount + "."); System.err.println("Total data size is " + (((long) inputPartitionSize) * ((long) inputPartitionCount)) + " bytes < " + input + " bytes."); System.err.println("Need to generate a larger input data set."); System.err.println(); throw new Exception("Input data set not large enough. Need to generate a larger data set."); // if exception thrown here, input set not large enough - generate bigger input set } alreadySampled = false; } inputPartitionSamples.add(new Integer(tryPartitionSample)); tryPartitionSample = (tryPartitionSample + 1) % inputPartitionCount; inputCopy -= inputPartitionSize; } FileWriter inputPathFile = new FileWriter(scriptDirPath + "/inputPath-job-" + i + ".txt"); String inputPath = ""; for (int j=0; j<inputPartitionSamples.size(); j++) { inputPath = (hdfsInputDir + "/part-" + String.format("%05d", inputPartitionSamples.get(j))); if (j != (inputPartitionSamples.size()-1)) inputPath += ","; inputPathFile.write(inputPath.toCharArray(), 0, inputPath.length()); } inputPathFile.close(); // write inputPath to separate file to get around ARG_MAX limit for large clusters inputPath = "inputPath-job-" + i + ".txt"; String outputPath = hdfsOutputPrefix + "-" + i; float SIRatio = ((float) shuffle) / ((float) input ); float OSRatio = ((float) output ) / ((float) shuffle); long numReduces = -1; if (totalDataPerReduce > 0) { numReduces = Math.round((shuffle + output) / ((double) totalDataPerReduce)); if (numReduces < 1) numReduces = 1; if (numReduces > clusterSizeWorkload) numReduces = clusterSizeWorkload / 5; toWrite = "" + hadoopCommand + " jar " + pathToWorkGenJar + " org.apache.hadoop.examples.WorkGen -conf " + pathToWorkGenConf + " " + "-r " + numReduces + " " + inputPath + " " + outputPath + " " + SIRatio + " " + OSRatio + " >> " + workloadOutputDir + "/job-" + i + ".txt 2>> " + workloadOutputDir + "/job-" + i + ".txt \n"; } else { toWrite = "" + hadoopCommand + " jar " + pathToWorkGenJar + " org.apache.hadoop.examples.WorkGen -conf " + pathToWorkGenConf + " " + inputPath + " " + outputPath + " " + SIRatio + " " + OSRatio + " >> " + workloadOutputDir + "/job-" + i + ".txt 2>> " + workloadOutputDir + "/job-" + i + ".txt \n"; } FileWriter runFile = new FileWriter(scriptDirPath + "/run-job-" + i + ".sh"); runFile.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "" + hadoopCommand + " dfs -rmr " + outputPath + "\n"; runFile.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputSize " + input + "\n"; runFile.write(toWrite.toCharArray(), 0, toWrite.length()); runFile.close(); // works for linux type systems only Runtime.getRuntime().exec("chmod +x " + scriptDirPath + "/run-job-" + i + ".sh"); toWrite = "./run-job-" + i + ".sh &\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "sleep " + sleep + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); written++; } System.out.println(written + " jobs written ... done."); System.out.println(); toWrite = "# max input " + maxInput + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputPartitionSize " + inputPartitionSize + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputPartitionCount " + inputPartitionCount + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); runAllJobs.close(); // works for linux type systems only Runtime.getRuntime().exec("chmod +x " + scriptDirPath + "/run-jobs-all.sh"); } }
public static void printOutput(ArrayList<ArrayList<String>> workloadData, int clusterSizeRaw, int clusterSizeWorkload, int inputPartitionSize, int inputPartitionCount, String scriptDirPath, String hdfsInputDir, String hdfsOutputPrefix, long totalDataPerReduce, String workloadOutputDir, String hadoopCommand, String pathToWorkGenJar, String pathToWorkGenConf) throws Exception { if (workloadData.size() > 0) { long maxInput = 0; String toWrite = ""; FileWriter runAllJobs = new FileWriter(scriptDirPath + "/run-jobs-all.sh"); toWrite = "#!/bin/bash\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "rm -r " + workloadOutputDir + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "mkdir " + workloadOutputDir + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); System.out.println(); System.out.println(workloadData.size() + " jobs in the workload."); System.out.println("Generating scripts ... please wait ... "); System.out.println(); int written = 0; for (int i=0; i<workloadData.size(); i++) { long sleep = Long.parseLong(workloadData.get(i).get(INTER_JOB_SLEEP_TIME)); long input = Long.parseLong(workloadData.get(i).get(INPUT_DATA_SIZE)); long shuffle = Long.parseLong(workloadData.get(i).get(SHUFFLE_DATA_SIZE)); long output = Long.parseLong(workloadData.get(i).get(OUTPUT_DATA_SIZE)); // Logic to scale sleep time such that smaller cluster = fewer jobs // Currently not done // // sleep = sleep * clusterSizeRaw / clusterSizeWorkload; input = input * clusterSizeWorkload / clusterSizeRaw; shuffle = shuffle * clusterSizeWorkload / clusterSizeRaw; output = output * clusterSizeWorkload / clusterSizeRaw; if (input > maxInput) maxInput = input; if (input < maxSeqFile(67108864)) input = maxSeqFile(67108864); // 64 MB minimum size if (shuffle < 1024 ) shuffle = 1024 ; if (output < 1024 ) output = 1024 ; ArrayList<Integer> inputPartitionSamples = new ArrayList<Integer>(); long inputCopy = input; java.util.Random rng = new java.util.Random(); int tryPartitionSample = rng.nextInt(inputPartitionCount); while (inputCopy > 0) { boolean alreadySampled = true; while (alreadySampled) { if (inputPartitionSamples.size()>=inputPartitionCount) { System.err.println(); System.err.println("ERROR!"); System.err.println("Not enough partitions for input size of " + input + " bytes."); System.err.println("Happened on job number " + i + "."); System.err.println("Input partition size is " + inputPartitionSize + " bytes."); System.err.println("Number of partitions is " + inputPartitionCount + "."); System.err.println("Total data size is " + (((long) inputPartitionSize) * ((long) inputPartitionCount)) + " bytes < " + input + " bytes."); System.err.println("Need to generate a larger input data set."); System.err.println(); throw new Exception("Input data set not large enough. Need to generate a larger data set."); // if exception thrown here, input set not large enough - generate bigger input set } alreadySampled = false; } inputPartitionSamples.add(new Integer(tryPartitionSample)); tryPartitionSample = (tryPartitionSample + 1) % inputPartitionCount; inputCopy -= inputPartitionSize; } FileWriter inputPathFile = new FileWriter(scriptDirPath + "/inputPath-job-" + i + ".txt"); String inputPath = ""; for (int j=0; j<inputPartitionSamples.size(); j++) { inputPath = (hdfsInputDir + "/part-" + String.format("%05d", inputPartitionSamples.get(j))); if (j != (inputPartitionSamples.size()-1)) inputPath += ","; inputPathFile.write(inputPath.toCharArray(), 0, inputPath.length()); } inputPathFile.close(); // write inputPath to separate file to get around ARG_MAX limit for large clusters inputPath = "inputPath-job-" + i + ".txt"; String outputPath = hdfsOutputPrefix + "-" + i; float SIRatio = ((float) shuffle) / ((float) input ); float OSRatio = ((float) output ) / ((float) shuffle); long numReduces = -1; if (totalDataPerReduce > 0) { numReduces = Math.round((shuffle + output) / ((double) totalDataPerReduce)); if (numReduces < 1) numReduces = 1; if (numReduces > clusterSizeWorkload) numReduces = clusterSizeWorkload / 5; toWrite = "" + hadoopCommand + " jar " + pathToWorkGenJar + " org.apache.hadoop.examples.WorkGen -conf " + pathToWorkGenConf + " " + "-r " + numReduces + " " + inputPath + " " + outputPath + " " + SIRatio + " " + OSRatio + " >> " + workloadOutputDir + "/job-" + i + ".txt 2>> " + workloadOutputDir + "/job-" + i + ".txt \n"; } else { toWrite = "" + hadoopCommand + " jar " + pathToWorkGenJar + " org.apache.hadoop.examples.WorkGen -conf " + pathToWorkGenConf + " " + inputPath + " " + outputPath + " " + SIRatio + " " + OSRatio + " >> " + workloadOutputDir + "/job-" + i + ".txt 2>> " + workloadOutputDir + "/job-" + i + ".txt \n"; } FileWriter runFile = new FileWriter(scriptDirPath + "/run-job-" + i + ".sh"); runFile.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "" + hadoopCommand + " dfs -rmr " + outputPath + "\n"; runFile.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputSize " + input + "\n"; runFile.write(toWrite.toCharArray(), 0, toWrite.length()); runFile.close(); // works for linux type systems only Runtime.getRuntime().exec("chmod +x " + scriptDirPath + "/run-job-" + i + ".sh"); toWrite = "./run-job-" + i + ".sh &\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "sleep " + sleep + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); written++; } System.out.println(written + " jobs written ... done."); System.out.println(); toWrite = "# max input " + maxInput + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputPartitionSize " + inputPartitionSize + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); toWrite = "# inputPartitionCount " + inputPartitionCount + "\n"; runAllJobs.write(toWrite.toCharArray(), 0, toWrite.length()); runAllJobs.close(); // works for linux type systems only Runtime.getRuntime().exec("chmod +x " + scriptDirPath + "/run-jobs-all.sh"); } }
diff --git a/src/org/nutz/dao/impl/link/DoDeleteLinkVisitor.java b/src/org/nutz/dao/impl/link/DoDeleteLinkVisitor.java index 23a7d7a55..3f2f44e31 100644 --- a/src/org/nutz/dao/impl/link/DoDeleteLinkVisitor.java +++ b/src/org/nutz/dao/impl/link/DoDeleteLinkVisitor.java @@ -1,40 +1,40 @@ package org.nutz.dao.impl.link; import org.nutz.dao.entity.LinkField; import org.nutz.dao.impl.AbstractLinkVisitor; import org.nutz.dao.sql.Pojo; import org.nutz.dao.util.Pojos; import org.nutz.lang.Each; import org.nutz.lang.ExitLoop; import org.nutz.lang.Lang; import org.nutz.lang.LoopException; import org.nutz.log.Log; import org.nutz.log.Logs; public class DoDeleteLinkVisitor extends AbstractLinkVisitor { private static final Log log = Logs.get(); public void visit(Object obj, LinkField lnk) { Object value = lnk.getValue(obj); - if (value == null) { - log.infof("Value of LinkField(@%s-->%s.%s) is null, ingore", + if (value == null || Lang.length(value) == 0) { + log.infof("Value of LinkField(@%s-->%s.%s) is null or isEmtry, ingore", lnk.getLinkType(), lnk.getEntity().getType().getSimpleName(), lnk.getHostField().getName()); return; } final Pojo pojo = opt.maker().makeDelete(lnk.getLinkedEntity()); pojo.setOperatingObject(value); pojo.append(Pojos.Items.cndAuto(lnk.getLinkedEntity(), null)); Lang.each(value, new Each<Object>() { public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException { pojo.addParamsBy(ele); } }); opt.add(pojo); } }
true
true
public void visit(Object obj, LinkField lnk) { Object value = lnk.getValue(obj); if (value == null) { log.infof("Value of LinkField(@%s-->%s.%s) is null, ingore", lnk.getLinkType(), lnk.getEntity().getType().getSimpleName(), lnk.getHostField().getName()); return; } final Pojo pojo = opt.maker().makeDelete(lnk.getLinkedEntity()); pojo.setOperatingObject(value); pojo.append(Pojos.Items.cndAuto(lnk.getLinkedEntity(), null)); Lang.each(value, new Each<Object>() { public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException { pojo.addParamsBy(ele); } }); opt.add(pojo); }
public void visit(Object obj, LinkField lnk) { Object value = lnk.getValue(obj); if (value == null || Lang.length(value) == 0) { log.infof("Value of LinkField(@%s-->%s.%s) is null or isEmtry, ingore", lnk.getLinkType(), lnk.getEntity().getType().getSimpleName(), lnk.getHostField().getName()); return; } final Pojo pojo = opt.maker().makeDelete(lnk.getLinkedEntity()); pojo.setOperatingObject(value); pojo.append(Pojos.Items.cndAuto(lnk.getLinkedEntity(), null)); Lang.each(value, new Each<Object>() { public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException { pojo.addParamsBy(ele); } }); opt.add(pojo); }
diff --git a/nfctools-ndef/src/main/java/org/nfctools/ndef/wkt/handover/decoder/CollisionResolutionRecordDecoder.java b/nfctools-ndef/src/main/java/org/nfctools/ndef/wkt/handover/decoder/CollisionResolutionRecordDecoder.java index 3b7a455..87940db 100644 --- a/nfctools-ndef/src/main/java/org/nfctools/ndef/wkt/handover/decoder/CollisionResolutionRecordDecoder.java +++ b/nfctools-ndef/src/main/java/org/nfctools/ndef/wkt/handover/decoder/CollisionResolutionRecordDecoder.java @@ -1,42 +1,42 @@ /** * Copyright 2011 Adrian Stabiszewski, [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 org.nfctools.ndef.wkt.handover.decoder; import org.nfctools.ndef.NdefMessageDecoder; import org.nfctools.ndef.wkt.WellKnownRecordPayloadDecoder; import org.nfctools.ndef.wkt.handover.records.CollisionResolutionRecord; import org.nfctools.ndef.wkt.records.WellKnownRecord; /** * * @author Thomas Rorvik Skjolberg ([email protected]) * */ public class CollisionResolutionRecordDecoder implements WellKnownRecordPayloadDecoder { @Override public WellKnownRecord decodePayload(byte[] payload, NdefMessageDecoder messageDecoder) { CollisionResolutionRecord collisionResolutionRecord = new CollisionResolutionRecord(); - collisionResolutionRecord.setRandomNumber((((payload[0] << 8) | payload[1]) & 0xFFFF)); + collisionResolutionRecord.setRandomNumber(((payload[0] & 0xFF) << 8) | (payload[1] & 0xFF)); return collisionResolutionRecord; } }
true
true
public WellKnownRecord decodePayload(byte[] payload, NdefMessageDecoder messageDecoder) { CollisionResolutionRecord collisionResolutionRecord = new CollisionResolutionRecord(); collisionResolutionRecord.setRandomNumber((((payload[0] << 8) | payload[1]) & 0xFFFF)); return collisionResolutionRecord; }
public WellKnownRecord decodePayload(byte[] payload, NdefMessageDecoder messageDecoder) { CollisionResolutionRecord collisionResolutionRecord = new CollisionResolutionRecord(); collisionResolutionRecord.setRandomNumber(((payload[0] & 0xFF) << 8) | (payload[1] & 0xFF)); return collisionResolutionRecord; }
diff --git a/src/main/java/git/volkov/kvstorage/StorageTester.java b/src/main/java/git/volkov/kvstorage/StorageTester.java index a01a064..056034d 100644 --- a/src/main/java/git/volkov/kvstorage/StorageTester.java +++ b/src/main/java/git/volkov/kvstorage/StorageTester.java @@ -1,115 +1,115 @@ package git.volkov.kvstorage; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for testing storages. * * @author Sergey Volkov * */ public class StorageTester { private static final Logger LOG = LoggerFactory .getLogger(StorageTester.class); /** * List of storage to test. */ private List<Storage> storages = new ArrayList<Storage>(); /** * Input file name for keys to put in database. */ private String putFile = "put"; /** * Input file name for keys to test get. */ private String getFile = "get"; /** * Runs put's. * * @param storage * @throws IOException */ private void runPut(Storage storage) throws IOException { LOG.info("Testing put for storage" + storage.toString()); BufferedReader reader = new BufferedReader(new FileReader(putFile)); String string; int count = 0; long start = System.currentTimeMillis(); while ((string = reader.readLine()) != null) { storage.put(string); count++; } long time = System.currentTimeMillis() - start; LOG.info(String.format("Finished %d put for %d ms", count, time)); } private void runGet(Storage storage) throws IOException { - LOG.info("Testing put for storage" + storage.toString()); + LOG.info("Testing get for storage" + storage.toString()); BufferedReader reader = new BufferedReader(new FileReader(getFile)); String string; int count = 0; int miss = 0; long start = System.currentTimeMillis(); while ((string = reader.readLine()) != null) { if (!storage.has(string)) miss++; count++; } long time = System.currentTimeMillis() - start; LOG.info(String.format("Finished %d get with %d miss for %d ms", count, miss, time)); } public void runTest() { for (Storage storage : storages) { try { storage.init(); runPut(storage); runGet(storage); storage.clean(); } catch (Exception e) { LOG.error("Some problem occured while testing storage " + storage, e); } } } public List<Storage> getStorages() { return storages; } public void setStorages(List<Storage> storages) { this.storages = storages; } public String getPutFile() { return putFile; } public void setPutFile(String putFile) { this.putFile = putFile; } public String getGetFile() { return getFile; } public void setGetFile(String getFile) { this.getFile = getFile; } }
true
true
private void runGet(Storage storage) throws IOException { LOG.info("Testing put for storage" + storage.toString()); BufferedReader reader = new BufferedReader(new FileReader(getFile)); String string; int count = 0; int miss = 0; long start = System.currentTimeMillis(); while ((string = reader.readLine()) != null) { if (!storage.has(string)) miss++; count++; } long time = System.currentTimeMillis() - start; LOG.info(String.format("Finished %d get with %d miss for %d ms", count, miss, time)); }
private void runGet(Storage storage) throws IOException { LOG.info("Testing get for storage" + storage.toString()); BufferedReader reader = new BufferedReader(new FileReader(getFile)); String string; int count = 0; int miss = 0; long start = System.currentTimeMillis(); while ((string = reader.readLine()) != null) { if (!storage.has(string)) miss++; count++; } long time = System.currentTimeMillis() - start; LOG.info(String.format("Finished %d get with %d miss for %d ms", count, miss, time)); }
diff --git a/src/api/org/openmrs/util/OpenmrsUtil.java b/src/api/org/openmrs/util/OpenmrsUtil.java index 2412dc31..199f68af 100644 --- a/src/api/org/openmrs/util/OpenmrsUtil.java +++ b/src/api/org/openmrs/util/OpenmrsUtil.java @@ -1,2006 +1,2005 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.zip.ZipEntry; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.openmrs.Cohort; import org.openmrs.Concept; import org.openmrs.ConceptNumeric; import org.openmrs.Drug; import org.openmrs.EncounterType; import org.openmrs.Form; import org.openmrs.Location; import org.openmrs.Person; import org.openmrs.PersonAttributeType; import org.openmrs.Program; import org.openmrs.ProgramWorkflowState; import org.openmrs.User; import org.openmrs.api.APIException; import org.openmrs.api.AdministrationService; import org.openmrs.api.ConceptService; import org.openmrs.api.InvalidCharactersPasswordException; import org.openmrs.api.PasswordException; import org.openmrs.api.PatientService; import org.openmrs.api.ShortPasswordException; import org.openmrs.api.WeakPasswordException; import org.openmrs.api.context.Context; import org.openmrs.cohort.CohortSearchHistory; import org.openmrs.logic.LogicCriteria; import org.openmrs.module.ModuleException; import org.openmrs.patient.IdentifierValidator; import org.openmrs.propertyeditor.CohortEditor; import org.openmrs.propertyeditor.ConceptEditor; import org.openmrs.propertyeditor.DrugEditor; import org.openmrs.propertyeditor.EncounterTypeEditor; import org.openmrs.propertyeditor.FormEditor; import org.openmrs.propertyeditor.LocationEditor; import org.openmrs.propertyeditor.PersonAttributeTypeEditor; import org.openmrs.propertyeditor.ProgramEditor; import org.openmrs.propertyeditor.ProgramWorkflowStateEditor; import org.openmrs.report.EvaluationContext; import org.openmrs.reporting.CohortFilter; import org.openmrs.reporting.PatientFilter; import org.openmrs.reporting.PatientSearch; import org.openmrs.reporting.PatientSearchReportObject; import org.openmrs.reporting.SearchArgument; import org.openmrs.xml.OpenmrsCycleStrategy; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.load.Persister; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.context.NoSuchMessageException; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; /** * Utility methods used in openmrs */ public class OpenmrsUtil { private static Log log = LogFactory.getLog(OpenmrsUtil.class); private static Map<Locale, SimpleDateFormat> dateFormatCache = new HashMap<Locale, SimpleDateFormat>(); /** * @param idWithoutCheckdigit * @return int - the calculated check digit for the given string * @throws Exception * @deprecated Use {@link PatientService#getIdentifierValidator(String)} * @should get valid check digits */ public static int getCheckDigit(String idWithoutCheckdigit) throws Exception { PatientService ps = Context.getPatientService(); IdentifierValidator piv = ps.getDefaultIdentifierValidator(); String withCheckDigit = piv.getValidIdentifier(idWithoutCheckdigit); char checkDigitChar = withCheckDigit.charAt(withCheckDigit.length() - 1); if (Character.isDigit(checkDigitChar)) return Integer.parseInt("" + checkDigitChar); else { switch (checkDigitChar) { case 'A': case 'a': return 0; case 'B': case 'b': return 1; case 'C': case 'c': return 2; case 'D': case 'd': return 3; case 'E': case 'e': return 4; case 'F': case 'f': return 5; case 'G': case 'g': return 6; case 'H': case 'h': return 7; case 'I': case 'i': return 8; case 'J': case 'j': return 9; default: return 10; } } } /** * @param id * @return true/false whether id has a valid check digit * @throws Exception on invalid characters and invalid id formation * @deprecated Should be using {@link PatientService#getIdentifierValidator(String)} * @should validate correct check digits * @should not validate invalid check digits * @should throw error if given an invalid character in id */ public static boolean isValidCheckDigit(String id) throws Exception { PatientService ps = Context.getPatientService(); IdentifierValidator piv = ps.getDefaultIdentifierValidator(); return piv.isValid(id); } /** * Compares origList to newList returning map of differences * * @param origList * @param newList * @return [List toAdd, List toDelete] with respect to origList */ public static <E extends Object> Collection<Collection<E>> compareLists(Collection<E> origList, Collection<E> newList) { // TODO finish function Collection<Collection<E>> returnList = new Vector<Collection<E>>(); Collection<E> toAdd = new LinkedList<E>(); Collection<E> toDel = new LinkedList<E>(); // loop over the new list. for (E currentNewListObj : newList) { // loop over the original list boolean foundInList = false; for (E currentOrigListObj : origList) { // checking if the current new list object is in the original // list if (currentNewListObj.equals(currentOrigListObj)) { foundInList = true; origList.remove(currentOrigListObj); break; } } if (!foundInList) toAdd.add(currentNewListObj); // all found new objects were removed from the orig list, // leaving only objects needing to be removed toDel = origList; } returnList.add(toAdd); returnList.add(toDel); return returnList; } public static boolean isStringInArray(String str, String[] arr) { boolean retVal = false; if (str != null && arr != null) { for (int i = 0; i < arr.length; i++) { if (str.equals(arr[i])) retVal = true; } } return retVal; } public static Boolean isInNormalNumericRange(Float value, ConceptNumeric concept) { if (concept.getHiNormal() == null || concept.getLowNormal() == null) return false; return (value <= concept.getHiNormal() && value >= concept.getLowNormal()); } public static Boolean isInCriticalNumericRange(Float value, ConceptNumeric concept) { if (concept.getHiCritical() == null || concept.getLowCritical() == null) return false; return (value <= concept.getHiCritical() && value >= concept.getLowCritical()); } public static Boolean isInAbsoluteNumericRange(Float value, ConceptNumeric concept) { if (concept.getHiAbsolute() == null || concept.getLowAbsolute() == null) return false; return (value <= concept.getHiAbsolute() && value >= concept.getLowAbsolute()); } public static Boolean isValidNumericValue(Float value, ConceptNumeric concept) { if (concept.getHiAbsolute() == null || concept.getLowAbsolute() == null) return true; return (value <= concept.getHiAbsolute() && value >= concept.getLowAbsolute()); } /** * Return a string representation of the given file * * @param file * @return String file contents * @throws IOException */ public static String getFileAsString(File file) throws IOException { StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = new BufferedReader(new FileReader(file)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); return fileData.toString(); } /** * Return a byte array representation of the given file * * @param file * @return byte[] file contents * @throws IOException */ public static byte[] getFileAsBytes(File file) throws IOException { try { FileInputStream fileInputStream = new FileInputStream(file); byte[] b = new byte[fileInputStream.available()]; fileInputStream.read(b); fileInputStream.close(); return b; } catch (Exception e) { log.error("Unable to get file as byte array", e); } return null; } /** * Copy file from inputStream onto the outputStream inputStream is not closed in this method * outputStream /is/ closed at completion of this method * * @param inputStream Stream to copy from * @param outputStream Stream/location to copy to * @throws IOException thrown if an error occurs during read/write */ public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { try { outputStream.close(); } catch (Exception e) { /* pass */} } return; } InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(inputStream); out = new BufferedOutputStream(outputStream); while (true) { int data = in.read(); if (data == -1) { break; } out.write(data); } } finally { if (in != null) in.close(); if (out != null) out.close(); try { outputStream.close(); } catch (Exception e) { /* pass */} } } /** * Look for a file named <code>filename</code> in folder * * @param folder * @param filename * @return true/false whether filename exists in folder */ public static boolean folderContains(File folder, String filename) { if (folder == null) return false; if (!folder.isDirectory()) return false; for (File f : folder.listFiles()) { if (f.getName().equals(filename)) return true; } return false; } /** * Initialize global settings Find and load modules * * @param p properties from runtime configuration */ public static void startup(Properties p) { // Override global OpenMRS constants if specified by the user // Allow for "demo" mode where patient data is obscured String val = p.getProperty("obscure_patients", null); if (val != null && "true".equalsIgnoreCase(val)) OpenmrsConstants.OBSCURE_PATIENTS = true; val = p.getProperty("obscure_patients.family_name", null); if (val != null) OpenmrsConstants.OBSCURE_PATIENTS_FAMILY_NAME = val; val = p.getProperty("obscure_patients.given_name", null); if (val != null) OpenmrsConstants.OBSCURE_PATIENTS_GIVEN_NAME = val; val = p.getProperty("obscure_patients.middle_name", null); if (val != null) OpenmrsConstants.OBSCURE_PATIENTS_MIDDLE_NAME = val; // Override the default "openmrs" database name val = p.getProperty("connection.database_name", null); if (val == null) { // the database name wasn't supplied explicitly, guess it // from the connection string val = p.getProperty("connection.url", null); if (val != null) { try { int endIndex = val.lastIndexOf("?"); if (endIndex == -1) endIndex = val.length(); int startIndex = val.lastIndexOf("/", endIndex); val = val.substring(startIndex + 1, endIndex); OpenmrsConstants.DATABASE_NAME = val; } catch (Exception e) { log.fatal("Database name cannot be configured from 'connection.url' ." + "Either supply 'connection.database_name' or correct the url", e); } } } // set the business database name val = p.getProperty("connection.database_business_name", null); if (val == null) val = OpenmrsConstants.DATABASE_NAME; OpenmrsConstants.DATABASE_BUSINESS_NAME = val; // set the application data directory val = p.getProperty(OpenmrsConstants.APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY, null); if (val != null) OpenmrsConstants.APPLICATION_DATA_DIRECTORY = val; // set global log level applyLogLevels(); } /** * Set the org.openmrs log4j logger's level if global property log.level.openmrs ( * OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL ) exists. Valid values for global property are * trace, debug, info, warn, error or fatal. */ public static void applyLogLevels() { AdministrationService adminService = Context.getAdministrationService(); String logLevel = adminService.getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL); String logClass = OpenmrsConstants.LOG_CLASS_DEFAULT; // potentially have different levels here. only doing org.openmrs right now applyLogLevel(logClass, logLevel); } /** * Set the log4j log level for class <code>logClass</code> to <code>logLevel</code>. * * @param logClass optional string giving the class level to change. Defaults to * OpenmrsConstants.LOG_CLASS_DEFAULT . Should be something like org.openmrs.___ * @param logLevel one of OpenmrsConstants.LOG_LEVEL_* */ public static void applyLogLevel(String logClass, String logLevel) { if (logLevel != null) { // the default log level is org.openmrs if (logClass == null || "".equals(logClass)) logClass = OpenmrsConstants.LOG_CLASS_DEFAULT; Logger logger = Logger.getLogger(logClass); logLevel = logLevel.toLowerCase(); if (OpenmrsConstants.LOG_LEVEL_TRACE.equals(logLevel)) { logger.setLevel(Level.TRACE); } else if (OpenmrsConstants.LOG_LEVEL_DEBUG.equals(logLevel)) { logger.setLevel(Level.DEBUG); } else if (OpenmrsConstants.LOG_LEVEL_INFO.equals(logLevel)) { logger.setLevel(Level.INFO); } else if (OpenmrsConstants.LOG_LEVEL_WARN.equals(logLevel)) { logger.setLevel(Level.WARN); } else if (OpenmrsConstants.LOG_LEVEL_ERROR.equals(logLevel)) { logger.setLevel(Level.ERROR); } else if (OpenmrsConstants.LOG_LEVEL_FATAL.equals(logLevel)) { logger.setLevel(Level.FATAL); } else { log.warn("Global property " + logLevel + " is invalid. " + "Valid values are trace, debug, info, warn, error or fatal"); } } } /** * Takes a String like "size=compact|order=date" and returns a Map<String,String> from the keys * to the values. * * @param paramList <code>String</code> with a list of parameters * @return Map<String, String> of the parameters passed */ public static Map<String, String> parseParameterList(String paramList) { Map<String, String> ret = new HashMap<String, String>(); if (paramList != null && paramList.length() > 0) { String[] args = paramList.split("\\|"); for (String s : args) { int ind = s.indexOf('='); if (ind <= 0) { throw new IllegalArgumentException("Misformed argument in dynamic page specification string: '" + s + "' is not 'key=value'."); } String name = s.substring(0, ind); String value = s.substring(ind + 1); ret.put(name, value); } } return ret; } public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) return d2 == null; else if (d2 == null) return false; else return d1.equals(d2); } /** * Compares two java.util.Date objects, but handles java.sql.Timestamp (which is not directly * comparable to a date) by dropping its nanosecond value. */ public static int compare(Date d1, Date d2) { if (d1 instanceof Timestamp && d2 instanceof Timestamp) { return d1.compareTo(d2); } if (d1 instanceof Timestamp) d1 = new Date(((Timestamp) d1).getTime()); if (d2 instanceof Timestamp) d2 = new Date(((Timestamp) d2).getTime()); return d1.compareTo(d2); } /** * Compares two Date/Timestamp objects, treating null as the earliest possible date. */ public static int compareWithNullAsEarliest(Date d1, Date d2) { if (d1 == null && d2 == null) return 0; if (d1 == null) return -1; else if (d2 == null) return 1; else return compare(d1, d2); } /** * Compares two Date/Timestamp objects, treating null as the earliest possible date. */ public static int compareWithNullAsLatest(Date d1, Date d2) { if (d1 == null && d2 == null) return 0; if (d1 == null) return 1; else if (d2 == null) return -1; else return compare(d1, d2); } public static <E extends Comparable<E>> int compareWithNullAsLowest(E c1, E c2) { if (c1 == null && c2 == null) return 0; if (c1 == null) return -1; else if (c2 == null) return 1; else return c1.compareTo(c2); } public static <E extends Comparable<E>> int compareWithNullAsGreatest(E c1, E c2) { if (c1 == null && c2 == null) return 0; if (c1 == null) return 1; else if (c2 == null) return -1; else return c1.compareTo(c2); } /** * @deprecated this method is not currently used within OpenMRS and is a duplicate of * {@link Person#getAge(Date)} */ public static Integer ageFromBirthdate(Date birthdate) { if (birthdate == null) return null; Calendar today = Calendar.getInstance(); Calendar bday = Calendar.getInstance(); bday.setTime(birthdate); int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR); //Adjust age when today's date is before the person's birthday int todaysMonth = today.get(Calendar.MONTH); int bdayMonth = bday.get(Calendar.MONTH); int todaysDay = today.get(Calendar.DAY_OF_MONTH); int bdayDay = bday.get(Calendar.DAY_OF_MONTH); if (todaysMonth < bdayMonth) { age--; } else if (todaysMonth == bdayMonth && todaysDay < bdayDay) { // we're only comparing on month and day, not minutes, etc age--; } return age; } /** * Converts a collection to a String with a specified separator between all elements * * @param c Collection to be joined * @param separator string to put between all elements * @return a String representing the toString() of all elements in c, separated by separator */ public static <E extends Object> String join(Collection<E> c, String separator) { if (c == null) return ""; StringBuilder ret = new StringBuilder(); for (Iterator<E> i = c.iterator(); i.hasNext();) { ret.append(i.next()); if (i.hasNext()) ret.append(separator); } return ret.toString(); } public static Set<Concept> conceptSetHelper(String descriptor) { Set<Concept> ret = new HashSet<Concept>(); if (descriptor == null || descriptor.length() == 0) return ret; ConceptService cs = Context.getConceptService(); for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens();) { String s = st.nextToken().trim(); boolean isSet = s.startsWith("set:"); if (isSet) s = s.substring(4).trim(); Concept c = null; if (s.startsWith("name:")) { String name = s.substring(5).trim(); c = cs.getConceptByName(name); } else { try { c = cs.getConcept(Integer.valueOf(s.trim())); } catch (Exception ex) {} } if (c != null) { if (isSet) { List<Concept> inSet = cs.getConceptsByConceptSet(c); ret.addAll(inSet); } else { ret.add(c); } } } return ret; } public static List<Concept> delimitedStringToConceptList(String delimitedString, String delimiter, Context context) { List<Concept> ret = null; if (delimitedString != null && context != null) { String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { Integer conceptId = null; try { conceptId = new Integer(token); } catch (NumberFormatException nfe) { conceptId = null; } Concept c = null; if (conceptId != null) { c = Context.getConceptService().getConcept(conceptId); } else { c = Context.getConceptService().getConceptByName(token); } if (c != null) { if (ret == null) ret = new ArrayList<Concept>(); ret.add(c); } } } return ret; } public static Map<String, Concept> delimitedStringToConceptMap(String delimitedString, String delimiter) { Map<String, Concept> ret = null; if (delimitedString != null) { String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { Concept c = OpenmrsUtil.getConceptByIdOrName(token); if (c != null) { if (ret == null) ret = new HashMap<String, Concept>(); ret.put(token, c); } } } return ret; } // DEPRECATED: This method should now be replaced with ConceptService.getConceptByIdOrName() public static Concept getConceptByIdOrName(String idOrName) { Concept c = null; Integer conceptId = null; try { conceptId = new Integer(idOrName); } catch (NumberFormatException nfe) { conceptId = null; } if (conceptId != null) { c = Context.getConceptService().getConcept(conceptId); } else { c = Context.getConceptService().getConceptByName(idOrName); } return c; } // TODO: properly handle duplicates public static List<Concept> conceptListHelper(String descriptor) { List<Concept> ret = new ArrayList<Concept>(); if (descriptor == null || descriptor.length() == 0) return ret; ConceptService cs = Context.getConceptService(); for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens();) { String s = st.nextToken().trim(); boolean isSet = s.startsWith("set:"); if (isSet) s = s.substring(4).trim(); Concept c = null; if (s.startsWith("name:")) { String name = s.substring(5).trim(); c = cs.getConceptByName(name); } else { try { c = cs.getConcept(Integer.valueOf(s.trim())); } catch (Exception ex) {} } if (c != null) { if (isSet) { List<Concept> inSet = cs.getConceptsByConceptSet(c); ret.addAll(inSet); } else { ret.add(c); } } } return ret; } /** * Return a date that is the same day as the passed in date, but the hours and seconds are the * latest possible for that day. * * @param date date to adjust * @return a date that is the last possible time in the day */ public static Date lastSecondOfDay(Date date) { if (date == null) return null; Calendar c = Calendar.getInstance(); c.setTime(date); // TODO: figure out the right way to do this (or at least set milliseconds to zero) c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.add(Calendar.DAY_OF_MONTH, 1); c.add(Calendar.SECOND, -1); return c.getTime(); } public static Date safeDate(Date d1) { return new Date(d1.getTime()); } /** * Recursively deletes files in the given <code>dir</code> folder * * @param dir File directory to delete * @return true/false whether the delete was completed successfully * @throws IOException if <code>dir</code> is not a directory */ public static boolean deleteDirectory(File dir) throws IOException { if (!dir.exists() || !dir.isDirectory()) throw new IOException("Could not delete directory '" + dir.getAbsolutePath() + "' (not a directory)"); if (log.isDebugEnabled()) log.debug("Deleting directory " + dir.getAbsolutePath()); File[] fileList = dir.listFiles(); for (File f : fileList) { if (f.isDirectory()) deleteDirectory(f); boolean success = f.delete(); if (log.isDebugEnabled()) log.debug(" deleting " + f.getName() + " : " + (success ? "ok" : "failed")); if (!success) f.deleteOnExit(); } boolean success = dir.delete(); if (!success) { log.warn(" ...could not remove directory: " + dir.getAbsolutePath()); dir.deleteOnExit(); } if (success && log.isDebugEnabled()) log.debug(" ...and directory itself"); return success; } /** * Utility method to convert local URL to a File object. * * @param url an URL * @return file object for given URL or <code>null</code> if URL is not local * @should return null given null parameter */ public static File url2file(final URL url) { if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { return null; } return new File(url.getFile().replaceAll("%20", " ")); } /** * Opens input stream for given resource. This method behaves differently for different URL * types: * <ul> * <li>for <b>local files</b> it returns buffered file input stream;</li> * <li>for <b>local JAR files</b> it reads resource content into memory buffer and returns byte * array input stream that wraps those buffer (this prevents locking JAR file);</li> * <li>for <b>common URL's</b> this method simply opens stream to that URL using standard URL * API.</li> * </ul> * It is not recommended to use this method for big resources within JAR files. * * @param url resource URL * @return input stream for given resource * @throws IOException if any I/O error has occurred */ public static InputStream getResourceInputStream(final URL url) throws IOException { File file = url2file(url); if (file != null) { return new BufferedInputStream(new FileInputStream(file)); } if (!"jar".equalsIgnoreCase(url.getProtocol())) { return url.openStream(); } String urlStr = url.toExternalForm(); if (urlStr.endsWith("!/")) { //JAR URL points to a root entry throw new FileNotFoundException(url.toExternalForm()); } int p = urlStr.indexOf("!/"); if (p == -1) { throw new MalformedURLException(url.toExternalForm()); } String path = urlStr.substring(p + 2); file = url2file(new URL(urlStr.substring(4, p))); if (file == null) {// non-local JAR file URL return url.openStream(); } JarFile jarFile = new JarFile(file); try { ZipEntry entry = jarFile.getEntry(path); if (entry == null) { throw new FileNotFoundException(url.toExternalForm()); } InputStream in = jarFile.getInputStream(entry); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyFile(in, out); return new ByteArrayInputStream(out.toByteArray()); } finally { in.close(); } } finally { jarFile.close(); } } /** * @return The path to the directory on the file system that will hold miscellaneous data about * the application (runtime properties, modules, etc) */ public static String getApplicationDataDirectory() { String filepath = null; if (OpenmrsConstants.APPLICATION_DATA_DIRECTORY != null) { filepath = OpenmrsConstants.APPLICATION_DATA_DIRECTORY; } else { if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) filepath = System.getProperty("user.home") + File.separator + ".OpenMRS"; else filepath = System.getProperty("user.home") + File.separator + "Application Data" + File.separator + "OpenMRS"; filepath = filepath + File.separator; } File folder = new File(filepath); if (!folder.exists()) folder.mkdirs(); return filepath; } /** * Find the given folderName in the application data directory. Or, treat folderName like an * absolute url to a directory * * @param folderName * @return folder capable of storing information */ public static File getDirectoryInApplicationDataDirectory(String folderName) throws APIException { // try to load the repository folder straight away. File folder = new File(folderName); // if the property wasn't a full path already, assume it was intended to be a folder in the // application directory if (!folder.isAbsolute()) { folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName); } // now create the directory folder if it doesn't exist if (!folder.exists()) { log.warn("'" + folder.getAbsolutePath() + "' doesn't exist. Creating directories now."); folder.mkdirs(); } if (!folder.isDirectory()) throw new APIException("'" + folder.getAbsolutePath() + "' should be a directory but it is not"); return folder; } /** * Save the given xml document to the given outfile * * @param doc Document to be saved * @param outFile file pointer to the location the xml file is to be saved to */ public static void saveDocument(Document doc, File outFile) { OutputStream outStream = null; try { outStream = new FileOutputStream(outFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DocumentType doctype = doc.getDoctype(); if (doctype != null) { transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId()); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outStream); transformer.transform(source, result); } catch (TransformerException e) { throw new ModuleException("Error while saving dwrmodulexml back to dwr-modules.xml", e); } catch (FileNotFoundException e) { throw new ModuleException("/WEB-INF/dwr-modules.xml file doesn't exist.", e); } finally { try { if (outStream != null) outStream.close(); } catch (Exception e) { log.warn("Unable to close outstream", e); } } } public static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter) { List<Integer> ret = new ArrayList<Integer>(); String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { token = token.trim(); if (token.length() == 0) continue; else ret.add(Integer.valueOf(token)); } return ret; } public static boolean isConceptInList(Concept concept, List<Concept> list) { boolean ret = false; if (concept != null && list != null) { for (Concept c : list) { if (c.equals(concept)) { ret = true; break; } } } return ret; } public static Date fromDateHelper(Date comparisonDate, Integer withinLastDays, Integer withinLastMonths, Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate) { Date ret = null; if (withinLastDays != null || withinLastMonths != null) { Calendar gc = Calendar.getInstance(); gc.setTime(comparisonDate != null ? comparisonDate : new Date()); if (withinLastDays != null) gc.add(Calendar.DAY_OF_MONTH, -withinLastDays); if (withinLastMonths != null) gc.add(Calendar.MONTH, -withinLastMonths); ret = gc.getTime(); } if (sinceDate != null && (ret == null || sinceDate.after(ret))) ret = sinceDate; return ret; } public static Date toDateHelper(Date comparisonDate, Integer withinLastDays, Integer withinLastMonths, Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate) { Date ret = null; if (untilDaysAgo != null || untilMonthsAgo != null) { Calendar gc = Calendar.getInstance(); gc.setTime(comparisonDate != null ? comparisonDate : new Date()); if (untilDaysAgo != null) gc.add(Calendar.DAY_OF_MONTH, -untilDaysAgo); if (untilMonthsAgo != null) gc.add(Calendar.MONTH, -untilMonthsAgo); ret = gc.getTime(); } if (untilDate != null && (ret == null || untilDate.before(ret))) ret = untilDate; return ret; } /** * @param collection * @param elements * @return Whether _collection_ contains any of _elements_ */ public static <T> boolean containsAny(Collection<T> collection, Collection<T> elements) { for (T obj : elements) { if (collection.contains(obj)) return true; } return false; } /** * Allows easy manipulation of a Map<?, Set> */ public static <K, V> void addToSetMap(Map<K, Set<V>> map, K key, V obj) { Set<V> set = map.get(key); if (set == null) { set = new HashSet<V>(); map.put(key, set); } set.add(obj); } public static <K, V> void addToListMap(Map<K, List<V>> map, K key, V obj) { List<V> list = map.get(key); if (list == null) { list = new ArrayList<V>(); map.put(key, list); } list.add(obj); } /** * Get the current user's date format Will look similar to "mm-dd-yyyy". Depends on user's * locale. * * @return a simple date format * @deprecated use {@link Context#getDateFormat()} or {@link #getDateFormat(Context#getLocale())} instead */ public static SimpleDateFormat getDateFormat() { return Context.getDateFormat(); } /** * Get the current user's date format Will look similar to "mm-dd-yyyy". Depends on user's * locale. * * @return a simple date format * @should return a pattern with four y characters in it * @since 1.5 */ public static SimpleDateFormat getDateFormat(Locale locale) { if (dateFormatCache.containsKey(locale)) return dateFormatCache.get(locale); SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale); String pattern = sdf.toPattern(); if (!pattern.contains("yyyy")) { // otherwise, change the pattern to be a four digit year pattern = pattern.replaceFirst("yy", "yyyy"); sdf.applyPattern(pattern); } if (!pattern.contains("MM")) { // change the pattern to be a two digit month pattern = pattern.replaceFirst("M", "MM"); sdf.applyPattern(pattern); } if (!pattern.contains("dd")) { // change the pattern to be a two digit day pattern = pattern.replaceFirst("d", "dd"); sdf.applyPattern(pattern); } dateFormatCache.put(locale, sdf); return sdf; } /** * @deprecated see reportingcompatibility module */ @Deprecated public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history) { return toPatientFilter(search, history, null); } /** * Takes a String (e.g. a user-entered one) and parses it into an object of the specified class * * @param string * @param clazz * @return Object of type <code>clazz</code> with the data from <code>string</code> */ @SuppressWarnings("unchecked") public static Object parse(String string, Class clazz) { try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = clazz.getMethod("valueOf", String.class); } catch (NoSuchMethodException ex) {} if (valueOfMethod != null) { return valueOfMethod.invoke(null, string); } else if (clazz.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) clazz.getEnumConstants()); for (Enum e : constants) if (e.toString().equals(string)) return e; throw new IllegalArgumentException(string + " is not a legal value of enum class " + clazz); } else if (String.class.equals(clazz)) { return string; } else if (Location.class.equals(clazz)) { try { Integer.parseInt(string); LocationEditor ed = new LocationEditor(); ed.setAsText(string); return ed.getValue(); } catch (NumberFormatException ex) { return Context.getLocationService().getLocation(string); } } else if (Concept.class.equals(clazz)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(string); return ed.getValue(); } else if (Program.class.equals(clazz)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(string); return ed.getValue(); } else if (ProgramWorkflowState.class.equals(clazz)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(string); return ed.getValue(); } else if (EncounterType.class.equals(clazz)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(string); return ed.getValue(); } else if (Form.class.equals(clazz)) { FormEditor ed = new FormEditor(); ed.setAsText(string); return ed.getValue(); } else if (Drug.class.equals(clazz)) { DrugEditor ed = new DrugEditor(); ed.setAsText(string); return ed.getValue(); } else if (PersonAttributeType.class.equals(clazz)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(string); return ed.getValue(); } else if (Cohort.class.equals(clazz)) { CohortEditor ed = new CohortEditor(); ed.setAsText(string); return ed.getValue(); } else if (Date.class.equals(clazz)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. CustomDateEditor ed = new CustomDateEditor(Context.getDateFormat(), true, 10); ed.setAsText(string); return ed.getValue(); } else if (Object.class.equals(clazz)) { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String return string; } else { throw new IllegalArgumentException("Don't know how to handle class: " + clazz); } } catch (Exception ex) { log.error("error converting \"" + string + "\" to " + clazz, ex); throw new IllegalArgumentException(ex); } } /** * Uses reflection to translate a PatientSearch into a PatientFilter * * @deprecated see reportingcompatibility module */ @SuppressWarnings("unchecked") @Deprecated public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject( search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId()); // to prevent lazy loading exceptions, cache the member ids here if (c != null) c.getMemberIds().size(); return new CohortFilter(c); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) throw new IllegalArgumentException("You can't evaluate this search without a history"); else return search.cloneCompositionAsFilter(history, evalContext); } else { Class clz = search.getFilterClass(); if (clz == null) throw new IllegalArgumentException("search must be saved, composition, or must have a class specified"); log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (testForExpression != null) { - valueAsString = testForExpression; - log.debug("Setting " + sa.getName() + " to: " + valueAsString); - if (evalContext != null && EvaluationContext.isExpression(valueAsString)) { + log.debug("Setting " + sa.getName() + " to: " + testForExpression); + if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) valueAsString = Context.getDateFormat().format((Date) evaluated); else valueAsString = evaluated.toString(); } log.debug("Evaluated " + sa.getName() + " to: " + valueAsString); } } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) {} if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else if (LogicCriteria.class.equals(valueClass)) { value = Context.getLogicService().parseString(valueAsString); } else { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error( "Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. I'm going with the following rules, which should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } } /** * Loops over the collection to check to see if the given object is in that collection. This * method <i>only</i> uses the .equals() method for comparison. This should be used in the * patient/person objects on their collections. Their collections are SortedSets which use the * compareTo method for equality as well. The compareTo method is currently optimized for * sorting, not for equality. A null <code>obj</code> will return false * * @param objects collection to loop over * @param obj Object to look for in the <code>objects</code> * @return true/false whether the given object is found * @should use equals method for comparison instead of compareTo given List collection * @should use equals method for comparison instead of compareTo given SortedSet collection */ public static boolean collectionContains(Collection<?> objects, Object obj) { if (obj == null || objects == null) return false; for (Object o : objects) { if (o != null && o.equals(obj)) return true; } return false; } /** * Get a serializer that will do the common type of serialization and deserialization. Cycles of * objects are taken into account * * @return Serializer to do the (de)serialization * @deprecated - Use OpenmrsSerializer from * Context.getSerializationService.getDefaultSerializer() Note, this uses a * different Serialization mechanism, so you may need to use this for conversion */ @Deprecated public static Serializer getSerializer() { return new Persister(new OpenmrsCycleStrategy()); } /** * Get a short serializer that will only do the very basic serialization necessary. This is * controlled by the objects that are being serialized via the @Replace methods * * @return Serializer to do the short (de)serialization * @see OpenmrsConstants#SHORT_SERIALIZATION * @deprecated - Use OpenmrsSerializer from * Context.getSerializationService.getDefaultSerializer() Note, this uses a * different Serialization mechanism, so you may need to use this for conversion */ @Deprecated public static Serializer getShortSerializer() { return new Persister(new OpenmrsCycleStrategy(true)); } /** * True/false whether the current serialization is supposed to be a short serialization. A * shortened serialization This should be called from methods marked with the @Replace notation * that take in a single <code>Map</code> parameter. * * @param sessionMap current serialization session * @return true/false whether or not to do the shortened serialization * @deprecated - use SerializationService and OpenmrsSerializer implementation for Serialization */ @Deprecated public static boolean isShortSerialization(Map<?, ?> sessionMap) { return sessionMap.containsKey(OpenmrsConstants.SHORT_SERIALIZATION); } /** * Gets an out File object. If date is not provided, the current timestamp is used. If user is * not provided, the user id is not put into the filename. Assumes dir is already created * * @param dir directory to make the random filename in * @param date optional Date object used for the name * @param user optional User creating this file object * @return file new file that is able to be written to */ public static File getOutFile(File dir, Date date, User user) { File outFile; do { // format to print date in filenmae DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd-HHmm-ssSSS"); // use current date if none provided if (date == null) date = new Date(); StringBuilder filename = new StringBuilder(); // the start of the filename is the time so we can do some sorting filename.append(dateFormat.format(date)); // insert the user id if they provided it if (user != null) { filename.append("-"); filename.append(user.getUserId()); filename.append("-"); } // the end of the filename is a randome number between 0 and 10000 filename.append((int) (Math.random() * 10000)); filename.append(".xml"); outFile = new File(dir, filename.toString()); // set to null to avoid very minimal possiblity of an infinite loop date = null; } while (outFile.exists()); return outFile; } /** * Creates a relatively acceptable unique string of the give size * * @return unique string */ public static String generateUid(Integer size) { StringBuffer sb = new StringBuffer(size); for (int i = 0; i < size; i++) { int ch = (int) (Math.random() * 62); if (ch < 10) // 0-9 sb.append(ch); else if (ch < 36) // a-z sb.append((char) (ch - 10 + 'a')); else sb.append((char) (ch - 36 + 'A')); } return sb.toString(); } /** * Creates a uid of length 20 * * @see #generateUid(Integer) */ public static String generateUid() { return generateUid(20); } /** * Post the given map of variables to the given url string * * @param urlString valid http url to post data to * @param dataToPost Map<String, String> of key value pairs to post to urlString * @return response from urlString after posting */ public static String postToUrl(String urlString, Map<String, String> dataToPost) { OutputStreamWriter wr = null; BufferedReader rd = null; String response = ""; StringBuffer data = null; try { // Construct data for (Map.Entry<String, String> entry : dataToPost.entrySet()) { // skip over invalid post variables if (entry.getKey() == null || entry.getValue() == null) continue; // create the string buffer if this is the first variable if (data == null) data = new StringBuffer(); else data.append("&"); // only append this if its _not_ the first datum // finally, setup the actual post string data.append(URLEncoder.encode(entry.getKey(), "UTF-8")); data.append("="); data.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } // Send the data URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Length", String.valueOf(data.length())); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data.toString()); wr.flush(); wr.close(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { response = response + line + "\n"; } } catch (Exception e) { log.warn("Exception while posting to : " + urlString, e); log.warn("Reponse from server was: " + response); } finally { if (wr != null) try { wr.close(); } catch (Exception e) { /* pass */} if (rd != null) try { rd.close(); } catch (Exception e) { /* pass */} } return response; } /** * Convenience method to replace Properties.store(), which isn't UTF-8 compliant * NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer * object as an argument, making this method unnecessary. * * @param properties * @param file * @param comment */ public static void storeProperties(Properties properties, File file, String comment) { OutputStream outStream = null; try { outStream = new FileOutputStream(file, true); storeProperties(properties, outStream, comment); } catch (IOException ex) { log.error("Unable to create file " + file.getAbsolutePath() + " in storeProperties routine."); } finally { try { if (outStream != null) outStream.close(); } catch (IOException ioe) { //pass } } } /** * Convenience method to replace Properties.store(), which isn't UTF-8 compliant * NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer * object as an argument. * * @param properties * @param file * @param comment (which appears in comments in properties file) */ public static void storeProperties(Properties properties, OutputStream outStream, String comment) { try { OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(outStream), "UTF-8"); Writer out = new BufferedWriter(osw); if (comment != null) out.write("\n#" + comment + "\n"); out.write("#" + new Date() + "\n"); for (Map.Entry<Object, Object> e : properties.entrySet()) { out.write(e.getKey() + "=" + e.getValue() + "\n"); } out.write("\n"); out.flush(); out.close(); } catch (FileNotFoundException fnfe) { log.error("target file not found" + fnfe); } catch (UnsupportedEncodingException ex) { //pass log.error("unsupported encoding error hit" + ex); } catch (IOException ioex) { log.error("IO exception encountered trying to append to properties file" + ioex); } } /** * This method is a replacement for Properties.load(InputStream) so that we can load in utf-8 * characters. Currently the load method expects the inputStream to point to a latin1 encoded * file. * NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer * object as an argument, making this method unnecesary. * * @param props the properties object to write into * @param input the input stream to read from */ public static void loadProperties(Properties props, InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); while (reader.ready()) { String line = reader.readLine(); if (line.length() > 0 && line.charAt(0) != '#') { int pos = line.indexOf("="); if (pos > 0) { String keyString = line.substring(0, pos); String valueString = line.substring(pos + 1); if (keyString != null && keyString.length() > 0) { props.put(keyString, fixPropertiesValueString(valueString)); } } } } reader.close(); } catch (UnsupportedEncodingException uee) { log.error("Unsupported encoding used in properties file " + uee); } catch (IOException ioe) { log.error("Unable to read properties from properties file " + ioe); } } /** * By default java will escape colons and equal signs when writing properites files. <br/> * <br/> * This method turns escaped colons into colons and escaped equal signs into just equal signs. * * @param value the value portion of a properties file to fix * @return the value with escaped characters fixed */ private static String fixPropertiesValueString(String value) { String returnString = value.replace("\n", ""); returnString = returnString.replace("\\:", ":"); returnString = returnString.replace("\\=", "="); return returnString; } /** * Utility method for getting the translation for the passed code * @param code the message key to lookup * @param args the replacement values for the translation string * @return the message, or if not found, the code */ public static String getMessage(String code, Object... args) { Locale l = Context.getLocale(); try { String translation = Context.getMessageSourceService().getMessage(code, args, l); if (translation != null) { return translation; } } catch (NoSuchMessageException e) { log.warn("Message code <"+code+"> not found for locale " + l); } return code; } /** * Utility to check the validity of a password for a certain {@link User}. * Passwords must be non-null. Their required strength is configured via global properties: * <table> * <tr><th>Description</th><th>Property</th><th>Default Value</th></tr> * <tr> * <th>Require that it not match the {@link User}'s username or system id * <th>{@link OpenmrsConstants#GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID}</th> * <th>true</th> * </tr> * <tr> * <th>Require a minimum length * <th>{@link OpenmrsConstants#GP_PASSWORD_MINIMUM_LENGTH}</th> * <th>8</th> * </tr> * <tr> * <th>Require both an upper and lower case character * <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE}</th> * <th>true</th> * </tr> * <tr> * <th>Require at least one numeric character * <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_DIGIT}</th> * <th>true</th> * </tr> * <tr> * <th>Require at least one non-numeric character * <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_NON_DIGIT}</th> * <th>true</th> * </tr> * <tr> * <th>Require a match on the specified regular expression * <th>{@link OpenmrsConstants#GP_PASSWORD_CUSTOM_REGEX}</th> * <th>null</th> * </tr> * </table> * * @param username user name of the user with password to validated * @param password string that will be validated * @param systemId system id of the user with password to be validated * @throws PasswordException * @since 1.5 * @should fail with short password by default * @should fail with short password if not allowed * @should pass with short password if allowed * @should fail with digit only password by default * @should fail with digit only password if not allowed * @should pass with digit only password if allowed * @should fail with char only password by default * @should fail with char only password if not allowed * @should pass with char only password if allowed * @should fail without both upper and lower case password by default * @should fail without both upper and lower case password if not allowed * @should pass without both upper and lower case password if allowed * @should fail with password equals to user name by default * @should fail with password equals to user name if not allowed * @should pass with password equals to user name if allowed * @should fail with password equals to system id by default * @should fail with password equals to system id if not allowed * @should pass with password equals to system id if allowed * @should fail with password not matching configured regex * @should pass with password matching configured regex * @should allow password to contain non alphanumeric characters * @should allow password to contain white spaces */ public static void validatePassword(String username, String password, String systemId) throws PasswordException { AdministrationService svc = Context.getAdministrationService(); if (password == null) { throw new WeakPasswordException(); } String userGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, "true"); if ("true".equals(userGp) && (password.equals(username) || password.equals(systemId))) { throw new WeakPasswordException(); } String lengthGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH, "8"); if (StringUtils.isNotEmpty(lengthGp)) { try { int minLength = Integer.parseInt(lengthGp); if (password.length() < minLength) { throw new ShortPasswordException(getMessage("error.password.length", lengthGp)); } } catch (NumberFormatException nfe) { log.warn("Error in global property <" + OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH + "> must be an Integer"); } } String caseGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, "true"); if ("true".equals(caseGp) && !containsUpperAndLowerCase(password)) { throw new InvalidCharactersPasswordException(getMessage("error.password.requireMixedCase")); } String digitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_DIGIT, "true"); if ("true".equals(digitGp) && !containsDigit(password)) { throw new InvalidCharactersPasswordException(getMessage("error.password.requireNumber")); } String nonDigitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_NON_DIGIT, "true"); if ("true".equals(nonDigitGp) && containsOnlyDigits(password)) { throw new InvalidCharactersPasswordException(getMessage("error.password.requireLetter")); } String regexGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX); if (StringUtils.isNotEmpty(regexGp)) { try { Pattern pattern = Pattern.compile(regexGp); Matcher matcher = pattern.matcher(password); if (!matcher.matches()) { throw new InvalidCharactersPasswordException(getMessage("error.password.different")); } } catch (PatternSyntaxException pse) { log.warn("Invalid regex of " + regexGp + " defined in global property <" + OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX + ">."); } } } /** * @param test the string to test * @return true if the passed string contains both upper and lower case characters * @should return true if string contains upper and lower case * @should return false if string does not contain lower case characters * @should return false if string does not contain upper case characters */ public static boolean containsUpperAndLowerCase(String test) { if (test != null) { Pattern pattern = Pattern.compile("^(?=.*?[A-Z])(?=.*?[a-z])[\\w|\\W]*$"); Matcher matcher = pattern.matcher(test); return matcher.matches(); } return false; } /** * @param test the string to test * @return true if the passed string contains only numeric characters * @should return true if string contains only digits * @should return false if string contains any non-digits */ public static boolean containsOnlyDigits(String test) { if (test != null) { for (char c : test.toCharArray()) { if (!Character.isDigit(c)) { return false; } } } return StringUtils.isNotEmpty(test); } /** * @param test the string to test * @return true if the passed string contains any numeric characters * @should return true if string contains any digits * @should return false if string contains no digits */ public static boolean containsDigit(String test) { if (test != null) { for (char c : test.toCharArray()) { if (Character.isDigit(c)) { return true; } } } return false; } }
true
true
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject( search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId()); // to prevent lazy loading exceptions, cache the member ids here if (c != null) c.getMemberIds().size(); return new CohortFilter(c); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) throw new IllegalArgumentException("You can't evaluate this search without a history"); else return search.cloneCompositionAsFilter(history, evalContext); } else { Class clz = search.getFilterClass(); if (clz == null) throw new IllegalArgumentException("search must be saved, composition, or must have a class specified"); log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (testForExpression != null) { valueAsString = testForExpression; log.debug("Setting " + sa.getName() + " to: " + valueAsString); if (evalContext != null && EvaluationContext.isExpression(valueAsString)) { Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) valueAsString = Context.getDateFormat().format((Date) evaluated); else valueAsString = evaluated.toString(); } log.debug("Evaluated " + sa.getName() + " to: " + valueAsString); } } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) {} if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else if (LogicCriteria.class.equals(valueClass)) { value = Context.getLogicService().parseString(valueAsString); } else { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error( "Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. I'm going with the following rules, which should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject( search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId()); // to prevent lazy loading exceptions, cache the member ids here if (c != null) c.getMemberIds().size(); return new CohortFilter(c); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) throw new IllegalArgumentException("You can't evaluate this search without a history"); else return search.cloneCompositionAsFilter(history, evalContext); } else { Class clz = search.getFilterClass(); if (clz == null) throw new IllegalArgumentException("search must be saved, composition, or must have a class specified"); log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (testForExpression != null) { log.debug("Setting " + sa.getName() + " to: " + testForExpression); if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) valueAsString = Context.getDateFormat().format((Date) evaluated); else valueAsString = evaluated.toString(); } log.debug("Evaluated " + sa.getName() + " to: " + valueAsString); } } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) {} if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else if (LogicCriteria.class.equals(valueClass)) { value = Context.getLogicService().parseString(valueAsString); } else { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error( "Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. I'm going with the following rules, which should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
diff --git a/closure/closure-compiler/src/com/google/javascript/jscomp/ant/CompileTask.java b/closure/closure-compiler/src/com/google/javascript/jscomp/ant/CompileTask.java index 4e636a39..38741720 100644 --- a/closure/closure-compiler/src/com/google/javascript/jscomp/ant/CompileTask.java +++ b/closure/closure-compiler/src/com/google/javascript/jscomp/ant/CompileTask.java @@ -1,279 +1,281 @@ /* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.ant; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CommandLineRunner; import com.google.javascript.jscomp.CompilationLevel; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerOptions; import com.google.javascript.jscomp.JSSourceFile; import com.google.javascript.jscomp.MessageFormatter; import com.google.javascript.jscomp.Result; import com.google.javascript.jscomp.WarningLevel; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileList; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.List; import java.util.logging.Level; /** * This class implements a simple Ant task to do almost the same as * CommandLineRunner. * * Most of the public methods of this class are entry points for the * Ant code to hook into. * * */ public final class CompileTask extends Task { private WarningLevel warningLevel; private boolean debugOptions; private String encoding = "UTF-8"; private String outputEncoding = "UTF-8"; private CompilationLevel compilationLevel; private boolean customExternsOnly; private boolean manageDependencies; private File outputFile; private final List<FileList> externFileLists; private final List<FileList> sourceFileLists; public CompileTask() { this.warningLevel = WarningLevel.DEFAULT; this.debugOptions = false; this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS; this.customExternsOnly = false; this.manageDependencies = false; this.externFileLists = Lists.newLinkedList(); this.sourceFileLists = Lists.newLinkedList(); } /** * Set the warning level. * @param value The warning level by string name. (default, quiet, verbose). */ public void setWarning(String value) { if ("default".equalsIgnoreCase(value)) { this.warningLevel = WarningLevel.DEFAULT; } else if ("quiet".equalsIgnoreCase(value)) { this.warningLevel = WarningLevel.QUIET; } else if ("verbose".equalsIgnoreCase(value)) { this.warningLevel = WarningLevel.VERBOSE; } else { throw new BuildException( "Unrecognized 'warning' option value (" + value + ")"); } } /** * Enable debugging options. * @param value True if debug mode is enabled. */ public void setDebug(boolean value) { this.debugOptions = value; } /** * Set the compilation level. * @param value The optimization level by string name. * (whitespace, simple, advanced). */ public void setCompilationLevel(String value) { if ("simple".equalsIgnoreCase(value)) { this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS; } else if ("advanced".equalsIgnoreCase(value)) { this.compilationLevel = CompilationLevel.ADVANCED_OPTIMIZATIONS; } else if ("whitespace".equalsIgnoreCase(value)) { this.compilationLevel = CompilationLevel.WHITESPACE_ONLY; } else { throw new BuildException( "Unrecognized 'compilation' option value (" + value + ")"); } } public void setManageDependencies(boolean value) { this.manageDependencies = value; } /** * Use only custom externs. */ public void setCustomExternsOnly(boolean value) { this.customExternsOnly = value; } /** * Set output file. */ public void setOutput(File value) { this.outputFile = value; } /** * Set input file encoding */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Set output file encoding */ public void setOutputEncoding(String outputEncoding) { this.outputEncoding = outputEncoding; } /** * Sets the externs file. */ public void addExterns(FileList list) { this.externFileLists.add(list); } /** * Sets the source files. */ public void addSources(FileList list) { this.sourceFileLists.add(list); } public void execute() { if (this.outputFile == null) { throw new BuildException("outputFile attribute must be set"); } Compiler.setLoggingLevel(Level.OFF); CompilerOptions options = createCompilerOptions(); Compiler compiler = createCompiler(options); JSSourceFile[] externs = findExternFiles(); JSSourceFile[] sources = findSourceFiles(); log("Compiling " + sources.length + " file(s) with " + externs.length + " extern(s)"); Result result = compiler.compile(externs, sources, options); if (result.success) { writeResult(compiler.toSource()); + } else { + throw new BuildException("Compilation failed."); } } private CompilerOptions createCompilerOptions() { CompilerOptions options = new CompilerOptions(); if (this.debugOptions) { this.compilationLevel.setDebugOptionsForCompilationLevel(options); } else { this.compilationLevel.setOptionsForCompilationLevel(options); } this.warningLevel.setOptionsForWarningLevel(options); options.setManageClosureDependencies(manageDependencies); return options; } private Compiler createCompiler(CompilerOptions options) { Compiler compiler = new Compiler(); MessageFormatter formatter = options.errorFormat.toFormatter(compiler, false); AntErrorManager errorManager = new AntErrorManager(formatter, this); compiler.setErrorManager(errorManager); return compiler; } private JSSourceFile[] findExternFiles() { List<JSSourceFile> files = Lists.newLinkedList(); if (!this.customExternsOnly) { files.addAll(getDefaultExterns()); } for (FileList list : this.externFileLists) { files.addAll(findJavaScriptFiles(list)); } return files.toArray(new JSSourceFile[files.size()]); } private JSSourceFile[] findSourceFiles() { List<JSSourceFile> files = Lists.newLinkedList(); for (FileList list : this.sourceFileLists) { files.addAll(findJavaScriptFiles(list)); } return files.toArray(new JSSourceFile[files.size()]); } /** * Translates an Ant file list into the file format that the compiler * expects. */ private List<JSSourceFile> findJavaScriptFiles(FileList fileList) { List<JSSourceFile> files = Lists.newLinkedList(); File baseDir = fileList.getDir(getProject()); for (String included : fileList.getFiles(getProject())) { files.add(JSSourceFile.fromFile(new File(baseDir, included), Charset.forName(encoding))); } return files; } /** * Gets the default externs set. * * Adapted from {@link CommandLineRunner}. */ private List<JSSourceFile> getDefaultExterns() { try { return CommandLineRunner.getDefaultExterns(); } catch (IOException e) { throw new BuildException(e); } } private void writeResult(String source) { if (this.outputFile.getParentFile().mkdirs()) { log("Created missing parent directory " + this.outputFile.getParentFile(), Project.MSG_DEBUG); } try { OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(this.outputFile), outputEncoding); out.append(source); out.flush(); out.close(); } catch (IOException e) { throw new BuildException(e); } log("Compiled javascript written to " + this.outputFile.getAbsolutePath(), Project.MSG_DEBUG); } }
true
true
public void execute() { if (this.outputFile == null) { throw new BuildException("outputFile attribute must be set"); } Compiler.setLoggingLevel(Level.OFF); CompilerOptions options = createCompilerOptions(); Compiler compiler = createCompiler(options); JSSourceFile[] externs = findExternFiles(); JSSourceFile[] sources = findSourceFiles(); log("Compiling " + sources.length + " file(s) with " + externs.length + " extern(s)"); Result result = compiler.compile(externs, sources, options); if (result.success) { writeResult(compiler.toSource()); } }
public void execute() { if (this.outputFile == null) { throw new BuildException("outputFile attribute must be set"); } Compiler.setLoggingLevel(Level.OFF); CompilerOptions options = createCompilerOptions(); Compiler compiler = createCompiler(options); JSSourceFile[] externs = findExternFiles(); JSSourceFile[] sources = findSourceFiles(); log("Compiling " + sources.length + " file(s) with " + externs.length + " extern(s)"); Result result = compiler.compile(externs, sources, options); if (result.success) { writeResult(compiler.toSource()); } else { throw new BuildException("Compilation failed."); } }
diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java index 9809b0ff..14f3ca7b 100644 --- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java +++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/PackagesPublishIntegrationTest.java @@ -1,127 +1,127 @@ /* * Copyright 2000-2011 JetBrains s.r.o. * * 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 jetbrains.buildServer.nuget.tests.integration; import com.intellij.execution.configurations.GeneralCommandLine; import jetbrains.buildServer.ExecResult; import jetbrains.buildServer.RunBuildException; import jetbrains.buildServer.SimpleCommandLineProcessRunner; import jetbrains.buildServer.agent.BuildFinishedStatus; import jetbrains.buildServer.agent.BuildProcess; import jetbrains.buildServer.nuget.agent.parameters.NuGetPublishParameters; import jetbrains.buildServer.nuget.agent.runner.publish.PackagesPublishRunner; import jetbrains.buildServer.util.FileUtil; import org.jetbrains.annotations.NotNull; import org.jmock.Expectations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; /** * Created by Eugene Petrenko ([email protected]) * Date: 22.07.11 1:25 */ public class PackagesPublishIntegrationTest extends IntegrationTestBase { protected NuGetPublishParameters myPublishParameters; @BeforeMethod @Override protected void setUp() throws Exception { super.setUp(); myPublishParameters = m.mock(NuGetPublishParameters.class); m.checking(new Expectations(){{ allowing(myLogger).activityStarted(with(equal("push")), with(any(String.class)), with(any(String.class))); allowing(myLogger).activityFinished(with(equal("push")), with(any(String.class))); }}); } @Test(dataProvider = NUGET_VERSIONS) public void test_publish_packages(@NotNull final NuGet nuget) throws IOException, RunBuildException { final File pkg = preparePackage(nuget); callPublishRunner(nuget, pkg); Assert.assertTrue(getCommandsOutput().contains("Your package was uploaded")); } @Test(dataProvider = NUGET_VERSIONS) public void test_create_mock_package(@NotNull final NuGet nuget) throws IOException { final File file = preparePackage(nuget); System.out.println(file); } private File preparePackage(@NotNull final NuGet nuget) throws IOException { @NotNull final File root = createTempDir(); final File spec = new File(root, "SamplePackage.nuspec"); FileUtil.copy(getTestDataPath("SamplePackage.nuspec"), spec); GeneralCommandLine cmd = new GeneralCommandLine(); cmd.setExePath(nuget.getPath().getPath()); cmd.setWorkingDirectory(root); cmd.addParameter("pack"); cmd.addParameter(spec.getPath()); cmd.addParameter("-Version"); long time = System.currentTimeMillis(); final long max = 65536; String build = ""; for(int i = 0; i <4; i++) { build = (Math.max(1, time % max)) + (build.length() == 0 ? "" : "." + build); time /= max; } cmd.addParameter(build); cmd.addParameter("-Verbose"); final ExecResult result = SimpleCommandLineProcessRunner.runCommand(cmd, new byte[0]); System.out.println(result.getStdout()); System.out.println(result.getStderr()); Assert.assertEquals(0, result.getExitCode()); - File pkg = new File(root, "SamplePackage." + build + ".nupkg"); + File pkg = new File(root, "jonnyzzz.nuget.teamcity.testPackage." + build + ".nupkg"); Assert.assertTrue(pkg.isFile()); return pkg; } private void callPublishRunner(@NotNull final NuGet nuget, @NotNull final File pkg) throws RunBuildException { m.checking(new Expectations(){{ allowing(myPublishParameters).getFiles(); will(returnValue(Arrays.asList(pkg.getPath()))); allowing(myPublishParameters).getCreateOnly(); will(returnValue(true)); allowing(myPublishParameters).getNuGetExeFile(); will(returnValue(nuget.getPath())); allowing(myPublishParameters).getPublishSource(); will(returnValue(null)); allowing(myPublishParameters).getApiKey(); will(returnValue(getQ())); allowing(myParametersFactory).loadPublishParameters(myContext);will(returnValue(myPublishParameters)); }}); final PackagesPublishRunner runner = new PackagesPublishRunner(myActionFactory, myParametersFactory); final BuildProcess proc = runner.createBuildProcess(myBuild, myContext); assertRunSuccessfully(proc, BuildFinishedStatus.FINISHED_SUCCESS); } private String getQ() { final int i1 = 88001628; final int universe = 42; final int num = 4015; final String nuget = 91 + "be" + "-" + num + "cf638bcf"; return (i1 + "-" + "cb" + universe + "-" + 4 + "c") + 35 + "-" + nuget; } }
true
true
private File preparePackage(@NotNull final NuGet nuget) throws IOException { @NotNull final File root = createTempDir(); final File spec = new File(root, "SamplePackage.nuspec"); FileUtil.copy(getTestDataPath("SamplePackage.nuspec"), spec); GeneralCommandLine cmd = new GeneralCommandLine(); cmd.setExePath(nuget.getPath().getPath()); cmd.setWorkingDirectory(root); cmd.addParameter("pack"); cmd.addParameter(spec.getPath()); cmd.addParameter("-Version"); long time = System.currentTimeMillis(); final long max = 65536; String build = ""; for(int i = 0; i <4; i++) { build = (Math.max(1, time % max)) + (build.length() == 0 ? "" : "." + build); time /= max; } cmd.addParameter(build); cmd.addParameter("-Verbose"); final ExecResult result = SimpleCommandLineProcessRunner.runCommand(cmd, new byte[0]); System.out.println(result.getStdout()); System.out.println(result.getStderr()); Assert.assertEquals(0, result.getExitCode()); File pkg = new File(root, "SamplePackage." + build + ".nupkg"); Assert.assertTrue(pkg.isFile()); return pkg; }
private File preparePackage(@NotNull final NuGet nuget) throws IOException { @NotNull final File root = createTempDir(); final File spec = new File(root, "SamplePackage.nuspec"); FileUtil.copy(getTestDataPath("SamplePackage.nuspec"), spec); GeneralCommandLine cmd = new GeneralCommandLine(); cmd.setExePath(nuget.getPath().getPath()); cmd.setWorkingDirectory(root); cmd.addParameter("pack"); cmd.addParameter(spec.getPath()); cmd.addParameter("-Version"); long time = System.currentTimeMillis(); final long max = 65536; String build = ""; for(int i = 0; i <4; i++) { build = (Math.max(1, time % max)) + (build.length() == 0 ? "" : "." + build); time /= max; } cmd.addParameter(build); cmd.addParameter("-Verbose"); final ExecResult result = SimpleCommandLineProcessRunner.runCommand(cmd, new byte[0]); System.out.println(result.getStdout()); System.out.println(result.getStderr()); Assert.assertEquals(0, result.getExitCode()); File pkg = new File(root, "jonnyzzz.nuget.teamcity.testPackage." + build + ".nupkg"); Assert.assertTrue(pkg.isFile()); return pkg; }
diff --git a/modules/jetm-core/src/main/java/etm/core/util/collection/CollectionFactory.java b/modules/jetm-core/src/main/java/etm/core/util/collection/CollectionFactory.java index 1e2bb22..82d1769 100644 --- a/modules/jetm-core/src/main/java/etm/core/util/collection/CollectionFactory.java +++ b/modules/jetm-core/src/main/java/etm/core/util/collection/CollectionFactory.java @@ -1,72 +1,72 @@ /* * * Copyright (c) void.fm * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name void.fm nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package etm.core.util.collection; import etm.core.util.collection.EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap; import java.util.Map; /** * Helper class for runtime related collection access. * * @author void.fm * @version $Revision$ * @since 1.2.1 */ public abstract class CollectionFactory { private static CollectionFactory collectionFactory; public abstract Map newConcurrentHashMapInstance(); public static CollectionFactory getInstance() { if (collectionFactory == null) { try { - Class clazz = Class.forName("etm.core.util.collection.Java50CollectionFactory"); + Class clazz = Class.forName("etm.core.util.collection.Java15CollectionFactory"); collectionFactory = (CollectionFactory) clazz.newInstance(); } catch (Throwable e) { collectionFactory = new DefaultCollectionFactory(); } } return collectionFactory; } static class DefaultCollectionFactory extends CollectionFactory { public Map newConcurrentHashMapInstance() { // this one should work for VMs >= JDK 1.2 return new ConcurrentReaderHashMap(); } } }
true
true
public static CollectionFactory getInstance() { if (collectionFactory == null) { try { Class clazz = Class.forName("etm.core.util.collection.Java50CollectionFactory"); collectionFactory = (CollectionFactory) clazz.newInstance(); } catch (Throwable e) { collectionFactory = new DefaultCollectionFactory(); } } return collectionFactory; }
public static CollectionFactory getInstance() { if (collectionFactory == null) { try { Class clazz = Class.forName("etm.core.util.collection.Java15CollectionFactory"); collectionFactory = (CollectionFactory) clazz.newInstance(); } catch (Throwable e) { collectionFactory = new DefaultCollectionFactory(); } } return collectionFactory; }
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/export/holders/ContextHolder.java b/CubicTestPlugin/src/main/java/org/cubictest/export/holders/ContextHolder.java index 4cb099c9..d678e3cd 100644 --- a/CubicTestPlugin/src/main/java/org/cubictest/export/holders/ContextHolder.java +++ b/CubicTestPlugin/src/main/java/org/cubictest/export/holders/ContextHolder.java @@ -1,200 +1,207 @@ /******************************************************************************* * Copyright (c) 2005, 2008 Stein K. Skytteren and Christian Schwarz * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stein K. Skytteren and Christian Schwarz - initial API and implementation *******************************************************************************/ package org.cubictest.export.holders; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.apache.commons.lang.StringUtils; import org.cubictest.common.settings.CubicTestProjectSettings; import org.cubictest.export.utils.exported.XPathBuilder; import org.cubictest.model.ConnectionPoint; import org.cubictest.model.PageElement; import org.cubictest.model.PropertyAwareObject; import org.cubictest.model.SubTest; import org.cubictest.model.context.Frame; import org.cubictest.model.context.IContext; /** * Holder for context info for runners and exporters. * * @author Christian Schwarz */ public abstract class ContextHolder implements IResultHolder { protected Stack<PropertyAwareObject> breadCrumbs = new Stack<PropertyAwareObject>(); private Stack<IContext> contextStack = new Stack<IContext>(); private Stack<Stack<IContext>> frameStack = new Stack<Stack<IContext>>(); private Map<PageElement, PageElement> elementParentMap = new HashMap<PageElement, PageElement>(); private boolean shouldFailOnAssertionFailure; private boolean useNamespace = false; protected CubicTestProjectSettings settings; public CubicTestProjectSettings getSettings() { return settings; } public void setSettings(CubicTestProjectSettings settings) { this.settings = settings; } /** * Set new context, i.e. XPath starting point (path) for lookup of elements. * @param ctx */ public void pushContext(IContext ctx) { //all interesting contexts are page elements if (ctx instanceof PageElement) { contextStack.push(ctx); for (PageElement pe : ctx.getRootElements()) { //setting current context as parent of each page element within context elementParentMap.put(pe, (PageElement) ctx); } } } /** * Get the previous context, i.e. the previous XPath starting point (path) for lookup of elements. */ public void popContext() { contextStack.pop(); } public String toResultString() { //should be subclassed return ""; } public boolean isInRootContext() { return contextStack.size() == 0; } /** * Gets "smart context" assertion for a page element. * Asserts all sibling elements in context present, and recurses into parent contexts to * give a precise XPath to identify the element. * Appends child element XPaths. */ public String getFullContextWithAllElements(PageElement pageElement) { String axis = "/descendant-or-self::"; if (!isInAContext(pageElement)) { axis = "//"; } return getFullContextWithAllElements(pageElement, axis, true, null); } private String getFullContextWithAllElements(PageElement pageElement, String axis, boolean traverseParents, PageElement elementToIgnore) { - String elementExp = axis + XPathBuilder.getXPathForSingleElement(pageElement, useNamespace); + String elementExpression = axis + XPathBuilder.getXPathForSingleElement(pageElement, useNamespace); if (pageElement instanceof IContext && !(pageElement instanceof Frame)) { IContext context = (IContext) pageElement; for (PageElement child : context.getRootElements()) { if (child == elementToIgnore) { continue; } - elementExp = elementExp + "[" + getFullContextWithAllElements(child, "descendant-or-self::", false, null) + "]"; + String notStart = ""; + String notEnd = ""; + if (child.isNot()) { + notStart = "not("; + notEnd = ")"; + } + String childExpression = "[" + notStart + getFullContextWithAllElements(child, "descendant-or-self::", false, null) + notEnd + "]"; + elementExpression += childExpression; } } if (traverseParents && isInAContext(pageElement) && !(getParent(pageElement) instanceof Frame)) { - elementExp = getFullContextWithAllElements(getParent(pageElement), "/descendant-or-self::", true, pageElement) + elementExp; + elementExpression = getFullContextWithAllElements(getParent(pageElement), "/descendant-or-self::", true, pageElement) + elementExpression; } - return elementExp; + return elementExpression; } private PageElement getParent(PageElement pageElement) { return elementParentMap.get(pageElement); } private boolean isInAContext(PageElement pageElement) { return elementParentMap.get(pageElement) != null; } public void updateStatus(SubTest subTest, boolean hadException, ConnectionPoint targetConnectionPoint) { //Empty. Can be overridden if exporters want to update sub test statuses. } public boolean shouldFailOnAssertionFailure() { return shouldFailOnAssertionFailure; } public void setShouldFailOnAssertionFailure(boolean shouldFailOnAssertionFailure) { this.shouldFailOnAssertionFailure = shouldFailOnAssertionFailure; } public void popBreadcrumb() { breadCrumbs.pop(); } public void pushBreadcrumb(PropertyAwareObject element) { breadCrumbs.push(element); } public String getCurrentBreadcrumbs() { String res = ""; for (PropertyAwareObject obj : breadCrumbs) { if (StringUtils.isNotBlank(res)) { res += " --> "; } res += obj.getClass().getSimpleName() + ": " + obj.getName(); } return res; } public void pushFrame(Frame frame) { frameStack.push(contextStack); contextStack = new Stack<IContext>(); for (PageElement pe : frame.getRootElements()) { //setting current context as parent of each page element within context elementParentMap.put(pe, frame); } } public void popFrame() { contextStack = frameStack.pop(); } public boolean isPageElementWithinFrame(PageElement element){ return getParentFrame(element) != null; } public Frame getParentFrame(PageElement element) { PageElement parent = elementParentMap.get(element); if(parent == null) return null; if(parent instanceof Frame) return (Frame) parent; return getParentFrame(parent); } public void setUseNamespace(boolean useNamespace) { this.useNamespace = useNamespace; } public boolean useNamespace() { return useNamespace; } }
false
true
private String getFullContextWithAllElements(PageElement pageElement, String axis, boolean traverseParents, PageElement elementToIgnore) { String elementExp = axis + XPathBuilder.getXPathForSingleElement(pageElement, useNamespace); if (pageElement instanceof IContext && !(pageElement instanceof Frame)) { IContext context = (IContext) pageElement; for (PageElement child : context.getRootElements()) { if (child == elementToIgnore) { continue; } elementExp = elementExp + "[" + getFullContextWithAllElements(child, "descendant-or-self::", false, null) + "]"; } } if (traverseParents && isInAContext(pageElement) && !(getParent(pageElement) instanceof Frame)) { elementExp = getFullContextWithAllElements(getParent(pageElement), "/descendant-or-self::", true, pageElement) + elementExp; } return elementExp; }
private String getFullContextWithAllElements(PageElement pageElement, String axis, boolean traverseParents, PageElement elementToIgnore) { String elementExpression = axis + XPathBuilder.getXPathForSingleElement(pageElement, useNamespace); if (pageElement instanceof IContext && !(pageElement instanceof Frame)) { IContext context = (IContext) pageElement; for (PageElement child : context.getRootElements()) { if (child == elementToIgnore) { continue; } String notStart = ""; String notEnd = ""; if (child.isNot()) { notStart = "not("; notEnd = ")"; } String childExpression = "[" + notStart + getFullContextWithAllElements(child, "descendant-or-self::", false, null) + notEnd + "]"; elementExpression += childExpression; } } if (traverseParents && isInAContext(pageElement) && !(getParent(pageElement) instanceof Frame)) { elementExpression = getFullContextWithAllElements(getParent(pageElement), "/descendant-or-self::", true, pageElement) + elementExpression; } return elementExpression; }
diff --git a/vaadin-touchkit-integration-tests/src/test/java/com/vaadin/addon/itest/SmokeITCase.java b/vaadin-touchkit-integration-tests/src/test/java/com/vaadin/addon/itest/SmokeITCase.java index 9f04d2f..4beb3a2 100644 --- a/vaadin-touchkit-integration-tests/src/test/java/com/vaadin/addon/itest/SmokeITCase.java +++ b/vaadin-touchkit-integration-tests/src/test/java/com/vaadin/addon/itest/SmokeITCase.java @@ -1,40 +1,40 @@ package com.vaadin.addon.itest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import junit.framework.Assert; import org.junit.Test; public class SmokeITCase { /** * Ensures a valid vaadin kickstart page is returned from deployment url. * * @throws IOException */ @Test public void smokeTest() throws IOException { URL url = new URL("http://localhost:5678/"); InputStream openStream = url.openStream(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(openStream)); String line; boolean isInitPage = false; while ((line = bufferedReader.readLine()) != null) { - if (line.contains("vaadin.vaadinConfigurations")) { + if (line.contains("vaadin.initApplication")) { isInitPage = true; } } bufferedReader.close(); Assert.assertEquals(true, isInitPage); } }
true
true
public void smokeTest() throws IOException { URL url = new URL("http://localhost:5678/"); InputStream openStream = url.openStream(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(openStream)); String line; boolean isInitPage = false; while ((line = bufferedReader.readLine()) != null) { if (line.contains("vaadin.vaadinConfigurations")) { isInitPage = true; } } bufferedReader.close(); Assert.assertEquals(true, isInitPage); }
public void smokeTest() throws IOException { URL url = new URL("http://localhost:5678/"); InputStream openStream = url.openStream(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(openStream)); String line; boolean isInitPage = false; while ((line = bufferedReader.readLine()) != null) { if (line.contains("vaadin.initApplication")) { isInitPage = true; } } bufferedReader.close(); Assert.assertEquals(true, isInitPage); }
diff --git a/archives/plugins/org.jboss.ide.eclipse.archives.ui/src/main/org/jboss/ide/eclipse/archives/ui/NodeContribution.java b/archives/plugins/org.jboss.ide.eclipse.archives.ui/src/main/org/jboss/ide/eclipse/archives/ui/NodeContribution.java index 78f56f0e8..b7c10f56a 100644 --- a/archives/plugins/org.jboss.ide.eclipse.archives.ui/src/main/org/jboss/ide/eclipse/archives/ui/NodeContribution.java +++ b/archives/plugins/org.jboss.ide.eclipse.archives.ui/src/main/org/jboss/ide/eclipse/archives/ui/NodeContribution.java @@ -1,95 +1,94 @@ /******************************************************************************* * Copyright (c) 2007 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.ide.eclipse.archives.ui; import java.net.URL; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.jboss.ide.eclipse.archives.ui.actions.INodeActionDelegate; import org.osgi.framework.Bundle; /** * This represents a menu element to be shown in the archives view * @author "Rob Stryker" <[email protected]> * */ public class NodeContribution implements Comparable { private static final String ID = "id"; //$NON-NLS-1$ private static final String LABEL = "label"; //$NON-NLS-1$ private static final String ICON = "icon"; //$NON-NLS-1$ private static final String WEIGHT = "weight"; //$NON-NLS-1$ private static final String CLASS = "class"; //$NON-NLS-1$ private String id, label; private INodeActionDelegate actionDelegate; private ImageDescriptor icon; private int weight; public NodeContribution (IConfigurationElement element) { id = element.getAttribute(ID); label = element.getAttribute(LABEL); try { actionDelegate = (INodeActionDelegate) element.createExecutableExtension(CLASS); } catch (CoreException e) { //TODO Trace.trace(getClass(), e); } String iconPath = element.getAttribute(ICON); String pluginId = element.getDeclaringExtension().getNamespaceIdentifier(); Bundle bundle = Platform.getBundle(pluginId); URL iconURL = iconPath == null ? null : FileLocator.find(bundle, new Path(iconPath), null); if (iconURL != null) { - iconURL = bundle.getEntry(iconPath); icon = ImageDescriptor.createFromURL(iconURL); } String weightString = element.getAttribute(WEIGHT); weight = Integer.parseInt(weightString == null ? new Integer(100).toString() : weightString); } public int compareTo(Object o) { if (o instanceof NodeContribution) { NodeContribution other = (NodeContribution) o; if (weight < other.getWeight()) return -1; else if (weight > other.getWeight()) return 1; else if (weight == other.getWeight()) { return label.compareTo(other.getLabel()); } } return -1; } public INodeActionDelegate getActionDelegate() { return actionDelegate; } public ImageDescriptor getIcon() { return icon; } public String getId() { return id; } public String getLabel() { return label; } public int getWeight() { return weight; } }
true
true
public NodeContribution (IConfigurationElement element) { id = element.getAttribute(ID); label = element.getAttribute(LABEL); try { actionDelegate = (INodeActionDelegate) element.createExecutableExtension(CLASS); } catch (CoreException e) { //TODO Trace.trace(getClass(), e); } String iconPath = element.getAttribute(ICON); String pluginId = element.getDeclaringExtension().getNamespaceIdentifier(); Bundle bundle = Platform.getBundle(pluginId); URL iconURL = iconPath == null ? null : FileLocator.find(bundle, new Path(iconPath), null); if (iconURL != null) { iconURL = bundle.getEntry(iconPath); icon = ImageDescriptor.createFromURL(iconURL); } String weightString = element.getAttribute(WEIGHT); weight = Integer.parseInt(weightString == null ? new Integer(100).toString() : weightString); }
public NodeContribution (IConfigurationElement element) { id = element.getAttribute(ID); label = element.getAttribute(LABEL); try { actionDelegate = (INodeActionDelegate) element.createExecutableExtension(CLASS); } catch (CoreException e) { //TODO Trace.trace(getClass(), e); } String iconPath = element.getAttribute(ICON); String pluginId = element.getDeclaringExtension().getNamespaceIdentifier(); Bundle bundle = Platform.getBundle(pluginId); URL iconURL = iconPath == null ? null : FileLocator.find(bundle, new Path(iconPath), null); if (iconURL != null) { icon = ImageDescriptor.createFromURL(iconURL); } String weightString = element.getAttribute(WEIGHT); weight = Integer.parseInt(weightString == null ? new Integer(100).toString() : weightString); }
diff --git a/gdx/src/com/badlogic/gdx/graphics/Texture.java b/gdx/src/com/badlogic/gdx/graphics/Texture.java index d0e755c81..4e1744d68 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Texture.java +++ b/gdx/src/com/badlogic/gdx/graphics/Texture.java @@ -1,464 +1,464 @@ /* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([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.badlogic.gdx.graphics; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.MathUtils; /** * <p> * A Texture wraps a standard OpenGL ES texture. * </p> * * <p> * A Texture can be managed. If the OpenGL context is lost all managed textures get invalidated. This happens when a user switches * to another application or receives an incoming call. Managed textures get reloaded automatically. * </p> * * <p> * A Texture has to be bound via the {@link Texture#bind()} method in order for it to be applied to geometry. The texture will be * bound to the currently active texture unit specified via {@link GLCommon#glActiveTexture(int)}. * </p> * * <p> * You can draw {@link Pixmap}s to a texture at any time. The changes will be automatically uploaded to texture memory. This is of * course not extremely fast so use it with care. It also only works with unmanaged textures. * </p> * * <p> * A Texture must be disposed when it is no longer used * </p> * * @author [email protected] * */ public class Texture implements Disposable { /** * Texture filter enum * * @author [email protected] * */ public enum TextureFilter { Nearest, Linear, MipMap, MipMapNearestNearest, MipMapLinearNearest, MipMapNearestLinear, MipMapLinearLinear; public static boolean isMipMap (TextureFilter filter) { return filter != Nearest && filter != Linear; } } /** * Texture wrap enum * * @author [email protected] * */ public enum TextureWrap { ClampToEdge, Repeat } final static IntBuffer buffer = BufferUtils.newIntBuffer(1); final static ArrayList<Texture> managedTextures = new ArrayList<Texture>(); int width; int height; final boolean isMipMap; final boolean isManaged; int glHandle; final FileHandle file; final TextureData textureData; TextureFilter minFilter = TextureFilter.Nearest; TextureFilter magFilter = TextureFilter.Nearest; TextureWrap uWrap = TextureWrap.ClampToEdge; TextureWrap vWrap = TextureWrap.ClampToEdge; Format format; /** * Creates a new texture from the given {@link FileHandle}. The * FileHandle must point to a Jpeg, Png or Bmp file. This constructor * will throw an runtime exception in case the dimensions are not powers of two. * The minification and magnification filters will be set to GL_NEAREST by default. The texture wrap for u and v is set to GL_CLAMP_TO_EDGE by default. * The texture will be managed and reloaded in case of a context loss. * * @param file the FileHandle to the image file. */ public Texture(FileHandle file) { this(file, false); } /** * Creates a new texture from the given {@link FileHandle}. The * FileHandle must point to a Jpeg, Png or Bmp file. This constructor * will throw an runtime exception in case the dimensions are not powers of two. * It will also throw an exception in case mipmapping is requested but the texture is not square * when using OpenGL ES 1.x. The minification and magnification filters will be set * to GL_NEAREST by default. The texture wrap for u and v is set to GL_CLAMP_TO_EDGE by default. * The texture will be managed and reloaded in case of a context loss. In case mipmapping is * set to true then the minification filter will be set to TextureFilter.MipMap automatically. * * @param file the FileHandle to the image file. * @param mipmap whether to build a mipmap chain. */ public Texture(FileHandle file, boolean mipmap) { this.isManaged = true; this.isMipMap = mipmap; this.file = file; this.textureData = null; glHandle = createGLHandle(); Pixmap pixmap = new Pixmap(file); format = pixmap.getFormat(); uploadImageData(pixmap); pixmap.dispose(); if(mipmap) minFilter = TextureFilter.MipMap; setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); managedTextures.add(this); } /** * Creates a new texture from the given {@link Pixmap}. The Pixmap must * have power of two dimensions. The minification and magnification filters will be set * to GL_NEAREST by default. The texture wrap for u and v is set to GL_CLAMP_TO_EDGE by default. * The texture is not managed and has to be reloaded manually on a context loss. * * @param pixmap the {@link Pixmap} */ public Texture(Pixmap pixmap) { this(pixmap, false); } /** * Creates a new texture from the given {@link Pixmap}. The Pixmap must * have power of two dimensions. In case mipmapping is requested the * pixmap must be square. The minification and magnification filters will be set * to GL_NEAREST by default. The texture wrap for u and v is set to GL_CLAMP_TO_EDGE by default. * The texture is not managed and has to be reloaded manually on a context loss. In case mipmapping is * set to true then the minification filter will be set to TextureFilter.MipMap automatically. * * @param pixmap the {@link Pixmap} * @param mipmap whether to generate mipmaps */ public Texture(Pixmap pixmap, boolean mipmap) { this.isManaged = false; this.isMipMap = mipmap; this.file = null; this.textureData = null; glHandle = createGLHandle(); format = pixmap.getFormat(); uploadImageData(pixmap); if(mipmap) minFilter = TextureFilter.MipMap; setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); } /** * Creates a new texture with the given width, height and format. The dimensions * must be powers of two. he minification and magnification filters will be set * to GL_NEAREST by default. The texture wrap for u and v is set to GL_CLAMP_TO_EDGE by default. * The texture is not managed and has to be reloaded manually on a context loss. * * @param width the width of the texture * @param height the height of the texture * @param format the {@link Format} of the texture */ public Texture(int width, int height, Format format) { this.isManaged = false; this.isMipMap = false; this.file = null; this.textureData = null; glHandle = createGLHandle(); Pixmap pixmap = new Pixmap(width, height, format); pixmap.setColor(0, 0, 0, 0); pixmap.fill(); format = pixmap.getFormat(); uploadImageData(pixmap); pixmap.dispose(); setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); } /** * Creates a new texture from the given {@link TextureData}. The * texture is managed and the TextureData instance is invoked * in case of a context loss to recreate the texture. The texture wrap for u and v is set to GL_CLAMP_TO_EDGE by default. * The texture is managed. * @param data the TextureData */ public Texture(TextureData data) { this.isManaged = true; this.isMipMap = false; this.textureData = data; this.file = null; glHandle = createGLHandle(); Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); textureData.load(); format = Format.RGBA8888; // FIXME, let TextureData return the format upon load. this.width = textureData.getWidth(); this.height = textureData.getHeight(); managedTextures.add(this); } private void reload() { glHandle = createGLHandle(); setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); if(file != null) { Pixmap pixmap = new Pixmap(file); uploadImageData(pixmap); pixmap.dispose(); } if(textureData != null) { Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); textureData.load(); } } private int createGLHandle() { buffer.position(0); buffer.limit(buffer.capacity()); Gdx.gl.glGenTextures(1, buffer); return buffer.get(0); } private void uploadImageData(Pixmap pixmap) { this.width = pixmap.getWidth(); this.height = pixmap.getHeight(); - if(!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) + if(Gdx.gl20 == null && (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height))) throw new GdxRuntimeException("texture width and height must be powers of two"); Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if(isMipMap) { if(!(Gdx.gl20==null) && width != height) throw new GdxRuntimeException("texture width and height must be square when using mipmapping in OpenGL ES 1.x"); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; while(width > 0 && height > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if(level > 1) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } pixmap.dispose(); } } /** * Binds this texture. The texture will be bound to the currently active texture unit specified via * {@link GLCommon#glActiveTexture(int)}. */ public void bind () { Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); } /** * Draws the given {@link Pixmap} to the texture at position x, y. No clipping is performed so you have to make sure that you * draw only inside the texture region. * * @param pixmap The Pixmap * @param x The x coordinate in pixels * @param y The y coordinate in pixels */ public void draw (Pixmap pixmap, int x, int y) { if(isManaged) throw new GdxRuntimeException("can't draw to a managed texture"); Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); Gdx.gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if(isMipMap) { int level = 1; int height = pixmap.getHeight(); int width = pixmap.getWidth(); while (height > 0 && width > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if(level > 1) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, level, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } } } /** * * @return the width of the texture in pixels */ public int getWidth () { return width; } /** * * @return the height of the texture in pixels */ public int getHeight () { return height; } /** * @return whether this texture is managed or not. */ public boolean isManaged () { return isManaged; } /** * Disposes all resources associated with the texture */ public void dispose () { buffer.put(0, glHandle); Gdx.gl.glDeleteTextures(1, buffer); if(isManaged) managedTextures.remove(this); } /** * @return the OpenGL texture object handle so you can change texture parameters. */ public int getTextureObjectHandle () { return glHandle; } /** * Sets the {@link TextureWrap} for this texture on the u and v axis. This will bind * this texture! * * @param u the u wrap * @param v the v wrap */ public void setWrap (TextureWrap u, TextureWrap v) { this.uWrap = u; this.vWrap = v; bind(); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, u == TextureWrap.ClampToEdge?GL10.GL_CLAMP_TO_EDGE:GL10.GL_REPEAT); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, v == TextureWrap.ClampToEdge?GL10.GL_CLAMP_TO_EDGE:GL10.GL_REPEAT); } public void setFilter(TextureFilter minFilter, TextureFilter magFilter) { this.minFilter = minFilter; this.magFilter = magFilter; bind(); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, getTextureFilter(magFilter)); } private int getTextureFilter (TextureFilter filter) { if (filter == TextureFilter.Linear) return GL10.GL_LINEAR; else if (filter == TextureFilter.Nearest) return GL10.GL_NEAREST; else if (filter == TextureFilter.MipMap) return GL10.GL_LINEAR_MIPMAP_LINEAR; else if (filter == TextureFilter.MipMapNearestNearest) return GL10.GL_NEAREST_MIPMAP_NEAREST; else if (filter == TextureFilter.MipMapNearestLinear) return GL10.GL_NEAREST_MIPMAP_LINEAR; else if (filter == TextureFilter.MipMapLinearNearest) return GL10.GL_LINEAR_MIPMAP_NEAREST; else if (filter == TextureFilter.MipMapLinearLinear) return GL10.GL_LINEAR_MIPMAP_LINEAR; else return GL10.GL_LINEAR_MIPMAP_LINEAR; } /** * Clears all managed textures. This is an internal method. Do not use it! */ public static void clearAllTextures () { managedTextures.clear(); } /** * Invalidate all managed textures. This is an internal method. Do not use it! */ public static void invalidateAllTextures () { for (int i = 0; i < managedTextures.size(); i++) { Texture texture = managedTextures.get(i); texture.reload(); } } /** * @return the {@link Format} of the Texture. For {@link TextureData} based textures this will always be RGBA8888. */ public Format getFormat() { return format; } // public static Texture getFrameBufferTexture () { // ByteBuffer pixels = BufferUtils.newByteBuffer(Gdx.graphics.getWidth() * Gdx.graphics.getHeight() * 4); // Gdx.gl.glReadPixels(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixels); // Pixmap pixmap = new Pixmap(MathUtils.nextPowerOfTwo(Gdx.graphics.getWidth()), MathUtils.nextPowerOfTwo(Gdx.graphics.getHeight()), Format.RGBA8888); // // pixels.position(0); // int scanSrc = Gdx.graphics.getWidth() * 4; // int scanDst = pixmap.getWidth() * 4; // int posSrc = 0; // int posDst = 0; // ByteBuffer dst = pixmap.getPixels(); // ByteBuffer src = pixels; // for(int i = 0; i < Gdx.graphics.getHeight(); i++) { // src.position(posSrc); // src.limit(posSrc + scanSrc); // dst.position(posDst); // dst.limit(posDst + scanDst); // dst.put(src); // // posSrc += scanSrc; // posDst += scanDst; // } // // dst.position(0); // dst.limit(pixmap.getWidth() * pixmap.getHeight() * 4); // return new Texture(pixmap); // // Texture texture = new Texture(MathUtils.nextPowerOfTwo(Gdx.graphics.getWidth()), // MathUtils.nextPowerOfTwo(Gdx.graphics.getHeight()), // Format.RGBA8888); // texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); // Gdx.gl.glFlush(); // texture.bind(); // Gdx.gl.glCopyTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), 0); // return texture; // } }
true
true
private void uploadImageData(Pixmap pixmap) { this.width = pixmap.getWidth(); this.height = pixmap.getHeight(); if(!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) throw new GdxRuntimeException("texture width and height must be powers of two"); Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if(isMipMap) { if(!(Gdx.gl20==null) && width != height) throw new GdxRuntimeException("texture width and height must be square when using mipmapping in OpenGL ES 1.x"); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; while(width > 0 && height > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if(level > 1) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } pixmap.dispose(); } }
private void uploadImageData(Pixmap pixmap) { this.width = pixmap.getWidth(); this.height = pixmap.getHeight(); if(Gdx.gl20 == null && (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height))) throw new GdxRuntimeException("texture width and height must be powers of two"); Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if(isMipMap) { if(!(Gdx.gl20==null) && width != height) throw new GdxRuntimeException("texture width and height must be square when using mipmapping in OpenGL ES 1.x"); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; while(width > 0 && height > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if(level > 1) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } pixmap.dispose(); } }
diff --git a/src/tiger/src/org/compass/annotations/config/binding/AnnotationsBindingUtils.java b/src/tiger/src/org/compass/annotations/config/binding/AnnotationsBindingUtils.java index 1b17c1ff..5c9d21c0 100644 --- a/src/tiger/src/org/compass/annotations/config/binding/AnnotationsBindingUtils.java +++ b/src/tiger/src/org/compass/annotations/config/binding/AnnotationsBindingUtils.java @@ -1,143 +1,143 @@ /* * Copyright 2004-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.compass.annotations.config.binding; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import org.compass.annotations.Cascade; import org.compass.annotations.Index; import org.compass.annotations.ManagedId; import org.compass.annotations.ManagedIdIndex; import org.compass.annotations.Reverse; import org.compass.annotations.Store; import org.compass.annotations.TermVector; import org.compass.core.Property; import org.compass.core.mapping.CascadeMapping; import org.compass.core.mapping.ResourcePropertyMapping; import org.compass.core.mapping.osem.ClassPropertyMapping; /** * @author kimchy */ public abstract class AnnotationsBindingUtils { public static String getCollectionParameterClassName(Class<?> clazz, Type type) { Class retVal = getCollectionParameterClass(clazz, type); if (retVal == null) { return null; } return retVal.getName(); } public static Class getCollectionParameterClass(Class<?> clazz, Type type) { if (Collection.class.isAssignableFrom(clazz)) { if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; Type[] actualTypeArguments = paramType.getActualTypeArguments(); if (actualTypeArguments != null && actualTypeArguments.length == 1) { return (Class) actualTypeArguments[0]; } } } return null; } public static ClassPropertyMapping.ManagedId convert(ManagedId managedId) throws IllegalArgumentException { if (managedId == ManagedId.AUTO) { return ClassPropertyMapping.ManagedId.AUTO; } else if (managedId == ManagedId.TRUE) { return ClassPropertyMapping.ManagedId.TRUE; } else if (managedId == ManagedId.FALSE) { return ClassPropertyMapping.ManagedId.FALSE; } throw new IllegalArgumentException("Failed to convert managedId [" + managedId + "]"); } public static Property.TermVector convert(TermVector termVector) throws IllegalArgumentException { if (termVector == TermVector.NO) { return Property.TermVector.NO; } else if (termVector == TermVector.YES) { return Property.TermVector.YES; } else if (termVector == TermVector.WITH_POSITIONS) { return Property.TermVector.WITH_POSITIONS; } else if (termVector == TermVector.WITH_OFFSETS) { return Property.TermVector.WITH_OFFSETS; - } else if (termVector == TermVector.WITH_POSITIONS_OFFESTS) { + } else if (termVector == TermVector.WITH_POSITIONS_OFFSETS) { return Property.TermVector.WITH_POSITIONS_OFFSETS; } throw new IllegalArgumentException("Failed to convert termVectory [" + termVector + "]"); } public static ResourcePropertyMapping.ReverseType convert(Reverse reverse) throws IllegalArgumentException { if (reverse == Reverse.NO) { return ResourcePropertyMapping.ReverseType.NO; } else if (reverse == Reverse.READER) { return ResourcePropertyMapping.ReverseType.READER; } else if (reverse == Reverse.STRING) { return ResourcePropertyMapping.ReverseType.STRING; } throw new IllegalArgumentException("Failed to convert reverse [" + reverse + "]"); } public static Property.Store convert(Store store) throws IllegalArgumentException { if (store == Store.NO) { return Property.Store.NO; } else if (store == Store.YES) { return Property.Store.YES; } else if (store == Store.COMPRESS) { return Property.Store.COMPRESS; } throw new IllegalArgumentException("Failed to convert store [" + store + "]"); } public static Property.Index convert(Index index) throws IllegalArgumentException { if (index == Index.NO) { return Property.Index.NO; } else if (index == Index.TOKENIZED) { return Property.Index.TOKENIZED; } else if (index == Index.UN_TOKENIZED) { return Property.Index.UN_TOKENIZED; } throw new IllegalArgumentException("Failed to convert index [" + index + "]"); } public static Property.Index convert(ManagedIdIndex index) throws IllegalArgumentException { if (index == ManagedIdIndex.NA) { return null; } else if (index == ManagedIdIndex.NO) { return Property.Index.NO; } else if (index == ManagedIdIndex.UN_TOKENIZED) { return Property.Index.UN_TOKENIZED; } throw new IllegalArgumentException("Failed to convert index [" + index + "]"); } public static CascadeMapping.Cascade convert(Cascade cascade) throws IllegalArgumentException { if (cascade == Cascade.ALL) { return CascadeMapping.Cascade.ALL; } else if (cascade == Cascade.CREATE) { return CascadeMapping.Cascade.CREATE; } else if (cascade == Cascade.DELETE) { return CascadeMapping.Cascade.DELETE; } else if (cascade == Cascade.SAVE) { return CascadeMapping.Cascade.SAVE; } throw new IllegalArgumentException("Failed to convert cascade [" + cascade + "]"); } }
true
true
public static Property.TermVector convert(TermVector termVector) throws IllegalArgumentException { if (termVector == TermVector.NO) { return Property.TermVector.NO; } else if (termVector == TermVector.YES) { return Property.TermVector.YES; } else if (termVector == TermVector.WITH_POSITIONS) { return Property.TermVector.WITH_POSITIONS; } else if (termVector == TermVector.WITH_OFFSETS) { return Property.TermVector.WITH_OFFSETS; } else if (termVector == TermVector.WITH_POSITIONS_OFFESTS) { return Property.TermVector.WITH_POSITIONS_OFFSETS; } throw new IllegalArgumentException("Failed to convert termVectory [" + termVector + "]"); }
public static Property.TermVector convert(TermVector termVector) throws IllegalArgumentException { if (termVector == TermVector.NO) { return Property.TermVector.NO; } else if (termVector == TermVector.YES) { return Property.TermVector.YES; } else if (termVector == TermVector.WITH_POSITIONS) { return Property.TermVector.WITH_POSITIONS; } else if (termVector == TermVector.WITH_OFFSETS) { return Property.TermVector.WITH_OFFSETS; } else if (termVector == TermVector.WITH_POSITIONS_OFFSETS) { return Property.TermVector.WITH_POSITIONS_OFFSETS; } throw new IllegalArgumentException("Failed to convert termVectory [" + termVector + "]"); }
diff --git a/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java b/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java index 4c479d3..63e91d7 100644 --- a/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java +++ b/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java @@ -1,52 +1,53 @@ package com.ctb.pilot.common.filter.login; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ctb.pilot.chat.dao.UserDao; import com.ctb.pilot.chat.dao.jdbc.JdbcUserDao; import com.ctb.pilot.chat.model.User; import com.ctb.pilot.common.util.HttpUtils; public class LoginCheckFilter implements Filter { private UserDao userDao = new JdbcUserDao(); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq"); if (sequenceInCookie == null) { httpResponse.sendRedirect("/pilot/login/login.html"); return; } Integer userSequence = Integer.valueOf(sequenceInCookie); user = userDao.getUserBySequence(userSequence); session.setAttribute("user", user); } + System.out.println("user: " + user); chain.doFilter(request, response); } @Override public void destroy() { } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq"); if (sequenceInCookie == null) { httpResponse.sendRedirect("/pilot/login/login.html"); return; } Integer userSequence = Integer.valueOf(sequenceInCookie); user = userDao.getUserBySequence(userSequence); session.setAttribute("user", user); } chain.doFilter(request, response); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq"); if (sequenceInCookie == null) { httpResponse.sendRedirect("/pilot/login/login.html"); return; } Integer userSequence = Integer.valueOf(sequenceInCookie); user = userDao.getUserBySequence(userSequence); session.setAttribute("user", user); } System.out.println("user: " + user); chain.doFilter(request, response); }
diff --git a/src/main/java/pl/agh/enrollme/model/Enroll.java b/src/main/java/pl/agh/enrollme/model/Enroll.java index efee001..0e94ce5 100644 --- a/src/main/java/pl/agh/enrollme/model/Enroll.java +++ b/src/main/java/pl/agh/enrollme/model/Enroll.java @@ -1,112 +1,111 @@ package pl.agh.enrollme.model; import pl.agh.enrollme.utils.EnrollmentMode; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author Michal Partyka */ @Entity public class Enroll implements Serializable { @Transient private static final long serialVersionUID = -577123547860923047L; @Id @GeneratedValue private Integer enrollID; private String name; private EnrollmentMode enrollmentMode; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private EnrollConfiguration enrollConfiguration; @OneToMany(mappedBy = "enroll", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List<Subject> subjects = new ArrayList<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Person> persons; public EnrollConfiguration getEnrollConfiguration() { return enrollConfiguration; } public Enroll(String name, EnrollmentMode enrollmentMode, EnrollConfiguration enrollConfiguration, List<Subject> subjects) { this.enrollmentMode = enrollmentMode; this.enrollConfiguration = enrollConfiguration; this.subjects = subjects; enrollID = 0; this.name = name; } public void addSubject(Subject subject) { subjects.add(subject); } public void setEnrollmentMode(EnrollmentMode enrollmentMode) { this.enrollmentMode = enrollmentMode; } public EnrollmentMode getEnrollmentMode() { return enrollmentMode; } public void setSubjects(List<Subject> subjects) { this.subjects = subjects; } public List<Subject> getSubjects() { return subjects; } public void setEnrollID(Integer enrollID) { this.enrollID = enrollID; } public List<Person> getPersons() { return persons; } public void setPersons(List<Person> persons) { this.persons = persons; } public void setEnrollConfiguration(EnrollConfiguration enrollConfiguration) { this.enrollConfiguration = enrollConfiguration; } public Enroll() { enrollID = 0; name = ""; } public void setName(String name) { this.name = name; } public Integer getEnrollID() { return enrollID; } public String getName() { return name; } @Override public String toString() { return "Enroll{" + "enrollID=" + enrollID + ", name='" + name + '\'' + ", enrollmentMode=" + enrollmentMode + ", enrollConfiguration=" + enrollConfiguration + ", subjects=" + subjects + - ", persons=" + persons + '}'; } }
true
true
public String toString() { return "Enroll{" + "enrollID=" + enrollID + ", name='" + name + '\'' + ", enrollmentMode=" + enrollmentMode + ", enrollConfiguration=" + enrollConfiguration + ", subjects=" + subjects + ", persons=" + persons + '}'; }
public String toString() { return "Enroll{" + "enrollID=" + enrollID + ", name='" + name + '\'' + ", enrollmentMode=" + enrollmentMode + ", enrollConfiguration=" + enrollConfiguration + ", subjects=" + subjects + '}'; }
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java index 6f7f5df3..1321898d 100644 --- a/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java +++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java @@ -1,2231 +1,2246 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec; import java.beans.DefaultPersistenceDelegate; import java.beans.Encoder; import java.beans.ExceptionListener; import java.beans.Expression; import java.beans.Statement; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLTransientException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.common.HiveInterruptCallback; import org.apache.hadoop.hive.common.HiveInterruptUtils; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.Warehouse; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Order; import org.apache.hadoop.hive.ql.Context; import org.apache.hadoop.hive.ql.QueryPlan; import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter; import org.apache.hadoop.hive.ql.io.ContentSummaryInputFormat; import org.apache.hadoop.hive.ql.io.HiveFileFormatUtils; import org.apache.hadoop.hive.ql.io.HiveInputFormat; import org.apache.hadoop.hive.ql.io.HiveOutputFormat; import org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat; import org.apache.hadoop.hive.ql.io.RCFile; import org.apache.hadoop.hive.ql.io.ReworkMapredInputFormat; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.parse.ErrorMsg; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.plan.DynamicPartitionCtx; import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.ql.plan.FileSinkDesc; import org.apache.hadoop.hive.ql.plan.GroupByDesc; import org.apache.hadoop.hive.ql.plan.MapredLocalWork; import org.apache.hadoop.hive.ql.plan.MapredWork; import org.apache.hadoop.hive.ql.plan.PartitionDesc; import org.apache.hadoop.hive.ql.plan.PlanUtils; import org.apache.hadoop.hive.ql.plan.PlanUtils.ExpressionTypes; import org.apache.hadoop.hive.ql.plan.TableDesc; import org.apache.hadoop.hive.ql.stats.StatsFactory; import org.apache.hadoop.hive.ql.stats.StatsPublisher; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPAnd; import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual; import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr; import org.apache.hadoop.hive.serde.Constants; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.Serializer; import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.hadoop.mapred.SequenceFileOutputFormat; import org.apache.hadoop.util.ReflectionUtils; /** * Utilities. * */ @SuppressWarnings("nls") public final class Utilities { /** * The object in the reducer are composed of these top level fields. */ public static String HADOOP_LOCAL_FS = "file:///"; /** * ReduceField. * */ public static enum ReduceField { KEY, VALUE, ALIAS }; private Utilities() { // prevent instantiation } private static Map<String, MapredWork> gWorkMap = Collections .synchronizedMap(new HashMap<String, MapredWork>()); private static final Log LOG = LogFactory.getLog(Utilities.class.getName()); public static void clearMapRedWork(Configuration job) { try { Path planPath = new Path(HiveConf.getVar(job, HiveConf.ConfVars.PLAN)); FileSystem fs = planPath.getFileSystem(job); if (fs.exists(planPath)) { try { fs.delete(planPath, true); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { } finally { // where a single process works with multiple plans - we must clear // the cache before working with the next plan. String jobID = getHiveJobID(job); if (jobID != null) { gWorkMap.remove(jobID); } } } public static MapredWork getMapRedWork(Configuration job) { MapredWork gWork = null; try { String jobID = getHiveJobID(job); assert jobID != null; gWork = gWorkMap.get(jobID); if (gWork == null) { String jtConf = HiveConf.getVar(job, HiveConf.ConfVars.HADOOPJT); String path; if (jtConf.equals("local")) { String planPath = HiveConf.getVar(job, HiveConf.ConfVars.PLAN); path = new Path(planPath).toUri().getPath(); } else { path = "HIVE_PLAN" + jobID; } InputStream in = new FileInputStream(path); MapredWork ret = deserializeMapRedWork(in, job); gWork = ret; gWork.initialize(); gWorkMap.put(jobID, gWork); } return (gWork); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public static List<String> getFieldSchemaString(List<FieldSchema> fl) { if (fl == null) { return null; } ArrayList<String> ret = new ArrayList<String>(); for (FieldSchema f : fl) { ret.add(f.getName() + " " + f.getType() + (f.getComment() != null ? (" " + f.getComment()) : "")); } return ret; } /** * Java 1.5 workaround. From http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5015403 */ public static class EnumDelegate extends DefaultPersistenceDelegate { @Override protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(Enum.class, "valueOf", new Object[] {oldInstance.getClass(), ((Enum<?>) oldInstance).name()}); } @Override protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance == newInstance; } } public static class MapDelegate extends DefaultPersistenceDelegate { @Override protected Expression instantiate(Object oldInstance, Encoder out) { Map oldMap = (Map) oldInstance; HashMap newMap = new HashMap(oldMap); return new Expression(newMap, HashMap.class, "new", new Object[] {}); } @Override protected boolean mutatesTo(Object oldInstance, Object newInstance) { return false; } @Override protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { java.util.Collection oldO = (java.util.Collection) oldInstance; java.util.Collection newO = (java.util.Collection) newInstance; if (newO.size() != 0) { out.writeStatement(new Statement(oldInstance, "clear", new Object[] {})); } for (Iterator i = oldO.iterator(); i.hasNext();) { out.writeStatement(new Statement(oldInstance, "add", new Object[] {i.next()})); } } } public static class SetDelegate extends DefaultPersistenceDelegate { @Override protected Expression instantiate(Object oldInstance, Encoder out) { Set oldSet = (Set) oldInstance; HashSet newSet = new HashSet(oldSet); return new Expression(newSet, HashSet.class, "new", new Object[] {}); } @Override protected boolean mutatesTo(Object oldInstance, Object newInstance) { return false; } @Override protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { java.util.Collection oldO = (java.util.Collection) oldInstance; java.util.Collection newO = (java.util.Collection) newInstance; if (newO.size() != 0) { out.writeStatement(new Statement(oldInstance, "clear", new Object[] {})); } for (Iterator i = oldO.iterator(); i.hasNext();) { out.writeStatement(new Statement(oldInstance, "add", new Object[] {i.next()})); } } } public static class ListDelegate extends DefaultPersistenceDelegate { @Override protected Expression instantiate(Object oldInstance, Encoder out) { List oldList = (List) oldInstance; ArrayList newList = new ArrayList(oldList); return new Expression(newList, ArrayList.class, "new", new Object[] {}); } @Override protected boolean mutatesTo(Object oldInstance, Object newInstance) { return false; } @Override protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { java.util.Collection oldO = (java.util.Collection) oldInstance; java.util.Collection newO = (java.util.Collection) newInstance; if (newO.size() != 0) { out.writeStatement(new Statement(oldInstance, "clear", new Object[] {})); } for (Iterator i = oldO.iterator(); i.hasNext();) { out.writeStatement(new Statement(oldInstance, "add", new Object[] {i.next()})); } } } public static void setMapRedWork(Configuration job, MapredWork w, String hiveScratchDir) { try { // this is the unique job ID, which is kept in JobConf as part of the plan file name String jobID = UUID.randomUUID().toString(); Path planPath = new Path(hiveScratchDir, jobID); HiveConf.setVar(job, HiveConf.ConfVars.PLAN, planPath.toUri().toString()); // use the default file system of the job FileSystem fs = planPath.getFileSystem(job); FSDataOutputStream out = fs.create(planPath); serializeMapRedWork(w, out); // Serialize the plan to the default hdfs instance // Except for hadoop local mode execution where we should be // able to get the plan directly from the cache if (!HiveConf.getVar(job, HiveConf.ConfVars.HADOOPJT).equals("local")) { // Set up distributed cache DistributedCache.createSymlink(job); String uriWithLink = planPath.toUri().toString() + "#HIVE_PLAN" + jobID; DistributedCache.addCacheFile(new URI(uriWithLink), job); // set replication of the plan file to a high number. we use the same // replication factor as used by the hadoop jobclient for job.xml etc. short replication = (short) job.getInt("mapred.submit.replication", 10); fs.setReplication(planPath, replication); } // Cache the plan in this process w.initialize(); gWorkMap.put(jobID, w); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public static String getHiveJobID(Configuration job) { String planPath = HiveConf.getVar(job, HiveConf.ConfVars.PLAN); if (planPath != null) { return (new Path(planPath)).getName(); } return null; } public static String serializeExpression(ExprNodeDesc expr) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(baos); try { encoder.writeObject(expr); } finally { encoder.close(); } try { return baos.toString("UTF-8"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException("UTF-8 support required", ex); } } public static ExprNodeDesc deserializeExpression(String s, Configuration conf) { byte[] bytes; try { bytes = s.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException("UTF-8 support required", ex); } ByteArrayInputStream bais = new ByteArrayInputStream(bytes); XMLDecoder decoder = new XMLDecoder(bais, null, null, conf.getClassLoader()); try { ExprNodeDesc expr = (ExprNodeDesc) decoder.readObject(); return expr; } finally { decoder.close(); } } /** * Serialize a single Task. */ public static void serializeTasks(Task<? extends Serializable> t, OutputStream out) { XMLEncoder e = null; try { e = new XMLEncoder(out); // workaround for java 1.5 e.setPersistenceDelegate(ExpressionTypes.class, new EnumDelegate()); e.setPersistenceDelegate(GroupByDesc.Mode.class, new EnumDelegate()); e.setPersistenceDelegate(Operator.ProgressCounter.class, new EnumDelegate()); e.writeObject(t); } finally { if (null != e) { e.close(); } } } public static class CollectionPersistenceDelegate extends DefaultPersistenceDelegate { @Override protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, oldInstance.getClass(), "new", null); } @Override protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { Iterator ite = ((Collection) oldInstance).iterator(); while (ite.hasNext()) { out.writeStatement(new Statement(oldInstance, "add", new Object[] {ite.next()})); } } } /** * Serialize the whole query plan. */ public static void serializeQueryPlan(QueryPlan plan, OutputStream out) { XMLEncoder e = new XMLEncoder(out); e.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { LOG.warn(org.apache.hadoop.util.StringUtils.stringifyException(e)); throw new RuntimeException("Cannot serialize the query plan", e); } }); // workaround for java 1.5 e.setPersistenceDelegate(ExpressionTypes.class, new EnumDelegate()); e.setPersistenceDelegate(GroupByDesc.Mode.class, new EnumDelegate()); e.setPersistenceDelegate(Operator.ProgressCounter.class, new EnumDelegate()); e.setPersistenceDelegate(org.datanucleus.sco.backed.Map.class, new MapDelegate()); e.setPersistenceDelegate(org.datanucleus.sco.backed.List.class, new ListDelegate()); e.writeObject(plan); e.close(); } /** * Deserialize the whole query plan. */ public static QueryPlan deserializeQueryPlan(InputStream in, Configuration conf) { XMLDecoder d = null; try { d = new XMLDecoder(in, null, null, conf.getClassLoader()); QueryPlan ret = (QueryPlan) d.readObject(); return (ret); } finally { if (null != d) { d.close(); } } } /** * Serialize the mapredWork object to an output stream. DO NOT use this to write to standard * output since it closes the output stream. DO USE mapredWork.toXML() instead. */ public static void serializeMapRedWork(MapredWork w, OutputStream out) { XMLEncoder e = null; try { e = new XMLEncoder(out); // workaround for java 1.5 e.setPersistenceDelegate(ExpressionTypes.class, new EnumDelegate()); e.setPersistenceDelegate(GroupByDesc.Mode.class, new EnumDelegate()); e.writeObject(w); } finally { if (null != e) { e.close(); } } } public static MapredWork deserializeMapRedWork(InputStream in, Configuration conf) { XMLDecoder d = null; try { d = new XMLDecoder(in, null, null, conf.getClassLoader()); MapredWork ret = (MapredWork) d.readObject(); return (ret); } finally { if (null != d) { d.close(); } } } /** * Serialize the mapredLocalWork object to an output stream. DO NOT use this to write to standard * output since it closes the output stream. DO USE mapredWork.toXML() instead. */ public static void serializeMapRedLocalWork(MapredLocalWork w, OutputStream out) { XMLEncoder e = null; try { e = new XMLEncoder(out); // workaround for java 1.5 e.setPersistenceDelegate(ExpressionTypes.class, new EnumDelegate()); e.setPersistenceDelegate(GroupByDesc.Mode.class, new EnumDelegate()); e.writeObject(w); } finally { if (null != e) { e.close(); } } } public static MapredLocalWork deserializeMapRedLocalWork(InputStream in, Configuration conf) { XMLDecoder d = null; try { d = new XMLDecoder(in, null, null, conf.getClassLoader()); MapredLocalWork ret = (MapredLocalWork) d.readObject(); return (ret); } finally { if (null != d) { d.close(); } } } /** * Tuple. * * @param <T> * @param <V> */ public static class Tuple<T, V> { private final T one; private final V two; public Tuple(T one, V two) { this.one = one; this.two = two; } public T getOne() { return this.one; } public V getTwo() { return this.two; } } public static TableDesc defaultTd; static { // by default we expect ^A separated strings // This tableDesc does not provide column names. We should always use // PlanUtils.getDefaultTableDesc(String separatorCode, String columns) // or getBinarySortableTableDesc(List<FieldSchema> fieldSchemas) when // we know the column names. defaultTd = PlanUtils.getDefaultTableDesc("" + Utilities.ctrlaCode); } public static final int newLineCode = 10; public static final int tabCode = 9; public static final int ctrlaCode = 1; public static final String INDENT = " "; // Note: When DDL supports specifying what string to represent null, // we should specify "NULL" to represent null in the temp table, and then // we can make the following translation deprecated. public static String nullStringStorage = "\\N"; public static String nullStringOutput = "NULL"; public static Random randGen = new Random(); /** * Gets the task id if we are running as a Hadoop job. Gets a random number otherwise. */ public static String getTaskId(Configuration hconf) { String taskid = (hconf == null) ? null : hconf.get("mapred.task.id"); if ((taskid == null) || taskid.equals("")) { return ("" + Math.abs(randGen.nextInt())); } else { /* * extract the task and attempt id from the hadoop taskid. in version 17 the leading component * was 'task_'. thereafter the leading component is 'attempt_'. in 17 - hadoop also seems to * have used _map_ and _reduce_ to denote map/reduce task types */ String ret = taskid.replaceAll(".*_[mr]_", "").replaceAll(".*_(map|reduce)_", ""); return (ret); } } public static HashMap makeMap(Object... olist) { HashMap ret = new HashMap(); for (int i = 0; i < olist.length; i += 2) { ret.put(olist[i], olist[i + 1]); } return (ret); } public static Properties makeProperties(String... olist) { Properties ret = new Properties(); for (int i = 0; i < olist.length; i += 2) { ret.setProperty(olist[i], olist[i + 1]); } return (ret); } public static ArrayList makeList(Object... olist) { ArrayList ret = new ArrayList(); for (Object element : olist) { ret.add(element); } return (ret); } /** * StreamPrinter. * */ public static class StreamPrinter extends Thread { InputStream is; String type; PrintStream os; public StreamPrinter(InputStream is, String type, PrintStream os) { this.is = is; this.type = type; this.os = os; } @Override public void run() { BufferedReader br = null; try { InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line = null; if (type != null) { while ((line = br.readLine()) != null) { os.println(type + ">" + line); } } else { while ((line = br.readLine()) != null) { os.println(line); } } br.close(); br=null; } catch (IOException ioe) { ioe.printStackTrace(); }finally{ IOUtils.closeStream(br); } } } public static TableDesc getTableDesc(Table tbl) { return (new TableDesc(tbl.getDeserializer().getClass(), tbl.getInputFormatClass(), tbl .getOutputFormatClass(), tbl.getSchema())); } // column names and column types are all delimited by comma public static TableDesc getTableDesc(String cols, String colTypes) { return (new TableDesc(LazySimpleSerDe.class, SequenceFileInputFormat.class, HiveSequenceFileOutputFormat.class, Utilities.makeProperties( org.apache.hadoop.hive.serde.Constants.SERIALIZATION_FORMAT, "" + Utilities.ctrlaCode, org.apache.hadoop.hive.serde.Constants.LIST_COLUMNS, cols, org.apache.hadoop.hive.serde.Constants.LIST_COLUMN_TYPES, colTypes))); } public static PartitionDesc getPartitionDesc(Partition part) throws HiveException { return (new PartitionDesc(part)); } public static PartitionDesc getPartitionDescFromTableDesc(TableDesc tblDesc, Partition part) throws HiveException { return new PartitionDesc(part, tblDesc); } public static void addMapWork(MapredWork mr, Table tbl, String alias, Operator<?> work) { mr.addMapWork(tbl.getDataLocation().getPath(), alias, work, new PartitionDesc( getTableDesc(tbl), (LinkedHashMap<String, String>) null)); } private static String getOpTreeSkel_helper(Operator<?> op, String indent) { if (op == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(indent); sb.append(op.toString()); sb.append("\n"); if (op.getChildOperators() != null) { for (Object child : op.getChildOperators()) { sb.append(getOpTreeSkel_helper((Operator<?>) child, indent + " ")); } } return sb.toString(); } public static String getOpTreeSkel(Operator<?> op) { return getOpTreeSkel_helper(op, ""); } private static boolean isWhitespace(int c) { if (c == -1) { return false; } return Character.isWhitespace((char) c); } public static boolean contentsEqual(InputStream is1, InputStream is2, boolean ignoreWhitespace) throws IOException { try { if ((is1 == is2) || (is1 == null && is2 == null)) { return true; } if (is1 == null || is2 == null) { return false; } while (true) { int c1 = is1.read(); while (ignoreWhitespace && isWhitespace(c1)) { c1 = is1.read(); } int c2 = is2.read(); while (ignoreWhitespace && isWhitespace(c2)) { c2 = is2.read(); } if (c1 == -1 && c2 == -1) { return true; } if (c1 != c2) { break; } } } catch (FileNotFoundException e) { e.printStackTrace(); } return false; } /** * convert "From src insert blah blah" to "From src insert ... blah" */ public static String abbreviate(String str, int max) { str = str.trim(); int len = str.length(); int suffixlength = 20; if (len <= max) { return str; } suffixlength = Math.min(suffixlength, (max - 3) / 2); String rev = StringUtils.reverse(str); // get the last few words String suffix = WordUtils.abbreviate(rev, 0, suffixlength, ""); suffix = StringUtils.reverse(suffix); // first few .. String prefix = StringUtils.abbreviate(str, max - suffix.length()); return prefix + suffix; } public static final String NSTR = ""; /** * StreamStatus. * */ public static enum StreamStatus { EOF, TERMINATED } public static StreamStatus readColumn(DataInput in, OutputStream out) throws IOException { while (true) { int b; try { b = in.readByte(); } catch (EOFException e) { return StreamStatus.EOF; } if (b == Utilities.newLineCode) { return StreamStatus.TERMINATED; } out.write(b); } // Unreachable } /** * Convert an output stream to a compressed output stream based on codecs and compression options * specified in the Job Configuration. * * @param jc * Job Configuration * @param out * Output Stream to be converted into compressed output stream * @return compressed output stream */ public static OutputStream createCompressedStream(JobConf jc, OutputStream out) throws IOException { boolean isCompressed = FileOutputFormat.getCompressOutput(jc); return createCompressedStream(jc, out, isCompressed); } /** * Convert an output stream to a compressed output stream based on codecs codecs in the Job * Configuration. Caller specifies directly whether file is compressed or not * * @param jc * Job Configuration * @param out * Output Stream to be converted into compressed output stream * @param isCompressed * whether the output stream needs to be compressed or not * @return compressed output stream */ public static OutputStream createCompressedStream(JobConf jc, OutputStream out, boolean isCompressed) throws IOException { if (isCompressed) { Class<? extends CompressionCodec> codecClass = FileOutputFormat.getOutputCompressorClass(jc, DefaultCodec.class); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, jc); return codec.createOutputStream(out); } else { return (out); } } /** * Based on compression option and configured output codec - get extension for output file. This * is only required for text files - not sequencefiles * * @param jc * Job Configuration * @param isCompressed * Whether the output file is compressed or not * @return the required file extension (example: .gz) */ public static String getFileExtension(JobConf jc, boolean isCompressed) { if (!isCompressed) { return ""; } else { Class<? extends CompressionCodec> codecClass = FileOutputFormat.getOutputCompressorClass(jc, DefaultCodec.class); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, jc); return codec.getDefaultExtension(); } } /** * Create a sequencefile output stream based on job configuration. * * @param jc * Job configuration * @param fs * File System to create file in * @param file * Path to be created * @param keyClass * Java Class for key * @param valClass * Java Class for value * @return output stream over the created sequencefile */ public static SequenceFile.Writer createSequenceWriter(JobConf jc, FileSystem fs, Path file, Class<?> keyClass, Class<?> valClass) throws IOException { boolean isCompressed = FileOutputFormat.getCompressOutput(jc); return createSequenceWriter(jc, fs, file, keyClass, valClass, isCompressed); } /** * Create a sequencefile output stream based on job configuration Uses user supplied compression * flag (rather than obtaining it from the Job Configuration). * * @param jc * Job configuration * @param fs * File System to create file in * @param file * Path to be created * @param keyClass * Java Class for key * @param valClass * Java Class for value * @return output stream over the created sequencefile */ public static SequenceFile.Writer createSequenceWriter(JobConf jc, FileSystem fs, Path file, Class<?> keyClass, Class<?> valClass, boolean isCompressed) throws IOException { CompressionCodec codec = null; CompressionType compressionType = CompressionType.NONE; Class codecClass = null; if (isCompressed) { compressionType = SequenceFileOutputFormat.getOutputCompressionType(jc); codecClass = FileOutputFormat.getOutputCompressorClass(jc, DefaultCodec.class); codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, jc); } return (SequenceFile.createWriter(fs, jc, file, keyClass, valClass, compressionType, codec)); } /** * Create a RCFile output stream based on job configuration Uses user supplied compression flag * (rather than obtaining it from the Job Configuration). * * @param jc * Job configuration * @param fs * File System to create file in * @param file * Path to be created * @return output stream over the created rcfile */ public static RCFile.Writer createRCFileWriter(JobConf jc, FileSystem fs, Path file, boolean isCompressed) throws IOException { CompressionCodec codec = null; Class<?> codecClass = null; if (isCompressed) { codecClass = FileOutputFormat.getOutputCompressorClass(jc, DefaultCodec.class); codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, jc); } return new RCFile.Writer(fs, jc, file, null, codec); } /** * Shamelessly cloned from GenericOptionsParser. */ public static String realFile(String newFile, Configuration conf) throws IOException { Path path = new Path(newFile); URI pathURI = path.toUri(); FileSystem fs; if (pathURI.getScheme() == null) { fs = FileSystem.getLocal(conf); } else { fs = path.getFileSystem(conf); } if (!fs.exists(path)) { return null; } try { fs.close(); } catch (IOException e) { } String file = path.makeQualified(fs).toString(); // For compatibility with hadoop 0.17, change file:/a/b/c to file:///a/b/c if (StringUtils.startsWith(file, "file:/") && !StringUtils.startsWith(file, "file:///")) { file = "file:///" + file.substring("file:/".length()); } return file; } public static List<String> mergeUniqElems(List<String> src, List<String> dest) { if (dest == null) { return src; } if (src == null) { return dest; } int pos = 0; while (pos < dest.size()) { if (!src.contains(dest.get(pos))) { src.add(dest.get(pos)); } pos++; } return src; } private static final String tmpPrefix = "_tmp."; public static Path toTempPath(Path orig) { if (orig.getName().indexOf(tmpPrefix) == 0) { return orig; } return new Path(orig.getParent(), tmpPrefix + orig.getName()); } /** * Given a path, convert to a temporary path. */ public static Path toTempPath(String orig) { return toTempPath(new Path(orig)); } /** * Detect if the supplied file is a temporary path. */ public static boolean isTempPath(FileStatus file) { String name = file.getPath().getName(); // in addition to detecting hive temporary files, we also check hadoop // temporary folders that used to show up in older releases return (name.startsWith("_task") || name.startsWith(tmpPrefix)); } /** * Rename src to dst, or in the case dst already exists, move files in src to dst. If there is an * existing file with the same name, the new file's name will be appended with "_1", "_2", etc. * * @param fs * the FileSystem where src and dst are on. * @param src * the src directory * @param dst * the target directory * @throws IOException */ public static void rename(FileSystem fs, Path src, Path dst) throws IOException, HiveException { if (!fs.rename(src, dst)) { throw new HiveException("Unable to move: " + src + " to: " + dst); } } /** * Rename src to dst, or in the case dst already exists, move files in src to dst. If there is an * existing file with the same name, the new file's name will be appended with "_1", "_2", etc. * * @param fs * the FileSystem where src and dst are on. * @param src * the src directory * @param dst * the target directory * @throws IOException */ public static void renameOrMoveFiles(FileSystem fs, Path src, Path dst) throws IOException, HiveException { if (!fs.exists(dst)) { if (!fs.rename(src, dst)) { throw new HiveException("Unable to move: " + src + " to: " + dst); } } else { // move file by file FileStatus[] files = fs.listStatus(src); for (FileStatus file : files) { Path srcFilePath = file.getPath(); String fileName = srcFilePath.getName(); Path dstFilePath = new Path(dst, fileName); if (fs.exists(dstFilePath)) { int suffix = 0; do { suffix++; dstFilePath = new Path(dst, fileName + "_" + suffix); } while (fs.exists(dstFilePath)); } if (!fs.rename(srcFilePath, dstFilePath)) { throw new HiveException("Unable to move: " + src + " to: " + dst); } } } } /** * The first group will contain the task id. The second group is the optional extension. The file * name looks like: "0_0" or "0_0.gz". There may be a leading prefix (tmp_). Since getTaskId() can * return an integer only - this should match a pure integer as well */ private static Pattern fileNameTaskIdRegex = Pattern.compile("^.*?([0-9]+)(_[0-9])?(\\..*)?$"); /** * Get the task id from the filename. It is assumed that the filename is derived from the output * of getTaskId * * @param filename * filename to extract taskid from */ public static String getTaskIdFromFilename(String filename) { String taskId = filename; int dirEnd = filename.lastIndexOf(Path.SEPARATOR); if (dirEnd != -1) { taskId = filename.substring(dirEnd + 1); } Matcher m = fileNameTaskIdRegex.matcher(taskId); if (!m.matches()) { LOG.warn("Unable to get task id from file name: " + filename + ". Using last component" + taskId + " as task id."); } else { taskId = m.group(1); } LOG.debug("TaskId for " + filename + " = " + taskId); return taskId; } /** * Replace the task id from the filename. It is assumed that the filename is derived from the * output of getTaskId * * @param filename * filename to replace taskid "0_0" or "0_0.gz" by 33 to "33_0" or "33_0.gz" */ public static String replaceTaskIdFromFilename(String filename, int bucketNum) { String taskId = getTaskIdFromFilename(filename); String newTaskId = replaceTaskId(taskId, bucketNum); String ret = replaceTaskIdFromFilename(filename, taskId, newTaskId); return (ret); } private static String replaceTaskId(String taskId, int bucketNum) { String strBucketNum = String.valueOf(bucketNum); int bucketNumLen = strBucketNum.length(); int taskIdLen = taskId.length(); StringBuffer s = new StringBuffer(); for (int i = 0; i < taskIdLen - bucketNumLen; i++) { s.append("0"); } return s.toString() + strBucketNum; } /** * Replace the oldTaskId appearing in the filename by the newTaskId. The string oldTaskId could * appear multiple times, we should only replace the last one. * * @param filename * @param oldTaskId * @param newTaskId * @return */ private static String replaceTaskIdFromFilename(String filename, String oldTaskId, String newTaskId) { String[] spl = filename.split(oldTaskId); if ((spl.length == 0) || (spl.length == 1)) { return filename.replaceAll(oldTaskId, newTaskId); } StringBuffer snew = new StringBuffer(); for (int idx = 0; idx < spl.length - 1; idx++) { if (idx > 0) { snew.append(oldTaskId); } snew.append(spl[idx]); } snew.append(newTaskId); snew.append(spl[spl.length - 1]); return snew.toString(); } /** * Get all file status from a root path and recursively go deep into certain levels. * * @param path * the root path * @param level * the depth of directory should explore * @param fs * the file system * @return array of FileStatus * @throws IOException */ public static FileStatus[] getFileStatusRecurse(Path path, int level, FileSystem fs) throws IOException { // construct a path pattern (e.g., /*/*) to find all dynamically generated paths StringBuilder sb = new StringBuilder(path.toUri().getPath()); for (int i = 0; i < level; ++i) { sb.append(Path.SEPARATOR).append("*"); } Path pathPattern = new Path(path, sb.toString()); return fs.globStatus(pathPattern); } public static void mvFileToFinalPath(String specPath, Configuration hconf, boolean success, Log log, DynamicPartitionCtx dpCtx, FileSinkDesc conf) throws IOException, HiveException { FileSystem fs = (new Path(specPath)).getFileSystem(hconf); Path tmpPath = Utilities.toTempPath(specPath); Path intermediatePath = new Path(tmpPath.getParent(), tmpPath.getName() + ".intermediate"); Path finalPath = new Path(specPath); if (success) { if (fs.exists(tmpPath)) { // Step1: rename tmp output folder to intermediate path. After this // point, updates from speculative tasks still writing to tmpPath // will not appear in finalPath. log.info("Moving tmp dir: " + tmpPath + " to: " + intermediatePath); Utilities.rename(fs, tmpPath, intermediatePath); // Step2: remove any tmp file or double-committed output files ArrayList<String> emptyBuckets = Utilities.removeTempOrDuplicateFiles(fs, intermediatePath, dpCtx); // create empty buckets if necessary if (emptyBuckets.size() > 0) { createEmptyBuckets(hconf, emptyBuckets, conf); } // Step3: move to the file destination log.info("Moving tmp dir: " + intermediatePath + " to: " + finalPath); Utilities.renameOrMoveFiles(fs, intermediatePath, finalPath); } } else { fs.delete(tmpPath, true); } } /** * Check the existence of buckets according to bucket specification. Create empty buckets if * needed. * * @param specPath * The final path where the dynamic partitions should be in. * @param conf * FileSinkDesc. * @param dpCtx * dynamic partition context. * @throws HiveException * @throws IOException */ private static void createEmptyBuckets(Configuration hconf, ArrayList<String> paths, FileSinkDesc conf) throws HiveException, IOException { JobConf jc; if (hconf instanceof JobConf) { jc = new JobConf(hconf); } else { // test code path jc = new JobConf(hconf, ExecDriver.class); } HiveOutputFormat<?, ?> hiveOutputFormat = null; Class<? extends Writable> outputClass = null; boolean isCompressed = conf.getCompressed(); TableDesc tableInfo = conf.getTableInfo(); try { Serializer serializer = (Serializer) tableInfo.getDeserializerClass().newInstance(); serializer.initialize(null, tableInfo.getProperties()); outputClass = serializer.getSerializedClass(); hiveOutputFormat = conf.getTableInfo().getOutputFileFormatClass().newInstance(); } catch (SerDeException e) { throw new HiveException(e); } catch (InstantiationException e) { throw new HiveException(e); } catch (IllegalAccessException e) { throw new HiveException(e); } for (String p : paths) { Path path = new Path(p); RecordWriter writer = HiveFileFormatUtils.getRecordWriter( jc, hiveOutputFormat, outputClass, isCompressed, tableInfo.getProperties(), path); writer.close(false); LOG.info("created empty bucket for enforcing bucketing at " + path); } } /** * Remove all temporary files and duplicate (double-committed) files from a given directory. * * @return a list of path names corresponding to should-be-created empty buckets. */ public static void removeTempOrDuplicateFiles(FileSystem fs, Path path) throws IOException { removeTempOrDuplicateFiles(fs, path, null); } /** * Remove all temporary files and duplicate (double-committed) files from a given directory. * * @return a list of path names corresponding to should-be-created empty buckets. */ public static ArrayList<String> removeTempOrDuplicateFiles(FileSystem fs, Path path, DynamicPartitionCtx dpCtx) throws IOException { if (path == null) { return null; } ArrayList<String> result = new ArrayList<String>(); if (dpCtx != null) { FileStatus parts[] = getFileStatusRecurse(path, dpCtx.getNumDPCols(), fs); HashMap<String, FileStatus> taskIDToFile = null; for (int i = 0; i < parts.length; ++i) { assert parts[i].isDir() : "dynamic partition " + parts[i].getPath() + " is not a direcgtory"; FileStatus[] items = fs.listStatus(parts[i].getPath()); // remove empty directory since DP insert should not generate empty partitions. // empty directories could be generated by crashed Task/ScriptOperator if (items.length == 0) { if (!fs.delete(parts[i].getPath(), true)) { LOG.error("Cannot delete empty directory " + parts[i].getPath()); throw new IOException("Cannot delete empty directory " + parts[i].getPath()); } } taskIDToFile = removeTempOrDuplicateFiles(items, fs); // if the table is bucketed and enforce bucketing, we should check and generate all buckets if (dpCtx.getNumBuckets() > 0 && taskIDToFile != null) { // refresh the file list items = fs.listStatus(parts[i].getPath()); // get the missing buckets and generate empty buckets String taskID1 = taskIDToFile.keySet().iterator().next(); Path bucketPath = taskIDToFile.values().iterator().next().getPath(); for (int j = 0; j < dpCtx.getNumBuckets(); ++j) { String taskID2 = replaceTaskId(taskID1, j); if (!taskIDToFile.containsKey(taskID2)) { // create empty bucket, file name should be derived from taskID2 String path2 = replaceTaskIdFromFilename(bucketPath.toUri().getPath().toString(), j); result.add(path2); } } } } } else { FileStatus[] items = fs.listStatus(path); removeTempOrDuplicateFiles(items, fs); } return result; } public static HashMap<String, FileStatus> removeTempOrDuplicateFiles(FileStatus[] items, FileSystem fs) throws IOException { if (items == null || fs == null) { return null; } HashMap<String, FileStatus> taskIdToFile = new HashMap<String, FileStatus>(); for (FileStatus one : items) { if (isTempPath(one)) { if (!fs.delete(one.getPath(), true)) { throw new IOException("Unable to delete tmp file: " + one.getPath()); } } else { String taskId = getTaskIdFromFilename(one.getPath().getName()); FileStatus otherFile = taskIdToFile.get(taskId); if (otherFile == null) { taskIdToFile.put(taskId, one); } else { // Compare the file sizes of all the attempt files for the same task, the largest win // any attempt files could contain partial results (due to task failures or // speculative runs), but the largest should be the correct one since the result // of a successful run should never be smaller than a failed/speculative run. FileStatus toDelete = null; if (otherFile.getLen() >= one.getLen()) { toDelete = one; } else { toDelete = otherFile; taskIdToFile.put(taskId, one); } long len1 = toDelete.getLen(); long len2 = taskIdToFile.get(taskId).getLen(); if (!fs.delete(toDelete.getPath(), true)) { throw new IOException("Unable to delete duplicate file: " + toDelete.getPath() + ". Existing file: " + taskIdToFile.get(taskId).getPath()); } else { LOG.warn("Duplicate taskid file removed: " + toDelete.getPath() + " with length " + len1 + ". Existing file: " + taskIdToFile.get(taskId).getPath() + " with length " + len2); } } } } return taskIdToFile; } public static String getNameMessage(Exception e) { return e.getClass().getName() + "(" + e.getMessage() + ")"; } /** * Add new elements to the classpath. * * @param newPaths * Array of classpath elements */ public static ClassLoader addToClassPath(ClassLoader cloader, String[] newPaths) throws Exception { URLClassLoader loader = (URLClassLoader) cloader; List<URL> curPath = Arrays.asList(loader.getURLs()); ArrayList<URL> newPath = new ArrayList<URL>(); // get a list with the current classpath components for (URL onePath : curPath) { newPath.add(onePath); } curPath = newPath; for (String onestr : newPaths) { // special processing for hadoop-17. file:// needs to be removed if (StringUtils.indexOf(onestr, "file://") == 0) { onestr = StringUtils.substring(onestr, 7); } URL oneurl = (new File(onestr)).toURL(); if (!curPath.contains(oneurl)) { curPath.add(oneurl); } } return new URLClassLoader(curPath.toArray(new URL[0]), loader); } /** * remove elements from the classpath. * * @param pathsToRemove * Array of classpath elements */ public static void removeFromClassPath(String[] pathsToRemove) throws Exception { Thread curThread = Thread.currentThread(); URLClassLoader loader = (URLClassLoader) curThread.getContextClassLoader(); Set<URL> newPath = new HashSet<URL>(Arrays.asList(loader.getURLs())); for (String onestr : pathsToRemove) { // special processing for hadoop-17. file:// needs to be removed if (StringUtils.indexOf(onestr, "file://") == 0) { onestr = StringUtils.substring(onestr, 7); } URL oneurl = (new File(onestr)).toURL(); newPath.remove(oneurl); } loader = new URLClassLoader(newPath.toArray(new URL[0])); curThread.setContextClassLoader(loader); } public static String formatBinaryString(byte[] array, int start, int length) { StringBuilder sb = new StringBuilder(); for (int i = start; i < start + length; i++) { sb.append("x"); sb.append(array[i] < 0 ? array[i] + 256 : array[i] + 0); } return sb.toString(); } public static List<String> getColumnNamesFromSortCols(List<Order> sortCols) { List<String> names = new ArrayList<String>(); for (Order o : sortCols) { names.add(o.getCol()); } return names; } public static List<String> getColumnNamesFromFieldSchema(List<FieldSchema> partCols) { List<String> names = new ArrayList<String>(); for (FieldSchema o : partCols) { names.add(o.getName()); } return names; } public static List<String> getColumnNames(Properties props) { List<String> names = new ArrayList<String>(); String colNames = props.getProperty(Constants.LIST_COLUMNS); String[] cols = colNames.trim().split(","); if (cols != null) { for (String col : cols) { if (col != null && !col.trim().equals("")) { names.add(col); } } } return names; } public static List<String> getColumnTypes(Properties props) { List<String> names = new ArrayList<String>(); String colNames = props.getProperty(Constants.LIST_COLUMN_TYPES); String[] cols = colNames.trim().split(","); if (cols != null) { for (String col : cols) { if (col != null && !col.trim().equals("")) { names.add(col); } } } return names; } public static void validateColumnNames(List<String> colNames, List<String> checkCols) throws SemanticException { Iterator<String> checkColsIter = checkCols.iterator(); while (checkColsIter.hasNext()) { String toCheck = checkColsIter.next(); boolean found = false; Iterator<String> colNamesIter = colNames.iterator(); while (colNamesIter.hasNext()) { String colName = colNamesIter.next(); if (toCheck.equalsIgnoreCase(colName)) { found = true; break; } } if (!found) { throw new SemanticException(ErrorMsg.INVALID_COLUMN.getMsg()); } } } /** * Gets the default notification interval to send progress updates to the tracker. Useful for * operators that may not output data for a while. * * @param hconf * @return the interval in milliseconds */ public static int getDefaultNotificationInterval(Configuration hconf) { int notificationInterval; Integer expInterval = Integer.decode(hconf.get("mapred.tasktracker.expiry.interval")); if (expInterval != null) { notificationInterval = expInterval.intValue() / 2; } else { // 5 minutes notificationInterval = 5 * 60 * 1000; } return notificationInterval; } /** * Copies the storage handler properties configured for a table descriptor to a runtime job * configuration. * * @param tbl * table descriptor from which to read * * @param job * configuration which receives configured properties */ public static void copyTableJobPropertiesToConf(TableDesc tbl, JobConf job) { Map<String, String> jobProperties = tbl.getJobProperties(); if (jobProperties == null) { return; } for (Map.Entry<String, String> entry : jobProperties.entrySet()) { job.set(entry.getKey(), entry.getValue()); } } public static Object getInputSummaryLock = new Object(); /** * Calculate the total size of input files. * * @param job * the hadoop job conf. * @param work * map reduce job plan * @param filter * filter to apply to the input paths before calculating size * @return the summary of all the input paths. * @throws IOException */ public static ContentSummary getInputSummary(Context ctx, MapredWork work, PathFilter filter) throws IOException { long[] summary = {0, 0, 0}; List<String> pathNeedProcess = new ArrayList<String>(); // Since multiple threads could call this method concurrently, locking // this method will avoid number of threads out of control. synchronized (getInputSummaryLock) { // For each input path, calculate the total size. for (String path : work.getPathToAliases().keySet()) { Path p = new Path(path); if (filter != null && !filter.accept(p)) { continue; } ContentSummary cs = ctx.getCS(path); if (cs == null) { if (path == null) { continue; } pathNeedProcess.add(path); } else { summary[0] += cs.getLength(); summary[1] += cs.getFileCount(); summary[2] += cs.getDirectoryCount(); } } // Process the case when name node call is needed final Map<String, ContentSummary> resultMap = new ConcurrentHashMap<String, ContentSummary>(); ArrayList<Future<?>> results = new ArrayList<Future<?>>(); final ThreadPoolExecutor executor; int maxThreads = ctx.getConf().getInt("mapred.dfsclient.parallelism.max", 0); if (pathNeedProcess.size() > 1 && maxThreads > 1) { int numExecutors = Math.min(pathNeedProcess.size(), maxThreads); LOG.info("Using " + numExecutors + " threads for getContentSummary"); executor = new ThreadPoolExecutor(numExecutors, numExecutors, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } else { executor = null; } HiveInterruptCallback interrup = HiveInterruptUtils.add(new HiveInterruptCallback() { @Override public void interrupt() { if (executor != null) { executor.shutdownNow(); } } }); try { Configuration conf = ctx.getConf(); JobConf jobConf = new JobConf(conf); for (String path : pathNeedProcess) { final Path p = new Path(path); final String pathStr = path; // All threads share the same Configuration and JobConf based on the // assumption that they are thread safe if only read operations are // executed. It is not stated in Hadoop's javadoc, the sourcce codes // clearly showed that they made efforts for it and we believe it is // thread safe. Will revisit this piece of codes if we find the assumption // is not correct. final Configuration myConf = conf; final JobConf myJobConf = jobConf; final PartitionDesc partDesc = work.getPathToPartitionInfo().get( p.toString()); Runnable r = new Runnable() { public void run() { try { ContentSummary resultCs; Class<? extends InputFormat> inputFormatCls = partDesc .getInputFileFormatClass(); InputFormat inputFormatObj = HiveInputFormat.getInputFormatFromCache( inputFormatCls, myJobConf); if (inputFormatObj instanceof ContentSummaryInputFormat) { resultCs = ((ContentSummaryInputFormat) inputFormatObj).getContentSummary(p, myJobConf); } else { FileSystem fs = p.getFileSystem(myConf); resultCs = fs.getContentSummary(p); } resultMap.put(pathStr, resultCs); } catch (IOException e) { // We safely ignore this exception for summary data. // We don't update the cache to protect it from polluting other // usages. The worst case is that IOException will always be // retried for another getInputSummary(), which is fine as // IOException is not considered as a common case. LOG.info("Cannot get size of " + pathStr + ". Safely ignored."); } } }; if (executor == null) { r.run(); } else { Future<?> result = executor.submit(r); results.add(result); } } if (executor != null) { + for (Future<?> result : results) { + boolean executorDone = false; + do { + try { + result.get(); + executorDone = true; + } catch (InterruptedException e) { + LOG.info("Interrupted when waiting threads: ", e); + Thread.currentThread().interrupt(); + break; + } catch (ExecutionException e) { + throw new IOException(e); + } + } while (!executorDone); + } executor.shutdown(); } HiveInterruptUtils.checkInterrupted(); for (Map.Entry<String, ContentSummary> entry : resultMap.entrySet()) { ContentSummary cs = entry.getValue(); summary[0] += cs.getLength(); summary[1] += cs.getFileCount(); summary[2] += cs.getDirectoryCount(); ctx.addCS(entry.getKey(), cs); LOG.info("Cache Content Summary for " + entry.getKey() + " length: " + cs.getLength() + " file count: " + cs.getFileCount() + " directory count: " + cs.getDirectoryCount()); } return new ContentSummary(summary[0], summary[1], summary[2]); } finally { HiveInterruptUtils.remove(interrup); } } } public static boolean isEmptyPath(JobConf job, String dirPath, Context ctx) throws Exception { ContentSummary cs = ctx.getCS(dirPath); if (cs != null) { LOG.info("Content Summary " + dirPath + "length: " + cs.getLength() + " num files: " + cs.getFileCount() + " num directories: " + cs.getDirectoryCount()); return (cs.getLength() == 0 && cs.getFileCount() == 0 && cs.getDirectoryCount() <= 1); } else { LOG.info("Content Summary not cached for " + dirPath); } Path p = new Path(dirPath); return isEmptyPath(job, p); } public static boolean isEmptyPath(JobConf job, Path dirPath) throws Exception { FileSystem inpFs = dirPath.getFileSystem(job); if (inpFs.exists(dirPath)) { FileStatus[] fStats = inpFs.listStatus(dirPath); if (fStats.length > 0) { return false; } } return true; } public static List<ExecDriver> getMRTasks(List<Task<? extends Serializable>> tasks) { List<ExecDriver> mrTasks = new ArrayList<ExecDriver>(); if (tasks != null) { getMRTasks(tasks, mrTasks); } return mrTasks; } private static void getMRTasks(List<Task<? extends Serializable>> tasks, List<ExecDriver> mrTasks) { for (Task<? extends Serializable> task : tasks) { if (task instanceof ExecDriver && !mrTasks.contains((ExecDriver) task)) { mrTasks.add((ExecDriver) task); } if (task.getDependentTasks() != null) { getMRTasks(task.getDependentTasks(), mrTasks); } } } public static boolean supportCombineFileInputFormat() { return ShimLoader.getHadoopShims().getCombineFileInputFormat() != null; } /** * Construct a list of full partition spec from Dynamic Partition Context and the directory names * corresponding to these dynamic partitions. */ public static List<LinkedHashMap<String, String>> getFullDPSpecs(Configuration conf, DynamicPartitionCtx dpCtx) throws HiveException { try { Path loadPath = new Path(dpCtx.getRootPath()); FileSystem fs = loadPath.getFileSystem(conf); int numDPCols = dpCtx.getNumDPCols(); FileStatus[] status = Utilities.getFileStatusRecurse(loadPath, numDPCols, fs); if (status.length == 0) { LOG.warn("No partition is genereated by dynamic partitioning"); return null; } // partial partition specification Map<String, String> partSpec = dpCtx.getPartSpec(); // list of full partition specification List<LinkedHashMap<String, String>> fullPartSpecs = new ArrayList<LinkedHashMap<String, String>>(); // for each dynamically created DP directory, construct a full partition spec // and load the partition based on that for (int i = 0; i < status.length; ++i) { // get the dynamically created directory Path partPath = status[i].getPath(); assert fs.getFileStatus(partPath).isDir() : "partitions " + partPath + " is not a directory !"; // generate a full partition specification LinkedHashMap<String, String> fullPartSpec = new LinkedHashMap<String, String>(partSpec); Warehouse.makeSpecFromName(fullPartSpec, partPath); fullPartSpecs.add(fullPartSpec); } return fullPartSpecs; } catch (IOException e) { throw new HiveException(e); } } public static StatsPublisher getStatsPublisher(JobConf jc) { String statsImplementationClass = HiveConf.getVar(jc, HiveConf.ConfVars.HIVESTATSDBCLASS); if (StatsFactory.setImplementation(statsImplementationClass, jc)) { return StatsFactory.getStatsPublisher(); } else { return null; } } public static void setColumnNameList(JobConf jobConf, Operator op) { RowSchema rowSchema = op.getSchema(); if (rowSchema == null) { return; } StringBuilder columnNames = new StringBuilder(); for (ColumnInfo colInfo : rowSchema.getSignature()) { if (columnNames.length() > 0) { columnNames.append(","); } columnNames.append(colInfo.getInternalName()); } String columnNamesString = columnNames.toString(); jobConf.set(Constants.LIST_COLUMNS, columnNamesString); } public static void validatePartSpec(Table tbl, Map<String, String> partSpec) throws SemanticException { List<FieldSchema> parts = tbl.getPartitionKeys(); Set<String> partCols = new HashSet<String>(parts.size()); for (FieldSchema col : parts) { partCols.add(col.getName()); } for (String col : partSpec.keySet()) { if (!partCols.contains(col)) { throw new SemanticException(ErrorMsg.NONEXISTPARTCOL.getMsg(col)); } } } public static String suffix = ".hashtable"; public static String generatePath(String baseURI, Byte tag, String bigBucketFileName) { String path = new String(baseURI + Path.SEPARATOR + "MapJoin-" + tag + "-" + bigBucketFileName + suffix); return path; } public static String generateFileName(Byte tag, String bigBucketFileName) { String fileName = new String("MapJoin-" + tag + "-" + bigBucketFileName + suffix); return fileName; } public static String generateTmpURI(String baseURI, String id) { String tmpFileURI = new String(baseURI + Path.SEPARATOR + "HashTable-" + id); return tmpFileURI; } public static String generateTarURI(String baseURI, String filename) { String tmpFileURI = new String(baseURI + Path.SEPARATOR + filename + ".tar.gz"); return tmpFileURI; } public static String generateTarURI(Path baseURI, String filename) { String tmpFileURI = new String(baseURI + Path.SEPARATOR + filename + ".tar.gz"); return tmpFileURI; } public static String generateTarFileName(String name) { String tmpFileURI = new String(name + ".tar.gz"); return tmpFileURI; } public static String generatePath(Path baseURI, String filename) { String path = new String(baseURI + Path.SEPARATOR + filename); return path; } public static String now() { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); return sdf.format(cal.getTime()); } public static double showTime(long time) { double result = (double) time / (double) 1000; return result; } /** * Determines whether a partition has been archived * * @param p * @return */ public static boolean isArchived(Partition p) { Map<String, String> params = p.getParameters(); if ("true".equalsIgnoreCase(params.get( org.apache.hadoop.hive.metastore.api.Constants.IS_ARCHIVED))) { return true; } else { return false; } } /** * Check if a function can be pushed down to JDO. * Now only {=, AND, OR} are supported. * @param func a generic function. * @return true if this function can be pushed down to JDO filter. */ private static boolean supportedJDOFuncs(GenericUDF func) { return func instanceof GenericUDFOPEqual || func instanceof GenericUDFOPAnd || func instanceof GenericUDFOPOr; } /** * Check if the partition pruning expression can be pushed down to JDO filtering. * The partition expression contains only partition columns. * The criteria that an expression can be pushed down are that: * 1) the expression only contains function specified in supportedJDOFuncs(). * Now only {=, AND, OR} can be pushed down. * 2) the partition column type and the constant type have to be String. This is * restriction by the current JDO filtering implementation. * @param tab The table that contains the partition columns. * @param expr the partition pruning expression * @return true if the partition pruning expression can be pushed down to JDO filtering. */ public static boolean checkJDOPushDown(Table tab, ExprNodeDesc expr) { if (expr instanceof ExprNodeConstantDesc) { // JDO filter now only support String typed literal -- see Filter.g and ExpressionTree.java Object value = ((ExprNodeConstantDesc)expr).getValue(); return (value instanceof String); } else if (expr instanceof ExprNodeColumnDesc) { // JDO filter now only support String typed literal -- see Filter.g and ExpressionTree.java TypeInfo type = expr.getTypeInfo(); if (type.getTypeName().equals(Constants.STRING_TYPE_NAME)) { String colName = ((ExprNodeColumnDesc)expr).getColumn(); for (FieldSchema fs: tab.getPartCols()) { if (fs.getName().equals(colName)) { return fs.getType().equals(Constants.STRING_TYPE_NAME); } } assert(false); // cannot find the partition column! } else { return false; } } else if (expr instanceof ExprNodeGenericFuncDesc) { ExprNodeGenericFuncDesc funcDesc = (ExprNodeGenericFuncDesc) expr; GenericUDF func = funcDesc.getGenericUDF(); if (!supportedJDOFuncs(func)) { return false; } List<ExprNodeDesc> children = funcDesc.getChildExprs(); for (ExprNodeDesc child: children) { if (!checkJDOPushDown(tab, child)) { return false; } } return true; } return false; } private static ThreadLocal<Map<String, Long>> perfKeyMaps = new ThreadLocal<Map<String, Long>>(); /** * Call this function when you start to measure time spent by a piece of code. * @param _log the logging object to be used. * @param method method or ID that identifies this perf log element. */ public static void PerfLogBegin(Log _log, String method) { long startTime = System.currentTimeMillis(); _log.info("<PERFLOG method=" + method + ">"); if (perfKeyMaps.get() == null) { perfKeyMaps.set(new HashMap<String, Long>()); } perfKeyMaps.get().put(method, new Long(startTime)); } /** * Call this function in correspondence of PerfLogBegin to mark the end of the measurement. * @param _log * @param method */ public static void PerfLogEnd(Log _log, String method) { Long startTime = perfKeyMaps.get().get(method); long endTime = System.currentTimeMillis(); StringBuilder sb = new StringBuilder("</PERFLOG method=").append(method); if (startTime != null) { sb.append(" start=").append(startTime); } sb.append(" end=").append(endTime); if (startTime != null) { sb.append(" duration=").append(endTime - startTime.longValue()); } sb.append(">"); _log.info(sb); } /** * The check here is kind of not clean. It first use a for loop to go through * all input formats, and choose the ones that extend ReworkMapredInputFormat * to a set. And finally go through the ReworkMapredInputFormat set, and call * rework for each one. * * Technically all these can be avoided if all Hive's input formats can share * a same interface. As in today's hive and Hadoop, it is not possible because * a lot of Hive's input formats are in Hadoop's code. And most of Hadoop's * input formats just extend InputFormat interface. * * @param task * @param reworkMapredWork * @param conf * @throws SemanticException */ public static void reworkMapRedWork(Task<? extends Serializable> task, boolean reworkMapredWork, HiveConf conf) throws SemanticException { if (reworkMapredWork && (task instanceof MapRedTask)) { try { MapredWork mapredWork = ((MapRedTask) task).getWork(); Set<Class<? extends InputFormat>> reworkInputFormats = new HashSet<Class<? extends InputFormat>>(); for (PartitionDesc part : mapredWork.getPathToPartitionInfo().values()) { Class<? extends InputFormat> inputFormatCls = part .getInputFileFormatClass(); if (ReworkMapredInputFormat.class.isAssignableFrom(inputFormatCls)) { reworkInputFormats.add(inputFormatCls); } } if (reworkInputFormats.size() > 0) { for (Class<? extends InputFormat> inputFormatCls : reworkInputFormats) { ReworkMapredInputFormat inst = (ReworkMapredInputFormat) ReflectionUtils .newInstance(inputFormatCls, null); inst.rework(conf, mapredWork); } } } catch (IOException e) { throw new SemanticException(e); } } } public static class SQLCommand<T> { public T run(PreparedStatement stmt) throws SQLException { return null; } } /** * Retry SQL execution with random backoff (same as the one implemented in HDFS-767). * This function only retries when the SQL query throws a SQLTransientException (which * might be able to succeed with a simple retry). It doesn't retry when the exception * is a SQLRecoverableException or SQLNonTransientException. For SQLRecoverableException * the caller needs to reconnect to the database and restart the whole transaction. * * @param query the prepared statement of SQL. * @param type either SQLCommandType.QUERY or SQLCommandType.UPDATE * @param baseWindow The base time window (in milliseconds) before the next retry. * see {@getRandomWaitTime} for details. * @param maxRetries the maximum # of retries when getting a SQLTransientException. * @throws SQLException throws SQLRecoverableException or SQLNonTransientException the * first time it is caught, or SQLTransientException when the maxRetries has reached. */ public static <T> T executeWithRetry(SQLCommand<T> cmd, PreparedStatement stmt, int baseWindow, int maxRetries) throws SQLException { Random r = new Random(); T result = null; // retry with # of maxRetries before throwing exception for (int failures = 0; ; failures++) { try { result = cmd.run(stmt); return result; } catch (SQLTransientException e) { LOG.warn("Failure and retry #" + failures + " with exception " + e.getMessage()); if (failures >= maxRetries) { throw e; } long waitTime = getRandomWaitTime(baseWindow, failures, r); try { Thread.sleep(waitTime); } catch (InterruptedException iex) { } } catch (SQLException e) { // throw other types of SQLExceptions (SQLNonTransientException / SQLRecoverableException) throw e; } } } /** * Retry connecting to a database with random backoff (same as the one implemented in HDFS-767). * This function only retries when the SQL query throws a SQLTransientException (which * might be able to succeed with a simple retry). It doesn't retry when the exception * is a SQLRecoverableException or SQLNonTransientException. For SQLRecoverableException * the caller needs to reconnect to the database and restart the whole transaction. * * @param connectionString the JDBC connection string. * @param baseWindow The base time window (in milliseconds) before the next retry. * see {@getRandomWaitTime} for details. * @param maxRetries the maximum # of retries when getting a SQLTransientException. * @throws SQLException throws SQLRecoverableException or SQLNonTransientException the * first time it is caught, or SQLTransientException when the maxRetries has reached. */ public static Connection connectWithRetry(String connectionString, int waitWindow, int maxRetries) throws SQLException { Random r = new Random(); // retry with # of maxRetries before throwing exception for (int failures = 0; ; failures++) { try { Connection conn = DriverManager.getConnection(connectionString); return conn; } catch (SQLTransientException e) { if (failures >= maxRetries) { LOG.error("Error during JDBC connection. " + e); throw e; } long waitTime = Utilities.getRandomWaitTime(waitWindow, failures, r); try { Thread.sleep(waitTime); } catch (InterruptedException e1) { } } catch (SQLException e) { // just throw other types (SQLNonTransientException / SQLRecoverableException) throw e; } } } /** * Retry preparing a SQL statement with random backoff (same as the one implemented in HDFS-767). * This function only retries when the SQL query throws a SQLTransientException (which * might be able to succeed with a simple retry). It doesn't retry when the exception * is a SQLRecoverableException or SQLNonTransientException. For SQLRecoverableException * the caller needs to reconnect to the database and restart the whole transaction. * * @param conn a JDBC connection. * @param stmt the SQL statement to be prepared. * @param baseWindow The base time window (in milliseconds) before the next retry. * see {@getRandomWaitTime} for details. * @param maxRetries the maximum # of retries when getting a SQLTransientException. * @throws SQLException throws SQLRecoverableException or SQLNonTransientException the * first time it is caught, or SQLTransientException when the maxRetries has reached. */ public static PreparedStatement prepareWithRetry(Connection conn, String stmt, int waitWindow, int maxRetries) throws SQLException { Random r = new Random(); // retry with # of maxRetries before throwing exception for (int failures = 0; ; failures++) { try { return conn.prepareStatement(stmt); } catch (SQLTransientException e) { if (failures >= maxRetries) { LOG.error("Error preparing JDBC Statement " + stmt + " :" + e); throw e; } long waitTime = Utilities.getRandomWaitTime(waitWindow, failures, r); try { Thread.sleep(waitTime); } catch (InterruptedException e1) { } } catch (SQLException e) { // just throw other types (SQLNonTransientException / SQLRecoverableException) throw e; } } } /** * Introducing a random factor to the wait time before another retry. * The wait time is dependent on # of failures and a random factor. * At the first time of getting an exception , the wait time * is a random number between 0..baseWindow msec. If the first retry * still fails, we will wait baseWindow msec grace period before the 2nd retry. * Also at the second retry, the waiting window is expanded to 2*baseWindow msec * alleviating the request rate from the server. Similarly the 3rd retry * will wait 2*baseWindow msec. grace period before retry and the waiting window is * expanded to 3*baseWindow msec and so on. * @param baseWindow the base waiting window. * @param failures number of failures so far. * @param r a random generator. * @return number of milliseconds for the next wait time. */ public static long getRandomWaitTime(int baseWindow, int failures, Random r) { return (long) ( baseWindow * failures + // grace period for the last round of attempt baseWindow * (failures + 1) * r.nextDouble()); // expanding time window for each failure } /** * Escape the '_', '%', as well as the escape characters inside the string key. * @param key the string that will be used for the SQL LIKE operator. * @param escape the escape character * @return a string with escaped '_' and '%'. */ public static final char sqlEscapeChar = '\\'; public static String escapeSqlLike(String key) { StringBuffer sb = new StringBuffer(key.length()); for (char c: key.toCharArray()) { switch(c) { case '_': case '%': case sqlEscapeChar: sb.append(sqlEscapeChar); // fall through default: sb.append(c); break; } } return sb.toString(); } }
true
true
public static ContentSummary getInputSummary(Context ctx, MapredWork work, PathFilter filter) throws IOException { long[] summary = {0, 0, 0}; List<String> pathNeedProcess = new ArrayList<String>(); // Since multiple threads could call this method concurrently, locking // this method will avoid number of threads out of control. synchronized (getInputSummaryLock) { // For each input path, calculate the total size. for (String path : work.getPathToAliases().keySet()) { Path p = new Path(path); if (filter != null && !filter.accept(p)) { continue; } ContentSummary cs = ctx.getCS(path); if (cs == null) { if (path == null) { continue; } pathNeedProcess.add(path); } else { summary[0] += cs.getLength(); summary[1] += cs.getFileCount(); summary[2] += cs.getDirectoryCount(); } } // Process the case when name node call is needed final Map<String, ContentSummary> resultMap = new ConcurrentHashMap<String, ContentSummary>(); ArrayList<Future<?>> results = new ArrayList<Future<?>>(); final ThreadPoolExecutor executor; int maxThreads = ctx.getConf().getInt("mapred.dfsclient.parallelism.max", 0); if (pathNeedProcess.size() > 1 && maxThreads > 1) { int numExecutors = Math.min(pathNeedProcess.size(), maxThreads); LOG.info("Using " + numExecutors + " threads for getContentSummary"); executor = new ThreadPoolExecutor(numExecutors, numExecutors, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } else { executor = null; } HiveInterruptCallback interrup = HiveInterruptUtils.add(new HiveInterruptCallback() { @Override public void interrupt() { if (executor != null) { executor.shutdownNow(); } } }); try { Configuration conf = ctx.getConf(); JobConf jobConf = new JobConf(conf); for (String path : pathNeedProcess) { final Path p = new Path(path); final String pathStr = path; // All threads share the same Configuration and JobConf based on the // assumption that they are thread safe if only read operations are // executed. It is not stated in Hadoop's javadoc, the sourcce codes // clearly showed that they made efforts for it and we believe it is // thread safe. Will revisit this piece of codes if we find the assumption // is not correct. final Configuration myConf = conf; final JobConf myJobConf = jobConf; final PartitionDesc partDesc = work.getPathToPartitionInfo().get( p.toString()); Runnable r = new Runnable() { public void run() { try { ContentSummary resultCs; Class<? extends InputFormat> inputFormatCls = partDesc .getInputFileFormatClass(); InputFormat inputFormatObj = HiveInputFormat.getInputFormatFromCache( inputFormatCls, myJobConf); if (inputFormatObj instanceof ContentSummaryInputFormat) { resultCs = ((ContentSummaryInputFormat) inputFormatObj).getContentSummary(p, myJobConf); } else { FileSystem fs = p.getFileSystem(myConf); resultCs = fs.getContentSummary(p); } resultMap.put(pathStr, resultCs); } catch (IOException e) { // We safely ignore this exception for summary data. // We don't update the cache to protect it from polluting other // usages. The worst case is that IOException will always be // retried for another getInputSummary(), which is fine as // IOException is not considered as a common case. LOG.info("Cannot get size of " + pathStr + ". Safely ignored."); } } }; if (executor == null) { r.run(); } else { Future<?> result = executor.submit(r); results.add(result); } } if (executor != null) { executor.shutdown(); } HiveInterruptUtils.checkInterrupted(); for (Map.Entry<String, ContentSummary> entry : resultMap.entrySet()) { ContentSummary cs = entry.getValue(); summary[0] += cs.getLength(); summary[1] += cs.getFileCount(); summary[2] += cs.getDirectoryCount(); ctx.addCS(entry.getKey(), cs); LOG.info("Cache Content Summary for " + entry.getKey() + " length: " + cs.getLength() + " file count: " + cs.getFileCount() + " directory count: " + cs.getDirectoryCount()); } return new ContentSummary(summary[0], summary[1], summary[2]); } finally { HiveInterruptUtils.remove(interrup); } } }
public static ContentSummary getInputSummary(Context ctx, MapredWork work, PathFilter filter) throws IOException { long[] summary = {0, 0, 0}; List<String> pathNeedProcess = new ArrayList<String>(); // Since multiple threads could call this method concurrently, locking // this method will avoid number of threads out of control. synchronized (getInputSummaryLock) { // For each input path, calculate the total size. for (String path : work.getPathToAliases().keySet()) { Path p = new Path(path); if (filter != null && !filter.accept(p)) { continue; } ContentSummary cs = ctx.getCS(path); if (cs == null) { if (path == null) { continue; } pathNeedProcess.add(path); } else { summary[0] += cs.getLength(); summary[1] += cs.getFileCount(); summary[2] += cs.getDirectoryCount(); } } // Process the case when name node call is needed final Map<String, ContentSummary> resultMap = new ConcurrentHashMap<String, ContentSummary>(); ArrayList<Future<?>> results = new ArrayList<Future<?>>(); final ThreadPoolExecutor executor; int maxThreads = ctx.getConf().getInt("mapred.dfsclient.parallelism.max", 0); if (pathNeedProcess.size() > 1 && maxThreads > 1) { int numExecutors = Math.min(pathNeedProcess.size(), maxThreads); LOG.info("Using " + numExecutors + " threads for getContentSummary"); executor = new ThreadPoolExecutor(numExecutors, numExecutors, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } else { executor = null; } HiveInterruptCallback interrup = HiveInterruptUtils.add(new HiveInterruptCallback() { @Override public void interrupt() { if (executor != null) { executor.shutdownNow(); } } }); try { Configuration conf = ctx.getConf(); JobConf jobConf = new JobConf(conf); for (String path : pathNeedProcess) { final Path p = new Path(path); final String pathStr = path; // All threads share the same Configuration and JobConf based on the // assumption that they are thread safe if only read operations are // executed. It is not stated in Hadoop's javadoc, the sourcce codes // clearly showed that they made efforts for it and we believe it is // thread safe. Will revisit this piece of codes if we find the assumption // is not correct. final Configuration myConf = conf; final JobConf myJobConf = jobConf; final PartitionDesc partDesc = work.getPathToPartitionInfo().get( p.toString()); Runnable r = new Runnable() { public void run() { try { ContentSummary resultCs; Class<? extends InputFormat> inputFormatCls = partDesc .getInputFileFormatClass(); InputFormat inputFormatObj = HiveInputFormat.getInputFormatFromCache( inputFormatCls, myJobConf); if (inputFormatObj instanceof ContentSummaryInputFormat) { resultCs = ((ContentSummaryInputFormat) inputFormatObj).getContentSummary(p, myJobConf); } else { FileSystem fs = p.getFileSystem(myConf); resultCs = fs.getContentSummary(p); } resultMap.put(pathStr, resultCs); } catch (IOException e) { // We safely ignore this exception for summary data. // We don't update the cache to protect it from polluting other // usages. The worst case is that IOException will always be // retried for another getInputSummary(), which is fine as // IOException is not considered as a common case. LOG.info("Cannot get size of " + pathStr + ". Safely ignored."); } } }; if (executor == null) { r.run(); } else { Future<?> result = executor.submit(r); results.add(result); } } if (executor != null) { for (Future<?> result : results) { boolean executorDone = false; do { try { result.get(); executorDone = true; } catch (InterruptedException e) { LOG.info("Interrupted when waiting threads: ", e); Thread.currentThread().interrupt(); break; } catch (ExecutionException e) { throw new IOException(e); } } while (!executorDone); } executor.shutdown(); } HiveInterruptUtils.checkInterrupted(); for (Map.Entry<String, ContentSummary> entry : resultMap.entrySet()) { ContentSummary cs = entry.getValue(); summary[0] += cs.getLength(); summary[1] += cs.getFileCount(); summary[2] += cs.getDirectoryCount(); ctx.addCS(entry.getKey(), cs); LOG.info("Cache Content Summary for " + entry.getKey() + " length: " + cs.getLength() + " file count: " + cs.getFileCount() + " directory count: " + cs.getDirectoryCount()); } return new ContentSummary(summary[0], summary[1], summary[2]); } finally { HiveInterruptUtils.remove(interrup); } } }
diff --git a/Pong/src/pong/PongGameView.java b/Pong/src/pong/PongGameView.java index b877a93..d77b932 100644 --- a/Pong/src/pong/PongGameView.java +++ b/Pong/src/pong/PongGameView.java @@ -1,71 +1,71 @@ package pong; import java.util.Collection; import java.util.List; import jgame.Context; import jgame.GContainer; import jgame.GObject; import jgame.GSprite; import jgame.ImageCache; import jgame.controller.ControlScheme; import jgame.listener.FrameListener; import jgame.listener.TimerListener; public class PongGameView extends GContainer { public PongGameView(){ super(new GSprite(ImageCache.forClass(Pong.class).get("explosion.png"))); setSize(640,480); // Add the paddle to the game view. PongPaddle paddle = new PongPaddle(ControlScheme.WASD); add(paddle); paddle.setLocation(50, 480/2); // Create a puck. PongPuck puck = new PongPuck(); // Add the puck. addAtCenter(puck); // Create another paddle to add. PongPaddle paddle2 = new PongPaddle(ControlScheme.ARROW_KEYS); add(paddle2); // Set the paddle's location. paddle2.setLocation(640 - 50, 480 / 2); TimerListener tl3 = new TimerListener(30*10) { @Override public void invoke(GObject target, Context context) { Collection<GObject> children = getObjects(); for (GObject someChild : children) { if (someChild instanceof PowerUp) { someChild.removeSelf(); } } PowerUp unpredictable = new PowerUp(); - addAt(unpredictable, (int)(Math.random() * 550 + 90), (int)(Math.random() * 380 + 50)); + addAt(unpredictable, Math.random() * 550 + 90, Math.random() * 380 + 50); } }; FrameListener fl = new FrameListener() { @Override public void invoke(GObject target, Context context) { // Get all the pucks. List<PongPuck> pucks = context.getInstancesOfClass(PongPuck.class); // Is it empty? boolean noPucksLeft = pucks.isEmpty(); // Set the current game view. if (noPucksLeft == true) { context.setCurrentGameView(Pong.View.GAME_OVER); } } }; addListener(fl); addListener(tl3); } }
true
true
public PongGameView(){ super(new GSprite(ImageCache.forClass(Pong.class).get("explosion.png"))); setSize(640,480); // Add the paddle to the game view. PongPaddle paddle = new PongPaddle(ControlScheme.WASD); add(paddle); paddle.setLocation(50, 480/2); // Create a puck. PongPuck puck = new PongPuck(); // Add the puck. addAtCenter(puck); // Create another paddle to add. PongPaddle paddle2 = new PongPaddle(ControlScheme.ARROW_KEYS); add(paddle2); // Set the paddle's location. paddle2.setLocation(640 - 50, 480 / 2); TimerListener tl3 = new TimerListener(30*10) { @Override public void invoke(GObject target, Context context) { Collection<GObject> children = getObjects(); for (GObject someChild : children) { if (someChild instanceof PowerUp) { someChild.removeSelf(); } } PowerUp unpredictable = new PowerUp(); addAt(unpredictable, (int)(Math.random() * 550 + 90), (int)(Math.random() * 380 + 50)); } }; FrameListener fl = new FrameListener() { @Override public void invoke(GObject target, Context context) { // Get all the pucks. List<PongPuck> pucks = context.getInstancesOfClass(PongPuck.class); // Is it empty? boolean noPucksLeft = pucks.isEmpty(); // Set the current game view. if (noPucksLeft == true) { context.setCurrentGameView(Pong.View.GAME_OVER); } } }; addListener(fl); addListener(tl3); }
public PongGameView(){ super(new GSprite(ImageCache.forClass(Pong.class).get("explosion.png"))); setSize(640,480); // Add the paddle to the game view. PongPaddle paddle = new PongPaddle(ControlScheme.WASD); add(paddle); paddle.setLocation(50, 480/2); // Create a puck. PongPuck puck = new PongPuck(); // Add the puck. addAtCenter(puck); // Create another paddle to add. PongPaddle paddle2 = new PongPaddle(ControlScheme.ARROW_KEYS); add(paddle2); // Set the paddle's location. paddle2.setLocation(640 - 50, 480 / 2); TimerListener tl3 = new TimerListener(30*10) { @Override public void invoke(GObject target, Context context) { Collection<GObject> children = getObjects(); for (GObject someChild : children) { if (someChild instanceof PowerUp) { someChild.removeSelf(); } } PowerUp unpredictable = new PowerUp(); addAt(unpredictable, Math.random() * 550 + 90, Math.random() * 380 + 50); } }; FrameListener fl = new FrameListener() { @Override public void invoke(GObject target, Context context) { // Get all the pucks. List<PongPuck> pucks = context.getInstancesOfClass(PongPuck.class); // Is it empty? boolean noPucksLeft = pucks.isEmpty(); // Set the current game view. if (noPucksLeft == true) { context.setCurrentGameView(Pong.View.GAME_OVER); } } }; addListener(fl); addListener(tl3); }
diff --git a/MSFSurveyFUP/src/org/msf/survey/monthly/fup/CSVDataExport.java b/MSFSurveyFUP/src/org/msf/survey/monthly/fup/CSVDataExport.java index 4346830..38d05ef 100644 --- a/MSFSurveyFUP/src/org/msf/survey/monthly/fup/CSVDataExport.java +++ b/MSFSurveyFUP/src/org/msf/survey/monthly/fup/CSVDataExport.java @@ -1,140 +1,140 @@ package org.msf.survey.monthly.fup; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import au.com.bytecode.opencsv.CSVWriter; public class CSVDataExport { public static List<File> generateDefaultReports(List<JSONObject> forms) throws JSONException, IOException { List<File> reports = new ArrayList<File>(forms.size()); for (JSONObject form : forms) { final String formName = form.getString("name"); File[] encountersForForm = Constants.ENCOUNTER_DIR.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return filename.startsWith("encounter-" + formName); } }); String reportName = FileUtilities.getSaveFileDatedName("report", formName, "csv"); File report = new File(Constants.REPORT_STORAGE_DIR, reportName); generateReport(form, encountersForForm, report); reports.add(report); } return reports; } public static void generateReport(JSONObject formJSON, File[] encounters, File reportFile) throws IOException, JSONException{ List<String> conceptIds = getFormConceptIds(formJSON); reportFile.createNewFile(); CSVWriter writer = new CSVWriter(new FileWriter(reportFile)); writer.writeNext(conceptIds.toArray(new String[conceptIds.size()])); String[] obs; for (File encounter : encounters) { obs = getObservationValues(new BufferedInputStream(new FileInputStream(encounter)), conceptIds); writer.writeNext(obs); } writer.close(); } public static List<String> getFormConceptIds(JSONObject formJSON) throws IOException, JSONException{ List<String> concepts = new ArrayList<String>(); //pages in form JSONArray pages = formJSON.optJSONArray("pages"); if (pages != null) { for(int i = 0; i < pages.length(); i++) { JSONObject page = pages.getJSONObject(i); JSONObject content = page.getJSONObject("content"); JSONArray views = content.optJSONArray("views"); if (views != null) { for(int j = 0; j < views.length(); j++) { readViewsWithRecursion(views.getJSONObject(j), concepts); } } } } else { throw new JSONException("Not a valid form!"); } return concepts; } private static void readViewsWithRecursion(JSONObject object, List<String> concepts) throws JSONException { if(object == null) { return; } String conceptId = object.optString("conceptId"); if (conceptId != null && conceptId.length() > 0) { concepts.add(conceptId); } //add child views with recursion JSONArray children = object.optJSONArray("children"); if (children != null) { for (int i = 0; i < children.length(); i++) { readViewsWithRecursion(children.optJSONObject(i), concepts); } } } private static String[] getObservationValues(InputStream encounterInputStream, List<String> concepts) throws IOException, JSONException { String[] result = new String[concepts.size()]; Arrays.fill(result, ""); String jsonString = FileUtilities.readStringFromInputStream(encounterInputStream); JSONObject encounter = new JSONObject(jsonString); JSONArray obsList = encounter.getJSONArray("obs"); JSONObject obs; String conceptId; String value; int conceptIndex; for (int i = 0; i < obsList.length(); i++) { try { obs = obsList.getJSONObject(i); conceptId = obs.getString("conceptId"); - value = obs.get("value").toString(); + value = obs.optString("value", "").toString(); conceptIndex = concepts.indexOf(conceptId); if (conceptId.length() == 0) { Log.d("CSVDataExport", "Blank conceptId! Value is: " + value); } else if (value == null) { value = ""; } else if (conceptIndex < 0 || conceptIndex >= result.length) { Log.d("CSVDataExport", "Illegal conceptId: " + conceptId + ", index " + conceptIndex + ", value" + value); } result[conceptIndex] = value; } catch (Exception e) { e.printStackTrace(); } } return result; } }
true
true
private static String[] getObservationValues(InputStream encounterInputStream, List<String> concepts) throws IOException, JSONException { String[] result = new String[concepts.size()]; Arrays.fill(result, ""); String jsonString = FileUtilities.readStringFromInputStream(encounterInputStream); JSONObject encounter = new JSONObject(jsonString); JSONArray obsList = encounter.getJSONArray("obs"); JSONObject obs; String conceptId; String value; int conceptIndex; for (int i = 0; i < obsList.length(); i++) { try { obs = obsList.getJSONObject(i); conceptId = obs.getString("conceptId"); value = obs.get("value").toString(); conceptIndex = concepts.indexOf(conceptId); if (conceptId.length() == 0) { Log.d("CSVDataExport", "Blank conceptId! Value is: " + value); } else if (value == null) { value = ""; } else if (conceptIndex < 0 || conceptIndex >= result.length) { Log.d("CSVDataExport", "Illegal conceptId: " + conceptId + ", index " + conceptIndex + ", value" + value); } result[conceptIndex] = value; } catch (Exception e) { e.printStackTrace(); } } return result; }
private static String[] getObservationValues(InputStream encounterInputStream, List<String> concepts) throws IOException, JSONException { String[] result = new String[concepts.size()]; Arrays.fill(result, ""); String jsonString = FileUtilities.readStringFromInputStream(encounterInputStream); JSONObject encounter = new JSONObject(jsonString); JSONArray obsList = encounter.getJSONArray("obs"); JSONObject obs; String conceptId; String value; int conceptIndex; for (int i = 0; i < obsList.length(); i++) { try { obs = obsList.getJSONObject(i); conceptId = obs.getString("conceptId"); value = obs.optString("value", "").toString(); conceptIndex = concepts.indexOf(conceptId); if (conceptId.length() == 0) { Log.d("CSVDataExport", "Blank conceptId! Value is: " + value); } else if (value == null) { value = ""; } else if (conceptIndex < 0 || conceptIndex >= result.length) { Log.d("CSVDataExport", "Illegal conceptId: " + conceptId + ", index " + conceptIndex + ", value" + value); } result[conceptIndex] = value; } catch (Exception e) { e.printStackTrace(); } } return result; }
diff --git a/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/Trust10.java b/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/Trust10.java index 5b930ef13..264a7b536 100644 --- a/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/Trust10.java +++ b/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/Trust10.java @@ -1,203 +1,204 @@ /* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ws.secpolicy.model; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.neethi.PolicyComponent; import org.apache.ws.secpolicy.SP11Constants; import org.apache.ws.secpolicy.SPConstants; import org.apache.ws.secpolicy.SP12Constants; /** * Model bean to capture Trust10 assertion info */ public class Trust10 extends AbstractSecurityAssertion { private boolean mustSupportClientChallenge; private boolean mustSupportServerChallenge; private boolean requireClientEntropy; private boolean requireServerEntropy; private boolean mustSupportIssuedTokens; public Trust10(int version){ setVersion(version); } /** * @return Returns the mustSupportClientChallenge. */ public boolean isMustSupportClientChallenge() { return mustSupportClientChallenge; } /** * @param mustSupportClientChallenge The mustSupportClientChallenge to set. */ public void setMustSupportClientChallenge(boolean mustSupportClientChallenge) { this.mustSupportClientChallenge = mustSupportClientChallenge; } /** * @return Returns the mustSupportIssuedTokens. */ public boolean isMustSupportIssuedTokens() { return mustSupportIssuedTokens; } /** * @param mustSupportIssuedTokens The mustSupportIssuedTokens to set. */ public void setMustSupportIssuedTokens(boolean mustSupportIssuedTokens) { this.mustSupportIssuedTokens = mustSupportIssuedTokens; } /** * @return Returns the mustSupportServerChallenge. */ public boolean isMustSupportServerChallenge() { return mustSupportServerChallenge; } /** * @param mustSupportServerChallenge The mustSupportServerChallenge to set. */ public void setMustSupportServerChallenge(boolean mustSupportServerChallenge) { this.mustSupportServerChallenge = mustSupportServerChallenge; } /** * @return Returns the requireClientEntropy. */ public boolean isRequireClientEntropy() { return requireClientEntropy; } /** * @param requireClientEntropy The requireClientEntropy to set. */ public void setRequireClientEntropy(boolean requireClientEntropy) { this.requireClientEntropy = requireClientEntropy; } /** * @return Returns the requireServerEntropy. */ public boolean isRequireServerEntropy() { return requireServerEntropy; } /** * @param requireServerEntropy The requireServerEntropy to set. */ public void setRequireServerEntropy(boolean requireServerEntropy) { this.requireServerEntropy = requireServerEntropy; } /* (non-Javadoc) * @see org.apache.neethi.Assertion#getName() */ public QName getName() { return SP11Constants.TRUST_10; } /* (non-Javadoc) * @see org.apache.neethi.Assertion#isOptional() */ public boolean isOptional() { // TODO TODO Sanka throw new UnsupportedOperationException("TODO Sanka"); } public PolicyComponent normalize() { return this; } public void serialize(XMLStreamWriter writer) throws XMLStreamException { String localname = getName().getLocalPart(); String namespaceURI = getName().getNamespaceURI(); String prefix = writer.getPrefix(namespaceURI); if (prefix == null) { prefix = getName().getPrefix(); writer.setPrefix(prefix, namespaceURI); } // <sp:Trust10> writer.writeStartElement(prefix, localname, namespaceURI); // xmlns:sp=".." writer.writeNamespace(prefix, namespaceURI); String wspPrefix = writer.getPrefix(SPConstants.POLICY.getNamespaceURI()); if (wspPrefix == null) { + wspPrefix = SPConstants.POLICY.getPrefix(); writer.setPrefix(wspPrefix, SPConstants.POLICY.getNamespaceURI()); } // <wsp:Policy> writer.writeStartElement(SPConstants.POLICY.getPrefix(), SPConstants.POLICY.getLocalPart(), SPConstants.POLICY.getNamespaceURI()); if (isMustSupportClientChallenge()) { // <sp:MustSupportClientChallenge /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_CLIENT_CHALLENGE, namespaceURI); writer.writeEndElement(); } if (isMustSupportServerChallenge()) { // <sp:MustSupportServerChallenge /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_SERVER_CHALLENGE, namespaceURI); writer.writeEndElement(); } if (isRequireClientEntropy()) { // <sp:RequireClientEntropy /> writer.writeStartElement(prefix, SPConstants.REQUIRE_CLIENT_ENTROPY, namespaceURI); writer.writeEndElement(); } if (isRequireServerEntropy()) { // <sp:RequireServerEntropy /> writer.writeStartElement(prefix, SPConstants.REQUIRE_SERVER_ENTROPY, namespaceURI); writer.writeEndElement(); } if (isMustSupportIssuedTokens()) { // <sp:MustSupportIssuedTokens /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_ISSUED_TOKENS, namespaceURI); writer.writeEndElement(); } // </wsp:Policy> writer.writeEndElement(); // </sp:Trust10> writer.writeEndElement(); } public short getType() { return org.apache.neethi.Constants.TYPE_ASSERTION; } }
true
true
public void serialize(XMLStreamWriter writer) throws XMLStreamException { String localname = getName().getLocalPart(); String namespaceURI = getName().getNamespaceURI(); String prefix = writer.getPrefix(namespaceURI); if (prefix == null) { prefix = getName().getPrefix(); writer.setPrefix(prefix, namespaceURI); } // <sp:Trust10> writer.writeStartElement(prefix, localname, namespaceURI); // xmlns:sp=".." writer.writeNamespace(prefix, namespaceURI); String wspPrefix = writer.getPrefix(SPConstants.POLICY.getNamespaceURI()); if (wspPrefix == null) { writer.setPrefix(wspPrefix, SPConstants.POLICY.getNamespaceURI()); } // <wsp:Policy> writer.writeStartElement(SPConstants.POLICY.getPrefix(), SPConstants.POLICY.getLocalPart(), SPConstants.POLICY.getNamespaceURI()); if (isMustSupportClientChallenge()) { // <sp:MustSupportClientChallenge /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_CLIENT_CHALLENGE, namespaceURI); writer.writeEndElement(); } if (isMustSupportServerChallenge()) { // <sp:MustSupportServerChallenge /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_SERVER_CHALLENGE, namespaceURI); writer.writeEndElement(); } if (isRequireClientEntropy()) { // <sp:RequireClientEntropy /> writer.writeStartElement(prefix, SPConstants.REQUIRE_CLIENT_ENTROPY, namespaceURI); writer.writeEndElement(); } if (isRequireServerEntropy()) { // <sp:RequireServerEntropy /> writer.writeStartElement(prefix, SPConstants.REQUIRE_SERVER_ENTROPY, namespaceURI); writer.writeEndElement(); } if (isMustSupportIssuedTokens()) { // <sp:MustSupportIssuedTokens /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_ISSUED_TOKENS, namespaceURI); writer.writeEndElement(); } // </wsp:Policy> writer.writeEndElement(); // </sp:Trust10> writer.writeEndElement(); }
public void serialize(XMLStreamWriter writer) throws XMLStreamException { String localname = getName().getLocalPart(); String namespaceURI = getName().getNamespaceURI(); String prefix = writer.getPrefix(namespaceURI); if (prefix == null) { prefix = getName().getPrefix(); writer.setPrefix(prefix, namespaceURI); } // <sp:Trust10> writer.writeStartElement(prefix, localname, namespaceURI); // xmlns:sp=".." writer.writeNamespace(prefix, namespaceURI); String wspPrefix = writer.getPrefix(SPConstants.POLICY.getNamespaceURI()); if (wspPrefix == null) { wspPrefix = SPConstants.POLICY.getPrefix(); writer.setPrefix(wspPrefix, SPConstants.POLICY.getNamespaceURI()); } // <wsp:Policy> writer.writeStartElement(SPConstants.POLICY.getPrefix(), SPConstants.POLICY.getLocalPart(), SPConstants.POLICY.getNamespaceURI()); if (isMustSupportClientChallenge()) { // <sp:MustSupportClientChallenge /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_CLIENT_CHALLENGE, namespaceURI); writer.writeEndElement(); } if (isMustSupportServerChallenge()) { // <sp:MustSupportServerChallenge /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_SERVER_CHALLENGE, namespaceURI); writer.writeEndElement(); } if (isRequireClientEntropy()) { // <sp:RequireClientEntropy /> writer.writeStartElement(prefix, SPConstants.REQUIRE_CLIENT_ENTROPY, namespaceURI); writer.writeEndElement(); } if (isRequireServerEntropy()) { // <sp:RequireServerEntropy /> writer.writeStartElement(prefix, SPConstants.REQUIRE_SERVER_ENTROPY, namespaceURI); writer.writeEndElement(); } if (isMustSupportIssuedTokens()) { // <sp:MustSupportIssuedTokens /> writer.writeStartElement(prefix, SPConstants.MUST_SUPPORT_ISSUED_TOKENS, namespaceURI); writer.writeEndElement(); } // </wsp:Policy> writer.writeEndElement(); // </sp:Trust10> writer.writeEndElement(); }
diff --git a/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/soar/SoarRobotInputLinkManager.java b/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/soar/SoarRobotInputLinkManager.java index 54389d940..cc389a53f 100644 --- a/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/soar/SoarRobotInputLinkManager.java +++ b/SoarSuite/soar-java/soar-soar2d/src/main/java/edu/umich/soar/gridmap2d/soar/SoarRobotInputLinkManager.java @@ -1,225 +1,225 @@ package edu.umich.soar.gridmap2d.soar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import jmat.LinAlg; import lcmtypes.pose_t; import sml.Agent; import sml.Identifier; import sml.Kernel; import sml.smlSystemEventId; import edu.umich.soar.gridmap2d.Gridmap2D; import edu.umich.soar.gridmap2d.Names; import edu.umich.soar.gridmap2d.map.CellObject; import edu.umich.soar.gridmap2d.map.RoomMap; import edu.umich.soar.gridmap2d.map.RoomObject; import edu.umich.soar.gridmap2d.players.CarryInterface; import edu.umich.soar.gridmap2d.players.Player; import edu.umich.soar.gridmap2d.players.Robot; import edu.umich.soar.gridmap2d.world.RoomWorld; import edu.umich.soar.robot.PointRelationship; import edu.umich.soar.robot.ReceiveMessagesInterface; import edu.umich.soar.robot.OffsetPose; import edu.umich.soar.robot.WaypointInterface; import edu.umich.soar.robot.TimeIL; import edu.umich.soar.robot.ConfigurationIL; public class SoarRobotInputLinkManager { private final Agent agent; private final Kernel kernel; private final OffsetPose opose; private SoarRobotSelfIL selfIL; private TimeIL timeIL; private ConfigurationIL configurationIL; private SoarRobotAreaDescriptionIL areaIL; private int oldLocationId = -1; private final Map<String, SoarRobotObjectIL> players = new HashMap<String, SoarRobotObjectIL>(); private final Map<Integer, SoarRobotObjectIL> objects = new HashMap<Integer, SoarRobotObjectIL>(); private long runtime; private final CarryInterface ci; public SoarRobotInputLinkManager(Agent agent, Kernel kernel, OffsetPose opose, CarryInterface ci) { this.agent = agent; this.kernel = kernel; this.opose = opose; this.ci = ci; } public void create() { runtime = 0; Identifier inputLink = agent.GetInputLink(); Identifier configuration = agent.CreateIdWME(inputLink, "configuration"); configurationIL = new ConfigurationIL(configuration, opose); Identifier time = agent.CreateIdWME(inputLink, "time"); timeIL = new TimeIL(time); kernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_START, timeIL, null); kernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_STOP, timeIL, null); Identifier self = agent.CreateIdWME(inputLink, "self"); selfIL = new SoarRobotSelfIL(agent, self, opose, configurationIL, ci); } public void destroy() { configurationIL.destroy(); configurationIL = null; timeIL.destroy(); timeIL = null; selfIL.destroy(); selfIL = null; for (SoarRobotObjectIL object : objects.values()) { object.destroy(); } objects.clear(); for (SoarRobotObjectIL object : players.values()) { object.destroy(); } players.clear(); if (areaIL != null) { areaIL.destroy(); areaIL = null; } } public WaypointInterface getWaypointInterface() { return selfIL.getWaypointsIL(); } public ReceiveMessagesInterface getReceiveMessagesInterface() { return selfIL.getMessagesIL(); } public void update(Robot player, RoomWorld world, RoomMap roomMap, boolean floatYawWmes) { configurationIL.update(); // FIXME: should be configurable //timeIL.update(); runtime += (long)(Gridmap2D.control.getTimeSlice() * 1000000000L); timeIL.updateExact(runtime); selfIL.update(player); if (areaIL == null || oldLocationId != player.getState().getLocationId()) { oldLocationId = player.getState().getLocationId(); if (areaIL != null) { areaIL.destroy(); } Identifier areaDescription = agent.GetInputLink().CreateIdWME("area-description"); boolean door = roomMap.hasAnyObjectWithProperty(player.getLocation(), Names.kPropertyGatewayRender); areaIL = new SoarRobotAreaDescriptionIL(areaDescription, player.getState().getLocationId(), opose, roomMap, door); } // objects Collection<RoomObject> roomObjects = roomMap.getRoomObjects(); for (RoomObject rObj : roomObjects) { pose_t pose = rObj.getPose(); if (pose == null) { continue; // not on map } if (rObj.getArea() == player.getState().getLocationId()) { final double MAX_ANGLE_OFF = Math.PI / 2; LinAlg.scaleEquals(pose.pos, SoarRobot.PIXELS_2_METERS); PointRelationship r = PointRelationship.calculate(opose.getPose(), pose.pos); if (Math.abs(r.getRelativeBearing()) <= MAX_ANGLE_OFF) { CellObject cObj = rObj.getCellObject(); SoarRobotObjectIL oIL = objects.get(rObj.getId()); if (oIL == null) { // create new object Identifier inputLink = agent.GetInputLink(); Identifier parent = inputLink.CreateIdWME("object"); oIL = new SoarRobotObjectIL(parent); oIL.initialize(pose, r); oIL.addProperty("type", cObj.getProperty("name")); oIL.addProperty("id", rObj.getId()); oIL.addProperty("color", cObj.getProperty("color")); - oIL.addProperty("weight", cObj.getProperty("weight")); + oIL.addProperty("weight", cObj.getDoubleProperty("weight", 0)); objects.put(rObj.getId(), oIL); } else { oIL.update(pose, r); } } } } // players if (world.getPlayers().length > 1) { for (Player temp : world.getPlayers()) { Robot rTarget = (Robot)temp; if (rTarget.equals(player)) { continue; } pose_t rTargetPose = rTarget.getState().getPose(); LinAlg.scaleEquals(rTargetPose.pos, SoarRobot.PIXELS_2_METERS); LinAlg.scaleEquals(rTargetPose.vel, SoarRobot.PIXELS_2_METERS); PointRelationship r = PointRelationship.calculate(opose.getPose(), rTargetPose.pos); String rName = rTarget.getName(); SoarRobotObjectIL pIL = players.get(rName); if (pIL == null) { // create new player Identifier inputLink = agent.GetInputLink(); Identifier parent = inputLink.CreateIdWME("object"); pIL = new SoarRobotObjectIL(parent); pIL.initialize(rTargetPose, r); pIL.addProperty("type", "player"); pIL.addProperty("name", rName); pIL.addProperty("color", rTarget.getColor()); players.put(rName, pIL); } else { pIL.update(rTargetPose, r); } } } purge(Gridmap2D.simulation.getWorldCount()); areaIL.update(); } private void purge(int cycle) { { Iterator<SoarRobotObjectIL> oiter = objects.values().iterator(); while (oiter.hasNext()) { SoarRobotObjectIL oIL = oiter.next(); if (oIL.getCycleTouched() < cycle) { if (oIL.getCycleTouched() > cycle - 3) { oIL.makeInvisible(); } else { oIL.destroy(); oiter.remove(); } } } } { Iterator<SoarRobotObjectIL> oiter = players.values().iterator(); while (oiter.hasNext()) { SoarRobotObjectIL oIL = oiter.next(); if (oIL.getCycleTouched() < cycle) { if (oIL.getCycleTouched() > cycle - 3) { oIL.makeInvisible(); } else { oIL.destroy(); oiter.remove(); } } } } } }
true
true
public void update(Robot player, RoomWorld world, RoomMap roomMap, boolean floatYawWmes) { configurationIL.update(); // FIXME: should be configurable //timeIL.update(); runtime += (long)(Gridmap2D.control.getTimeSlice() * 1000000000L); timeIL.updateExact(runtime); selfIL.update(player); if (areaIL == null || oldLocationId != player.getState().getLocationId()) { oldLocationId = player.getState().getLocationId(); if (areaIL != null) { areaIL.destroy(); } Identifier areaDescription = agent.GetInputLink().CreateIdWME("area-description"); boolean door = roomMap.hasAnyObjectWithProperty(player.getLocation(), Names.kPropertyGatewayRender); areaIL = new SoarRobotAreaDescriptionIL(areaDescription, player.getState().getLocationId(), opose, roomMap, door); } // objects Collection<RoomObject> roomObjects = roomMap.getRoomObjects(); for (RoomObject rObj : roomObjects) { pose_t pose = rObj.getPose(); if (pose == null) { continue; // not on map } if (rObj.getArea() == player.getState().getLocationId()) { final double MAX_ANGLE_OFF = Math.PI / 2; LinAlg.scaleEquals(pose.pos, SoarRobot.PIXELS_2_METERS); PointRelationship r = PointRelationship.calculate(opose.getPose(), pose.pos); if (Math.abs(r.getRelativeBearing()) <= MAX_ANGLE_OFF) { CellObject cObj = rObj.getCellObject(); SoarRobotObjectIL oIL = objects.get(rObj.getId()); if (oIL == null) { // create new object Identifier inputLink = agent.GetInputLink(); Identifier parent = inputLink.CreateIdWME("object"); oIL = new SoarRobotObjectIL(parent); oIL.initialize(pose, r); oIL.addProperty("type", cObj.getProperty("name")); oIL.addProperty("id", rObj.getId()); oIL.addProperty("color", cObj.getProperty("color")); oIL.addProperty("weight", cObj.getProperty("weight")); objects.put(rObj.getId(), oIL); } else { oIL.update(pose, r); } } } } // players if (world.getPlayers().length > 1) { for (Player temp : world.getPlayers()) { Robot rTarget = (Robot)temp; if (rTarget.equals(player)) { continue; } pose_t rTargetPose = rTarget.getState().getPose(); LinAlg.scaleEquals(rTargetPose.pos, SoarRobot.PIXELS_2_METERS); LinAlg.scaleEquals(rTargetPose.vel, SoarRobot.PIXELS_2_METERS); PointRelationship r = PointRelationship.calculate(opose.getPose(), rTargetPose.pos); String rName = rTarget.getName(); SoarRobotObjectIL pIL = players.get(rName); if (pIL == null) { // create new player Identifier inputLink = agent.GetInputLink(); Identifier parent = inputLink.CreateIdWME("object"); pIL = new SoarRobotObjectIL(parent); pIL.initialize(rTargetPose, r); pIL.addProperty("type", "player"); pIL.addProperty("name", rName); pIL.addProperty("color", rTarget.getColor()); players.put(rName, pIL); } else { pIL.update(rTargetPose, r); } } } purge(Gridmap2D.simulation.getWorldCount()); areaIL.update(); }
public void update(Robot player, RoomWorld world, RoomMap roomMap, boolean floatYawWmes) { configurationIL.update(); // FIXME: should be configurable //timeIL.update(); runtime += (long)(Gridmap2D.control.getTimeSlice() * 1000000000L); timeIL.updateExact(runtime); selfIL.update(player); if (areaIL == null || oldLocationId != player.getState().getLocationId()) { oldLocationId = player.getState().getLocationId(); if (areaIL != null) { areaIL.destroy(); } Identifier areaDescription = agent.GetInputLink().CreateIdWME("area-description"); boolean door = roomMap.hasAnyObjectWithProperty(player.getLocation(), Names.kPropertyGatewayRender); areaIL = new SoarRobotAreaDescriptionIL(areaDescription, player.getState().getLocationId(), opose, roomMap, door); } // objects Collection<RoomObject> roomObjects = roomMap.getRoomObjects(); for (RoomObject rObj : roomObjects) { pose_t pose = rObj.getPose(); if (pose == null) { continue; // not on map } if (rObj.getArea() == player.getState().getLocationId()) { final double MAX_ANGLE_OFF = Math.PI / 2; LinAlg.scaleEquals(pose.pos, SoarRobot.PIXELS_2_METERS); PointRelationship r = PointRelationship.calculate(opose.getPose(), pose.pos); if (Math.abs(r.getRelativeBearing()) <= MAX_ANGLE_OFF) { CellObject cObj = rObj.getCellObject(); SoarRobotObjectIL oIL = objects.get(rObj.getId()); if (oIL == null) { // create new object Identifier inputLink = agent.GetInputLink(); Identifier parent = inputLink.CreateIdWME("object"); oIL = new SoarRobotObjectIL(parent); oIL.initialize(pose, r); oIL.addProperty("type", cObj.getProperty("name")); oIL.addProperty("id", rObj.getId()); oIL.addProperty("color", cObj.getProperty("color")); oIL.addProperty("weight", cObj.getDoubleProperty("weight", 0)); objects.put(rObj.getId(), oIL); } else { oIL.update(pose, r); } } } } // players if (world.getPlayers().length > 1) { for (Player temp : world.getPlayers()) { Robot rTarget = (Robot)temp; if (rTarget.equals(player)) { continue; } pose_t rTargetPose = rTarget.getState().getPose(); LinAlg.scaleEquals(rTargetPose.pos, SoarRobot.PIXELS_2_METERS); LinAlg.scaleEquals(rTargetPose.vel, SoarRobot.PIXELS_2_METERS); PointRelationship r = PointRelationship.calculate(opose.getPose(), rTargetPose.pos); String rName = rTarget.getName(); SoarRobotObjectIL pIL = players.get(rName); if (pIL == null) { // create new player Identifier inputLink = agent.GetInputLink(); Identifier parent = inputLink.CreateIdWME("object"); pIL = new SoarRobotObjectIL(parent); pIL.initialize(rTargetPose, r); pIL.addProperty("type", "player"); pIL.addProperty("name", rName); pIL.addProperty("color", rTarget.getColor()); players.put(rName, pIL); } else { pIL.update(rTargetPose, r); } } } purge(Gridmap2D.simulation.getWorldCount()); areaIL.update(); }
diff --git a/src/org/apache/ws/security/components/crypto/CryptoFactory.java b/src/org/apache/ws/security/components/crypto/CryptoFactory.java index 180d6c192..c52630b08 100644 --- a/src/org/apache/ws/security/components/crypto/CryptoFactory.java +++ b/src/org/apache/ws/security/components/crypto/CryptoFactory.java @@ -1,163 +1,156 @@ /* * Copyright 2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ws.security.components.crypto; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ws.security.util.Loader; import java.lang.reflect.Constructor; import java.net.URL; import java.util.Properties; /** * CryptoFactory. * <p/> * * @author Davanum Srinivas ([email protected]). */ public abstract class CryptoFactory { private static Log log = LogFactory.getLog(CryptoFactory.class); private static final String defaultCryptoClassName = "org.apache.ws.security.components.crypto.BouncyCastle"; /** * getInstance * <p/> * Returns an instance of Crypto. This method uses the file * <code>crypto.properties</code> to determine which implementation to * use. Thus the property <code>org.apache.ws.security.crypto.provider</code> * must define the classname of the Crypto implementation. The file * may contain other property definitions as well. These properties are * handed over to the Crypto implementation. The file * <code>crypto.properties</code> is loaded with the * <code>Loader.getResource()</code> method. * <p/> * * @return The cyrpto implementation was defined */ public static Crypto getInstance() { return getInstance("crypto.properties"); } /** * getInstance * <p/> * Returns an instance of Crypto. The properties are handed over the the crypto * implementation. The porperties can be <code>null</code>. It is depenend on the * Crypto implementation how the initialization is done in this case. * <p/> * * @param cryptoClassName This is the crypto implementation class. No default is * provided here. * @param properties The Properties that are forwarded to the crypto implementaion. * These properties are dependend on the crypto implementatin * @return The cyrpto implementation or null if no cryptoClassName was defined */ public static Crypto getInstance(String cryptoClassName, Properties properties) { return loadClass(cryptoClassName, properties); } /** * getInstance * <p/> * Returns an instance of Crypto. This method uses the specifed filename * to load a property file. This file shall use the property * <code>org.apache.ws.security.crypto.provider</code> * to define the classname of the Crypto implementation. The file * may contain other property definitions as well. These properties are * handed over to the Crypto implementation. The specified file * is loaded with the <code>Loader.getResource()</code> method. * <p/> * * @param propFilename The name of the property file to load * @return The cyrpto implementation that was defined */ public static Crypto getInstance(String propFilename) { Properties properties = null; String cryptoClassName = null; // cryptoClassName = System.getProperty("org.apache.ws.security.crypto.provider"); if ((cryptoClassName == null) || (cryptoClassName.length() == 0)) { properties = getProperties(propFilename); // use the default Crypto implementation cryptoClassName = properties.getProperty("org.apache.ws.security.crypto.provider", defaultCryptoClassName); } return loadClass(cryptoClassName, properties); } private static Crypto loadClass(String cryptoClassName, Properties properties) { Class cryptogenClass = null; Crypto crypto = null; try { // instruct the class loader to load the crypto implementation cryptogenClass = java.lang.Class.forName(cryptoClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(cryptoClassName + " Not Found"); } log.info("Using Crypto Engine [" + cryptoClassName + "]"); try { Class[] classes = new Class[]{Properties.class}; Constructor c = cryptogenClass.getConstructor(classes); crypto = (Crypto) c.newInstance(new Object[]{properties}); return crypto; - } catch (java.lang.reflect.InvocationTargetException e) { - if(e.getCause() != null) { - e.getCause().printStackTrace(); - log.error(e.getCause()); - } - e.printStackTrace(); - log.error(e); } catch (java.lang.Exception e) { e.printStackTrace(); - log.error(e); + log.error("Unable to instantiate (1): " + cryptoClassName, e); } try { // try to instantiate the Crypto subclass crypto = (Crypto) cryptogenClass.newInstance(); return crypto; } catch (java.lang.Exception e) { e.printStackTrace(); - log.error(e); + log.error("Unable to instantiate (2): " + cryptoClassName, e); throw new RuntimeException(cryptoClassName + " cannot create instance"); } } /** * Gets the properties for crypto. * The functions loads the property file via * {@link Loader.getResource(String)}, thus the property file * should be accesible via the classpath * * @param propFilename the properties file to load * @return a <code>Properties</code> object loaded from the filename */ private static Properties getProperties(String propFilename) { Properties properties = new Properties(); try { URL url = Loader.getResource(propFilename); properties.load(url.openStream()); } catch (Exception e) { log.debug("Cannot find crypto property file: " + propFilename); throw new RuntimeException("CryptoFactory: Cannot load properties: "+ propFilename); } return properties; } }
false
true
private static Crypto loadClass(String cryptoClassName, Properties properties) { Class cryptogenClass = null; Crypto crypto = null; try { // instruct the class loader to load the crypto implementation cryptogenClass = java.lang.Class.forName(cryptoClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(cryptoClassName + " Not Found"); } log.info("Using Crypto Engine [" + cryptoClassName + "]"); try { Class[] classes = new Class[]{Properties.class}; Constructor c = cryptogenClass.getConstructor(classes); crypto = (Crypto) c.newInstance(new Object[]{properties}); return crypto; } catch (java.lang.reflect.InvocationTargetException e) { if(e.getCause() != null) { e.getCause().printStackTrace(); log.error(e.getCause()); } e.printStackTrace(); log.error(e); } catch (java.lang.Exception e) { e.printStackTrace(); log.error(e); } try { // try to instantiate the Crypto subclass crypto = (Crypto) cryptogenClass.newInstance(); return crypto; } catch (java.lang.Exception e) { e.printStackTrace(); log.error(e); throw new RuntimeException(cryptoClassName + " cannot create instance"); } }
private static Crypto loadClass(String cryptoClassName, Properties properties) { Class cryptogenClass = null; Crypto crypto = null; try { // instruct the class loader to load the crypto implementation cryptogenClass = java.lang.Class.forName(cryptoClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(cryptoClassName + " Not Found"); } log.info("Using Crypto Engine [" + cryptoClassName + "]"); try { Class[] classes = new Class[]{Properties.class}; Constructor c = cryptogenClass.getConstructor(classes); crypto = (Crypto) c.newInstance(new Object[]{properties}); return crypto; } catch (java.lang.Exception e) { e.printStackTrace(); log.error("Unable to instantiate (1): " + cryptoClassName, e); } try { // try to instantiate the Crypto subclass crypto = (Crypto) cryptogenClass.newInstance(); return crypto; } catch (java.lang.Exception e) { e.printStackTrace(); log.error("Unable to instantiate (2): " + cryptoClassName, e); throw new RuntimeException(cryptoClassName + " cannot create instance"); } }
diff --git a/server/src/main/java/com/metamx/druid/initialization/ServerInit.java b/server/src/main/java/com/metamx/druid/initialization/ServerInit.java index 8b38872608..bb1d0d631d 100644 --- a/server/src/main/java/com/metamx/druid/initialization/ServerInit.java +++ b/server/src/main/java/com/metamx/druid/initialization/ServerInit.java @@ -1,173 +1,173 @@ /* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.metamx.druid.initialization; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.metamx.common.ISE; import com.metamx.common.logger.Logger; import com.metamx.druid.DruidProcessingConfig; import com.metamx.druid.GroupByQueryEngine; import com.metamx.druid.GroupByQueryEngineConfig; import com.metamx.druid.Query; import com.metamx.druid.collect.StupidPool; import com.metamx.druid.loading.DelegatingStorageAdapterLoader; import com.metamx.druid.loading.MMappedStorageAdapterFactory; import com.metamx.druid.loading.QueryableLoaderConfig; import com.metamx.druid.loading.RealtimeSegmentGetter; import com.metamx.druid.loading.S3SegmentGetter; import com.metamx.druid.loading.S3ZippedSegmentGetter; import com.metamx.druid.loading.SingleStorageAdapterLoader; import com.metamx.druid.loading.StorageAdapterFactory; import com.metamx.druid.loading.StorageAdapterLoader; import com.metamx.druid.query.QueryRunnerFactory; import com.metamx.druid.query.group.GroupByQuery; import com.metamx.druid.query.group.GroupByQueryRunnerFactory; import com.metamx.druid.query.search.SearchQuery; import com.metamx.druid.query.search.SearchQueryRunnerFactory; import com.metamx.druid.query.timeboundary.TimeBoundaryQuery; import com.metamx.druid.query.timeboundary.TimeBoundaryQueryRunnerFactory; import com.metamx.druid.query.timeseries.TimeseriesQuery; import com.metamx.druid.query.timeseries.TimeseriesQueryRunnerFactory; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.skife.config.ConfigurationObjectFactory; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; /** */ public class ServerInit { private static Logger log = new Logger(ServerInit.class); public static StorageAdapterLoader makeDefaultQueryableLoader( RestS3Service s3Client, QueryableLoaderConfig config ) { DelegatingStorageAdapterLoader delegateLoader = new DelegatingStorageAdapterLoader(); final S3SegmentGetter segmentGetter = new S3SegmentGetter(s3Client, config); final S3ZippedSegmentGetter zippedGetter = new S3ZippedSegmentGetter(s3Client, config); final RealtimeSegmentGetter realtimeGetter = new RealtimeSegmentGetter(config); final StorageAdapterFactory factory; if ("mmap".equals(config.getQueryableFactoryType())) { factory = new MMappedStorageAdapterFactory(); } else { throw new ISE("Unknown queryableFactoryType[%s]", config.getQueryableFactoryType()); } delegateLoader.setLoaderTypes( ImmutableMap.<String, StorageAdapterLoader>builder() .put("s3", new SingleStorageAdapterLoader(segmentGetter, factory)) .put("s3_zip", new SingleStorageAdapterLoader(zippedGetter, factory)) .put("realtime", new SingleStorageAdapterLoader(realtimeGetter, factory)) .build() ); return delegateLoader; } public static StupidPool<ByteBuffer> makeComputeScratchPool(DruidProcessingConfig config) { try { Class<?> vmClass = Class.forName("sun.misc.VM"); Object maxDirectMemoryObj = vmClass.getMethod("maxDirectMemory").invoke(null); if (maxDirectMemoryObj == null || !(maxDirectMemoryObj instanceof Number)) { log.info("Cannot determine maxDirectMemory from[%s]", maxDirectMemoryObj); } else { long maxDirectMemory = ((Number) maxDirectMemoryObj).longValue(); final long memoryNeeded = (long) config.intermediateComputeSizeBytes() * (config.getNumThreads() + 1); if (maxDirectMemory < memoryNeeded) { throw new ISE( - "Not enough direct memory. Please adjust -XX:MaxDirectMemory or druid.computation.buffer.size: " + "Not enough direct memory. Please adjust -XX:MaxDirectMemorySize or druid.computation.buffer.size: " + "maxDirectMemory[%,d], memoryNeeded[%,d], druid.computation.buffer.size[%,d], numThreads[%,d]", maxDirectMemory, memoryNeeded, config.intermediateComputeSizeBytes(), config.getNumThreads() ); } } } catch (ClassNotFoundException e) { log.info("No VM class, cannot do memory check."); } catch (NoSuchMethodException e) { log.info("VM.maxDirectMemory doesn't exist, cannot do memory check."); } catch (InvocationTargetException e) { log.warn(e, "static method shouldn't throw this"); } catch (IllegalAccessException e) { log.warn(e, "public method, shouldn't throw this"); } return new ComputeScratchPool(config.intermediateComputeSizeBytes()); } public static Map<Class<? extends Query>, QueryRunnerFactory> initDefaultQueryTypes( ConfigurationObjectFactory configFactory, StupidPool<ByteBuffer> computationBufferPool ) { Map<Class<? extends Query>, QueryRunnerFactory> queryRunners = Maps.newLinkedHashMap(); queryRunners.put(TimeseriesQuery.class, new TimeseriesQueryRunnerFactory()); queryRunners.put( GroupByQuery.class, new GroupByQueryRunnerFactory( new GroupByQueryEngine( configFactory.build(GroupByQueryEngineConfig.class), computationBufferPool ) ) ); queryRunners.put(SearchQuery.class, new SearchQueryRunnerFactory()); queryRunners.put(TimeBoundaryQuery.class, new TimeBoundaryQueryRunnerFactory()); return queryRunners; } private static class ComputeScratchPool extends StupidPool<ByteBuffer> { private static final Logger log = new Logger(ComputeScratchPool.class); public ComputeScratchPool(final int computationBufferSize) { super( new Supplier<ByteBuffer>() { final AtomicLong count = new AtomicLong(0); @Override public ByteBuffer get() { log.info( "Allocating new computeScratchPool[%,d] of size[%,d]", count.getAndIncrement(), computationBufferSize ); return ByteBuffer.allocateDirect(computationBufferSize); } } ); } } }
true
true
public static StupidPool<ByteBuffer> makeComputeScratchPool(DruidProcessingConfig config) { try { Class<?> vmClass = Class.forName("sun.misc.VM"); Object maxDirectMemoryObj = vmClass.getMethod("maxDirectMemory").invoke(null); if (maxDirectMemoryObj == null || !(maxDirectMemoryObj instanceof Number)) { log.info("Cannot determine maxDirectMemory from[%s]", maxDirectMemoryObj); } else { long maxDirectMemory = ((Number) maxDirectMemoryObj).longValue(); final long memoryNeeded = (long) config.intermediateComputeSizeBytes() * (config.getNumThreads() + 1); if (maxDirectMemory < memoryNeeded) { throw new ISE( "Not enough direct memory. Please adjust -XX:MaxDirectMemory or druid.computation.buffer.size: " + "maxDirectMemory[%,d], memoryNeeded[%,d], druid.computation.buffer.size[%,d], numThreads[%,d]", maxDirectMemory, memoryNeeded, config.intermediateComputeSizeBytes(), config.getNumThreads() ); } } } catch (ClassNotFoundException e) { log.info("No VM class, cannot do memory check."); } catch (NoSuchMethodException e) { log.info("VM.maxDirectMemory doesn't exist, cannot do memory check."); } catch (InvocationTargetException e) { log.warn(e, "static method shouldn't throw this"); } catch (IllegalAccessException e) { log.warn(e, "public method, shouldn't throw this"); } return new ComputeScratchPool(config.intermediateComputeSizeBytes()); }
public static StupidPool<ByteBuffer> makeComputeScratchPool(DruidProcessingConfig config) { try { Class<?> vmClass = Class.forName("sun.misc.VM"); Object maxDirectMemoryObj = vmClass.getMethod("maxDirectMemory").invoke(null); if (maxDirectMemoryObj == null || !(maxDirectMemoryObj instanceof Number)) { log.info("Cannot determine maxDirectMemory from[%s]", maxDirectMemoryObj); } else { long maxDirectMemory = ((Number) maxDirectMemoryObj).longValue(); final long memoryNeeded = (long) config.intermediateComputeSizeBytes() * (config.getNumThreads() + 1); if (maxDirectMemory < memoryNeeded) { throw new ISE( "Not enough direct memory. Please adjust -XX:MaxDirectMemorySize or druid.computation.buffer.size: " + "maxDirectMemory[%,d], memoryNeeded[%,d], druid.computation.buffer.size[%,d], numThreads[%,d]", maxDirectMemory, memoryNeeded, config.intermediateComputeSizeBytes(), config.getNumThreads() ); } } } catch (ClassNotFoundException e) { log.info("No VM class, cannot do memory check."); } catch (NoSuchMethodException e) { log.info("VM.maxDirectMemory doesn't exist, cannot do memory check."); } catch (InvocationTargetException e) { log.warn(e, "static method shouldn't throw this"); } catch (IllegalAccessException e) { log.warn(e, "public method, shouldn't throw this"); } return new ComputeScratchPool(config.intermediateComputeSizeBytes()); }
diff --git a/src/biz/bokhorst/xprivacy/RState.java b/src/biz/bokhorst/xprivacy/RState.java index 681f733f..3293c226 100644 --- a/src/biz/bokhorst/xprivacy/RState.java +++ b/src/biz/bokhorst/xprivacy/RState.java @@ -1,112 +1,112 @@ package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Process; public class RState { public int mUid; public String mRestrictionName; public String mMethodName; public boolean restricted; public boolean asked = false; public boolean partialRestricted = false; public boolean partialAsk = false; public RState(int uid, String restrictionName, String methodName) { mUid = uid; mRestrictionName = restrictionName; mMethodName = methodName; int userId = Util.getUserId(Process.myUid()); // Get if on demand boolean onDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true, false); if (onDemand) onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false, false); boolean allRestricted = true; boolean someRestricted = false; boolean allAsk = true; boolean someAsk = false; if (methodName == null) { if (restrictionName == null) { // Examine the category state for (String rRestrictionName : PrivacyManager.getRestrictions()) { PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null); allRestricted = (allRestricted && query.restricted); someRestricted = (someRestricted || query.restricted); allAsk = (allAsk && !query.asked); someAsk = (someAsk || !query.asked); } - asked = !someAsk; + asked = !onDemand; } else { // Examine the category/method states PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null); someRestricted = query.restricted; someAsk = !query.asked; for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) { allRestricted = (allRestricted && restriction.restricted); someRestricted = (someRestricted || restriction.restricted); allAsk = (allAsk && !restriction.asked); someAsk = (someAsk || !restriction.asked); } asked = query.asked; } } else { // Examine the method state PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName); allRestricted = query.restricted; someRestricted = false; asked = query.asked; } restricted = (allRestricted || someRestricted); asked = (!onDemand || !PrivacyManager.isApplication(uid) || asked); partialRestricted = (!allRestricted && someRestricted); partialAsk = (onDemand && PrivacyManager.isApplication(uid) && !allAsk && someAsk); } public void toggleRestriction() { if (mMethodName == null) { // Get restrictions to change List<String> listRestriction; if (mRestrictionName == null) listRestriction = PrivacyManager.getRestrictions(); else { listRestriction = new ArrayList<String>(); listRestriction.add(mRestrictionName); } // Change restriction if (restricted) PrivacyManager.deleteRestrictions(mUid, mRestrictionName, (mRestrictionName == null)); else { for (String restrictionName : listRestriction) PrivacyManager.setRestriction(mUid, restrictionName, null, true, false); PrivacyManager.updateState(mUid); } } else { PRestriction query = PrivacyManager.getRestrictionEx(mUid, mRestrictionName, null); PrivacyManager.setRestriction(mUid, mRestrictionName, mMethodName, !restricted, query.asked); PrivacyManager.updateState(mUid); } } public void toggleAsked() { asked = !asked; if (mRestrictionName == null) PrivacyManager.setSetting(mUid, PrivacyManager.cSettingOnDemand, Boolean.toString(!asked)); else { // Avoid re-doing all exceptions for dangerous functions List<PRestriction> listPRestriction = new ArrayList<PRestriction>(); listPRestriction.add(new PRestriction(mUid, mRestrictionName, mMethodName, restricted, asked)); PrivacyManager.setRestrictionList(listPRestriction); PrivacyManager.setSetting(mUid, PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED)); PrivacyManager.setSetting(mUid, PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis())); } } }
true
true
public RState(int uid, String restrictionName, String methodName) { mUid = uid; mRestrictionName = restrictionName; mMethodName = methodName; int userId = Util.getUserId(Process.myUid()); // Get if on demand boolean onDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true, false); if (onDemand) onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false, false); boolean allRestricted = true; boolean someRestricted = false; boolean allAsk = true; boolean someAsk = false; if (methodName == null) { if (restrictionName == null) { // Examine the category state for (String rRestrictionName : PrivacyManager.getRestrictions()) { PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null); allRestricted = (allRestricted && query.restricted); someRestricted = (someRestricted || query.restricted); allAsk = (allAsk && !query.asked); someAsk = (someAsk || !query.asked); } asked = !someAsk; } else { // Examine the category/method states PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null); someRestricted = query.restricted; someAsk = !query.asked; for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) { allRestricted = (allRestricted && restriction.restricted); someRestricted = (someRestricted || restriction.restricted); allAsk = (allAsk && !restriction.asked); someAsk = (someAsk || !restriction.asked); } asked = query.asked; } } else { // Examine the method state PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName); allRestricted = query.restricted; someRestricted = false; asked = query.asked; } restricted = (allRestricted || someRestricted); asked = (!onDemand || !PrivacyManager.isApplication(uid) || asked); partialRestricted = (!allRestricted && someRestricted); partialAsk = (onDemand && PrivacyManager.isApplication(uid) && !allAsk && someAsk); }
public RState(int uid, String restrictionName, String methodName) { mUid = uid; mRestrictionName = restrictionName; mMethodName = methodName; int userId = Util.getUserId(Process.myUid()); // Get if on demand boolean onDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true, false); if (onDemand) onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false, false); boolean allRestricted = true; boolean someRestricted = false; boolean allAsk = true; boolean someAsk = false; if (methodName == null) { if (restrictionName == null) { // Examine the category state for (String rRestrictionName : PrivacyManager.getRestrictions()) { PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null); allRestricted = (allRestricted && query.restricted); someRestricted = (someRestricted || query.restricted); allAsk = (allAsk && !query.asked); someAsk = (someAsk || !query.asked); } asked = !onDemand; } else { // Examine the category/method states PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null); someRestricted = query.restricted; someAsk = !query.asked; for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) { allRestricted = (allRestricted && restriction.restricted); someRestricted = (someRestricted || restriction.restricted); allAsk = (allAsk && !restriction.asked); someAsk = (someAsk || !restriction.asked); } asked = query.asked; } } else { // Examine the method state PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName); allRestricted = query.restricted; someRestricted = false; asked = query.asked; } restricted = (allRestricted || someRestricted); asked = (!onDemand || !PrivacyManager.isApplication(uid) || asked); partialRestricted = (!allRestricted && someRestricted); partialAsk = (onDemand && PrivacyManager.isApplication(uid) && !allAsk && someAsk); }
diff --git a/servers/media/jar/src/main/java/org/mobicents/media/server/impl/ivr/LocalSplitter.java b/servers/media/jar/src/main/java/org/mobicents/media/server/impl/ivr/LocalSplitter.java index 80d303ff0..3928d6c24 100755 --- a/servers/media/jar/src/main/java/org/mobicents/media/server/impl/ivr/LocalSplitter.java +++ b/servers/media/jar/src/main/java/org/mobicents/media/server/impl/ivr/LocalSplitter.java @@ -1,122 +1,121 @@ /* * The source code contained in this file is in in the public domain. * It can be used in any project or product without prior permission, * license or royalty payments. There is NO WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR STATUTORY, INCLUDING, WITHOUT LIMITATION, * THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * AND DATA ACCURACY. We do not warrant or make any representations * regarding the use of the software or the results thereof, including * but not limited to the correctness, accuracy, reliability or * usefulness of the software. */ package org.mobicents.media.server.impl.ivr; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.mobicents.media.format.UnsupportedFormatException; import org.mobicents.media.protocol.PushBufferStream; import org.apache.log4j.Logger; import org.mobicents.media.server.impl.BaseConnection; import org.mobicents.media.server.impl.BaseResource; import org.mobicents.media.server.impl.common.MediaResourceState; import org.mobicents.media.server.impl.jmf.splitter.MediaSplitter; import org.mobicents.media.server.spi.Connection; import org.mobicents.media.server.spi.Endpoint; import org.mobicents.media.server.spi.MediaSink; import org.mobicents.media.server.spi.NotificationListener; /** * * @author Oleg Kulikov */ public class LocalSplitter extends BaseResource implements MediaSink { private String id; private Map streams = Collections.synchronizedMap(new HashMap()); private MediaSplitter splitter = new MediaSplitter(); private IVREndpointImpl endpoint; private BaseConnection connection; private static Logger logger = Logger.getLogger(LocalSplitter.class); public LocalSplitter(Endpoint endpoint, Connection connection) { this.endpoint = (IVREndpointImpl) endpoint; this.connection = (BaseConnection) connection; this.id = connection.getId(); this.addStateListener(this.endpoint.splitterStateListener); } public LocalSplitter(String id) { this.id = id; } public void setInputStream(PushBufferStream pushStream) { splitter.setInputStream(pushStream); } public PushBufferStream newBranch(String id) { PushBufferStream branch = splitter.newBranch(); streams.put(id, branch); if (logger.isDebugEnabled()) { logger.debug("id=" + this.id + ", created new branch for connection id = " + id + ", branches=" + splitter.getSize()); } return branch; } - public PushBufferStream remove(String id) { + public void remove(String id) { PushBufferStream pushStream = (PushBufferStream) streams.remove(id); if (pushStream != null) { splitter.closeBranch(pushStream); if (logger.isDebugEnabled()) { logger.debug("id=" + this.id + ", removed branch for connection id = " + id + ", branches=" + splitter.getSize()); } } - return pushStream; } public void close() { splitter.close(); if (logger.isDebugEnabled()) { logger.debug("id=" + this.id + " close splitter"); } } @Override public String toString() { return "LocalSplitter[" + id + "]"; } public void configure(Properties config) { setState(MediaResourceState.CONFIGURED); } public void prepare(Endpoint endpoint, PushBufferStream mediaStream) throws UnsupportedFormatException { splitter.setInputStream(mediaStream); setState(MediaResourceState.PREPARED); } public void addListener(NotificationListener listener) { throw new UnsupportedOperationException("Not supported yet."); } public void removeListener(NotificationListener listener) { throw new UnsupportedOperationException("Not supported yet."); } public void start() { setState(MediaResourceState.STARTED); } public void stop() { if (getState() == MediaResourceState.STARTED) { setState(MediaResourceState.PREPARED); } } public void release() { setState(MediaResourceState.NULL); } }
false
true
public PushBufferStream remove(String id) { PushBufferStream pushStream = (PushBufferStream) streams.remove(id); if (pushStream != null) { splitter.closeBranch(pushStream); if (logger.isDebugEnabled()) { logger.debug("id=" + this.id + ", removed branch for connection id = " + id + ", branches=" + splitter.getSize()); } } return pushStream; }
public void remove(String id) { PushBufferStream pushStream = (PushBufferStream) streams.remove(id); if (pushStream != null) { splitter.closeBranch(pushStream); if (logger.isDebugEnabled()) { logger.debug("id=" + this.id + ", removed branch for connection id = " + id + ", branches=" + splitter.getSize()); } } }
diff --git a/src/littlegruz/autoruncommands/listeners/CommandServerListener.java b/src/littlegruz/autoruncommands/listeners/CommandServerListener.java index 9e4cf35..5eb71ef 100644 --- a/src/littlegruz/autoruncommands/listeners/CommandServerListener.java +++ b/src/littlegruz/autoruncommands/listeners/CommandServerListener.java @@ -1,110 +1,113 @@ package littlegruz.autoruncommands.listeners; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import java.util.Map.Entry; import littlegruz.autoruncommands.CommandMain; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.scheduler.BukkitTask; public class CommandServerListener implements Listener { private CommandMain plugin; public CommandServerListener(CommandMain instance){ plugin = instance; } @EventHandler public void onPluginEnable(PluginEnableEvent event){ // Run the startup tasks one second after everything has loaded plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ public void run(){ String cmd; StringTokenizer st = new StringTokenizer(plugin.getStartupCommands(), ":"); if(!plugin.isStartupDone()){ while(st.countTokens() > 0){ cmd = st.nextToken(); if(plugin.getCommandMap().get(cmd) != null) plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(cmd)); else plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(cmd + "[op]")); } plugin.setStartupDone(true); } } }, 20L); /* Start the repeating tasks one and a half seconds after everything has * loaded. * I heard you like scheduled tasks, so I put a scheduled task in your * scheduled task */ plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ public void run(){ int interval; BukkitTask repeatTask; HashMap<String, Integer> remainderMap = new HashMap<String, Integer>(); Iterator<Map.Entry<String, Integer>> it = plugin.getRepeatMap().entrySet().iterator(); // Attach the remainder times onto the tasks that need to repeat try{ BufferedReader br = new BufferedReader(new FileReader(plugin.getRemainderFile())); StringTokenizer st; String input; while((input = br.readLine()) != null){ if(input.compareToIgnoreCase("<Command> <Remainder>") == 0){ continue; } st = new StringTokenizer(input, " "); remainderMap.put(st.nextToken(), Integer.parseInt(st.nextToken())); } br.close(); }catch(FileNotFoundException e){ plugin.getServer().getLogger().info("No original repeating task remaining file, a new one will be created on shutdown/restart."); }catch(Exception e){ plugin.getServer().getLogger().info("Incorrectly formatted repeating task remaining file"); } // The running of the tasks while(it.hasNext()){ Entry<String, Integer> mp = it.next(); final String command = mp.getKey(); long time = new Date().getTime(); time /= 1000; interval = mp.getValue(); if((plugin.getCommandMap().get(command) != null || plugin.getCommandMap().get(command + "[op]") != null) && plugin.getRunningRepeatMap().get(command) == null){ repeatTask = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable(){ public void run() { - plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(command)); + if(plugin.getCommandMap().get(command) != null) + plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(command)); + else if(plugin.getCommandMap().get(command + "[op]") != null) + plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(command + "[op]")); } }, remainderMap.get(command) * 20, interval * 20); // This sets the "starting" time to be what it would be if the server was running time = time - (interval - remainderMap.get(command)); plugin.getRunningRepeatMap().put(command, Integer.toString(repeatTask.getTaskId()) + "|" + Long.toString(time)); } } } }, 40L); } }
true
true
public void onPluginEnable(PluginEnableEvent event){ // Run the startup tasks one second after everything has loaded plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ public void run(){ String cmd; StringTokenizer st = new StringTokenizer(plugin.getStartupCommands(), ":"); if(!plugin.isStartupDone()){ while(st.countTokens() > 0){ cmd = st.nextToken(); if(plugin.getCommandMap().get(cmd) != null) plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(cmd)); else plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(cmd + "[op]")); } plugin.setStartupDone(true); } } }, 20L); /* Start the repeating tasks one and a half seconds after everything has * loaded. * I heard you like scheduled tasks, so I put a scheduled task in your * scheduled task */ plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ public void run(){ int interval; BukkitTask repeatTask; HashMap<String, Integer> remainderMap = new HashMap<String, Integer>(); Iterator<Map.Entry<String, Integer>> it = plugin.getRepeatMap().entrySet().iterator(); // Attach the remainder times onto the tasks that need to repeat try{ BufferedReader br = new BufferedReader(new FileReader(plugin.getRemainderFile())); StringTokenizer st; String input; while((input = br.readLine()) != null){ if(input.compareToIgnoreCase("<Command> <Remainder>") == 0){ continue; } st = new StringTokenizer(input, " "); remainderMap.put(st.nextToken(), Integer.parseInt(st.nextToken())); } br.close(); }catch(FileNotFoundException e){ plugin.getServer().getLogger().info("No original repeating task remaining file, a new one will be created on shutdown/restart."); }catch(Exception e){ plugin.getServer().getLogger().info("Incorrectly formatted repeating task remaining file"); } // The running of the tasks while(it.hasNext()){ Entry<String, Integer> mp = it.next(); final String command = mp.getKey(); long time = new Date().getTime(); time /= 1000; interval = mp.getValue(); if((plugin.getCommandMap().get(command) != null || plugin.getCommandMap().get(command + "[op]") != null) && plugin.getRunningRepeatMap().get(command) == null){ repeatTask = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable(){ public void run() { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(command)); } }, remainderMap.get(command) * 20, interval * 20); // This sets the "starting" time to be what it would be if the server was running time = time - (interval - remainderMap.get(command)); plugin.getRunningRepeatMap().put(command, Integer.toString(repeatTask.getTaskId()) + "|" + Long.toString(time)); } } } }, 40L); }
public void onPluginEnable(PluginEnableEvent event){ // Run the startup tasks one second after everything has loaded plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ public void run(){ String cmd; StringTokenizer st = new StringTokenizer(plugin.getStartupCommands(), ":"); if(!plugin.isStartupDone()){ while(st.countTokens() > 0){ cmd = st.nextToken(); if(plugin.getCommandMap().get(cmd) != null) plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(cmd)); else plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(cmd + "[op]")); } plugin.setStartupDone(true); } } }, 20L); /* Start the repeating tasks one and a half seconds after everything has * loaded. * I heard you like scheduled tasks, so I put a scheduled task in your * scheduled task */ plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ public void run(){ int interval; BukkitTask repeatTask; HashMap<String, Integer> remainderMap = new HashMap<String, Integer>(); Iterator<Map.Entry<String, Integer>> it = plugin.getRepeatMap().entrySet().iterator(); // Attach the remainder times onto the tasks that need to repeat try{ BufferedReader br = new BufferedReader(new FileReader(plugin.getRemainderFile())); StringTokenizer st; String input; while((input = br.readLine()) != null){ if(input.compareToIgnoreCase("<Command> <Remainder>") == 0){ continue; } st = new StringTokenizer(input, " "); remainderMap.put(st.nextToken(), Integer.parseInt(st.nextToken())); } br.close(); }catch(FileNotFoundException e){ plugin.getServer().getLogger().info("No original repeating task remaining file, a new one will be created on shutdown/restart."); }catch(Exception e){ plugin.getServer().getLogger().info("Incorrectly formatted repeating task remaining file"); } // The running of the tasks while(it.hasNext()){ Entry<String, Integer> mp = it.next(); final String command = mp.getKey(); long time = new Date().getTime(); time /= 1000; interval = mp.getValue(); if((plugin.getCommandMap().get(command) != null || plugin.getCommandMap().get(command + "[op]") != null) && plugin.getRunningRepeatMap().get(command) == null){ repeatTask = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable(){ public void run() { if(plugin.getCommandMap().get(command) != null) plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(command)); else if(plugin.getCommandMap().get(command + "[op]") != null) plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getCommandMap().get(command + "[op]")); } }, remainderMap.get(command) * 20, interval * 20); // This sets the "starting" time to be what it would be if the server was running time = time - (interval - remainderMap.get(command)); plugin.getRunningRepeatMap().put(command, Integer.toString(repeatTask.getTaskId()) + "|" + Long.toString(time)); } } } }, 40L); }
diff --git a/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java b/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java index 202f9625..651fc865 100644 --- a/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java +++ b/xjc/src/com/sun/tools/xjc/generator/bean/BeanGenerator.java @@ -1,770 +1,775 @@ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.xjc.generator.bean; import static com.sun.tools.xjc.outline.Aspect.EXPOSED; import java.io.Serializable; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlAttachmentRef; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlMimeType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; import com.sun.codemodel.ClassType; import com.sun.codemodel.JAnnotatable; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JClassContainer; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JEnumConstant; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JForEach; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JJavaName; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JPackage; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.codemodel.fmt.JStaticJavaFile; import com.sun.tools.xjc.AbortException; import com.sun.tools.xjc.ErrorReceiver; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.generator.annotation.spec.XmlAnyAttributeWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlEnumValueWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlEnumWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlJavaTypeAdapterWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlMimeTypeWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlRootElementWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlSeeAlsoWriter; import com.sun.tools.xjc.generator.annotation.spec.XmlTypeWriter; import com.sun.tools.xjc.generator.bean.field.FieldRenderer; import com.sun.tools.xjc.model.CAdapter; import com.sun.tools.xjc.model.CAttributePropertyInfo; import com.sun.tools.xjc.model.CClassInfo; import com.sun.tools.xjc.model.CClassInfoParent; import com.sun.tools.xjc.model.CElementInfo; import com.sun.tools.xjc.model.CEnumConstant; import com.sun.tools.xjc.model.CEnumLeafInfo; import com.sun.tools.xjc.model.CPropertyInfo; import com.sun.tools.xjc.model.CTypeRef; import com.sun.tools.xjc.model.Model; import com.sun.tools.xjc.model.CClassRef; import com.sun.tools.xjc.outline.Aspect; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.EnumConstantOutline; import com.sun.tools.xjc.outline.EnumOutline; import com.sun.tools.xjc.outline.FieldOutline; import com.sun.tools.xjc.outline.Outline; import com.sun.tools.xjc.outline.PackageOutline; import com.sun.tools.xjc.util.CodeModelClassFactory; import com.sun.xml.bind.v2.model.core.PropertyInfo; import com.sun.xml.bind.v2.runtime.SwaRefAdapter; import com.sun.xml.xsom.XmlString; /** * Generates fields and accessors. */ public final class BeanGenerator implements Outline { /** Simplifies class/interface creation and collision detection. */ private final CodeModelClassFactory codeModelClassFactory; private final ErrorReceiver errorReceiver; /** all {@link PackageOutline}s keyed by their {@link PackageOutline#_package}. */ private final Map<JPackage,PackageOutlineImpl> packageContexts = new HashMap<JPackage,PackageOutlineImpl>(); /** all {@link ClassOutline}s keyed by their {@link ClassOutline#target}. */ private final Map<CClassInfo,ClassOutlineImpl> classes = new HashMap<CClassInfo,ClassOutlineImpl>(); /** all {@link EnumOutline}s keyed by their {@link EnumOutline#target}. */ private final Map<CEnumLeafInfo,EnumOutline> enums = new HashMap<CEnumLeafInfo,EnumOutline>(); /** * Generated runtime classes. */ private final Map<Class,JClass> generatedRuntime = new HashMap<Class, JClass>(); /** the model object which we are processing. */ private final Model model; private final JCodeModel codeModel; /** * for each property, the information about the generated field. */ private final Map<CPropertyInfo,FieldOutline> fields = new HashMap<CPropertyInfo,FieldOutline>(); /** * elements that generate classes to the generated classes. */ /*package*/ final Map<CElementInfo,ElementOutlineImpl> elements = new HashMap<CElementInfo,ElementOutlineImpl>(); /** * Generates beans into code model according to the BGM, * and produces the reflection model. * * @param _errorReceiver * This object will receive all the errors discovered * during the back-end stage. * * @return * returns a {@link Outline} which will in turn * be used to further generate marshaller/unmarshaller, * or null if the processing fails (errors should have been * reported to the error recevier.) */ public static Outline generate(Model model, ErrorReceiver _errorReceiver) { try { return new BeanGenerator(model, _errorReceiver); } catch( AbortException e ) { return null; } } private BeanGenerator(Model _model, ErrorReceiver _errorReceiver) { this.model = _model; this.codeModel = model.codeModel; this.errorReceiver = _errorReceiver; this.codeModelClassFactory = new CodeModelClassFactory(errorReceiver); // build enum classes for( CEnumLeafInfo p : model.enums().values() ) enums.put( p, generateEnum(p) ); JPackage[] packages = getUsedPackages(EXPOSED); // generates per-package code and remember the results as contexts. for( JPackage pkg : packages ) getPackageContext(pkg); // create the class definitions for all the beans first. // this should also fill in PackageContext#getClasses for( CClassInfo bean : model.beans().values() ) getClazz(bean); // compute the package-level setting for (PackageOutlineImpl p : packageContexts.values()) p.calcDefaultValues(); JClass OBJECT = codeModel.ref(Object.class); // inheritance relationship needs to be set before we generate fields, or otherwise // we'll fail to compute the correct type signature (namely the common base type computation) for( ClassOutlineImpl cc : getClasses() ) { // setup inheritance between implementation hierarchy. CClassInfo superClass = cc.target.getBaseClass(); if(superClass!=null) { // use the specified super class model.strategy._extends(cc,getClazz(superClass)); } else { CClassRef refSuperClass = cc.target.getRefBaseClass(); if(refSuperClass!=null) { cc.implClass._extends(refSuperClass.toType(this,EXPOSED)); } else { // use the default one, if any if( model.rootClass!=null && cc.implClass._extends().equals(OBJECT) ) cc.implClass._extends(model.rootClass); if( model.rootInterface!=null) cc.ref._implements(model.rootInterface); } } } // fill in implementation classes for( ClassOutlineImpl co : getClasses() ) generateClassBody(co); // create factories for the impl-less elements for( CElementInfo ei : model.getAllElements()) getPackageContext(ei._package()).objectFactoryGenerator().populate(ei); if(model.options.debugMode) generateClassList(); } /** * Generates a class that knows how to create an instance of JAXBContext * * <p> * This is used in the debug mode so that a new properly configured * {@link JAXBContext} object can be used. */ private void generateClassList() { try { JDefinedClass jc = codeModel.rootPackage()._class("JAXBDebug"); JMethod m = jc.method(JMod.PUBLIC|JMod.STATIC,JAXBContext.class,"createContext"); JVar $classLoader = m.param(ClassLoader.class,"classLoader"); m._throws(JAXBException.class); JInvocation inv = codeModel.ref(JAXBContext.class).staticInvoke("newInstance"); m.body()._return(inv); switch(model.strategy) { case INTF_AND_IMPL: { StringBuilder buf = new StringBuilder(); for( PackageOutlineImpl po : packageContexts.values() ) { if(buf.length()>0) buf.append(':'); buf.append(po._package().name()); } inv.arg(buf.toString()).arg($classLoader); break; } case BEAN_ONLY: for( ClassOutlineImpl cc : getClasses() ) inv.arg(cc.implRef.dotclass()); for( PackageOutlineImpl po : packageContexts.values() ) inv.arg(po.objectFactory().dotclass()); break; default: throw new IllegalStateException(); } } catch (JClassAlreadyExistsException e) { e.printStackTrace(); // after all, we are in the debug mode. a little sloppiness is OK. // this error is not fatal. just continue. } } public Model getModel() { return model; } public JCodeModel getCodeModel() { return codeModel; } public JClassContainer getContainer(CClassInfoParent parent, Aspect aspect) { CClassInfoParent.Visitor<JClassContainer> v; switch(aspect) { case EXPOSED: v = exposedContainerBuilder; break; case IMPLEMENTATION: v = implContainerBuilder; break; default: assert false; throw new IllegalStateException(); } return parent.accept(v); } public final JType resolve(CTypeRef ref,Aspect a) { return ref.getTarget().getType().toType(this,a); } private final CClassInfoParent.Visitor<JClassContainer> exposedContainerBuilder = new CClassInfoParent.Visitor<JClassContainer>() { public JClassContainer onBean(CClassInfo bean) { return getClazz(bean).ref; } public JClassContainer onElement(CElementInfo element) { // hmm... return getElement(element).implClass; } public JClassContainer onPackage(JPackage pkg) { return model.strategy.getPackage(pkg, EXPOSED); } }; private final CClassInfoParent.Visitor<JClassContainer> implContainerBuilder = new CClassInfoParent.Visitor<JClassContainer>() { public JClassContainer onBean(CClassInfo bean) { return getClazz(bean).implClass; } public JClassContainer onElement(CElementInfo element) { return getElement(element).implClass; } public JClassContainer onPackage(JPackage pkg) { return model.strategy.getPackage(pkg,Aspect.IMPLEMENTATION); } }; /** * Returns all <i>used</i> JPackages. * * A JPackage is considered as "used" if a ClassItem or * a InterfaceItem resides in that package. * * This value is dynamically calculated every time because * one can freely remove ClassItem/InterfaceItem. * * @return * Given the same input, the order of packages in the array * is always the same regardless of the environment. */ public final JPackage[] getUsedPackages( Aspect aspect ) { Set<JPackage> s = new TreeSet<JPackage>(); for( CClassInfo bean : model.beans().values() ) { JClassContainer cont = getContainer(bean.parent(),aspect); if(cont.isPackage()) s.add( (JPackage)cont ); } for( CElementInfo e : model.getElementMappings(null).values() ) { // at the first glance you might think we should be iterating all elements, // not just global ones, but if you think about it, local ones live inside // another class, so those packages are already enumerated when we were // walking over CClassInfos. s.add( e._package() ); } return s.toArray(new JPackage[s.size()]); } public ErrorReceiver getErrorReceiver() { return errorReceiver; } public CodeModelClassFactory getClassFactory() { return codeModelClassFactory; } public PackageOutlineImpl getPackageContext( JPackage p ) { PackageOutlineImpl r = packageContexts.get(p); if(r==null) { r=new PackageOutlineImpl(this,model,p); packageContexts.put(p,r); } return r; } /** * Generates the minimum {@link JDefinedClass} skeleton * without filling in its body. */ private ClassOutlineImpl generateClassDef(CClassInfo bean) { ImplStructureStrategy.Result r = model.strategy.createClasses(this,bean); JClass implRef; if( bean.getUserSpecifiedImplClass()!=null ) { // create a place holder for a user-specified class. JDefinedClass usr; try { usr = codeModel._class(bean.getUserSpecifiedImplClass()); // but hide that file so that it won't be generated. usr.hide(); } catch( JClassAlreadyExistsException e ) { // it's OK for this to collide. usr = e.getExistingClass(); } usr._extends(r.implementation); implRef = usr; } else implRef = r.implementation; return new ClassOutlineImpl(this,bean,r.exposed,r.implementation,implRef); } public Collection<ClassOutlineImpl> getClasses() { // make sure that classes are fully populated assert model.beans().size()==classes.size(); return classes.values(); } public ClassOutlineImpl getClazz( CClassInfo bean ) { ClassOutlineImpl r = classes.get(bean); if(r==null) classes.put( bean, r=generateClassDef(bean) ); return r; } public ElementOutlineImpl getElement(CElementInfo ei) { ElementOutlineImpl def = elements.get(ei); if(def==null && ei.hasClass()) { // create one. in the constructor it adds itself to the elements. def = new ElementOutlineImpl(this,ei); } return def; } public EnumOutline getEnum(CEnumLeafInfo eli) { return enums.get(eli); } public Collection<EnumOutline> getEnums() { return enums.values(); } public Iterable<? extends PackageOutline> getAllPackageContexts() { return packageContexts.values(); } public FieldOutline getField( CPropertyInfo prop ) { return fields.get(prop); } /** * Generates the body of a class. * */ private void generateClassBody( ClassOutlineImpl cc ) { CClassInfo target = cc.target; // if serialization support is turned on, generate // [RESULT] // class ... implements Serializable { // private static final long serialVersionUID = <id>; // .... // } if( model.serializable ) { cc.implClass._implements(Serializable.class); if( model.serialVersionUID!=null ) { cc.implClass.field( JMod.PRIVATE|JMod.STATIC|JMod.FINAL, codeModel.LONG, "serialVersionUID", JExpr.lit(model.serialVersionUID)); } } // used to simplify the generated annotations String mostUsedNamespaceURI = cc._package().getMostUsedNamespaceURI(); // [RESULT] // @XmlType(name="foo", targetNamespace="bar://baz") XmlTypeWriter xtw = cc.implClass.annotate2(XmlTypeWriter.class); QName typeName = cc.target.getTypeName(); if(typeName==null) { xtw.name(""); } else { xtw.name(typeName.getLocalPart()); final String typeNameURI = typeName.getNamespaceURI(); if(!typeNameURI.equals(mostUsedNamespaceURI)) // only generate if necessary xtw.namespace(typeNameURI); } if(model.options.target.isLaterThan(Options.Target.V2_1)) { // @XmlSeeAlso Iterator<CClassInfo> subclasses = cc.target.listSubclasses(); if(subclasses.hasNext()) { XmlSeeAlsoWriter saw = cc.implClass.annotate2(XmlSeeAlsoWriter.class); while (subclasses.hasNext()) { CClassInfo s = subclasses.next(); saw.value(getClazz(s).implRef); } } } if(target.isElement()) { String namespaceURI = target.getElementName().getNamespaceURI(); String localPart = target.getElementName().getLocalPart(); // [RESULT] // @XmlRootElement(name="foo", targetNamespace="bar://baz") XmlRootElementWriter xrew = cc.implClass.annotate2(XmlRootElementWriter.class); xrew.name(localPart); if(!namespaceURI.equals(mostUsedNamespaceURI)) // only generate if necessary xrew.namespace(namespaceURI); } if(target.isOrdered()) { for(CPropertyInfo p : target.getProperties() ) { if( ! (p instanceof CAttributePropertyInfo )) { xtw.propOrder(p.getName(false)); } } } else { // produce empty array xtw.getAnnotationUse().paramArray("propOrder"); } for( CPropertyInfo prop : target.getProperties() ) { generateFieldDecl(cc,prop); } if( target.declaresAttributeWildcard() ) { generateAttributeWildcard(cc); } // generate some class level javadoc cc.ref.javadoc().append(target.javadoc); cc._package().objectFactoryGenerator().populate(cc); } /** * Generates an attribute wildcard property on a class. */ private void generateAttributeWildcard( ClassOutlineImpl cc ) { String FIELD_NAME = "otherAttributes"; String METHOD_SEED = model.getNameConverter().toClassName(FIELD_NAME); JClass mapType = codeModel.ref(Map.class).narrow(QName.class,String.class); JClass mapImpl = codeModel.ref(HashMap.class).narrow(QName.class,String.class); // [RESULT] // Map<QName,String> m = new HashMap<QName,String>(); JFieldVar $ref = cc.implClass.field(JMod.PRIVATE, mapType, FIELD_NAME, JExpr._new(mapImpl) ); $ref.annotate2(XmlAnyAttributeWriter.class); MethodWriter writer = cc.createMethodWriter(); JMethod $get = writer.declareMethod( mapType, "get"+METHOD_SEED ); $get.javadoc().append( "Gets a map that contains attributes that aren't bound to any typed property on this class.\n\n" + "<p>\n" + "the map is keyed by the name of the attribute and \n" + "the value is the string value of the attribute.\n" + "\n" + "the map returned by this method is live, and you can add new attribute\n" + "by updating the map directly. Because of this design, there's no setter.\n"); $get.javadoc().addReturn().append("always non-null"); $get.body()._return($ref); } private EnumOutline generateEnum(CEnumLeafInfo e) { JDefinedClass type; // since constant values are never null, no point in using the boxed types. JType baseExposedType = e.base.toType(this, EXPOSED).unboxify(); JType baseImplType = e.base.toType(this,Aspect.IMPLEMENTATION).unboxify(); type = getClassFactory().createClass( getContainer(e.parent, EXPOSED),e.shortName,e.getLocator(), ClassType.ENUM); type.javadoc().append(e.javadoc); XmlEnumWriter xew = type.annotate2(XmlEnumWriter.class); xew.value(baseExposedType); JCodeModel codeModel = model.codeModel; EnumOutline enumOutline = new EnumOutline(e, type) {}; boolean needsValue = e.needsValueField(); // for each member <m>, // [RESULT] // <EnumName>(<deserializer of m>(<value>)); Set<String> enumFieldNames = new HashSet<String>(); // record generated field names to detect collision for( CEnumConstant mem : e.members ) { String constName = mem.getName(); if(!JJavaName.isJavaIdentifier(constName)) { // didn't produce a name. getErrorReceiver().error( e.getLocator(), Messages.ERR_UNUSABLE_NAME.format(mem.getLexicalValue(), constName ) ); } if( !enumFieldNames.add(constName) ) getErrorReceiver().error( e.getLocator(), Messages.ERR_NAME_COLLISION.format(constName)); // [RESULT] // <Const>(...) // ASSUMPTION: datatype is outline-independent JEnumConstant constRef = type.enumConstant(constName); if(needsValue) constRef.arg(e.base.createConstant(this, new XmlString(mem.getLexicalValue()))); if(!mem.getLexicalValue().equals(constName)) constRef.annotate2(XmlEnumValueWriter.class).value(mem.getLexicalValue()); // set javadoc if( mem.javadoc!=null ) constRef.javadoc().append(mem.javadoc); enumOutline.constants.add(new EnumConstantOutline(mem,constRef){}); } if(needsValue) { // [RESULT] // final <valueType> value; JFieldVar $value = type.field( JMod.PRIVATE|JMod.FINAL, baseExposedType, "value" ); // [RESULT] // public <valuetype> value() { return value; } type.method(JMod.PUBLIC, baseExposedType, "value" ).body()._return($value); // [RESULT] // <constructor>(<valueType> v) { // this.value=v; // } { JMethod m = type.constructor(0); m.body().assign( $value, m.param( baseImplType, "v" ) ); } // [RESULT] // public static <Const> fromValue(<valueType> v) { // for( <Const> c : <Const>.values() ) { // if(c.value == v) // or equals // return c; // } // throw new IllegalArgumentException(...); // } { JMethod m = type.method(JMod.PUBLIC|JMod.STATIC , type, "fromValue" ); JVar $v = m.param(baseExposedType,"v"); JForEach fe = m.body().forEach(type,"c", type.staticInvoke("values") ); JExpression eq; if(baseExposedType.isPrimitive()) eq = fe.var().ref($value).eq($v); else eq = fe.var().ref($value).invoke("equals").arg($v); fe.body()._if(eq)._then()._return(fe.var()); JInvocation ex = JExpr._new(codeModel.ref(IllegalArgumentException.class)); + JExpression strForm; if(baseExposedType.isPrimitive()) { - m.body()._throw(ex.arg(codeModel.ref(String.class).staticInvoke("valueOf").arg($v))); + strForm = codeModel.ref(String.class).staticInvoke("valueOf").arg($v); + } else + if(baseExposedType==codeModel.ref(String.class)){ + strForm = $v; } else { - m.body()._throw(ex.arg($v.invoke("toString"))); + strForm = $v.invoke("toString"); } + m.body()._throw(ex.arg(strForm)); } } else { // [RESULT] // public String value() { return name(); } type.method(JMod.PUBLIC, String.class, "value" ).body()._return(JExpr.invoke("name")); // [RESULT] // public <Const> fromValue(String v) { return valueOf(v); } JMethod m = type.method(JMod.PUBLIC|JMod.STATIC, type, "fromValue" ); m.body()._return( JExpr.invoke("valueOf").arg(m.param(String.class,"v"))); } return enumOutline; } /** * Determines the FieldRenderer used for the given FieldUse, * then generates the field declaration and accessor methods. * * The <code>fields</code> map will be updated with the newly * created FieldRenderer. */ private FieldOutline generateFieldDecl( ClassOutlineImpl cc, CPropertyInfo prop ) { FieldRenderer fr = prop.realization; if(fr==null) // none is specified. use the default factory fr = model.options.getFieldRendererFactory().getDefault(); FieldOutline field = fr.generate(cc,prop); fields.put(prop,field); return field; } /** * Generates {@link XmlJavaTypeAdapter} from {@link PropertyInfo} if necessary. * Also generates other per-property annotations * (such as {@link XmlID}, {@link XmlIDREF}, and {@link XmlMimeType} if necessary. */ public final void generateAdapterIfNecessary(CPropertyInfo prop, JAnnotatable field) { CAdapter adapter = prop.getAdapter(); if (adapter != null ) { if(adapter.getAdapterIfKnown()==SwaRefAdapter.class) { field.annotate(XmlAttachmentRef.class); } else { // [RESULT] // @XmlJavaTypeAdapter( Foo.class ) XmlJavaTypeAdapterWriter xjtw = field.annotate2(XmlJavaTypeAdapterWriter.class); xjtw.value(adapter.adapterType.toType(this, EXPOSED)); } } switch(prop.id()) { case ID: field.annotate(XmlID.class); break; case IDREF: field.annotate(XmlIDREF.class); break; } if(prop.getExpectedMimeType()!=null) field.annotate2(XmlMimeTypeWriter.class).value(prop.getExpectedMimeType().toString()); } public final JClass addRuntime(Class clazz) { JClass g = generatedRuntime.get(clazz); if(g==null) { // put code into a separate package to avoid name conflicts. JPackage implPkg = getUsedPackages(Aspect.IMPLEMENTATION)[0].subPackage("runtime"); g = generateStaticClass(clazz,implPkg); generatedRuntime.put(clazz,g); } return g; } public JClass generateStaticClass(Class src, JPackage out) { String shortName = getShortName(src.getName()); // some people didn't like our jars to contain files with .java extension, // so when we build jars, we'' use ".java_". But when we run from the workspace, // we want the original source code to be used, so we check both here. // see bug 6211503. URL res = src.getResource(shortName+".java"); if(res==null) res = src.getResource(shortName+".java_"); if(res==null) throw new InternalError("Unable to load source code of "+src.getName()+" as a resource"); JStaticJavaFile sjf = new JStaticJavaFile(out,shortName, res, null ); out.addResourceFile(sjf); return sjf.getJClass(); } private String getShortName( String name ) { return name.substring(name.lastIndexOf('.')+1); } }
false
true
private EnumOutline generateEnum(CEnumLeafInfo e) { JDefinedClass type; // since constant values are never null, no point in using the boxed types. JType baseExposedType = e.base.toType(this, EXPOSED).unboxify(); JType baseImplType = e.base.toType(this,Aspect.IMPLEMENTATION).unboxify(); type = getClassFactory().createClass( getContainer(e.parent, EXPOSED),e.shortName,e.getLocator(), ClassType.ENUM); type.javadoc().append(e.javadoc); XmlEnumWriter xew = type.annotate2(XmlEnumWriter.class); xew.value(baseExposedType); JCodeModel codeModel = model.codeModel; EnumOutline enumOutline = new EnumOutline(e, type) {}; boolean needsValue = e.needsValueField(); // for each member <m>, // [RESULT] // <EnumName>(<deserializer of m>(<value>)); Set<String> enumFieldNames = new HashSet<String>(); // record generated field names to detect collision for( CEnumConstant mem : e.members ) { String constName = mem.getName(); if(!JJavaName.isJavaIdentifier(constName)) { // didn't produce a name. getErrorReceiver().error( e.getLocator(), Messages.ERR_UNUSABLE_NAME.format(mem.getLexicalValue(), constName ) ); } if( !enumFieldNames.add(constName) ) getErrorReceiver().error( e.getLocator(), Messages.ERR_NAME_COLLISION.format(constName)); // [RESULT] // <Const>(...) // ASSUMPTION: datatype is outline-independent JEnumConstant constRef = type.enumConstant(constName); if(needsValue) constRef.arg(e.base.createConstant(this, new XmlString(mem.getLexicalValue()))); if(!mem.getLexicalValue().equals(constName)) constRef.annotate2(XmlEnumValueWriter.class).value(mem.getLexicalValue()); // set javadoc if( mem.javadoc!=null ) constRef.javadoc().append(mem.javadoc); enumOutline.constants.add(new EnumConstantOutline(mem,constRef){}); } if(needsValue) { // [RESULT] // final <valueType> value; JFieldVar $value = type.field( JMod.PRIVATE|JMod.FINAL, baseExposedType, "value" ); // [RESULT] // public <valuetype> value() { return value; } type.method(JMod.PUBLIC, baseExposedType, "value" ).body()._return($value); // [RESULT] // <constructor>(<valueType> v) { // this.value=v; // } { JMethod m = type.constructor(0); m.body().assign( $value, m.param( baseImplType, "v" ) ); } // [RESULT] // public static <Const> fromValue(<valueType> v) { // for( <Const> c : <Const>.values() ) { // if(c.value == v) // or equals // return c; // } // throw new IllegalArgumentException(...); // } { JMethod m = type.method(JMod.PUBLIC|JMod.STATIC , type, "fromValue" ); JVar $v = m.param(baseExposedType,"v"); JForEach fe = m.body().forEach(type,"c", type.staticInvoke("values") ); JExpression eq; if(baseExposedType.isPrimitive()) eq = fe.var().ref($value).eq($v); else eq = fe.var().ref($value).invoke("equals").arg($v); fe.body()._if(eq)._then()._return(fe.var()); JInvocation ex = JExpr._new(codeModel.ref(IllegalArgumentException.class)); if(baseExposedType.isPrimitive()) { m.body()._throw(ex.arg(codeModel.ref(String.class).staticInvoke("valueOf").arg($v))); } else { m.body()._throw(ex.arg($v.invoke("toString"))); } } } else { // [RESULT] // public String value() { return name(); } type.method(JMod.PUBLIC, String.class, "value" ).body()._return(JExpr.invoke("name")); // [RESULT] // public <Const> fromValue(String v) { return valueOf(v); } JMethod m = type.method(JMod.PUBLIC|JMod.STATIC, type, "fromValue" ); m.body()._return( JExpr.invoke("valueOf").arg(m.param(String.class,"v"))); } return enumOutline; }
private EnumOutline generateEnum(CEnumLeafInfo e) { JDefinedClass type; // since constant values are never null, no point in using the boxed types. JType baseExposedType = e.base.toType(this, EXPOSED).unboxify(); JType baseImplType = e.base.toType(this,Aspect.IMPLEMENTATION).unboxify(); type = getClassFactory().createClass( getContainer(e.parent, EXPOSED),e.shortName,e.getLocator(), ClassType.ENUM); type.javadoc().append(e.javadoc); XmlEnumWriter xew = type.annotate2(XmlEnumWriter.class); xew.value(baseExposedType); JCodeModel codeModel = model.codeModel; EnumOutline enumOutline = new EnumOutline(e, type) {}; boolean needsValue = e.needsValueField(); // for each member <m>, // [RESULT] // <EnumName>(<deserializer of m>(<value>)); Set<String> enumFieldNames = new HashSet<String>(); // record generated field names to detect collision for( CEnumConstant mem : e.members ) { String constName = mem.getName(); if(!JJavaName.isJavaIdentifier(constName)) { // didn't produce a name. getErrorReceiver().error( e.getLocator(), Messages.ERR_UNUSABLE_NAME.format(mem.getLexicalValue(), constName ) ); } if( !enumFieldNames.add(constName) ) getErrorReceiver().error( e.getLocator(), Messages.ERR_NAME_COLLISION.format(constName)); // [RESULT] // <Const>(...) // ASSUMPTION: datatype is outline-independent JEnumConstant constRef = type.enumConstant(constName); if(needsValue) constRef.arg(e.base.createConstant(this, new XmlString(mem.getLexicalValue()))); if(!mem.getLexicalValue().equals(constName)) constRef.annotate2(XmlEnumValueWriter.class).value(mem.getLexicalValue()); // set javadoc if( mem.javadoc!=null ) constRef.javadoc().append(mem.javadoc); enumOutline.constants.add(new EnumConstantOutline(mem,constRef){}); } if(needsValue) { // [RESULT] // final <valueType> value; JFieldVar $value = type.field( JMod.PRIVATE|JMod.FINAL, baseExposedType, "value" ); // [RESULT] // public <valuetype> value() { return value; } type.method(JMod.PUBLIC, baseExposedType, "value" ).body()._return($value); // [RESULT] // <constructor>(<valueType> v) { // this.value=v; // } { JMethod m = type.constructor(0); m.body().assign( $value, m.param( baseImplType, "v" ) ); } // [RESULT] // public static <Const> fromValue(<valueType> v) { // for( <Const> c : <Const>.values() ) { // if(c.value == v) // or equals // return c; // } // throw new IllegalArgumentException(...); // } { JMethod m = type.method(JMod.PUBLIC|JMod.STATIC , type, "fromValue" ); JVar $v = m.param(baseExposedType,"v"); JForEach fe = m.body().forEach(type,"c", type.staticInvoke("values") ); JExpression eq; if(baseExposedType.isPrimitive()) eq = fe.var().ref($value).eq($v); else eq = fe.var().ref($value).invoke("equals").arg($v); fe.body()._if(eq)._then()._return(fe.var()); JInvocation ex = JExpr._new(codeModel.ref(IllegalArgumentException.class)); JExpression strForm; if(baseExposedType.isPrimitive()) { strForm = codeModel.ref(String.class).staticInvoke("valueOf").arg($v); } else if(baseExposedType==codeModel.ref(String.class)){ strForm = $v; } else { strForm = $v.invoke("toString"); } m.body()._throw(ex.arg(strForm)); } } else { // [RESULT] // public String value() { return name(); } type.method(JMod.PUBLIC, String.class, "value" ).body()._return(JExpr.invoke("name")); // [RESULT] // public <Const> fromValue(String v) { return valueOf(v); } JMethod m = type.method(JMod.PUBLIC|JMod.STATIC, type, "fromValue" ); m.body()._return( JExpr.invoke("valueOf").arg(m.param(String.class,"v"))); } return enumOutline; }
diff --git a/src/main/org/jboss/jms/client/remoting/CallbackServerFactory.java b/src/main/org/jboss/jms/client/remoting/CallbackServerFactory.java index 5c61f9368..904bb449d 100644 --- a/src/main/org/jboss/jms/client/remoting/CallbackServerFactory.java +++ b/src/main/org/jboss/jms/client/remoting/CallbackServerFactory.java @@ -1,215 +1,215 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jms.client.remoting; import java.net.InetAddress; import java.util.HashMap; import java.util.Map; import org.jboss.jms.util.MessagingJMSException; import org.jboss.logging.Logger; import org.jboss.remoting.InvokerLocator; import org.jboss.remoting.security.SSLSocketBuilder; import org.jboss.remoting.transport.Connector; import org.jboss.remoting.transport.PortUtil; /** * * A CallbackServerFactory. * * We maintain only one callbackserver per transport per client VM. * This is to avoid having too many resources e.g. server sockets in use on the client * E.g. in the case of a socket transport, if we had one callbackserver per connection then * we would have one server socket listening per connection, so we could run out of available * ports with a lot of connections. * * @author <a href="[email protected]">Tim Fox</a> * @version $Revision$ * * $Id$ */ public class CallbackServerFactory { private static final Logger log = Logger.getLogger(CallbackServerFactory.class); private static final String CALLBACK_SERVER_PARAMS = "/?marshaller=org.jboss.jms.server.remoting.JMSWireFormat&" + "unmarshaller=org.jboss.jms.server.remoting.JMSWireFormat&" + "dataType=jms&" + "timeout=0&" + "socket.check_connection=false"; public static final String JMS_CALLBACK_SUBSYSTEM = "CALLBACK"; public static CallbackServerFactory instance = new CallbackServerFactory(); private Map holders; private CallbackServerFactory() { holders = new HashMap(); } public synchronized boolean containsCallbackServer(String protocol) { return holders.containsKey(protocol); } public synchronized Connector getCallbackServer(InvokerLocator serverLocator) throws Exception { String protocol = serverLocator.getProtocol(); Holder h = (Holder)holders.get(protocol); if (h == null) { h = new Holder(); h.server = startCallbackServer(serverLocator); holders.put(protocol, h); } else { h.refCount++; } return h.server; } public synchronized void stopCallbackServer(String protocol) { Holder h = (Holder)holders.get(protocol); if (h == null) { throw new IllegalArgumentException("Cannot find callback server for protocol: " + protocol); } h.refCount--; if (h.refCount == 0) { stopCallbackServer(h.server); holders.remove(protocol); } } protected Connector startCallbackServer(InvokerLocator serverLocator) throws Exception { if (log.isTraceEnabled()) { log.trace(this + " setting up connection to " + serverLocator); } final int MAX_RETRIES = 50; boolean completed = false; Connector server = null; String serializationType = null; int count = 0; - String thisAddress = InetAddress.getLocalHost().getHostAddress(); + String thisAddress = serverLocator.getHost(); boolean isSSL = serverLocator.getProtocol().equals("sslsocket"); Map params = serverLocator.getParameters(); if (params != null) { serializationType = (String)params.get("serializationtype"); } while (!completed && count < MAX_RETRIES) { try { - int bindPort = PortUtil.findFreePort("localhost"); + int bindPort = PortUtil.findFreePort(thisAddress); String callbackServerURI; if (isSSL) { // See http://jira.jboss.com/jira/browse/JBREM-470 callbackServerURI = "sslsocket://" + thisAddress + ":" + bindPort + CALLBACK_SERVER_PARAMS + "&" + SSLSocketBuilder.REMOTING_SERVER_SOCKET_USE_CLIENT_MODE + "=true"; } else { callbackServerURI = serverLocator.getProtocol() + "://" + thisAddress + ":" + bindPort + CALLBACK_SERVER_PARAMS; } if (serializationType != null) { callbackServerURI += "&serializationType=" + serializationType; } InvokerLocator callbackServerLocator = new InvokerLocator(callbackServerURI); log.debug(this + " starting callback server " + callbackServerLocator.getLocatorURI()); server = new Connector(); server.setInvokerLocator(callbackServerLocator.getLocatorURI()); server.create(); server.addInvocationHandler(JMS_CALLBACK_SUBSYSTEM, new CallbackManager()); server.start(); if (log.isTraceEnabled()) { log.trace("callback server started"); } completed = true; } catch (Exception e) { log.warn("Failed to start connection. Will retry", e); // Intermittently we can fail to open a socket on the address since it's already in use // This is despite remoting having checked the port is free. This is probably because // of the small window between remoting checking the port is free and getting the // port number and actually opening the connection during which some one else can use // that port. Therefore we catch this and retry. count++; if (count == MAX_RETRIES) { final String msg = "Cannot start callbackserver after " + MAX_RETRIES + " retries"; log.error(msg, e); throw new MessagingJMSException(msg, e); } } } return server; } protected void stopCallbackServer(Connector server) { log.debug("Stopping and destroying callback server " + server.getLocator().getLocatorURI()); server.stop(); server.destroy(); } private class Holder { Connector server; int refCount = 1; } }
false
true
protected Connector startCallbackServer(InvokerLocator serverLocator) throws Exception { if (log.isTraceEnabled()) { log.trace(this + " setting up connection to " + serverLocator); } final int MAX_RETRIES = 50; boolean completed = false; Connector server = null; String serializationType = null; int count = 0; String thisAddress = InetAddress.getLocalHost().getHostAddress(); boolean isSSL = serverLocator.getProtocol().equals("sslsocket"); Map params = serverLocator.getParameters(); if (params != null) { serializationType = (String)params.get("serializationtype"); } while (!completed && count < MAX_RETRIES) { try { int bindPort = PortUtil.findFreePort("localhost"); String callbackServerURI; if (isSSL) { // See http://jira.jboss.com/jira/browse/JBREM-470 callbackServerURI = "sslsocket://" + thisAddress + ":" + bindPort + CALLBACK_SERVER_PARAMS + "&" + SSLSocketBuilder.REMOTING_SERVER_SOCKET_USE_CLIENT_MODE + "=true"; } else { callbackServerURI = serverLocator.getProtocol() + "://" + thisAddress + ":" + bindPort + CALLBACK_SERVER_PARAMS; } if (serializationType != null) { callbackServerURI += "&serializationType=" + serializationType; } InvokerLocator callbackServerLocator = new InvokerLocator(callbackServerURI); log.debug(this + " starting callback server " + callbackServerLocator.getLocatorURI()); server = new Connector(); server.setInvokerLocator(callbackServerLocator.getLocatorURI()); server.create(); server.addInvocationHandler(JMS_CALLBACK_SUBSYSTEM, new CallbackManager()); server.start(); if (log.isTraceEnabled()) { log.trace("callback server started"); } completed = true; } catch (Exception e) { log.warn("Failed to start connection. Will retry", e); // Intermittently we can fail to open a socket on the address since it's already in use // This is despite remoting having checked the port is free. This is probably because // of the small window between remoting checking the port is free and getting the // port number and actually opening the connection during which some one else can use // that port. Therefore we catch this and retry. count++; if (count == MAX_RETRIES) { final String msg = "Cannot start callbackserver after " + MAX_RETRIES + " retries"; log.error(msg, e); throw new MessagingJMSException(msg, e); } } } return server; }
protected Connector startCallbackServer(InvokerLocator serverLocator) throws Exception { if (log.isTraceEnabled()) { log.trace(this + " setting up connection to " + serverLocator); } final int MAX_RETRIES = 50; boolean completed = false; Connector server = null; String serializationType = null; int count = 0; String thisAddress = serverLocator.getHost(); boolean isSSL = serverLocator.getProtocol().equals("sslsocket"); Map params = serverLocator.getParameters(); if (params != null) { serializationType = (String)params.get("serializationtype"); } while (!completed && count < MAX_RETRIES) { try { int bindPort = PortUtil.findFreePort(thisAddress); String callbackServerURI; if (isSSL) { // See http://jira.jboss.com/jira/browse/JBREM-470 callbackServerURI = "sslsocket://" + thisAddress + ":" + bindPort + CALLBACK_SERVER_PARAMS + "&" + SSLSocketBuilder.REMOTING_SERVER_SOCKET_USE_CLIENT_MODE + "=true"; } else { callbackServerURI = serverLocator.getProtocol() + "://" + thisAddress + ":" + bindPort + CALLBACK_SERVER_PARAMS; } if (serializationType != null) { callbackServerURI += "&serializationType=" + serializationType; } InvokerLocator callbackServerLocator = new InvokerLocator(callbackServerURI); log.debug(this + " starting callback server " + callbackServerLocator.getLocatorURI()); server = new Connector(); server.setInvokerLocator(callbackServerLocator.getLocatorURI()); server.create(); server.addInvocationHandler(JMS_CALLBACK_SUBSYSTEM, new CallbackManager()); server.start(); if (log.isTraceEnabled()) { log.trace("callback server started"); } completed = true; } catch (Exception e) { log.warn("Failed to start connection. Will retry", e); // Intermittently we can fail to open a socket on the address since it's already in use // This is despite remoting having checked the port is free. This is probably because // of the small window between remoting checking the port is free and getting the // port number and actually opening the connection during which some one else can use // that port. Therefore we catch this and retry. count++; if (count == MAX_RETRIES) { final String msg = "Cannot start callbackserver after " + MAX_RETRIES + " retries"; log.error(msg, e); throw new MessagingJMSException(msg, e); } } } return server; }
diff --git a/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/items/MythicDropBuilder.java b/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/items/MythicDropBuilder.java index e8bb2715..ef87f235 100644 --- a/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/items/MythicDropBuilder.java +++ b/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/items/MythicDropBuilder.java @@ -1,531 +1,533 @@ package net.nunnerycode.bukkit.mythicdrops.items; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.enchantments.MythicEnchantment; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.items.MythicItemStack; import net.nunnerycode.bukkit.mythicdrops.api.items.NonrepairableItemStack; import net.nunnerycode.bukkit.mythicdrops.api.items.builders.DropBuilder; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.RandomItemGenerationEvent; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.RandomRangeUtil; import org.apache.commons.lang.Validate; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.EnchantmentWrapper; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.material.MaterialData; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public final class MythicDropBuilder implements DropBuilder { private Tier tier; private MaterialData materialData; private ItemGenerationReason itemGenerationReason; private World world; private boolean useDurability; private boolean callEvent; public MythicDropBuilder() { tier = null; itemGenerationReason = ItemGenerationReason.DEFAULT; world = Bukkit.getServer().getWorlds().get(0); useDurability = false; callEvent = true; } public DropBuilder withCallEvent(boolean b) { this.callEvent = b; return this; } @Override public DropBuilder withTier(Tier tier) { this.tier = tier; return this; } @Override public DropBuilder withTier(String tierName) { this.tier = TierMap.getInstance().get(tierName); return this; } @Override public DropBuilder withMaterialData(MaterialData materialData) { this.materialData = materialData; return this; } @Override public DropBuilder withMaterialData(String materialDataString) { MaterialData matData = null; if (materialDataString.contains(";")) { String[] split = materialDataString.split(";"); matData = new MaterialData(NumberUtils.toInt(split[0], 0), (byte) NumberUtils.toInt(split[1], 0)); } else { matData = new MaterialData(NumberUtils.toInt(materialDataString, 0)); } this.materialData = matData; return this; } @Override public DropBuilder withItemGenerationReason(ItemGenerationReason reason) { this.itemGenerationReason = reason; return this; } @Override public DropBuilder inWorld(World world) { this.world = world; return this; } @Override public DropBuilder inWorld(String worldName) { this.world = Bukkit.getWorld(worldName); return this; } @Override public DropBuilder useDurability(boolean b) { this.useDurability = b; return this; } @Override public MythicItemStack build() { World w = world != null ? world : Bukkit.getWorlds().get(0); Tier t = (tier != null) ? tier : TierMap.getInstance().getRandomWithChance(w.getName()); if (t == null) { t = TierMap.getInstance().getRandomWithChance("default"); if (t == null) { return null; } } MaterialData md = (materialData != null) ? materialData : ItemUtil.getRandomMaterialDataFromCollection (ItemUtil.getMaterialDatasFromTier(t)); NonrepairableItemStack nis = new NonrepairableItemStack(md.getItemType(), 1, (short) 0, ""); ItemMeta im = nis.getItemMeta(); Map<Enchantment, Integer> baseEnchantmentMap = getBaseEnchantments(nis, t); Map<Enchantment, Integer> bonusEnchantmentMap = getBonusEnchantments(nis, t); for (Map.Entry<Enchantment, Integer> baseEnch : baseEnchantmentMap.entrySet()) { im.addEnchant(baseEnch.getKey(), baseEnch.getValue(), true); } for (Map.Entry<Enchantment, Integer> bonusEnch : bonusEnchantmentMap.entrySet()) { im.addEnchant(bonusEnch.getKey(), bonusEnch.getValue(), true); } if (useDurability) { nis.setDurability(ItemStackUtil.getDurabilityForMaterial(nis.getType(), t.getMinimumDurabilityPercentage (), t.getMaximumDurabilityPercentage())); } String name = generateName(nis); List<String> lore = generateLore(nis); im.setDisplayName(name); im.setLore(lore); if (nis.getItemMeta() instanceof LeatherArmorMeta) { ((LeatherArmorMeta) im).setColor(Color.fromRGB(RandomUtils.nextInt(255), RandomUtils.nextInt(255), RandomUtils.nextInt(255))); } nis.setItemMeta(im); if (callEvent) { RandomItemGenerationEvent rige = new RandomItemGenerationEvent(t, nis, itemGenerationReason); Bukkit.getPluginManager().callEvent(rige); if (rige.isCancelled()) { return null; } return rige.getItemStack(); } return nis; } private Map<Enchantment, Integer> getBonusEnchantments(MythicItemStack is, Tier t) { Validate.notNull(is, "MythicItemStack cannot be null"); Validate.notNull(t, "Tier cannot be null"); if (t.getBonusEnchantments().isEmpty()) { return new HashMap<>(); } Map<Enchantment, Integer> map = new HashMap<>(); int added = 0; int attempts = 0; int range = (int) RandomRangeUtil.randomRangeDoubleInclusive(t.getMinimumBonusEnchantments(), t.getMaximumBonusEnchantments()); MythicEnchantment[] array = t.getBonusEnchantments().toArray(new MythicEnchantment[t.getBonusEnchantments() .size()]); while (added < range && attempts < 10) { MythicEnchantment chosenEnch = array[RandomUtils.nextInt(array.length)]; if (chosenEnch == null || chosenEnch.getEnchantment() == null) { attempts++; continue; } Enchantment e = chosenEnch.getEnchantment(); int randLevel = (int) RandomRangeUtil.randomRangeLongInclusive(chosenEnch.getMinimumLevel(), chosenEnch.getMaximumLevel()); if (is.containsEnchantment(e)) { randLevel += is.getEnchantmentLevel(e); } if (t.isSafeBonusEnchantments() && e.canEnchantItem(is)) { if (t.isAllowHighBonusEnchantments()) { map.put(e, randLevel); } else { map.put(e, getAcceptableEnchantmentLevel(e, randLevel)); } } else if (!t.isSafeBonusEnchantments()) { if (t.isAllowHighBonusEnchantments()) { map.put(e, randLevel); } else { map.put(e, getAcceptableEnchantmentLevel(e, randLevel)); } } else { continue; } added++; } return map; } private Map<Enchantment, Integer> getBaseEnchantments(MythicItemStack is, Tier t) { Validate.notNull(is, "MythicItemStack cannot be null"); Validate.notNull(t, "Tier cannot be null"); if (t.getBaseEnchantments().isEmpty()) { return new HashMap<>(); } Map<Enchantment, Integer> map = new HashMap<>(); for (MythicEnchantment me : t.getBaseEnchantments()) { if (me == null || me.getEnchantment() == null) { continue; } Enchantment e = me.getEnchantment(); int minimumLevel = Math.max(me.getMinimumLevel(), e.getStartLevel()); int maximumLevel = Math.min(me.getMaximumLevel(), e.getMaxLevel()); if (t.isSafeBaseEnchantments() && e.canEnchantItem(is)) { if (t.isAllowHighBaseEnchantments()) { map.put(e, (int) RandomRangeUtil.randomRangeLongInclusive (minimumLevel, maximumLevel)); } else { map.put(e, getAcceptableEnchantmentLevel(e, (int) RandomRangeUtil.randomRangeLongInclusive(minimumLevel, maximumLevel))); } } else if (!t.isSafeBaseEnchantments()) { map.put(e, (int) RandomRangeUtil.randomRangeLongInclusive (minimumLevel, maximumLevel)); } } return map; } private int getAcceptableEnchantmentLevel(Enchantment ench, int level) { EnchantmentWrapper ew = new EnchantmentWrapper(ench.getId()); return Math.max(Math.min(level, ew.getMaxLevel()), ew.getStartLevel()); } private List<String> generateLore(ItemStack itemStack) { List<String> lore = new ArrayList<String>(); if (itemStack == null || tier == null) { return lore; } List<String> tooltipFormat = MythicDropsPlugin.getInstance().getConfigSettings().getTooltipFormat(); String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String itemType = getItemTypeName(ItemUtil.getItemTypeFromMaterialData(itemStack.getData())); String materialType = getItemTypeName(ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData())); String tierName = tier.getDisplayName(); String enchantment = getEnchantmentTypeName(itemStack); if (MythicDropsPlugin.getInstance().getConfigSettings().isRandomLoreEnabled() && RandomUtils.nextDouble() < MythicDropsPlugin.getInstance().getConfigSettings().getRandomLoreChance()) { String generalLoreString = NameMap.getInstance().getRandom(NameType.GENERAL_LORE, ""); String materialLoreString = NameMap.getInstance().getRandom(NameType.MATERIAL_LORE, itemStack.getType().name()); String tierLoreString = NameMap.getInstance().getRandom(NameType.TIER_LORE, tier.getName()); String enchantmentLoreString = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_LORE, enchantment != null ? enchantment : ""); List<String> generalLore = null; if (generalLoreString != null && !generalLoreString.isEmpty()) { generalLore = Arrays.asList(generalLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> materialLore = null; if (materialLoreString != null && !materialLoreString.isEmpty()) { materialLore = Arrays.asList(materialLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> tierLore = null; if (tierLoreString != null && !tierLoreString.isEmpty()) { tierLore = Arrays.asList(tierLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> enchantmentLore = null; if (enchantmentLoreString != null && !enchantmentLoreString.isEmpty()) { enchantmentLore = Arrays.asList(enchantmentLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } if (generalLore != null && !generalLore.isEmpty()) { lore.addAll(generalLore); } if (materialLore != null && !materialLore.isEmpty()) { lore.addAll(materialLore); } if (tierLore != null && !tierLore.isEmpty()) { lore.addAll(tierLore); } if (enchantmentLore != null && !enchantmentLore.isEmpty()) { lore.addAll(enchantmentLore); } } for (String s : tooltipFormat) { String line = s; line = line.replace("%basematerial%", minecraftName != null ? minecraftName : ""); line = line.replace("%mythicmaterial%", mythicName != null ? mythicName : ""); line = line.replace("%itemtype%", itemType != null ? itemType : ""); line = line.replace("%materialtype%", materialType != null ? materialType : ""); line = line.replace("%tiername%", tierName != null ? tierName : ""); line = line.replace("%enchantment%", enchantment != null ? enchantment : ""); line = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"); lore.add(line); } for (String s : tier.getBaseLore()) { String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n"); lore.addAll(Arrays.asList(strings)); } int numOfBonusLore = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumBonusLore(), tier.getMaximumBonusLore()); List<String> chosenLore = new ArrayList<>(); for (int i = 0; i < numOfBonusLore; i++) { if (tier.getBonusLore() == null || tier.getBonusLore().isEmpty() || chosenLore.size() == tier .getBonusLore().size()) { continue; } // choose a random String out of the tier's bonus lore String s = tier.getBonusLore().get(RandomUtils.nextInt(tier.getBonusLore().size())); if (chosenLore.contains(s)) { i--; continue; } chosenLore.add(s); // split on the next line \n String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n"); // add to lore by wrapping in Arrays.asList(Object...) lore.addAll(Arrays.asList(strings)); } if (MythicDropsPlugin.getInstance().getSockettingSettings().isEnabled() && RandomUtils.nextDouble() < tier .getChanceToHaveSockets()) { int numberOfSockets = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumSockets(), tier.getMaximumSockets()); for (int i = 0; i < numberOfSockets; i++) { lore.add(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemString().replace ('&', '\u00A7').replace("\u00A7\u00A7", "&")); } if (numberOfSockets > 0) { - lore.addAll(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemLore()); + for (String s : MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemLore()) { + lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&")); + } } } return lore; } private String getEnchantmentTypeName(ItemStack itemStack) { Enchantment enchantment = ItemStackUtil.getHighestEnchantment(itemStack); if (enchantment == null) { return MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString("displayNames" + ".Ordinary"); } String ench = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString("displayNames." + enchantment.getName()); if (ench != null) { return ench; } return "Ordinary"; } private String getMythicMaterialName(MaterialData matData) { String comb = String.format("%s;%s", String.valueOf(matData.getItemTypeId()), String.valueOf(matData.getData())); String comb2; if (matData.getData() == (byte) 0) { comb2 = String.valueOf(matData.getItemTypeId()); } else { comb2 = comb; } String mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + comb.toLowerCase()); if (mythicMatName == null || mythicMatName.equals("displayNames." + comb.toLowerCase())) { mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + comb2.toLowerCase()); if (mythicMatName == null || mythicMatName.equals("displayNames." + comb2.toLowerCase())) { mythicMatName = getMinecraftMaterialName(matData.getItemType()); } } return WordUtils.capitalize(mythicMatName); } private String getMinecraftMaterialName(Material material) { String prettyMaterialName = ""; String matName = material.name(); String[] split = matName.split("_"); for (String s : split) { if (s.equals(split[split.length - 1])) { prettyMaterialName = String .format("%s%s%s", prettyMaterialName, s.substring(0, 1).toUpperCase(), s.substring(1, s.length()).toLowerCase()); } else { prettyMaterialName = prettyMaterialName + (String.format("%s%s", s.substring(0, 1).toUpperCase(), s.substring(1, s.length()).toLowerCase())) + " "; } } return WordUtils.capitalizeFully(prettyMaterialName); } private String getItemTypeName(String itemType) { if (itemType == null) { return null; } String mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + itemType.toLowerCase()); if (mythicMatName == null) { mythicMatName = itemType; } return WordUtils.capitalizeFully(mythicMatName); } private String getItemTypeFromMaterialData(MaterialData matData) { String comb = String.format("%s;%s", String.valueOf(matData.getItemTypeId()), String.valueOf(matData.getData())); String comb2; if (matData.getData() == (byte) 0) { comb2 = String.valueOf(matData.getItemTypeId()); } else { comb2 = comb; } String comb3 = String.valueOf(matData.getItemTypeId()); Map<String, List<String>> ids = new HashMap<String, List<String>>(); ids.putAll(MythicDropsPlugin.getInstance().getConfigSettings().getItemTypesWithIds()); for (Map.Entry<String, List<String>> e : ids.entrySet()) { if (e.getValue().contains(comb) || e.getValue().contains(comb2) || e.getValue().contains(comb3)) { if (MythicDropsPlugin.getInstance().getConfigSettings().getMaterialTypes().contains(e.getKey())) { continue; } return e.getKey(); } } return null; } private String generateName(ItemStack itemStack) { Validate.notNull(itemStack, "ItemStack cannot be null"); Validate.notNull(tier, "Tier cannot be null"); String format = MythicDropsPlugin.getInstance().getConfigSettings().getItemDisplayNameFormat(); if (format == null) { return "Mythic Item"; } String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String generalPrefix = NameMap.getInstance().getRandom(NameType.GENERAL_PREFIX, ""); String generalSuffix = NameMap.getInstance().getRandom(NameType.GENERAL_SUFFIX, ""); String materialPrefix = NameMap.getInstance().getRandom(NameType.MATERIAL_PREFIX, itemStack.getType().name()); String materialSuffix = NameMap.getInstance().getRandom(NameType.MATERIAL_SUFFIX, itemStack.getType().name()); String tierPrefix = NameMap.getInstance().getRandom(NameType.TIER_PREFIX, tier.getName()); String tierSuffix = NameMap.getInstance().getRandom(NameType.TIER_SUFFIX, tier.getName()); String itemType = ItemUtil.getItemTypeFromMaterialData(itemStack.getData()); String materialType = ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData()); String tierName = tier.getDisplayName(); String enchantment = getEnchantmentTypeName(itemStack); Enchantment highestEnch = ItemStackUtil.getHighestEnchantment(itemStack.getItemMeta()); String enchantmentPrefix = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_PREFIX, highestEnch != null ? highestEnch.getName() : ""); String enchantmentSuffix = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_SUFFIX, highestEnch != null ? highestEnch.getName() : ""); String name = format; if (name.contains("%basematerial%")) { name = name.replace("%basematerial%", minecraftName); } if (name.contains("%mythicmaterial%")) { name = name.replace("%mythicmaterial%", mythicName); } if (name.contains("%generalprefix%")) { name = name.replace("%generalprefix%", generalPrefix); } if (name.contains("%generalsuffix%")) { name = name.replace("%generalsuffix%", generalSuffix); } if (name.contains("%materialprefix%")) { name = name.replace("%materialprefix%", materialPrefix); } if (name.contains("%materialsuffix%")) { name = name.replace("%materialsuffix%", materialSuffix); } if (name.contains("%tierprefix%")) { name = name.replace("%tierprefix%", tierPrefix); } if (name.contains("%tiersuffix%")) { name = name.replace("%tiersuffix%", tierSuffix); } if (name.contains("%itemtype%")) { name = name.replace("%itemtype%", itemType); } if (name.contains("%materialtype%")) { name = name.replace("%materialtype%", materialType); } if (name.contains("%tiername%")) { name = name.replace("%tiername%", tierName); } if (name.contains("%enchantment%")) { name = name.replace("%enchantment%", enchantment); } if (name.contains("%enchantmentprefix%")) { name = name.replace("%enchantmentprefix%", enchantmentPrefix); } if (name.contains("%enchantmentsuffix%")) { name = name.replace("%enchantmentsuffix%", enchantmentSuffix); } return tier.getDisplayColor() + name.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").trim() + tier.getIdentificationColor(); } }
true
true
private List<String> generateLore(ItemStack itemStack) { List<String> lore = new ArrayList<String>(); if (itemStack == null || tier == null) { return lore; } List<String> tooltipFormat = MythicDropsPlugin.getInstance().getConfigSettings().getTooltipFormat(); String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String itemType = getItemTypeName(ItemUtil.getItemTypeFromMaterialData(itemStack.getData())); String materialType = getItemTypeName(ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData())); String tierName = tier.getDisplayName(); String enchantment = getEnchantmentTypeName(itemStack); if (MythicDropsPlugin.getInstance().getConfigSettings().isRandomLoreEnabled() && RandomUtils.nextDouble() < MythicDropsPlugin.getInstance().getConfigSettings().getRandomLoreChance()) { String generalLoreString = NameMap.getInstance().getRandom(NameType.GENERAL_LORE, ""); String materialLoreString = NameMap.getInstance().getRandom(NameType.MATERIAL_LORE, itemStack.getType().name()); String tierLoreString = NameMap.getInstance().getRandom(NameType.TIER_LORE, tier.getName()); String enchantmentLoreString = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_LORE, enchantment != null ? enchantment : ""); List<String> generalLore = null; if (generalLoreString != null && !generalLoreString.isEmpty()) { generalLore = Arrays.asList(generalLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> materialLore = null; if (materialLoreString != null && !materialLoreString.isEmpty()) { materialLore = Arrays.asList(materialLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> tierLore = null; if (tierLoreString != null && !tierLoreString.isEmpty()) { tierLore = Arrays.asList(tierLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> enchantmentLore = null; if (enchantmentLoreString != null && !enchantmentLoreString.isEmpty()) { enchantmentLore = Arrays.asList(enchantmentLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } if (generalLore != null && !generalLore.isEmpty()) { lore.addAll(generalLore); } if (materialLore != null && !materialLore.isEmpty()) { lore.addAll(materialLore); } if (tierLore != null && !tierLore.isEmpty()) { lore.addAll(tierLore); } if (enchantmentLore != null && !enchantmentLore.isEmpty()) { lore.addAll(enchantmentLore); } } for (String s : tooltipFormat) { String line = s; line = line.replace("%basematerial%", minecraftName != null ? minecraftName : ""); line = line.replace("%mythicmaterial%", mythicName != null ? mythicName : ""); line = line.replace("%itemtype%", itemType != null ? itemType : ""); line = line.replace("%materialtype%", materialType != null ? materialType : ""); line = line.replace("%tiername%", tierName != null ? tierName : ""); line = line.replace("%enchantment%", enchantment != null ? enchantment : ""); line = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"); lore.add(line); } for (String s : tier.getBaseLore()) { String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n"); lore.addAll(Arrays.asList(strings)); } int numOfBonusLore = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumBonusLore(), tier.getMaximumBonusLore()); List<String> chosenLore = new ArrayList<>(); for (int i = 0; i < numOfBonusLore; i++) { if (tier.getBonusLore() == null || tier.getBonusLore().isEmpty() || chosenLore.size() == tier .getBonusLore().size()) { continue; } // choose a random String out of the tier's bonus lore String s = tier.getBonusLore().get(RandomUtils.nextInt(tier.getBonusLore().size())); if (chosenLore.contains(s)) { i--; continue; } chosenLore.add(s); // split on the next line \n String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n"); // add to lore by wrapping in Arrays.asList(Object...) lore.addAll(Arrays.asList(strings)); } if (MythicDropsPlugin.getInstance().getSockettingSettings().isEnabled() && RandomUtils.nextDouble() < tier .getChanceToHaveSockets()) { int numberOfSockets = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumSockets(), tier.getMaximumSockets()); for (int i = 0; i < numberOfSockets; i++) { lore.add(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemString().replace ('&', '\u00A7').replace("\u00A7\u00A7", "&")); } if (numberOfSockets > 0) { lore.addAll(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemLore()); } } return lore; }
private List<String> generateLore(ItemStack itemStack) { List<String> lore = new ArrayList<String>(); if (itemStack == null || tier == null) { return lore; } List<String> tooltipFormat = MythicDropsPlugin.getInstance().getConfigSettings().getTooltipFormat(); String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String itemType = getItemTypeName(ItemUtil.getItemTypeFromMaterialData(itemStack.getData())); String materialType = getItemTypeName(ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData())); String tierName = tier.getDisplayName(); String enchantment = getEnchantmentTypeName(itemStack); if (MythicDropsPlugin.getInstance().getConfigSettings().isRandomLoreEnabled() && RandomUtils.nextDouble() < MythicDropsPlugin.getInstance().getConfigSettings().getRandomLoreChance()) { String generalLoreString = NameMap.getInstance().getRandom(NameType.GENERAL_LORE, ""); String materialLoreString = NameMap.getInstance().getRandom(NameType.MATERIAL_LORE, itemStack.getType().name()); String tierLoreString = NameMap.getInstance().getRandom(NameType.TIER_LORE, tier.getName()); String enchantmentLoreString = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_LORE, enchantment != null ? enchantment : ""); List<String> generalLore = null; if (generalLoreString != null && !generalLoreString.isEmpty()) { generalLore = Arrays.asList(generalLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> materialLore = null; if (materialLoreString != null && !materialLoreString.isEmpty()) { materialLore = Arrays.asList(materialLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> tierLore = null; if (tierLoreString != null && !tierLoreString.isEmpty()) { tierLore = Arrays.asList(tierLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } List<String> enchantmentLore = null; if (enchantmentLoreString != null && !enchantmentLoreString.isEmpty()) { enchantmentLore = Arrays.asList(enchantmentLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n")); } if (generalLore != null && !generalLore.isEmpty()) { lore.addAll(generalLore); } if (materialLore != null && !materialLore.isEmpty()) { lore.addAll(materialLore); } if (tierLore != null && !tierLore.isEmpty()) { lore.addAll(tierLore); } if (enchantmentLore != null && !enchantmentLore.isEmpty()) { lore.addAll(enchantmentLore); } } for (String s : tooltipFormat) { String line = s; line = line.replace("%basematerial%", minecraftName != null ? minecraftName : ""); line = line.replace("%mythicmaterial%", mythicName != null ? mythicName : ""); line = line.replace("%itemtype%", itemType != null ? itemType : ""); line = line.replace("%materialtype%", materialType != null ? materialType : ""); line = line.replace("%tiername%", tierName != null ? tierName : ""); line = line.replace("%enchantment%", enchantment != null ? enchantment : ""); line = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"); lore.add(line); } for (String s : tier.getBaseLore()) { String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n"); lore.addAll(Arrays.asList(strings)); } int numOfBonusLore = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumBonusLore(), tier.getMaximumBonusLore()); List<String> chosenLore = new ArrayList<>(); for (int i = 0; i < numOfBonusLore; i++) { if (tier.getBonusLore() == null || tier.getBonusLore().isEmpty() || chosenLore.size() == tier .getBonusLore().size()) { continue; } // choose a random String out of the tier's bonus lore String s = tier.getBonusLore().get(RandomUtils.nextInt(tier.getBonusLore().size())); if (chosenLore.contains(s)) { i--; continue; } chosenLore.add(s); // split on the next line \n String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("\n"); // add to lore by wrapping in Arrays.asList(Object...) lore.addAll(Arrays.asList(strings)); } if (MythicDropsPlugin.getInstance().getSockettingSettings().isEnabled() && RandomUtils.nextDouble() < tier .getChanceToHaveSockets()) { int numberOfSockets = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumSockets(), tier.getMaximumSockets()); for (int i = 0; i < numberOfSockets; i++) { lore.add(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemString().replace ('&', '\u00A7').replace("\u00A7\u00A7", "&")); } if (numberOfSockets > 0) { for (String s : MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemLore()) { lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&")); } } } return lore; }
diff --git a/samples/RSSReader/src/com/example/android/rssreader/RssReader.java b/samples/RSSReader/src/com/example/android/rssreader/RssReader.java index 2f273c40..b3772bc0 100644 --- a/samples/RSSReader/src/com/example/android/rssreader/RssReader.java +++ b/samples/RSSReader/src/com/example/android/rssreader/RssReader.java @@ -1,599 +1,599 @@ /* * Copyright (C) 2007 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.example.android.rssreader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.TwoLineListItem; import android.util.Xml; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; /** * The RssReader example demonstrates forking off a thread to download * rss data in the background and post the results to a ListView in the UI. * It also shows how to display custom data in a ListView * with a ArrayAdapter subclass. * * <ul> * <li>We own a ListView * <li>The ListView uses our custom RSSListAdapter which * <ul> * <li>The adapter feeds data to the ListView * <li>Override of getView() in the adapter provides the display view * used for selected list items * </ul> * <li>Override of onListItemClick() creates an intent to open the url for that * RssItem in the browser. * <li>Download = fork off a worker thread * <li>The worker thread opens a network connection for the rss data * <li>Uses XmlPullParser to extract the rss item data * <li>Uses mHandler.post() to send new RssItems to the UI * <li>Supports onSaveInstanceState()/onRestoreInstanceState() to save list/selection state on app * pause, so can resume seamlessly * </ul> */ public class RssReader extends ListActivity { /** * Custom list adapter that fits our rss data into the list. */ private RSSListAdapter mAdapter; /** * Url edit text field. */ private EditText mUrlText; /** * Status text field. */ private TextView mStatusText; /** * Handler used to post runnables to the UI thread. */ private Handler mHandler; /** * Currently running background network thread. */ private RSSWorker mWorker; // Take this many chars from the front of the description. public static final int SNIPPET_LENGTH = 90; // Keys used for data in the onSaveInstanceState() Map. public static final String STRINGS_KEY = "strings"; public static final String SELECTION_KEY = "selection"; public static final String URL_KEY = "url"; public static final String STATUS_KEY = "status"; /** * Called when the activity starts up. Do activity initialization * here, not in a constructor. * * @see Activity#onCreate */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rss_layout); // The above layout contains a list id "android:list" // which ListActivity adopts as its list -- we can // access it with getListView(). // Install our custom RSSListAdapter. List<RssItem> items = new ArrayList<RssItem>(); mAdapter = new RSSListAdapter(this, items); getListView().setAdapter(mAdapter); // Get pointers to the UI elements in the rss_layout mUrlText = (EditText)findViewById(R.id.urltext); mStatusText = (TextView)findViewById(R.id.statustext); Button download = (Button)findViewById(R.id.download); download.setOnClickListener(new OnClickListener() { public void onClick(View v) { doRSS(mUrlText.getText()); } }); // Need one of these to post things back to the UI thread. mHandler = new Handler(); // NOTE: this could use the icicle as done in // onRestoreInstanceState(). } /** * ArrayAdapter encapsulates a java.util.List of T, for presentation in a * ListView. This subclass specializes it to hold RssItems and display * their title/description data in a TwoLineListItem. */ private class RSSListAdapter extends ArrayAdapter<RssItem> { private LayoutInflater mInflater; public RSSListAdapter(Context context, List<RssItem> objects) { super(context, 0, objects); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * This is called to render a particular item for the on screen list. * Uses an off-the-shelf TwoLineListItem view, which contains text1 and * text2 TextViews. We pull data from the RssItem and set it into the * view. The convertView is the view from a previous getView(), so * we can re-use it. * * @see ArrayAdapter#getView */ @Override public View getView(int position, View convertView, ViewGroup parent) { TwoLineListItem view; // Here view may be passed in for re-use, or we make a new one. if (convertView == null) { view = (TwoLineListItem) mInflater.inflate(android.R.layout.simple_list_item_2, null); } else { view = (TwoLineListItem) convertView; } RssItem item = this.getItem(position); // Set the item title and description into the view. // This example does not render real HTML, so as a hack to make // the description look better, we strip out the // tags and take just the first SNIPPET_LENGTH chars. view.getText1().setText(item.getTitle()); String descr = item.getDescription().toString(); descr = removeTags(descr); view.getText2().setText(descr.substring(0, Math.min(descr.length(), SNIPPET_LENGTH))); return view; } } /** * Simple code to strip out <tag>s -- primitive way to sortof display HTML as * plain text. */ public String removeTags(String str) { str = str.replaceAll("<.*?>", " "); str = str.replaceAll("\\s+", " "); return str; } /** * Called when user clicks an item in the list. Starts an activity to * open the url for that item. */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { RssItem item = mAdapter.getItem(position); // Creates and starts an intent to open the item.link url. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getLink().toString())); startActivity(intent); } /** * Resets the output UI -- list and status text empty. */ public void resetUI() { // Reset the list to be empty. List<RssItem> items = new ArrayList<RssItem>(); mAdapter = new RSSListAdapter(this, items); getListView().setAdapter(mAdapter); mStatusText.setText(""); mUrlText.requestFocus(); } /** * Sets the currently active running worker. Interrupts any earlier worker, * so we only have one at a time. * * @param worker the new worker */ public synchronized void setCurrentWorker(RSSWorker worker) { if (mWorker != null) mWorker.interrupt(); mWorker = worker; } /** * Is the given worker the currently active one. * * @param worker * @return */ public synchronized boolean isCurrentWorker(RSSWorker worker) { return (mWorker == worker); } /** * Given an rss url string, starts the rss-download-thread going. * * @param rssUrl */ private void doRSS(CharSequence rssUrl) { RSSWorker worker = new RSSWorker(rssUrl); setCurrentWorker(worker); resetUI(); mStatusText.setText("Downloading\u2026"); worker.start(); } /** * Runnable that the worker thread uses to post RssItems to the * UI via mHandler.post */ private class ItemAdder implements Runnable { RssItem mItem; ItemAdder(RssItem item) { mItem = item; } public void run() { mAdapter.add(mItem); } // NOTE: Performance idea -- would be more efficient to have he option // to add multiple items at once, so you get less "update storm" in the UI // compared to adding things one at a time. } /** * Worker thread takes in an rss url string, downloads its data, parses * out the rss items, and communicates them back to the UI as they are read. */ private class RSSWorker extends Thread { private CharSequence mUrl; public RSSWorker(CharSequence url) { mUrl = url; } @Override public void run() { String status = ""; try { // Standard code to make an HTTP connection. URL url = new URL(mUrl.toString()); URLConnection connection = url.openConnection(); connection.setConnectTimeout(10000); connection.connect(); InputStream in = connection.getInputStream(); parseRSS(in, mAdapter); status = "done"; } catch (Exception e) { status = "failed:" + e.getMessage(); } // Send status to UI (unless a newer worker has started) // To communicate back to the UI from a worker thread, // pass a Runnable to handler.post(). final String temp = status; if (isCurrentWorker(this)) { mHandler.post(new Runnable() { public void run() { mStatusText.setText(temp); } }); } } } /** * Populates the menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, 0, 0, "Slashdot") .setOnMenuItemClickListener(new RSSMenu("http://rss.slashdot.org/Slashdot/slashdot")); menu.add(0, 0, 0, "Google News") .setOnMenuItemClickListener(new RSSMenu("http://news.google.com/?output=rss")); menu.add(0, 0, 0, "News.com") .setOnMenuItemClickListener(new RSSMenu("http://news.com.com/2547-1_3-0-20.xml")); menu.add(0, 0, 0, "Bad Url") .setOnMenuItemClickListener(new RSSMenu("http://nifty.stanford.edu:8080")); menu.add(0, 0, 0, "Reset") .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { resetUI(); return true; } }); return true; } /** * Puts text in the url text field and gives it focus. Used to make a Runnable * for each menu item. This way, one inner class works for all items vs. an * anonymous inner class for each menu item. */ private class RSSMenu implements MenuItem.OnMenuItemClickListener { private CharSequence mUrl; RSSMenu(CharSequence url) { mUrl = url; } public boolean onMenuItemClick(MenuItem item) { mUrlText.setText(mUrl); mUrlText.requestFocus(); return true; } } /** * Called for us to save out our current state before we are paused, * such a for example if the user switches to another app and memory * gets scarce. The given outState is a Bundle to which we can save * objects, such as Strings, Integers or lists of Strings. In this case, we * save out the list of currently downloaded rss data, (so we don't have to * re-do all the networking just because the user goes back and forth * between aps) which item is currently selected, and the data for the text views. * In onRestoreInstanceState() we look at the map to reconstruct the run-state of the * application, so returning to the activity looks seamlessly correct. * TODO: the Activity javadoc should give more detail about what sort of * data can go in the outState map. * * @see android.app.Activity#onSaveInstanceState */ @SuppressWarnings("unchecked") @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Make a List of all the RssItem data for saving // NOTE: there may be a way to save the RSSItems directly, // rather than their string data. int count = mAdapter.getCount(); // Save out the items as a flat list of CharSequence objects -- // title0, link0, descr0, title1, link1, ... ArrayList<CharSequence> strings = new ArrayList<CharSequence>(); for (int i = 0; i < count; i++) { RssItem item = mAdapter.getItem(i); strings.add(item.getTitle()); strings.add(item.getLink()); strings.add(item.getDescription()); } outState.putSerializable(STRINGS_KEY, strings); // Save current selection index (if focussed) if (getListView().hasFocus()) { outState.putInt(SELECTION_KEY, Integer.valueOf(getListView().getSelectedItemPosition())); } // Save url outState.putString(URL_KEY, mUrlText.getText().toString()); // Save status outState.putCharSequence(STATUS_KEY, mStatusText.getText()); } /** * Called to "thaw" re-animate the app from a previous onSaveInstanceState(). * * @see android.app.Activity#onRestoreInstanceState */ @SuppressWarnings("unchecked") @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); // Note: null is a legal value for onRestoreInstanceState. if (state == null) return; // Restore items from the big list of CharSequence objects List<CharSequence> strings = (ArrayList<CharSequence>)state.getSerializable(STRINGS_KEY); List<RssItem> items = new ArrayList<RssItem>(); for (int i = 0; i < strings.size(); i += 3) { items.add(new RssItem(strings.get(i), strings.get(i + 1), strings.get(i + 2))); } // Reset the list view to show this data. mAdapter = new RSSListAdapter(this, items); getListView().setAdapter(mAdapter); // Restore selection if (state.containsKey(SELECTION_KEY)) { getListView().requestFocus(View.FOCUS_FORWARD); // todo: is above right? needed it to work getListView().setSelection(state.getInt(SELECTION_KEY)); } // Restore url mUrlText.setText(state.getCharSequence(URL_KEY)); // Restore status mStatusText.setText(state.getCharSequence(STATUS_KEY)); } /** * Does rudimentary RSS parsing on the given stream and posts rss items to * the UI as they are found. Uses Android's XmlPullParser facility. This is * not a production quality RSS parser -- it just does a basic job of it. * * @param in stream to read * @param adapter adapter for ui events */ void parseRSS(InputStream in, RSSListAdapter adapter) throws IOException, XmlPullParserException { // TODO: switch to sax XmlPullParser xpp = Xml.newPullParser(); - xpp.setInput(in, null); // null = parser figures out encoding + xpp.setInput(in, null); // null = default to UTF-8 int eventType; String title = ""; String link = ""; String description = ""; eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { String tag = xpp.getName(); if (tag.equals("item")) { title = link = description = ""; } else if (tag.equals("title")) { xpp.next(); // Skip to next element -- assume text is directly inside the tag title = xpp.getText(); } else if (tag.equals("link")) { xpp.next(); link = xpp.getText(); } else if (tag.equals("description")) { xpp.next(); description = xpp.getText(); } } else if (eventType == XmlPullParser.END_TAG) { // We have a comlete item -- post it back to the UI // using the mHandler (necessary because we are not // running on the UI thread). String tag = xpp.getName(); if (tag.equals("item")) { RssItem item = new RssItem(title, link, description); mHandler.post(new ItemAdder(item)); } } eventType = xpp.next(); } } // SAX version of the code to do the parsing. /* private class RSSHandler extends DefaultHandler { RSSListAdapter mAdapter; String mTitle; String mLink; String mDescription; StringBuilder mBuff; boolean mInItem; public RSSHandler(RSSListAdapter adapter) { mAdapter = adapter; mInItem = false; mBuff = new StringBuilder(); } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { String tag = localName; if (tag.equals("")) tag = qName; // If inside <item>, clear out buff on each tag start if (mInItem) { mBuff.delete(0, mBuff.length()); } if (tag.equals("item")) { mTitle = mLink = mDescription = ""; mInItem = true; } } public void characters(char[] ch, int start, int length) throws SAXException { // Buffer up all the chars when inside <item> if (mInItem) mBuff.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { String tag = localName; if (tag.equals("")) tag = qName; // For each tag, copy buff chars to right variable if (tag.equals("title")) mTitle = mBuff.toString(); else if (tag.equals("link")) mLink = mBuff.toString(); if (tag.equals("description")) mDescription = mBuff.toString(); // Have all the data at this point .... post it to the UI. if (tag.equals("item")) { RssItem item = new RssItem(mTitle, mLink, mDescription); mHandler.post(new ItemAdder(item)); mInItem = false; } } } */ /* public void parseRSS2(InputStream in, RSSListAdapter adapter) throws IOException { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); DefaultHandler handler = new RSSHandler(adapter); parser.parse(in, handler); // TODO: does the parser figure out the encoding right on its own? } */ }
true
true
void parseRSS(InputStream in, RSSListAdapter adapter) throws IOException, XmlPullParserException { // TODO: switch to sax XmlPullParser xpp = Xml.newPullParser(); xpp.setInput(in, null); // null = parser figures out encoding int eventType; String title = ""; String link = ""; String description = ""; eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { String tag = xpp.getName(); if (tag.equals("item")) { title = link = description = ""; } else if (tag.equals("title")) { xpp.next(); // Skip to next element -- assume text is directly inside the tag title = xpp.getText(); } else if (tag.equals("link")) { xpp.next(); link = xpp.getText(); } else if (tag.equals("description")) { xpp.next(); description = xpp.getText(); } } else if (eventType == XmlPullParser.END_TAG) { // We have a comlete item -- post it back to the UI // using the mHandler (necessary because we are not // running on the UI thread). String tag = xpp.getName(); if (tag.equals("item")) { RssItem item = new RssItem(title, link, description); mHandler.post(new ItemAdder(item)); } } eventType = xpp.next(); } }
void parseRSS(InputStream in, RSSListAdapter adapter) throws IOException, XmlPullParserException { // TODO: switch to sax XmlPullParser xpp = Xml.newPullParser(); xpp.setInput(in, null); // null = default to UTF-8 int eventType; String title = ""; String link = ""; String description = ""; eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { String tag = xpp.getName(); if (tag.equals("item")) { title = link = description = ""; } else if (tag.equals("title")) { xpp.next(); // Skip to next element -- assume text is directly inside the tag title = xpp.getText(); } else if (tag.equals("link")) { xpp.next(); link = xpp.getText(); } else if (tag.equals("description")) { xpp.next(); description = xpp.getText(); } } else if (eventType == XmlPullParser.END_TAG) { // We have a comlete item -- post it back to the UI // using the mHandler (necessary because we are not // running on the UI thread). String tag = xpp.getName(); if (tag.equals("item")) { RssItem item = new RssItem(title, link, description); mHandler.post(new ItemAdder(item)); } } eventType = xpp.next(); } }
diff --git a/sip-servlets-tomcat-jboss4/src/main/java/org/jboss/web/tomcat/service/session/JBossCacheClusteredSipApplicationSession.java b/sip-servlets-tomcat-jboss4/src/main/java/org/jboss/web/tomcat/service/session/JBossCacheClusteredSipApplicationSession.java index c0d5f591b..c9c4f0b33 100644 --- a/sip-servlets-tomcat-jboss4/src/main/java/org/jboss/web/tomcat/service/session/JBossCacheClusteredSipApplicationSession.java +++ b/sip-servlets-tomcat-jboss4/src/main/java/org/jboss/web/tomcat/service/session/JBossCacheClusteredSipApplicationSession.java @@ -1,207 +1,209 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.web.tomcat.service.session; import java.util.Map.Entry; import java.util.concurrent.CopyOnWriteArraySet; import org.apache.log4j.Logger; import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey; import org.mobicents.servlet.sip.core.session.SipSessionKey; import org.mobicents.servlet.sip.startup.SipContext; /** * Common superclass of ClusteredSipApplicationSession types that use JBossCache * as their distributed cache. * * @author <A HREF="mailto:[email protected]">Jean Deruelle</A> * */ public abstract class JBossCacheClusteredSipApplicationSession extends ClusteredSipApplicationSession { private static transient final Logger logger = Logger.getLogger(JBossCacheClusteredSipApplicationSession.class); /** * Our proxy to the cache. */ protected transient ConvergedJBossCacheService proxy_; protected JBossCacheClusteredSipApplicationSession(SipApplicationSessionKey key, SipContext sipContext) { super(key, sipContext, ((JBossCacheSipManager)sipContext.getSipManager()).getUseJK()); int maxUnrep = ((JBossCacheSipManager)sipContext.getSipManager()).getMaxUnreplicatedInterval() * 1000; setMaxUnreplicatedInterval(maxUnrep); establishProxy(); } /** * Initialize fields marked as transient after loading this session from the * distributed store * * @param manager * the manager for this session */ public void initAfterLoad(JBossCacheSipManager manager) { sipContext = (SipContext) manager.getContainer(); establishProxy(); populateMetaData(); // Since attribute map may be transient, we may need to populate it // from the underlying store. populateAttributes(); // Notify all attributes of type SipApplicationSessionActivationListener this.activate(); // We are no longer outdated vis a vis distributed cache clearOutdated(); } /** * Gets a reference to the JBossCacheService. */ protected void establishProxy() { if (proxy_ == null) { proxy_ = (ConvergedJBossCacheService)((JBossCacheSipManager) getSipContext().getSipManager()).getCacheService(); // still null??? if (proxy_ == null) { throw new RuntimeException( "JBossCacheClusteredSession: Cache service is null."); } } } protected abstract void populateAttributes(); /** * Override the superclass to additionally reset this class' fields. * <p> * <strong>NOTE:</strong> It is not anticipated that this method will be * called on a ClusteredSession, but we are overriding the method to be * thorough. * </p> */ // public void recycle() { // super.recycle(); // // proxy_ = null; // } protected void populateMetaData() { final String sipAppSessionId = getHaId(); Long ct = (Long) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, CREATION_TIME); if(ct != null) { creationTime = ct; } Integer ip = (Integer) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, INVALIDATION_POLICY); if(ip != null) { invalidationPolicy = ip; } Boolean valid = (Boolean) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, IS_VALID); if(valid != null) { setValid(valid); } sipSessions.clear(); SipSessionKey[] sipSessionKeys = (SipSessionKey[]) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, SIP_SESSIONS); - for (SipSessionKey sipSessionKey : sipSessionKeys) { - sipSessionKey.setApplicationName(proxy_.getSipApplicationName()); - sipSessionKey.setApplicationName(sipAppSessionId); - sipSessionKey.computeToString(); - sipSessions.add(sipSessionKey); - } + if(sipSessionKeys != null && sipSessionKeys.length > 0) { + for (SipSessionKey sipSessionKey : sipSessionKeys) { + sipSessionKey.setApplicationName(proxy_.getSipApplicationName()); + sipSessionKey.setApplicationName(sipAppSessionId); + sipSessionKey.computeToString(); + sipSessions.add(sipSessionKey); + } + } String[] httpSessionIds = (String[]) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, HTTP_SESSIONS); if(httpSessionIds != null && httpSessionIds.length > 0) { if(httpSessions == null) { httpSessions = new CopyOnWriteArraySet<String>(); } else { httpSessions.clear(); } for (String httpSessionId : httpSessionIds) { httpSessions.add(httpSessionId); } } isNew = false; } /** * Increment our version and place ourself in the cache. */ public void processSessionRepl() { // Replicate the session. if (logger.isDebugEnabled()) { logger.debug("processSessionRepl(): session is dirty. Will increment " + "version from: " + getVersion() + " and replicate."); } final String sipAppSessionKey = getHaId(); if(isNew) { proxy_.putSipApplicationSessionMetaData(sipAppSessionKey, CREATION_TIME, creationTime); proxy_.putSipApplicationSessionMetaData(sipAppSessionKey, INVALIDATION_POLICY, invalidationPolicy); isNew = false; } if(sessionMetadataDirty) { for (Entry<String, Object> entry : metaDataModifiedMap.entrySet()) { proxy_.putSipApplicationSessionMetaData(sipAppSessionKey, entry.getKey(), entry.getValue()); } metaDataModifiedMap.clear(); } if(sipSessionsMapModified) { proxy_.putSipApplicationSessionMetaData(sipAppSessionKey, SIP_SESSIONS, sipSessions.toArray(new SipSessionKey[sipSessions.size()])); sipSessionsMapModified = false; } if(httpSessionsMapModified) { proxy_.putSipApplicationSessionMetaData(sipAppSessionKey, HTTP_SESSIONS, httpSessions.toArray(new String[httpSessions.size()])); httpSessionsMapModified = false; } this.incrementVersion(); proxy_.putSipApplicationSession(sipAppSessionKey, this); sessionMetadataDirty = false; sessionAttributesDirty = false; sessionLastAccessTimeDirty = false; updateLastReplicated(); } /** * Overrides the superclass impl by doing nothing if <code>localCall</code> * is <code>false</code>. The JBossCacheManager will already be aware of a * remote invalidation and will handle removal itself. */ protected void removeFromManager(boolean localCall, boolean localOnly) { if (localCall) { super.removeFromManager(localCall, localOnly); } } protected Object removeAttributeInternal(String name, boolean localCall, boolean localOnly) { return removeJBossInternalAttribute(name, localCall, localOnly); } protected Object removeJBossInternalAttribute(String name) { throw new UnsupportedOperationException( "removeJBossInternalAttribute(String) " + "is not supported by JBossCacheClusteredSession; use " + "removeJBossInternalAttribute(String, boolean, boolean"); } protected abstract Object removeJBossInternalAttribute(String name, boolean localCall, boolean localOnly); }
true
true
protected void populateMetaData() { final String sipAppSessionId = getHaId(); Long ct = (Long) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, CREATION_TIME); if(ct != null) { creationTime = ct; } Integer ip = (Integer) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, INVALIDATION_POLICY); if(ip != null) { invalidationPolicy = ip; } Boolean valid = (Boolean) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, IS_VALID); if(valid != null) { setValid(valid); } sipSessions.clear(); SipSessionKey[] sipSessionKeys = (SipSessionKey[]) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, SIP_SESSIONS); for (SipSessionKey sipSessionKey : sipSessionKeys) { sipSessionKey.setApplicationName(proxy_.getSipApplicationName()); sipSessionKey.setApplicationName(sipAppSessionId); sipSessionKey.computeToString(); sipSessions.add(sipSessionKey); } String[] httpSessionIds = (String[]) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, HTTP_SESSIONS); if(httpSessionIds != null && httpSessionIds.length > 0) { if(httpSessions == null) { httpSessions = new CopyOnWriteArraySet<String>(); } else { httpSessions.clear(); } for (String httpSessionId : httpSessionIds) { httpSessions.add(httpSessionId); } } isNew = false; }
protected void populateMetaData() { final String sipAppSessionId = getHaId(); Long ct = (Long) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, CREATION_TIME); if(ct != null) { creationTime = ct; } Integer ip = (Integer) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, INVALIDATION_POLICY); if(ip != null) { invalidationPolicy = ip; } Boolean valid = (Boolean) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, IS_VALID); if(valid != null) { setValid(valid); } sipSessions.clear(); SipSessionKey[] sipSessionKeys = (SipSessionKey[]) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, SIP_SESSIONS); if(sipSessionKeys != null && sipSessionKeys.length > 0) { for (SipSessionKey sipSessionKey : sipSessionKeys) { sipSessionKey.setApplicationName(proxy_.getSipApplicationName()); sipSessionKey.setApplicationName(sipAppSessionId); sipSessionKey.computeToString(); sipSessions.add(sipSessionKey); } } String[] httpSessionIds = (String[]) proxy_.getSipApplicationSessionMetaData(sipAppSessionId, HTTP_SESSIONS); if(httpSessionIds != null && httpSessionIds.length > 0) { if(httpSessions == null) { httpSessions = new CopyOnWriteArraySet<String>(); } else { httpSessions.clear(); } for (String httpSessionId : httpSessionIds) { httpSessions.add(httpSessionId); } } isNew = false; }
diff --git a/client/src/es/deusto/weblab/client/lab/ui/themes/es/deusto/weblab/defaultweb/AllowedExperimentsWindow.java b/client/src/es/deusto/weblab/client/lab/ui/themes/es/deusto/weblab/defaultweb/AllowedExperimentsWindow.java index e662149ee..930a8794b 100644 --- a/client/src/es/deusto/weblab/client/lab/ui/themes/es/deusto/weblab/defaultweb/AllowedExperimentsWindow.java +++ b/client/src/es/deusto/weblab/client/lab/ui/themes/es/deusto/weblab/defaultweb/AllowedExperimentsWindow.java @@ -1,248 +1,248 @@ /* * Copyright (C) 2005 onwards University of Deusto * All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. * * This software consists of contributions made by many individuals, * listed below: * * Author: Pablo Orduña <[email protected]> * */ package es.deusto.weblab.client.lab.ui.themes.es.deusto.weblab.defaultweb; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.DisclosurePanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import es.deusto.weblab.client.HistoryProperties; import es.deusto.weblab.client.configuration.IConfigurationManager; import es.deusto.weblab.client.configuration.IConfigurationRetriever; import es.deusto.weblab.client.dto.experiments.ExperimentAllowed; import es.deusto.weblab.client.dto.users.User; import es.deusto.weblab.client.lab.experiments.ExperimentFactory; import es.deusto.weblab.client.ui.widgets.WlAHref; import es.deusto.weblab.client.ui.widgets.WlUtil; import es.deusto.weblab.client.ui.widgets.WlWaitingLabel; /** * Window that displays the list of allowed experiments for the logged in * user, and lets the user select one. */ class AllowedExperimentsWindow extends BaseWindow { interface MyUiBinder extends UiBinder<Widget, AllowedExperimentsWindow> {} private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); public interface IAllowedExperimentsWindowCallback { public boolean startedLoggedIn(); public void onLogoutButtonClicked(); public void onChooseExperimentButtonClicked(ExperimentAllowed experimentAllowed); } // Widgets @UiField Image logoImage; @UiField VerticalPanel containerPanel; @UiField Label userLabel; @UiField Anchor logoutLink; @UiField AbsolutePanel navigationPanel; @UiField Label contentTitleLabel; @UiField Grid experimentsTable; @UiField WlWaitingLabel waitingLabel; @UiField Label generalErrorLabel; @UiField Label separatorLabel; @UiField Label separatorLabel2; @UiField HorizontalPanel headerPanel; @UiField WlAHref institutionLink; // Callbacks private final IAllowedExperimentsWindowCallback callback; // DTOs private final User user; private Map<String, Map<ExperimentAllowed, IConfigurationRetriever>> experimentsAllowed; private ExperimentAllowed [] failedExperiments; public AllowedExperimentsWindow(IConfigurationManager configurationManager, User user, ExperimentAllowed[] experimentsAllowed, IAllowedExperimentsWindowCallback callback) { super(configurationManager); this.user = user; this.callback = callback; loadExperimentsAllowedConfigurations(experimentsAllowed); this.loadWidgets(); } private void loadExperimentsAllowedConfigurations(ExperimentAllowed [] experimentsAllowed) { final List<ExperimentAllowed> failedExperiments = new Vector<ExperimentAllowed>(); this.experimentsAllowed = new HashMap<String, Map<ExperimentAllowed, IConfigurationRetriever>>(); for(ExperimentAllowed experimentAllowed : experimentsAllowed) { // Try to retrieve the configuration for that experiment final IConfigurationRetriever retriever; try{ retriever = ExperimentFactory.getExperimentConfigurationRetriever(experimentAllowed.getExperiment().getExperimentUniqueName()); }catch(IllegalArgumentException e){ failedExperiments.add(experimentAllowed); e.printStackTrace(); continue; } // if not failed, then add it to the map final String category = experimentAllowed.getExperiment().getCategory().getCategory(); if(!this.experimentsAllowed .containsKey(category)) this.experimentsAllowed .put(category, new HashMap<ExperimentAllowed, IConfigurationRetriever>()); this.experimentsAllowed .get(category).put(experimentAllowed, retriever); } this.failedExperiments = failedExperiments.toArray(new ExperimentAllowed[]{}); } public ExperimentAllowed [] getFailedLoadingExperiments(){ return this.failedExperiments; } @Override public Widget getWidget(){ return this.containerPanel; } protected void loadWidgets(){ AllowedExperimentsWindow.uiBinder.createAndBindUi(this); final String hostEntityImage = this.configurationManager.getProperty(DefaultTheme.Configuration.HOST_ENTITY_IMAGE, ""); this.logoImage.setUrl(GWT.getModuleBaseURL() + hostEntityImage); final String hostEntityLink = this.configurationManager.getProperty(DefaultTheme.Configuration.HOST_ENTITY_LINK, ""); this.institutionLink.setHref(hostEntityLink); final boolean visibleHeader = HistoryProperties.getBooleanValue(HistoryProperties.HEADER_VISIBLE, true); this.headerPanel.setVisible(visibleHeader); this.navigationPanel.setVisible(visibleHeader); if(this.user != null) this.userLabel.setText(WlUtil.escapeNotQuote(this.user.getFullName())); final int INTENDED_COLUMNS = (80 * Window.getClientWidth() / 100) / 260; final int COLUMNS = this.experimentsAllowed.size() > INTENDED_COLUMNS? INTENDED_COLUMNS : this.experimentsAllowed.size(); this.experimentsTable.resize(this.experimentsAllowed.size() / COLUMNS + 1, COLUMNS); final List<String> categories = new Vector<String>(this.experimentsAllowed.keySet()); Collections.sort(categories); for(int i = 0; i < categories.size(); ++i) { final String category = categories.get(i); final List<ExperimentAllowed> categoryExperiments = new Vector<ExperimentAllowed>(this.experimentsAllowed.get(category).keySet()); Collections.sort(categoryExperiments); final Grid categoryGrid = new Grid(); categoryGrid.resize(categoryExperiments.size(), 2); categoryGrid.setWidth("100%"); for(int j = 0; j < categoryExperiments.size(); ++j) { final ExperimentAllowed experiment = categoryExperiments.get(j); ExperimentClickListener listener = new ExperimentClickListener(experiment); final Anchor nameLink = new Anchor(experiment.getExperiment().getName()); nameLink.addClickHandler(listener); IConfigurationRetriever retriever = this.experimentsAllowed.get(category).get(experiment); String picture = retriever.getProperty("experiment.picture", ""); if(picture.isEmpty()) picture = retriever.getProperty("experiments.default_picture", ""); if(picture.startsWith("/")) picture = GWT.getModuleBaseURL() + picture; final Image img = new Image(picture); img.setHeight("40px"); img.setStyleName("web-allowedexperiments-image"); img.addClickHandler(listener); categoryGrid.setWidget(j, 0, nameLink); categoryGrid.setWidget(j, 1, new SimplePanel(img)); categoryGrid.getCellFormatter().setHorizontalAlignment(j, 1, HasHorizontalAlignment.ALIGN_CENTER); } final DisclosurePanel categoryPanel = new DisclosurePanel(category); categoryPanel.add(categoryGrid); categoryPanel.setAnimationEnabled(true); categoryPanel.setOpen(true); categoryPanel.setWidth("250px"); categoryPanel.addStyleName("experiment-list-category-panel"); final SimplePanel decoratedCategoryPanel = new SimplePanel(categoryPanel); decoratedCategoryPanel.setWidth("250px"); decoratedCategoryPanel.addStyleName("experiment-list-category-container"); - this.experimentsTable.setWidget(i / COLUMNS, i % COLUMNS, categoryPanel); + this.experimentsTable.setWidget(i / COLUMNS, i % COLUMNS, decoratedCategoryPanel); this.experimentsTable.getCellFormatter().setVerticalAlignment(i / COLUMNS, i % COLUMNS, HasVerticalAlignment.ALIGN_TOP); } if(this.callback.startedLoggedIn()){ this.logoutLink.setVisible(false); this.separatorLabel.setVisible(false); this.separatorLabel2.setVisible(false); } } @Override public void showError(String message) { this.generalErrorLabel.setText(message); this.waitingLabel.stop(); this.waitingLabel.setText(""); } @Override public void showMessage(String message) { this.generalErrorLabel.setText(message); } @UiHandler("logoutLink") void onLogoutClicked(@SuppressWarnings("unused") ClickEvent ev) { this.callback.onLogoutButtonClicked(); } private class ExperimentClickListener implements ClickHandler { private final ExperimentAllowed experimentAllowed; public ExperimentClickListener(ExperimentAllowed experimentAllowed) { this.experimentAllowed = experimentAllowed; } @Override public void onClick(ClickEvent event) { AllowedExperimentsWindow.this.callback.onChooseExperimentButtonClicked(this.experimentAllowed); } } }
true
true
protected void loadWidgets(){ AllowedExperimentsWindow.uiBinder.createAndBindUi(this); final String hostEntityImage = this.configurationManager.getProperty(DefaultTheme.Configuration.HOST_ENTITY_IMAGE, ""); this.logoImage.setUrl(GWT.getModuleBaseURL() + hostEntityImage); final String hostEntityLink = this.configurationManager.getProperty(DefaultTheme.Configuration.HOST_ENTITY_LINK, ""); this.institutionLink.setHref(hostEntityLink); final boolean visibleHeader = HistoryProperties.getBooleanValue(HistoryProperties.HEADER_VISIBLE, true); this.headerPanel.setVisible(visibleHeader); this.navigationPanel.setVisible(visibleHeader); if(this.user != null) this.userLabel.setText(WlUtil.escapeNotQuote(this.user.getFullName())); final int INTENDED_COLUMNS = (80 * Window.getClientWidth() / 100) / 260; final int COLUMNS = this.experimentsAllowed.size() > INTENDED_COLUMNS? INTENDED_COLUMNS : this.experimentsAllowed.size(); this.experimentsTable.resize(this.experimentsAllowed.size() / COLUMNS + 1, COLUMNS); final List<String> categories = new Vector<String>(this.experimentsAllowed.keySet()); Collections.sort(categories); for(int i = 0; i < categories.size(); ++i) { final String category = categories.get(i); final List<ExperimentAllowed> categoryExperiments = new Vector<ExperimentAllowed>(this.experimentsAllowed.get(category).keySet()); Collections.sort(categoryExperiments); final Grid categoryGrid = new Grid(); categoryGrid.resize(categoryExperiments.size(), 2); categoryGrid.setWidth("100%"); for(int j = 0; j < categoryExperiments.size(); ++j) { final ExperimentAllowed experiment = categoryExperiments.get(j); ExperimentClickListener listener = new ExperimentClickListener(experiment); final Anchor nameLink = new Anchor(experiment.getExperiment().getName()); nameLink.addClickHandler(listener); IConfigurationRetriever retriever = this.experimentsAllowed.get(category).get(experiment); String picture = retriever.getProperty("experiment.picture", ""); if(picture.isEmpty()) picture = retriever.getProperty("experiments.default_picture", ""); if(picture.startsWith("/")) picture = GWT.getModuleBaseURL() + picture; final Image img = new Image(picture); img.setHeight("40px"); img.setStyleName("web-allowedexperiments-image"); img.addClickHandler(listener); categoryGrid.setWidget(j, 0, nameLink); categoryGrid.setWidget(j, 1, new SimplePanel(img)); categoryGrid.getCellFormatter().setHorizontalAlignment(j, 1, HasHorizontalAlignment.ALIGN_CENTER); } final DisclosurePanel categoryPanel = new DisclosurePanel(category); categoryPanel.add(categoryGrid); categoryPanel.setAnimationEnabled(true); categoryPanel.setOpen(true); categoryPanel.setWidth("250px"); categoryPanel.addStyleName("experiment-list-category-panel"); final SimplePanel decoratedCategoryPanel = new SimplePanel(categoryPanel); decoratedCategoryPanel.setWidth("250px"); decoratedCategoryPanel.addStyleName("experiment-list-category-container"); this.experimentsTable.setWidget(i / COLUMNS, i % COLUMNS, categoryPanel); this.experimentsTable.getCellFormatter().setVerticalAlignment(i / COLUMNS, i % COLUMNS, HasVerticalAlignment.ALIGN_TOP); } if(this.callback.startedLoggedIn()){ this.logoutLink.setVisible(false); this.separatorLabel.setVisible(false); this.separatorLabel2.setVisible(false); } }
protected void loadWidgets(){ AllowedExperimentsWindow.uiBinder.createAndBindUi(this); final String hostEntityImage = this.configurationManager.getProperty(DefaultTheme.Configuration.HOST_ENTITY_IMAGE, ""); this.logoImage.setUrl(GWT.getModuleBaseURL() + hostEntityImage); final String hostEntityLink = this.configurationManager.getProperty(DefaultTheme.Configuration.HOST_ENTITY_LINK, ""); this.institutionLink.setHref(hostEntityLink); final boolean visibleHeader = HistoryProperties.getBooleanValue(HistoryProperties.HEADER_VISIBLE, true); this.headerPanel.setVisible(visibleHeader); this.navigationPanel.setVisible(visibleHeader); if(this.user != null) this.userLabel.setText(WlUtil.escapeNotQuote(this.user.getFullName())); final int INTENDED_COLUMNS = (80 * Window.getClientWidth() / 100) / 260; final int COLUMNS = this.experimentsAllowed.size() > INTENDED_COLUMNS? INTENDED_COLUMNS : this.experimentsAllowed.size(); this.experimentsTable.resize(this.experimentsAllowed.size() / COLUMNS + 1, COLUMNS); final List<String> categories = new Vector<String>(this.experimentsAllowed.keySet()); Collections.sort(categories); for(int i = 0; i < categories.size(); ++i) { final String category = categories.get(i); final List<ExperimentAllowed> categoryExperiments = new Vector<ExperimentAllowed>(this.experimentsAllowed.get(category).keySet()); Collections.sort(categoryExperiments); final Grid categoryGrid = new Grid(); categoryGrid.resize(categoryExperiments.size(), 2); categoryGrid.setWidth("100%"); for(int j = 0; j < categoryExperiments.size(); ++j) { final ExperimentAllowed experiment = categoryExperiments.get(j); ExperimentClickListener listener = new ExperimentClickListener(experiment); final Anchor nameLink = new Anchor(experiment.getExperiment().getName()); nameLink.addClickHandler(listener); IConfigurationRetriever retriever = this.experimentsAllowed.get(category).get(experiment); String picture = retriever.getProperty("experiment.picture", ""); if(picture.isEmpty()) picture = retriever.getProperty("experiments.default_picture", ""); if(picture.startsWith("/")) picture = GWT.getModuleBaseURL() + picture; final Image img = new Image(picture); img.setHeight("40px"); img.setStyleName("web-allowedexperiments-image"); img.addClickHandler(listener); categoryGrid.setWidget(j, 0, nameLink); categoryGrid.setWidget(j, 1, new SimplePanel(img)); categoryGrid.getCellFormatter().setHorizontalAlignment(j, 1, HasHorizontalAlignment.ALIGN_CENTER); } final DisclosurePanel categoryPanel = new DisclosurePanel(category); categoryPanel.add(categoryGrid); categoryPanel.setAnimationEnabled(true); categoryPanel.setOpen(true); categoryPanel.setWidth("250px"); categoryPanel.addStyleName("experiment-list-category-panel"); final SimplePanel decoratedCategoryPanel = new SimplePanel(categoryPanel); decoratedCategoryPanel.setWidth("250px"); decoratedCategoryPanel.addStyleName("experiment-list-category-container"); this.experimentsTable.setWidget(i / COLUMNS, i % COLUMNS, decoratedCategoryPanel); this.experimentsTable.getCellFormatter().setVerticalAlignment(i / COLUMNS, i % COLUMNS, HasVerticalAlignment.ALIGN_TOP); } if(this.callback.startedLoggedIn()){ this.logoutLink.setVisible(false); this.separatorLabel.setVisible(false); this.separatorLabel2.setVisible(false); } }
diff --git a/src/gov/nih/nci/caintegrator/analysis/server/FTestTaskR.java b/src/gov/nih/nci/caintegrator/analysis/server/FTestTaskR.java index f5e769a..f60006f 100644 --- a/src/gov/nih/nci/caintegrator/analysis/server/FTestTaskR.java +++ b/src/gov/nih/nci/caintegrator/analysis/server/FTestTaskR.java @@ -1,247 +1,247 @@ package gov.nih.nci.caintegrator.analysis.server; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Vector; import org.apache.log4j.Logger; import org.rosuda.JRclient.REXP; import gov.nih.nci.caintegrator.analysis.messaging.AnalysisRequest; import gov.nih.nci.caintegrator.analysis.messaging.AnalysisResult; import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonResultEntry; import gov.nih.nci.caintegrator.analysis.messaging.CorrelationRequest; import gov.nih.nci.caintegrator.analysis.messaging.CorrelationResult; import gov.nih.nci.caintegrator.analysis.messaging.FTestRequest; import gov.nih.nci.caintegrator.analysis.messaging.FTestResult; import gov.nih.nci.caintegrator.analysis.messaging.FTestResultEntry; import gov.nih.nci.caintegrator.analysis.messaging.SampleGroup; import gov.nih.nci.caintegrator.enumeration.CorrelationType; import gov.nih.nci.caintegrator.enumeration.MultiGroupComparisonAdjustmentType; import gov.nih.nci.caintegrator.exceptions.AnalysisServerException; public class FTestTaskR extends AnalysisTaskR { private FTestResult result; private static Logger logger = Logger.getLogger(CorrelationTaskR.class); private Comparator ftComparator = new FTestComparator(); public FTestTaskR(AnalysisRequest request) { this(request, false); } public FTestTaskR(AnalysisRequest request, boolean debugRcommands) { super(request, debugRcommands); } @Override public void run() { FTestRequest ftRequest = (FTestRequest) getRequest(); result = new FTestResult(getRequest().getSessionId(), getRequest().getTaskId()); logger.info(getExecutingThreadName() + " processing FTestRequest request=" + ftRequest); try { String dataFileName = ftRequest.getDataFileName(); if (dataFileName != null) { setDataFile(ftRequest.getDataFileName()); } else { throw new AnalysisServerException("Null data file name"); } } catch (AnalysisServerException e) { e.setFailedRequest(ftRequest); logger.error("Internal Error. " + e.getMessage()); setException(e); return; } try { List<SampleGroup> sampleGroups = ftRequest.getSampleGroups(); SampleGroup grp = null; String cmd; String cmd2; String grpName = null; String bindCmd = "compMat <- cbind("; String matName = null; - String phenoCmd = "pheno <- cbind("; + String phenoCmd = "pheno <- as.factor(c("; result.setSampleGroups(sampleGroups); for (int i=0; i < sampleGroups.size(); i++) { grp = (SampleGroup)sampleGroups.get(i); grpName = "GRP" + i; cmd = getRgroupCmd(grpName, grp); doRvoidEval(cmd); matName = "M" + grpName; cmd = matName + " <- getSubmatrix.onegrp(dataMatrix," + grpName + ")"; doRvoidEval(cmd); bindCmd += matName; phenoCmd += "rep(" + i + "," + grp.size() + ")"; if (i < sampleGroups.size()-1) { bindCmd += ","; phenoCmd += ","; } else { bindCmd += ")"; - phenoCmd += ")"; + phenoCmd += "))"; } //to build pheno matrix use c(rep(i,grp.size()) //then outside the loop use pheno <- as.factor(pheno) } doRvoidEval(bindCmd); doRvoidEval(phenoCmd); //now call the Ftest function cmd ="ftResult <- Ftests(compMat,pheno)"; doRvoidEval(cmd); // do filtering String rCmd; double foldChangeThreshold = ftRequest.getFoldChangeThreshold(); double pValueThreshold = ftRequest.getPValueThreshold(); MultiGroupComparisonAdjustmentType adjMethod = ftRequest.getMultiGrpComparisonAdjType(); if (adjMethod == MultiGroupComparisonAdjustmentType.NONE) { // get differentially expressed reporters using // unadjusted Pvalue // shouldn't need to pass in ccInputMatrix rCmd = "ftResult <- mydiferentiallygenes(ftResult," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(false); } else if (adjMethod == MultiGroupComparisonAdjustmentType.FDR) { // do adjustment rCmd = "adjust.result <- adjustP.Benjamini.Hochberg(ftResult)"; doRvoidEval(rCmd); // get differentially expressed reporters using adjusted Pvalue rCmd = "ftResult <- mydiferentiallygenes.adjustP(adjust.result," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(true); } else if (adjMethod == MultiGroupComparisonAdjustmentType.FWER) { // do adjustment rCmd = "adjust.result <- adjustP.Bonferroni(ftResult)"; doRvoidEval(rCmd); // get differentially expresseed reporters using adjusted Pvalue rCmd = "ftResult <- mydiferentiallygenes.adjustP(adjust.result," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(true); } else { logger.error("FTest Adjustment Type unrecognized."); this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type.")); return; } //now extract the result // double[] meanGrp1 = doREval("mean1 <- ftResult[,1]").asDoubleArray(); // double[] meanBaselineGrp = doREval("meanBaseline <- ftResult[,2]").asDoubleArray(); // double[] meanDif = doREval("meanDif <- ftResult[,3]").asDoubleArray(); // double[] absoluteFoldChange = doREval("fc <- ftResult[,4]").asDoubleArray(); // double[] pva = doREval("pva <- ftResult[,5]").asDoubleArray(); double[][] grpMean = doREval("mean <- ftResult[,1:" + sampleGroups.size() + "]").asDoubleMatrix(); int index = sampleGroups.size() + 1; double[] maxFoldChange = doREval("maxFC <- ftResult[," + index + "]").asDoubleArray(); index++; double[] pval = doREval("pval <- ftResult[," + index + "]").asDoubleArray(); // get the labels Vector reporterIds = doREval("ftLabels <- dimnames(ftResult)[[1]]") .asVector(); // load the result object // need to see if this works for single group comparison List<FTestResultEntry> resultEntries = new ArrayList<FTestResultEntry>( maxFoldChange.length); FTestResultEntry resultEntry; int numEntries = maxFoldChange.length; for (int i = 0; i < numEntries; i++) { resultEntry = new FTestResultEntry(); resultEntry.setReporterId(((REXP) reporterIds.get(i)).asString()); //resultEntry.setMeanGrp1(meanGrp1[i]); for (int j=0; j < sampleGroups.size(); j++) { resultEntry.setGroupAverage(j, grpMean[i][j]); } resultEntry.setMaximumFoldChange(maxFoldChange[i]); resultEntry.setPvalue(pval[i]); resultEntries.add(resultEntry); } Collections.sort(resultEntries, ftComparator); result.setResultEntries(resultEntries); //create the data matrix //computeMatrix //for (each group) { //submat[i] <- getSubmatrix(dataMatrix, groupIds[i]) //computeMatix <- cbind(submat[i]) //pheno <- as.factor(i,rep(length(group)[i]) //perform the FTest } catch (AnalysisServerException asex) { AnalysisServerException aex = new AnalysisServerException( "Problem computing correlation. Caught AnalysisServerException in CorrelationTaskR." + asex.getMessage()); aex.setFailedRequest(ftRequest); setException(aex); return; } catch (Exception ex) { AnalysisServerException asex = new AnalysisServerException( "Internal Error. Caught Exception in CorrelationTaskR exClass=" + ex.getClass() + " msg=" + ex.getMessage()); asex.setFailedRequest(ftRequest); setException(asex); return; } } @Override public void cleanUp() { try { setRComputeConnection(null); } catch (AnalysisServerException e) { logger.error("Error in cleanUp method."); logger.error(e); setException(e); } } @Override public AnalysisResult getResult() { return result; } }
false
true
public void run() { FTestRequest ftRequest = (FTestRequest) getRequest(); result = new FTestResult(getRequest().getSessionId(), getRequest().getTaskId()); logger.info(getExecutingThreadName() + " processing FTestRequest request=" + ftRequest); try { String dataFileName = ftRequest.getDataFileName(); if (dataFileName != null) { setDataFile(ftRequest.getDataFileName()); } else { throw new AnalysisServerException("Null data file name"); } } catch (AnalysisServerException e) { e.setFailedRequest(ftRequest); logger.error("Internal Error. " + e.getMessage()); setException(e); return; } try { List<SampleGroup> sampleGroups = ftRequest.getSampleGroups(); SampleGroup grp = null; String cmd; String cmd2; String grpName = null; String bindCmd = "compMat <- cbind("; String matName = null; String phenoCmd = "pheno <- cbind("; result.setSampleGroups(sampleGroups); for (int i=0; i < sampleGroups.size(); i++) { grp = (SampleGroup)sampleGroups.get(i); grpName = "GRP" + i; cmd = getRgroupCmd(grpName, grp); doRvoidEval(cmd); matName = "M" + grpName; cmd = matName + " <- getSubmatrix.onegrp(dataMatrix," + grpName + ")"; doRvoidEval(cmd); bindCmd += matName; phenoCmd += "rep(" + i + "," + grp.size() + ")"; if (i < sampleGroups.size()-1) { bindCmd += ","; phenoCmd += ","; } else { bindCmd += ")"; phenoCmd += ")"; } //to build pheno matrix use c(rep(i,grp.size()) //then outside the loop use pheno <- as.factor(pheno) } doRvoidEval(bindCmd); doRvoidEval(phenoCmd); //now call the Ftest function cmd ="ftResult <- Ftests(compMat,pheno)"; doRvoidEval(cmd); // do filtering String rCmd; double foldChangeThreshold = ftRequest.getFoldChangeThreshold(); double pValueThreshold = ftRequest.getPValueThreshold(); MultiGroupComparisonAdjustmentType adjMethod = ftRequest.getMultiGrpComparisonAdjType(); if (adjMethod == MultiGroupComparisonAdjustmentType.NONE) { // get differentially expressed reporters using // unadjusted Pvalue // shouldn't need to pass in ccInputMatrix rCmd = "ftResult <- mydiferentiallygenes(ftResult," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(false); } else if (adjMethod == MultiGroupComparisonAdjustmentType.FDR) { // do adjustment rCmd = "adjust.result <- adjustP.Benjamini.Hochberg(ftResult)"; doRvoidEval(rCmd); // get differentially expressed reporters using adjusted Pvalue rCmd = "ftResult <- mydiferentiallygenes.adjustP(adjust.result," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(true); } else if (adjMethod == MultiGroupComparisonAdjustmentType.FWER) { // do adjustment rCmd = "adjust.result <- adjustP.Bonferroni(ftResult)"; doRvoidEval(rCmd); // get differentially expresseed reporters using adjusted Pvalue rCmd = "ftResult <- mydiferentiallygenes.adjustP(adjust.result," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(true); } else { logger.error("FTest Adjustment Type unrecognized."); this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type.")); return; } //now extract the result // double[] meanGrp1 = doREval("mean1 <- ftResult[,1]").asDoubleArray(); // double[] meanBaselineGrp = doREval("meanBaseline <- ftResult[,2]").asDoubleArray(); // double[] meanDif = doREval("meanDif <- ftResult[,3]").asDoubleArray(); // double[] absoluteFoldChange = doREval("fc <- ftResult[,4]").asDoubleArray(); // double[] pva = doREval("pva <- ftResult[,5]").asDoubleArray(); double[][] grpMean = doREval("mean <- ftResult[,1:" + sampleGroups.size() + "]").asDoubleMatrix(); int index = sampleGroups.size() + 1; double[] maxFoldChange = doREval("maxFC <- ftResult[," + index + "]").asDoubleArray(); index++; double[] pval = doREval("pval <- ftResult[," + index + "]").asDoubleArray(); // get the labels Vector reporterIds = doREval("ftLabels <- dimnames(ftResult)[[1]]") .asVector(); // load the result object // need to see if this works for single group comparison List<FTestResultEntry> resultEntries = new ArrayList<FTestResultEntry>( maxFoldChange.length); FTestResultEntry resultEntry; int numEntries = maxFoldChange.length; for (int i = 0; i < numEntries; i++) { resultEntry = new FTestResultEntry(); resultEntry.setReporterId(((REXP) reporterIds.get(i)).asString()); //resultEntry.setMeanGrp1(meanGrp1[i]); for (int j=0; j < sampleGroups.size(); j++) { resultEntry.setGroupAverage(j, grpMean[i][j]); } resultEntry.setMaximumFoldChange(maxFoldChange[i]); resultEntry.setPvalue(pval[i]); resultEntries.add(resultEntry); } Collections.sort(resultEntries, ftComparator); result.setResultEntries(resultEntries); //create the data matrix //computeMatrix //for (each group) { //submat[i] <- getSubmatrix(dataMatrix, groupIds[i]) //computeMatix <- cbind(submat[i]) //pheno <- as.factor(i,rep(length(group)[i]) //perform the FTest } catch (AnalysisServerException asex) { AnalysisServerException aex = new AnalysisServerException( "Problem computing correlation. Caught AnalysisServerException in CorrelationTaskR." + asex.getMessage()); aex.setFailedRequest(ftRequest); setException(aex); return; } catch (Exception ex) { AnalysisServerException asex = new AnalysisServerException( "Internal Error. Caught Exception in CorrelationTaskR exClass=" + ex.getClass() + " msg=" + ex.getMessage()); asex.setFailedRequest(ftRequest); setException(asex); return; } }
public void run() { FTestRequest ftRequest = (FTestRequest) getRequest(); result = new FTestResult(getRequest().getSessionId(), getRequest().getTaskId()); logger.info(getExecutingThreadName() + " processing FTestRequest request=" + ftRequest); try { String dataFileName = ftRequest.getDataFileName(); if (dataFileName != null) { setDataFile(ftRequest.getDataFileName()); } else { throw new AnalysisServerException("Null data file name"); } } catch (AnalysisServerException e) { e.setFailedRequest(ftRequest); logger.error("Internal Error. " + e.getMessage()); setException(e); return; } try { List<SampleGroup> sampleGroups = ftRequest.getSampleGroups(); SampleGroup grp = null; String cmd; String cmd2; String grpName = null; String bindCmd = "compMat <- cbind("; String matName = null; String phenoCmd = "pheno <- as.factor(c("; result.setSampleGroups(sampleGroups); for (int i=0; i < sampleGroups.size(); i++) { grp = (SampleGroup)sampleGroups.get(i); grpName = "GRP" + i; cmd = getRgroupCmd(grpName, grp); doRvoidEval(cmd); matName = "M" + grpName; cmd = matName + " <- getSubmatrix.onegrp(dataMatrix," + grpName + ")"; doRvoidEval(cmd); bindCmd += matName; phenoCmd += "rep(" + i + "," + grp.size() + ")"; if (i < sampleGroups.size()-1) { bindCmd += ","; phenoCmd += ","; } else { bindCmd += ")"; phenoCmd += "))"; } //to build pheno matrix use c(rep(i,grp.size()) //then outside the loop use pheno <- as.factor(pheno) } doRvoidEval(bindCmd); doRvoidEval(phenoCmd); //now call the Ftest function cmd ="ftResult <- Ftests(compMat,pheno)"; doRvoidEval(cmd); // do filtering String rCmd; double foldChangeThreshold = ftRequest.getFoldChangeThreshold(); double pValueThreshold = ftRequest.getPValueThreshold(); MultiGroupComparisonAdjustmentType adjMethod = ftRequest.getMultiGrpComparisonAdjType(); if (adjMethod == MultiGroupComparisonAdjustmentType.NONE) { // get differentially expressed reporters using // unadjusted Pvalue // shouldn't need to pass in ccInputMatrix rCmd = "ftResult <- mydiferentiallygenes(ftResult," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(false); } else if (adjMethod == MultiGroupComparisonAdjustmentType.FDR) { // do adjustment rCmd = "adjust.result <- adjustP.Benjamini.Hochberg(ftResult)"; doRvoidEval(rCmd); // get differentially expressed reporters using adjusted Pvalue rCmd = "ftResult <- mydiferentiallygenes.adjustP(adjust.result," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(true); } else if (adjMethod == MultiGroupComparisonAdjustmentType.FWER) { // do adjustment rCmd = "adjust.result <- adjustP.Bonferroni(ftResult)"; doRvoidEval(rCmd); // get differentially expresseed reporters using adjusted Pvalue rCmd = "ftResult <- mydiferentiallygenes.adjustP(adjust.result," + foldChangeThreshold + "," + pValueThreshold + ")"; doRvoidEval(rCmd); result.setArePvaluesAdjusted(true); } else { logger.error("FTest Adjustment Type unrecognized."); this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type.")); return; } //now extract the result // double[] meanGrp1 = doREval("mean1 <- ftResult[,1]").asDoubleArray(); // double[] meanBaselineGrp = doREval("meanBaseline <- ftResult[,2]").asDoubleArray(); // double[] meanDif = doREval("meanDif <- ftResult[,3]").asDoubleArray(); // double[] absoluteFoldChange = doREval("fc <- ftResult[,4]").asDoubleArray(); // double[] pva = doREval("pva <- ftResult[,5]").asDoubleArray(); double[][] grpMean = doREval("mean <- ftResult[,1:" + sampleGroups.size() + "]").asDoubleMatrix(); int index = sampleGroups.size() + 1; double[] maxFoldChange = doREval("maxFC <- ftResult[," + index + "]").asDoubleArray(); index++; double[] pval = doREval("pval <- ftResult[," + index + "]").asDoubleArray(); // get the labels Vector reporterIds = doREval("ftLabels <- dimnames(ftResult)[[1]]") .asVector(); // load the result object // need to see if this works for single group comparison List<FTestResultEntry> resultEntries = new ArrayList<FTestResultEntry>( maxFoldChange.length); FTestResultEntry resultEntry; int numEntries = maxFoldChange.length; for (int i = 0; i < numEntries; i++) { resultEntry = new FTestResultEntry(); resultEntry.setReporterId(((REXP) reporterIds.get(i)).asString()); //resultEntry.setMeanGrp1(meanGrp1[i]); for (int j=0; j < sampleGroups.size(); j++) { resultEntry.setGroupAverage(j, grpMean[i][j]); } resultEntry.setMaximumFoldChange(maxFoldChange[i]); resultEntry.setPvalue(pval[i]); resultEntries.add(resultEntry); } Collections.sort(resultEntries, ftComparator); result.setResultEntries(resultEntries); //create the data matrix //computeMatrix //for (each group) { //submat[i] <- getSubmatrix(dataMatrix, groupIds[i]) //computeMatix <- cbind(submat[i]) //pheno <- as.factor(i,rep(length(group)[i]) //perform the FTest } catch (AnalysisServerException asex) { AnalysisServerException aex = new AnalysisServerException( "Problem computing correlation. Caught AnalysisServerException in CorrelationTaskR." + asex.getMessage()); aex.setFailedRequest(ftRequest); setException(aex); return; } catch (Exception ex) { AnalysisServerException asex = new AnalysisServerException( "Internal Error. Caught Exception in CorrelationTaskR exClass=" + ex.getClass() + " msg=" + ex.getMessage()); asex.setFailedRequest(ftRequest); setException(asex); return; } }
diff --git a/src/cz/muni/stanse/codestructures/ArgumentPassingManager.java b/src/cz/muni/stanse/codestructures/ArgumentPassingManager.java index b49a350..7dea89c 100644 --- a/src/cz/muni/stanse/codestructures/ArgumentPassingManager.java +++ b/src/cz/muni/stanse/codestructures/ArgumentPassingManager.java @@ -1,104 +1,104 @@ package cz.muni.stanse.codestructures; import cz.muni.stanse.codestructures.builders.XMLLinearizeASTElement; import cz.muni.stanse.utils.Pair; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import java.util.Iterator; import org.dom4j.Element; public final class ArgumentPassingManager { // public section public ArgumentPassingManager(final CFGsNavigator navigator, final Map<CFGNode,CFGHandle> nodeToCFGdict) { mapping = new HashMap<Pair<CFGNode,CFGNode>, LinkedList<Pair<String,String>>>(); build(navigator,nodeToCFGdict); } public boolean isIdentityPass(final CFGNode from, final CFGNode to) { return getMapping().get(Pair.make(from,to)) == null; } public String pass(final CFGNode from, final String argument, final CFGNode to) { return PassingSolver.pass(argument, getMapping().get(Pair.make(from,to))); } // private section private void build(final CFGsNavigator navigator, final Map<CFGNode,CFGHandle> nodeToCFGdict) { for (final CFGNode caller : navigator.callSites()) { final CFGNode start = navigator.getCalleeStart(caller); buildPassingsForCallSite(caller, nodeToCFGdict.get(start)); } } private void buildPassingsForCallSite(final CFGNode caller, final CFGHandle callee) { final LinkedList<Pair<String,String>> map = buildMappingFromCallSiteToCallee(caller, callee); getMapping().put(Pair.make(caller, callee.getStartNode()),map); getMapping().put(Pair.make(caller, callee.getEndNode()), map); final LinkedList<Pair<String,String>> mapTransposed = transposeCallSiteMapping(map); getMapping().put(Pair.make(callee.getStartNode(), caller),mapTransposed); getMapping().put(Pair.make(callee.getEndNode(), caller),mapTransposed); } private static LinkedList<Pair<String,String>> buildMappingFromCallSiteToCallee(final CFGNode caller, final CFGHandle callee) { final LinkedList<Pair<String,String>> result = new LinkedList<Pair<String,String>>(); if (caller.getNodeType() != CFGNode.NodeType.none) { Iterator<CFGNode.Operand> opIter = caller.getOperands().iterator(); opIter.next(); Iterator<String> paramIter = callee.getParams().iterator(); while (opIter.hasNext()) { assert paramIter.hasNext(); - result.add(Pair.make(paramIter.next(), PassingSolver.makeArgument(opIter.next()))); + result.add(Pair.make(PassingSolver.makeArgument(opIter.next()), paramIter.next())); } assert !paramIter.hasNext(); } else { final Iterator<Element> callIter = XMLLinearizeASTElement.functionCall(caller.getElement()).iterator(); final Iterator<Element> calleeIter = XMLLinearizeASTElement.functionDeclaration(callee.getElement()).iterator(); for (callIter.next(), calleeIter.next(); callIter.hasNext(); ) result.add(Pair.make(PassingSolver .makeArgument(callIter.next()), PassingSolver .makeArgument(calleeIter.next()))); } return result; } private static LinkedList<Pair<String,String>> transposeCallSiteMapping(final LinkedList<Pair<String, String>> map) { final LinkedList<Pair<String, String>> result = new LinkedList<Pair<String, String>>(); for (final Pair<String,String> item : map) result.add(Pair.make(item.getSecond(),item.getFirst())); return result; } private HashMap<Pair<CFGNode,CFGNode>,LinkedList<Pair<String, String>>> getMapping() { return mapping; } private final HashMap<Pair<CFGNode,CFGNode>, LinkedList<Pair<String,String>>> mapping; }
true
true
private static LinkedList<Pair<String,String>> buildMappingFromCallSiteToCallee(final CFGNode caller, final CFGHandle callee) { final LinkedList<Pair<String,String>> result = new LinkedList<Pair<String,String>>(); if (caller.getNodeType() != CFGNode.NodeType.none) { Iterator<CFGNode.Operand> opIter = caller.getOperands().iterator(); opIter.next(); Iterator<String> paramIter = callee.getParams().iterator(); while (opIter.hasNext()) { assert paramIter.hasNext(); result.add(Pair.make(paramIter.next(), PassingSolver.makeArgument(opIter.next()))); } assert !paramIter.hasNext(); } else { final Iterator<Element> callIter = XMLLinearizeASTElement.functionCall(caller.getElement()).iterator(); final Iterator<Element> calleeIter = XMLLinearizeASTElement.functionDeclaration(callee.getElement()).iterator(); for (callIter.next(), calleeIter.next(); callIter.hasNext(); ) result.add(Pair.make(PassingSolver .makeArgument(callIter.next()), PassingSolver .makeArgument(calleeIter.next()))); } return result; }
private static LinkedList<Pair<String,String>> buildMappingFromCallSiteToCallee(final CFGNode caller, final CFGHandle callee) { final LinkedList<Pair<String,String>> result = new LinkedList<Pair<String,String>>(); if (caller.getNodeType() != CFGNode.NodeType.none) { Iterator<CFGNode.Operand> opIter = caller.getOperands().iterator(); opIter.next(); Iterator<String> paramIter = callee.getParams().iterator(); while (opIter.hasNext()) { assert paramIter.hasNext(); result.add(Pair.make(PassingSolver.makeArgument(opIter.next()), paramIter.next())); } assert !paramIter.hasNext(); } else { final Iterator<Element> callIter = XMLLinearizeASTElement.functionCall(caller.getElement()).iterator(); final Iterator<Element> calleeIter = XMLLinearizeASTElement.functionDeclaration(callee.getElement()).iterator(); for (callIter.next(), calleeIter.next(); callIter.hasNext(); ) result.add(Pair.make(PassingSolver .makeArgument(callIter.next()), PassingSolver .makeArgument(calleeIter.next()))); } return result; }
diff --git a/app/java/com/kittens/controller/ErrorController.java b/app/java/com/kittens/controller/ErrorController.java index 21ab6f6..4a676c9 100644 --- a/app/java/com/kittens/controller/ErrorController.java +++ b/app/java/com/kittens/controller/ErrorController.java @@ -1,33 +1,34 @@ package com.kittens.controller; import com.kittens.Utils; import com.kittens.view.ViewRenderer; import java.io.IOException; import java.lang.String; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; public class ErrorController extends BaseController { // the version of this object public static final long serialVersionUID = 0L; /** * Process GET requests. */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ask for this response to not be cached Utils.pleaseDontCache(response); // map all the values final HashMap<String, String> values = new HashMap<String, String>(); values.put("title", "Error 404 (Not Found)!!1"); + values.put("logo", "Group Data"); // render the view response.setContentType("text/html"); ViewRenderer.render(response, "error", values); } }
true
true
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ask for this response to not be cached Utils.pleaseDontCache(response); // map all the values final HashMap<String, String> values = new HashMap<String, String>(); values.put("title", "Error 404 (Not Found)!!1"); // render the view response.setContentType("text/html"); ViewRenderer.render(response, "error", values); }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ask for this response to not be cached Utils.pleaseDontCache(response); // map all the values final HashMap<String, String> values = new HashMap<String, String>(); values.put("title", "Error 404 (Not Found)!!1"); values.put("logo", "Group Data"); // render the view response.setContentType("text/html"); ViewRenderer.render(response, "error", values); }
diff --git a/src/org/ebookdroid/ui/settings/BookSettingsActivity.java b/src/org/ebookdroid/ui/settings/BookSettingsActivity.java index 79e205e2..19e5030c 100644 --- a/src/org/ebookdroid/ui/settings/BookSettingsActivity.java +++ b/src/org/ebookdroid/ui/settings/BookSettingsActivity.java @@ -1,58 +1,59 @@ package org.ebookdroid.ui.settings; import org.ebookdroid.R; import org.ebookdroid.common.settings.AppSettings; import org.ebookdroid.common.settings.SettingsManager; import org.ebookdroid.common.settings.books.BookSettings; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import org.emdev.common.filesystem.PathFromUri; public class BookSettingsActivity extends BaseSettingsActivity { private BookSettings current; @SuppressWarnings("deprecation") @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(AppSettings.current().rotation.getOrientation()); final Uri uri = getIntent().getData(); final String fileName = PathFromUri.retrieve(getContentResolver(), uri); current = SettingsManager.getBookSettings(fileName); if (current == null) { finish(); + return; } SettingsManager.onBookSettingsActivityCreated(current); try { addPreferencesFromResource(R.xml.fragment_book); } catch (final ClassCastException e) { LCTX.e("Book preferences are corrupt! Resetting to default values."); final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); PreferenceManager.setDefaultValues(this, R.xml.fragment_book, true); addPreferencesFromResource(R.xml.fragment_book); } decorator.decoratePreference(getRoot()); decorator.decorateBooksSettings(current); } @Override protected void onPause() { SettingsManager.onBookSettingsActivityClosed(current); super.onPause(); } }
true
true
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(AppSettings.current().rotation.getOrientation()); final Uri uri = getIntent().getData(); final String fileName = PathFromUri.retrieve(getContentResolver(), uri); current = SettingsManager.getBookSettings(fileName); if (current == null) { finish(); } SettingsManager.onBookSettingsActivityCreated(current); try { addPreferencesFromResource(R.xml.fragment_book); } catch (final ClassCastException e) { LCTX.e("Book preferences are corrupt! Resetting to default values."); final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); PreferenceManager.setDefaultValues(this, R.xml.fragment_book, true); addPreferencesFromResource(R.xml.fragment_book); } decorator.decoratePreference(getRoot()); decorator.decorateBooksSettings(current); }
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(AppSettings.current().rotation.getOrientation()); final Uri uri = getIntent().getData(); final String fileName = PathFromUri.retrieve(getContentResolver(), uri); current = SettingsManager.getBookSettings(fileName); if (current == null) { finish(); return; } SettingsManager.onBookSettingsActivityCreated(current); try { addPreferencesFromResource(R.xml.fragment_book); } catch (final ClassCastException e) { LCTX.e("Book preferences are corrupt! Resetting to default values."); final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); PreferenceManager.setDefaultValues(this, R.xml.fragment_book, true); addPreferencesFromResource(R.xml.fragment_book); } decorator.decoratePreference(getRoot()); decorator.decorateBooksSettings(current); }
diff --git a/bindings/java/src/net/hyperic/sigar/cmd/Ulimit.java b/bindings/java/src/net/hyperic/sigar/cmd/Ulimit.java index 643cc665..58a62a8c 100644 --- a/bindings/java/src/net/hyperic/sigar/cmd/Ulimit.java +++ b/bindings/java/src/net/hyperic/sigar/cmd/Ulimit.java @@ -1,80 +1,80 @@ package net.hyperic.sigar.cmd; import net.hyperic.sigar.ResourceLimit; import net.hyperic.sigar.SigarException; import net.hyperic.sigar.jmx.SigarInvokerJMX; /** * Display system resource limits. */ public class Ulimit extends SigarCommandBase { private SigarInvokerJMX invoker; private String mode; public Ulimit(Shell shell) { super(shell); } public Ulimit() { super(); } public String getUsageShort() { return "Display system resource limits"; } protected boolean validateArgs(String[] args) { return true; } private static String format(long val) { if (val == ResourceLimit.INFINITY()) { return "unlimited"; } else { return String.valueOf(val); } } private String getValue(String attr) throws SigarException { Long val = (Long)this.invoker.invoke(attr + this.mode); return format(val.longValue()); } public void output(String[] args) throws SigarException { this.mode = "Cur"; this.invoker = SigarInvokerJMX.getInstance(this.proxy, "Type=ResourceLimit"); for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg.equals("-H")) { this.mode = "Max"; } else if (arg.equals("-S")) { this.mode = "Cur"; } else { throw new SigarException("Unknown argument: " + arg); } } println("core file size......." + getValue("Core")); println("data seg size........" + getValue("Data")); println("file size............" + getValue("FileSize")); println("pipe size............" + getValue("PipeSize")); println("max memory size......" + getValue("Memory")); println("open files..........." + getValue("OpenFiles")); println("stack size..........." + getValue("Stack")); println("cpu time............." + getValue("Cpu")); println("max user processes..." + getValue("Processes")); - println("virual memory........" + getValue("VirtualMemory")); + println("virtual memory......." + getValue("VirtualMemory")); } public static void main(String[] args) throws Exception { new Ulimit().processCommand(args); } }
true
true
public void output(String[] args) throws SigarException { this.mode = "Cur"; this.invoker = SigarInvokerJMX.getInstance(this.proxy, "Type=ResourceLimit"); for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg.equals("-H")) { this.mode = "Max"; } else if (arg.equals("-S")) { this.mode = "Cur"; } else { throw new SigarException("Unknown argument: " + arg); } } println("core file size......." + getValue("Core")); println("data seg size........" + getValue("Data")); println("file size............" + getValue("FileSize")); println("pipe size............" + getValue("PipeSize")); println("max memory size......" + getValue("Memory")); println("open files..........." + getValue("OpenFiles")); println("stack size..........." + getValue("Stack")); println("cpu time............." + getValue("Cpu")); println("max user processes..." + getValue("Processes")); println("virual memory........" + getValue("VirtualMemory")); }
public void output(String[] args) throws SigarException { this.mode = "Cur"; this.invoker = SigarInvokerJMX.getInstance(this.proxy, "Type=ResourceLimit"); for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg.equals("-H")) { this.mode = "Max"; } else if (arg.equals("-S")) { this.mode = "Cur"; } else { throw new SigarException("Unknown argument: " + arg); } } println("core file size......." + getValue("Core")); println("data seg size........" + getValue("Data")); println("file size............" + getValue("FileSize")); println("pipe size............" + getValue("PipeSize")); println("max memory size......" + getValue("Memory")); println("open files..........." + getValue("OpenFiles")); println("stack size..........." + getValue("Stack")); println("cpu time............." + getValue("Cpu")); println("max user processes..." + getValue("Processes")); println("virtual memory......." + getValue("VirtualMemory")); }
diff --git a/src/java/main/ru/alepar/minesweeper/SteppedOnABomb.java b/src/java/main/ru/alepar/minesweeper/SteppedOnABomb.java index dea041a..67ec9c1 100644 --- a/src/java/main/ru/alepar/minesweeper/SteppedOnABomb.java +++ b/src/java/main/ru/alepar/minesweeper/SteppedOnABomb.java @@ -1,9 +1,9 @@ package ru.alepar.minesweeper; public class SteppedOnABomb extends Exception { public SteppedOnABomb(Point p) { - super(String.format("stepped on a bomdb at (%d, %d)", p.x, p.y)); + super(String.format("stepped on a bomb at (%d, %d)", p.x, p.y)); } }
true
true
public SteppedOnABomb(Point p) { super(String.format("stepped on a bomdb at (%d, %d)", p.x, p.y)); }
public SteppedOnABomb(Point p) { super(String.format("stepped on a bomb at (%d, %d)", p.x, p.y)); }
diff --git a/org.eclipse.egit.core/src/org/eclipse/egit/core/op/PushOperation.java b/org.eclipse.egit.core/src/org/eclipse/egit/core/op/PushOperation.java index 217db801..3404696d 100644 --- a/org.eclipse.egit.core/src/org/eclipse/egit/core/op/PushOperation.java +++ b/org.eclipse.egit.core/src/org/eclipse/egit/core/op/PushOperation.java @@ -1,175 +1,176 @@ /******************************************************************************* * Copyright (C) 2008, Marek Zawirski <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.core.op; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.egit.core.CoreText; import org.eclipse.egit.core.EclipseGitProgressTransformer; import org.eclipse.jgit.errors.NoRemoteRepositoryException; import org.eclipse.jgit.errors.NotSupportedException; import org.eclipse.jgit.errors.TransportException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.osgi.util.NLS; /** * Push operation: pushing from local repository to one or many remote ones. */ public class PushOperation { private static final int WORK_UNITS_PER_TRANSPORT = 10; private final Repository localDb; private final PushOperationSpecification specification; private final boolean dryRun; private final RemoteConfig rc; private PushOperationResult operationResult; /** * Create push operation for provided specification. * <p> * Operation is not performed within constructor, * {@link #run(IProgressMonitor)} method must be called for that. * * @param localDb * local repository. * @param specification * specification of ref updates for remote repositories. * @param rc * optional remote config to apply on used transports. May be * null. * @param dryRun * true if push operation should just check for possible result * and not really update remote refs, false otherwise - when push * should act normally. */ public PushOperation(final Repository localDb, final PushOperationSpecification specification, final boolean dryRun, final RemoteConfig rc) { this.localDb = localDb; this.specification = specification; this.dryRun = dryRun; this.rc = rc; } /** * @return push operation result. */ public PushOperationResult getOperationResult() { if (operationResult == null) throw new IllegalStateException(CoreText.OperationNotYetExecuted); return operationResult; } /** * @return operation specification, as provided in constructor. */ public PushOperationSpecification getSpecification() { return specification; } /** * Execute operation and store result. Operation is executed independently * on each remote repository. * <p> * * @param actMonitor * the monitor to be used for reporting progress and responding * to cancellation. The monitor is never <code>null</code> * * @throws InvocationTargetException * Cause of this exceptions may include * {@link TransportException}, {@link NotSupportedException} or * some unexpected {@link RuntimeException}. */ public void run(IProgressMonitor actMonitor) throws InvocationTargetException { if (operationResult != null) throw new IllegalStateException(CoreText.OperationAlreadyExecuted); for (URIish uri : this.specification.getURIs()) { for (RemoteRefUpdate update : this.specification.getRefUpdates(uri)) if (update.getStatus() != Status.NOT_ATTEMPTED) throw new IllegalStateException( CoreText.RemoteRefUpdateCantBeReused); } IProgressMonitor monitor; if (actMonitor == null) monitor = new NullProgressMonitor(); else monitor = actMonitor; final int totalWork = specification.getURIsNumber() * WORK_UNITS_PER_TRANSPORT; if (dryRun) monitor.beginTask(CoreText.PushOperation_taskNameDryRun, totalWork); else monitor.beginTask(CoreText.PushOperation_taskNameNormalRun, totalWork); operationResult = new PushOperationResult(); for (final URIish uri : specification.getURIs()) { final SubProgressMonitor subMonitor = new SubProgressMonitor( monitor, WORK_UNITS_PER_TRANSPORT, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); Transport transport = null; try { if (monitor.isCanceled()) { operationResult.addOperationResult(uri, CoreText.PushOperation_resultCancelled); continue; } transport = Transport.open(localDb, uri); if (rc != null) transport.applyConfig(rc); transport.setDryRun(dryRun); final EclipseGitProgressTransformer gitSubMonitor = new EclipseGitProgressTransformer( subMonitor); final PushResult pr = transport.push(gitSubMonitor, specification.getRefUpdates(uri)); operationResult.addOperationResult(uri, pr); + monitor.worked(WORK_UNITS_PER_TRANSPORT); } catch (final NoRemoteRepositoryException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultNoServiceError, e .getMessage())); } catch (final TransportException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultTransportError, e .getMessage())); } catch (final NotSupportedException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultNotSupported, e .getMessage())); } finally { if (transport != null) { transport.close(); } // Dirty trick to get things always working. subMonitor.beginTask("", WORK_UNITS_PER_TRANSPORT); //$NON-NLS-1$ subMonitor.done(); subMonitor.done(); } } monitor.done(); } }
true
true
public void run(IProgressMonitor actMonitor) throws InvocationTargetException { if (operationResult != null) throw new IllegalStateException(CoreText.OperationAlreadyExecuted); for (URIish uri : this.specification.getURIs()) { for (RemoteRefUpdate update : this.specification.getRefUpdates(uri)) if (update.getStatus() != Status.NOT_ATTEMPTED) throw new IllegalStateException( CoreText.RemoteRefUpdateCantBeReused); } IProgressMonitor monitor; if (actMonitor == null) monitor = new NullProgressMonitor(); else monitor = actMonitor; final int totalWork = specification.getURIsNumber() * WORK_UNITS_PER_TRANSPORT; if (dryRun) monitor.beginTask(CoreText.PushOperation_taskNameDryRun, totalWork); else monitor.beginTask(CoreText.PushOperation_taskNameNormalRun, totalWork); operationResult = new PushOperationResult(); for (final URIish uri : specification.getURIs()) { final SubProgressMonitor subMonitor = new SubProgressMonitor( monitor, WORK_UNITS_PER_TRANSPORT, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); Transport transport = null; try { if (monitor.isCanceled()) { operationResult.addOperationResult(uri, CoreText.PushOperation_resultCancelled); continue; } transport = Transport.open(localDb, uri); if (rc != null) transport.applyConfig(rc); transport.setDryRun(dryRun); final EclipseGitProgressTransformer gitSubMonitor = new EclipseGitProgressTransformer( subMonitor); final PushResult pr = transport.push(gitSubMonitor, specification.getRefUpdates(uri)); operationResult.addOperationResult(uri, pr); } catch (final NoRemoteRepositoryException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultNoServiceError, e .getMessage())); } catch (final TransportException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultTransportError, e .getMessage())); } catch (final NotSupportedException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultNotSupported, e .getMessage())); } finally { if (transport != null) { transport.close(); } // Dirty trick to get things always working. subMonitor.beginTask("", WORK_UNITS_PER_TRANSPORT); //$NON-NLS-1$ subMonitor.done(); subMonitor.done(); } } monitor.done(); }
public void run(IProgressMonitor actMonitor) throws InvocationTargetException { if (operationResult != null) throw new IllegalStateException(CoreText.OperationAlreadyExecuted); for (URIish uri : this.specification.getURIs()) { for (RemoteRefUpdate update : this.specification.getRefUpdates(uri)) if (update.getStatus() != Status.NOT_ATTEMPTED) throw new IllegalStateException( CoreText.RemoteRefUpdateCantBeReused); } IProgressMonitor monitor; if (actMonitor == null) monitor = new NullProgressMonitor(); else monitor = actMonitor; final int totalWork = specification.getURIsNumber() * WORK_UNITS_PER_TRANSPORT; if (dryRun) monitor.beginTask(CoreText.PushOperation_taskNameDryRun, totalWork); else monitor.beginTask(CoreText.PushOperation_taskNameNormalRun, totalWork); operationResult = new PushOperationResult(); for (final URIish uri : specification.getURIs()) { final SubProgressMonitor subMonitor = new SubProgressMonitor( monitor, WORK_UNITS_PER_TRANSPORT, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); Transport transport = null; try { if (monitor.isCanceled()) { operationResult.addOperationResult(uri, CoreText.PushOperation_resultCancelled); continue; } transport = Transport.open(localDb, uri); if (rc != null) transport.applyConfig(rc); transport.setDryRun(dryRun); final EclipseGitProgressTransformer gitSubMonitor = new EclipseGitProgressTransformer( subMonitor); final PushResult pr = transport.push(gitSubMonitor, specification.getRefUpdates(uri)); operationResult.addOperationResult(uri, pr); monitor.worked(WORK_UNITS_PER_TRANSPORT); } catch (final NoRemoteRepositoryException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultNoServiceError, e .getMessage())); } catch (final TransportException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultTransportError, e .getMessage())); } catch (final NotSupportedException e) { operationResult.addOperationResult(uri, NLS.bind( CoreText.PushOperation_resultNotSupported, e .getMessage())); } finally { if (transport != null) { transport.close(); } // Dirty trick to get things always working. subMonitor.beginTask("", WORK_UNITS_PER_TRANSPORT); //$NON-NLS-1$ subMonitor.done(); subMonitor.done(); } } monitor.done(); }
diff --git a/WEB-INF/src/edu/wustl/query/util/listener/QueryServletContextListenerUtil.java b/WEB-INF/src/edu/wustl/query/util/listener/QueryServletContextListenerUtil.java index cfa72bd1..5f317c9d 100644 --- a/WEB-INF/src/edu/wustl/query/util/listener/QueryServletContextListenerUtil.java +++ b/WEB-INF/src/edu/wustl/query/util/listener/QueryServletContextListenerUtil.java @@ -1,133 +1,134 @@ package edu.wustl.query.util.listener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.util.Properties; import javax.naming.InitialContext; import javax.servlet.ServletContextEvent; import javax.sql.DataSource; import edu.wustl.cab2b.server.path.PathFinder; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.logger.Logger; import edu.wustl.common.vocab.VocabularyException; import edu.wustl.common.vocab.utility.VocabUtil; import edu.wustl.query.util.filter.StrutsConfigReader; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.global.VIProperties; import edu.wustl.query.util.global.Variables; public class QueryServletContextListenerUtil { public static void initializeQuery(ServletContextEvent sce, String datasourceJNDIName) throws Exception { Logger.configDefaultLogger(sce.getServletContext()); Variables.applicationHome = sce.getServletContext().getRealPath(""); setGlobalVariable(); //Added by Baljeet....This method caches all the Meta data initEntityCache(datasourceJNDIName); // Added to create map of query actions which will be used by QueryRequestFilter to check authorization StrutsConfigReader.init(Variables.applicationHome+File.separator+Constants.WEB_INF_FOLDER_NAME+File.separator+Constants.AQ_STRUTS_CONFIG_FILE_NAME); } private static void initEntityCache(String datasourceJNDIName) { try { //Added for initializing PathFinder and EntityCache InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(datasourceJNDIName); Connection conn = ds.getConnection(); PathFinder.getInstance(conn); } catch (Exception e) { //logger.debug("Exception occured while initialising entity cache"); } } private static void setGlobalVariable() throws Exception { String path = System.getProperty("app.propertiesFile"); XMLPropertyHandler.init(path); File propetiesDirPath = new File(path); Variables.propertiesDirPath = propetiesDirPath.getParent(); Variables.applicationName = ApplicationProperties.getValue("app.name"); Variables.applicationVersion = ApplicationProperties.getValue("app.version"); int maximumTreeNodeLimit = Integer.parseInt(XMLPropertyHandler.getValue(Constants.MAXIMUM_TREE_NODE_LIMIT)); Variables.maximumTreeNodeLimit = maximumTreeNodeLimit; readProperties(); path = System.getProperty("app.propertiesFile"); //configure VI setVIProperties(); } private static void setVIProperties() throws VocabularyException { Properties vocabProperties = VocabUtil.getVocabProperties(); VIProperties.sourceVocabName = vocabProperties.getProperty("source.vocab.name"); VIProperties.sourceVocabVersion = vocabProperties.getProperty("source.vocab.version"); VIProperties.sourceVocabUrn = vocabProperties.getProperty("source.vocab.urn"); VIProperties.searchAlgorithm = vocabProperties.getProperty("match.algorithm"); VIProperties.maxPVsToShow = Integer.valueOf(vocabProperties.getProperty("pvs.to.show")); VIProperties.maxToReturnFromSearch = Integer.valueOf(vocabProperties.getProperty("max.to.return.from.search")); VIProperties.translationAssociation = vocabProperties.getProperty("vocab.translation.association.name"); VIProperties.medClassName = vocabProperties.getProperty("med.class.name"); } private static void readProperties() { File file = new File(Variables.applicationHome + System.getProperty("file.separator") + "WEB-INF" + System.getProperty("file.separator") + "classes" + System.getProperty("file.separator") + "query.properties"); if (file.exists()) { Properties queryProperties = new Properties(); try { queryProperties.load(new FileInputStream(file)); Variables.queryGeneratorClassName = queryProperties.getProperty("query.queryGeneratorClassName"); //Added to get AbstractQuery Implementer Class Name. Variables.abstractQueryClassName = queryProperties.getProperty("query.abstractQueryClassName"); Variables.abstractQueryManagerClassName = queryProperties.getProperty("query.abstractQueryManagerClassName"); Variables.abstractQueryUIManagerClassName = queryProperties.getProperty("query.abstractQueryUIManagerClassName"); Variables.abstractQueryITableManagerClassName = queryProperties.getProperty("query.abstractQueryITableManagerClassName"); Variables.viewIQueryGeneratorClassName = queryProperties.getProperty("query.viewIQueryGeneratorClassName"); Variables.recordsPerPageForSpreadSheet = Integer.parseInt(queryProperties.getProperty("spreadSheet.recordsPerPage")); Variables.recordsPerPageForTree = Integer.parseInt(queryProperties.getProperty("tree.recordsPerPage")); Variables.resultLimit = Integer.parseInt(queryProperties.getProperty("datasecurity.resultLimit")); Variables.exportDataThreadClassName = queryProperties.getProperty("query.exportDataThreadClassName"); Variables.dataQueryExecutionClassName = queryProperties.getProperty("query.dataQueryExecutionClassName"); Variables.properties = queryProperties; Variables.csmUtility = queryProperties.getProperty("query.csmUtility"); + Variables.spreadSheetGeneratorClassName = queryProperties.getProperty("query.spreadSheetGeneratorClassName"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
true
true
private static void readProperties() { File file = new File(Variables.applicationHome + System.getProperty("file.separator") + "WEB-INF" + System.getProperty("file.separator") + "classes" + System.getProperty("file.separator") + "query.properties"); if (file.exists()) { Properties queryProperties = new Properties(); try { queryProperties.load(new FileInputStream(file)); Variables.queryGeneratorClassName = queryProperties.getProperty("query.queryGeneratorClassName"); //Added to get AbstractQuery Implementer Class Name. Variables.abstractQueryClassName = queryProperties.getProperty("query.abstractQueryClassName"); Variables.abstractQueryManagerClassName = queryProperties.getProperty("query.abstractQueryManagerClassName"); Variables.abstractQueryUIManagerClassName = queryProperties.getProperty("query.abstractQueryUIManagerClassName"); Variables.abstractQueryITableManagerClassName = queryProperties.getProperty("query.abstractQueryITableManagerClassName"); Variables.viewIQueryGeneratorClassName = queryProperties.getProperty("query.viewIQueryGeneratorClassName"); Variables.recordsPerPageForSpreadSheet = Integer.parseInt(queryProperties.getProperty("spreadSheet.recordsPerPage")); Variables.recordsPerPageForTree = Integer.parseInt(queryProperties.getProperty("tree.recordsPerPage")); Variables.resultLimit = Integer.parseInt(queryProperties.getProperty("datasecurity.resultLimit")); Variables.exportDataThreadClassName = queryProperties.getProperty("query.exportDataThreadClassName"); Variables.dataQueryExecutionClassName = queryProperties.getProperty("query.dataQueryExecutionClassName"); Variables.properties = queryProperties; Variables.csmUtility = queryProperties.getProperty("query.csmUtility"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
private static void readProperties() { File file = new File(Variables.applicationHome + System.getProperty("file.separator") + "WEB-INF" + System.getProperty("file.separator") + "classes" + System.getProperty("file.separator") + "query.properties"); if (file.exists()) { Properties queryProperties = new Properties(); try { queryProperties.load(new FileInputStream(file)); Variables.queryGeneratorClassName = queryProperties.getProperty("query.queryGeneratorClassName"); //Added to get AbstractQuery Implementer Class Name. Variables.abstractQueryClassName = queryProperties.getProperty("query.abstractQueryClassName"); Variables.abstractQueryManagerClassName = queryProperties.getProperty("query.abstractQueryManagerClassName"); Variables.abstractQueryUIManagerClassName = queryProperties.getProperty("query.abstractQueryUIManagerClassName"); Variables.abstractQueryITableManagerClassName = queryProperties.getProperty("query.abstractQueryITableManagerClassName"); Variables.viewIQueryGeneratorClassName = queryProperties.getProperty("query.viewIQueryGeneratorClassName"); Variables.recordsPerPageForSpreadSheet = Integer.parseInt(queryProperties.getProperty("spreadSheet.recordsPerPage")); Variables.recordsPerPageForTree = Integer.parseInt(queryProperties.getProperty("tree.recordsPerPage")); Variables.resultLimit = Integer.parseInt(queryProperties.getProperty("datasecurity.resultLimit")); Variables.exportDataThreadClassName = queryProperties.getProperty("query.exportDataThreadClassName"); Variables.dataQueryExecutionClassName = queryProperties.getProperty("query.dataQueryExecutionClassName"); Variables.properties = queryProperties; Variables.csmUtility = queryProperties.getProperty("query.csmUtility"); Variables.spreadSheetGeneratorClassName = queryProperties.getProperty("query.spreadSheetGeneratorClassName"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
diff --git a/library/src/main/java/net/sourceforge/cilib/pso/iterationstrategies/PSPGIterationStrategy.java b/library/src/main/java/net/sourceforge/cilib/pso/iterationstrategies/PSPGIterationStrategy.java index 5263f0fc..33501e40 100644 --- a/library/src/main/java/net/sourceforge/cilib/pso/iterationstrategies/PSPGIterationStrategy.java +++ b/library/src/main/java/net/sourceforge/cilib/pso/iterationstrategies/PSPGIterationStrategy.java @@ -1,134 +1,134 @@ /** __ __ * _____ _/ /_/ /_ Computational Intelligence Library (CIlib) * / ___/ / / / __ \ (c) CIRG @ UP * / /__/ / / / /_/ / http://cilib.net * \___/_/_/_/_.___/ */ package net.sourceforge.cilib.pso.iterationstrategies; import com.google.common.collect.Lists; import fj.F; import java.util.Collections; import java.util.Iterator; import java.util.List; import net.sourceforge.cilib.algorithm.population.AbstractIterationStrategy; import net.sourceforge.cilib.algorithm.population.IterationStrategy; import net.sourceforge.cilib.controlparameter.ConstantControlParameter; import net.sourceforge.cilib.controlparameter.ControlParameter; import net.sourceforge.cilib.entity.Topologies; import net.sourceforge.cilib.entity.comparator.DescendingFitnessComparator; import net.sourceforge.cilib.entity.comparator.SocialBestFitnessComparator; import net.sourceforge.cilib.entity.operators.crossover.parentprovider.BestParentProvider; import net.sourceforge.cilib.entity.operators.crossover.real.ParentCentricCrossoverStrategy; import net.sourceforge.cilib.math.random.generator.Rand; import net.sourceforge.cilib.pso.PSO; import net.sourceforge.cilib.pso.crossover.ParticleCrossoverStrategy; import net.sourceforge.cilib.pso.particle.Particle; import net.sourceforge.cilib.util.selection.Samples; import net.sourceforge.cilib.util.selection.recipes.RandomSelector; /** * Reference: * <p> * "Enhanced Performance of Particle Swarm Optimization with Generalized Generation * Gap Model with Parent-Centric Recombination Operator", by C. Worasucheep, * C Pipopwatthana, S Srimontha, W. Phanmak, in ECTI Transactions on Computer * and Information Technology, vol 6, Non 2, 2012 * </p> */ public class PSPGIterationStrategy extends AbstractIterationStrategy<PSO> { private ControlParameter iterationProbability; private ParticleCrossoverStrategy crossoverStrategy; private IterationStrategy iterationStrategy; public PSPGIterationStrategy() { ParentCentricCrossoverStrategy pcx = new ParentCentricCrossoverStrategy(); pcx.setNumberOfParents(ConstantControlParameter.of(3)); pcx.setNumberOfOffspring(ConstantControlParameter.of(2)); pcx.setParentProvider(new BestParentProvider()); ParticleCrossoverStrategy xover = new ParticleCrossoverStrategy(); xover.setCrossoverStrategy(pcx); this.crossoverStrategy = xover; this.iterationProbability = ConstantControlParameter.of(0.05); this.iterationStrategy = new SynchronousIterationStrategy(); } public PSPGIterationStrategy(PSPGIterationStrategy copy) { this.iterationProbability = copy.iterationProbability.getClone(); this.crossoverStrategy = copy.crossoverStrategy.getClone(); } @Override public PSPGIterationStrategy getClone() { return new PSPGIterationStrategy(this); } @Override public void performIteration(PSO algorithm) { if (Rand.nextDouble() < iterationProbability.getParameter()) { crossoverStep(algorithm); } else { iterationStrategy.performIteration(algorithm); } } private void crossoverStep(PSO algorithm) { fj.data.List<Particle> topology = algorithm.getTopology(); Particle gbest = Topologies.getBestEntity(topology, new SocialBestFitnessComparator<>()); // Get parents final List<Particle> parents = Lists.newArrayList(new RandomSelector<Particle>() .on(topology) .exclude(gbest) .select(Samples.first(crossoverStrategy.getNumberOfParents() - 1))); parents.add(gbest); // Add offspring parents.addAll(crossoverStrategy.crossover(parents)); Collections.sort(parents, new DescendingFitnessComparator<>()); // Get particles to replace final List<Particle> rp = Lists.newArrayList(new RandomSelector<Particle>() .on(topology) .exclude(gbest) .select(Samples.first(crossoverStrategy.getNumberOfParents() - 1))); rp.add(gbest); // Replace particles final Iterator<Particle> iter = parents.iterator(); algorithm.setTopology(topology.map(new F<Particle, Particle>() { @Override public Particle f(Particle a) { - if (rp.contains(a)) { + if (rp.contains(a) && iter.hasNext()) { return iter.next(); } return a; } })); // Update nhood for (Particle current : algorithm.getTopology()) { for (Particle other : algorithm.getNeighbourhood().f(topology, current)) { if (current.getSocialFitness().compareTo(other.getNeighbourhoodBest().getSocialFitness()) > 0) { other.setNeighbourhoodBest(current); } } } } public void setIterationStrategy(IterationStrategy iterationStrategy) { this.iterationStrategy = iterationStrategy; } public void setIterationProbability(ControlParameter iterationProbability) { this.iterationProbability = iterationProbability; } public void setCrossoverStrategy(ParticleCrossoverStrategy crossoverStrategy) { this.crossoverStrategy = crossoverStrategy; } }
true
true
private void crossoverStep(PSO algorithm) { fj.data.List<Particle> topology = algorithm.getTopology(); Particle gbest = Topologies.getBestEntity(topology, new SocialBestFitnessComparator<>()); // Get parents final List<Particle> parents = Lists.newArrayList(new RandomSelector<Particle>() .on(topology) .exclude(gbest) .select(Samples.first(crossoverStrategy.getNumberOfParents() - 1))); parents.add(gbest); // Add offspring parents.addAll(crossoverStrategy.crossover(parents)); Collections.sort(parents, new DescendingFitnessComparator<>()); // Get particles to replace final List<Particle> rp = Lists.newArrayList(new RandomSelector<Particle>() .on(topology) .exclude(gbest) .select(Samples.first(crossoverStrategy.getNumberOfParents() - 1))); rp.add(gbest); // Replace particles final Iterator<Particle> iter = parents.iterator(); algorithm.setTopology(topology.map(new F<Particle, Particle>() { @Override public Particle f(Particle a) { if (rp.contains(a)) { return iter.next(); } return a; } })); // Update nhood for (Particle current : algorithm.getTopology()) { for (Particle other : algorithm.getNeighbourhood().f(topology, current)) { if (current.getSocialFitness().compareTo(other.getNeighbourhoodBest().getSocialFitness()) > 0) { other.setNeighbourhoodBest(current); } } } }
private void crossoverStep(PSO algorithm) { fj.data.List<Particle> topology = algorithm.getTopology(); Particle gbest = Topologies.getBestEntity(topology, new SocialBestFitnessComparator<>()); // Get parents final List<Particle> parents = Lists.newArrayList(new RandomSelector<Particle>() .on(topology) .exclude(gbest) .select(Samples.first(crossoverStrategy.getNumberOfParents() - 1))); parents.add(gbest); // Add offspring parents.addAll(crossoverStrategy.crossover(parents)); Collections.sort(parents, new DescendingFitnessComparator<>()); // Get particles to replace final List<Particle> rp = Lists.newArrayList(new RandomSelector<Particle>() .on(topology) .exclude(gbest) .select(Samples.first(crossoverStrategy.getNumberOfParents() - 1))); rp.add(gbest); // Replace particles final Iterator<Particle> iter = parents.iterator(); algorithm.setTopology(topology.map(new F<Particle, Particle>() { @Override public Particle f(Particle a) { if (rp.contains(a) && iter.hasNext()) { return iter.next(); } return a; } })); // Update nhood for (Particle current : algorithm.getTopology()) { for (Particle other : algorithm.getNeighbourhood().f(topology, current)) { if (current.getSocialFitness().compareTo(other.getNeighbourhoodBest().getSocialFitness()) > 0) { other.setNeighbourhoodBest(current); } } } }
diff --git a/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java b/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java index 6747a900..795d7c05 100644 --- a/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java +++ b/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java @@ -1,73 +1,78 @@ package org.springframework.persistence.support; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.ClassUtils; /** * Try for a constructor taking state: failing that, try a no-arg * constructor and then setUnderlyingNode(). * * @author Rod Johnson */ public abstract class AbstractConstructorEntityInstantiator<BACKING_INTERFACE, STATE> implements EntityInstantiator<BACKING_INTERFACE, STATE> { private final Log log = LogFactory.getLog(getClass()); final public <T extends BACKING_INTERFACE> T createEntityFromState(STATE n, Class<T> c) { try { return fromStateInternal(n, c); } catch (InstantiationException e) { throw new IllegalArgumentException(e); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e); } } final private <T extends BACKING_INTERFACE> T fromStateInternal(STATE n, Class<T> c) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // TODO this is fragile Class<? extends STATE> stateInterface = (Class<? extends STATE>) n.getClass().getInterfaces()[0]; Constructor<T> nodeConstructor = ClassUtils.getConstructorIfAvailable(c, stateInterface); if (nodeConstructor != null) { // TODO is this the correct way to instantiate or does Spring have a preferred way? log.info("Using " + c + " constructor taking " + stateInterface); return nodeConstructor.newInstance(n); } Constructor<T> noArgConstructor = ClassUtils.getConstructorIfAvailable(c); if (noArgConstructor == null) noArgConstructor = getDeclaredConstructor(c); if (noArgConstructor != null) { log.info("Using " + c + " no-arg constructor"); StateProvider.setUnderlyingState(n); - T t = noArgConstructor.newInstance(); - setState(t, n); + T t; + try { + t = noArgConstructor.newInstance(); + setState(t, n); + } finally { + StateProvider.retrieveState(); + } return t; } throw new IllegalArgumentException(getClass().getSimpleName() + ": entity " + c + " must have either a constructor taking [" + stateInterface + "] or a no-arg constructor and state set method"); } private <T> Constructor<T> getDeclaredConstructor(Class<T> c) { try { final Constructor<T> declaredConstructor = c.getDeclaredConstructor(); declaredConstructor.setAccessible(true); return declaredConstructor; } catch (NoSuchMethodException e) { return null; } } /** * Subclasses must implement to set state * @param entity * @param s */ protected abstract void setState(BACKING_INTERFACE entity, STATE s); }
true
true
final private <T extends BACKING_INTERFACE> T fromStateInternal(STATE n, Class<T> c) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // TODO this is fragile Class<? extends STATE> stateInterface = (Class<? extends STATE>) n.getClass().getInterfaces()[0]; Constructor<T> nodeConstructor = ClassUtils.getConstructorIfAvailable(c, stateInterface); if (nodeConstructor != null) { // TODO is this the correct way to instantiate or does Spring have a preferred way? log.info("Using " + c + " constructor taking " + stateInterface); return nodeConstructor.newInstance(n); } Constructor<T> noArgConstructor = ClassUtils.getConstructorIfAvailable(c); if (noArgConstructor == null) noArgConstructor = getDeclaredConstructor(c); if (noArgConstructor != null) { log.info("Using " + c + " no-arg constructor"); StateProvider.setUnderlyingState(n); T t = noArgConstructor.newInstance(); setState(t, n); return t; } throw new IllegalArgumentException(getClass().getSimpleName() + ": entity " + c + " must have either a constructor taking [" + stateInterface + "] or a no-arg constructor and state set method"); }
final private <T extends BACKING_INTERFACE> T fromStateInternal(STATE n, Class<T> c) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // TODO this is fragile Class<? extends STATE> stateInterface = (Class<? extends STATE>) n.getClass().getInterfaces()[0]; Constructor<T> nodeConstructor = ClassUtils.getConstructorIfAvailable(c, stateInterface); if (nodeConstructor != null) { // TODO is this the correct way to instantiate or does Spring have a preferred way? log.info("Using " + c + " constructor taking " + stateInterface); return nodeConstructor.newInstance(n); } Constructor<T> noArgConstructor = ClassUtils.getConstructorIfAvailable(c); if (noArgConstructor == null) noArgConstructor = getDeclaredConstructor(c); if (noArgConstructor != null) { log.info("Using " + c + " no-arg constructor"); StateProvider.setUnderlyingState(n); T t; try { t = noArgConstructor.newInstance(); setState(t, n); } finally { StateProvider.retrieveState(); } return t; } throw new IllegalArgumentException(getClass().getSimpleName() + ": entity " + c + " must have either a constructor taking [" + stateInterface + "] or a no-arg constructor and state set method"); }
diff --git a/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/builder/DroolsBuilder.java b/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/builder/DroolsBuilder.java index 39c76034..83f991ff 100644 --- a/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/builder/DroolsBuilder.java +++ b/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/builder/DroolsBuilder.java @@ -1,477 +1,478 @@ package org.drools.eclipse.builder; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.antlr.runtime.RecognitionException; import org.drools.guvnor.client.modeldriven.brl.RuleModel; import org.drools.guvnor.server.util.BRDRLPersistence; import org.drools.guvnor.server.util.BRXMLPersistence; import org.drools.commons.jci.problems.CompilationProblem; import org.drools.compiler.DescrBuildError; import org.drools.compiler.DroolsError; import org.drools.compiler.DroolsParserException; import org.drools.compiler.FactTemplateError; import org.drools.compiler.FieldTemplateError; import org.drools.compiler.FunctionError; import org.drools.compiler.GlobalError; import org.drools.compiler.ImportError; import org.drools.compiler.ParserError; import org.drools.compiler.RuleBuildError; import org.drools.decisiontable.InputType; import org.drools.decisiontable.SpreadsheetCompiler; import org.drools.eclipse.DRLInfo; import org.drools.eclipse.DroolsEclipsePlugin; import org.drools.eclipse.ProcessInfo; import org.drools.eclipse.preferences.IDroolsConstants; import org.drools.lang.ExpanderException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; /** * Automatically syntax checks .drl files and adds possible * errors or warnings to the problem list. Nominally is triggerd on save. * * @author <a href="mailto:[email protected]">kris verlaenen </a> */ public class DroolsBuilder extends IncrementalProjectBuilder { public static final String BUILDER_ID = "org.drools.eclipse.droolsbuilder"; protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { IProject currentProject = getProject(); if (currentProject == null || !currentProject.isAccessible()) { return new IProject[0]; } try { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); if (kind == IncrementalProjectBuilder.FULL_BUILD) { fullBuild(monitor); } else { IResourceDelta delta = getDelta(getProject()); if (delta == null) { fullBuild(monitor); } else { incrementalBuild(delta, monitor); } } } catch (CoreException e) { IMarker marker = currentProject.createMarker(IDroolsModelMarker.DROOLS_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "Error when trying to build Drools project: " + e.getLocalizedMessage()); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); } return getRequiredProjects(currentProject); } protected void fullBuild(IProgressMonitor monitor) throws CoreException { getProject().accept(new DroolsBuildVisitor()); } protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException { boolean buildAll = DroolsEclipsePlugin.getDefault().getPreferenceStore().getBoolean(IDroolsConstants.BUILD_ALL); if (buildAll) { // to make sure that all rules are checked when a java file is changed fullBuild(monitor); } else { delta.accept(new DroolsBuildDeltaVisitor()); } } private class DroolsBuildVisitor implements IResourceVisitor { public boolean visit(IResource res) { return parseResource(res, true); } } private class DroolsBuildDeltaVisitor implements IResourceDeltaVisitor { public boolean visit(IResourceDelta delta) throws CoreException { return parseResource(delta.getResource(), false); } } protected boolean parseResource(IResource res, boolean clean) { try { IJavaProject project = JavaCore.create(res.getProject()); // exclude files that are located in the output directory, // unless the ouput directory is the same as the project location if (!project.getOutputLocation().equals(project.getPath()) && project.getOutputLocation().isPrefixOf(res.getFullPath())) { return false; } } catch (JavaModelException e) { // do nothing } if (res instanceof IFile && ("drl".equals(res.getFileExtension()) || "dslr".equals(res.getFileExtension()) || ".package".equals(res.getName()))) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseDRLFile((IFile) res, new String(Util.getResourceContentsAsCharArray((IFile) res))); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { + DroolsEclipsePlugin.log(t); createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "xls".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseXLSFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "csv".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseCSVFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "brl".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseBRLFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "rf".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseRuleFlowFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } return true; } private DroolsBuildMarker[] parseDRLFile(IFile file, String content) { List markers = new ArrayList(); try { DRLInfo drlInfo = DroolsEclipsePlugin.getDefault().parseResource(file, true); //parser errors markParseErrors(markers, drlInfo.getParserErrors()); markOtherErrors(markers, drlInfo.getBuilderErrors()); } catch (DroolsParserException e) { // we have an error thrown from DrlParser Throwable cause = e.getCause(); if (cause instanceof RecognitionException ) { RecognitionException recogErr = (RecognitionException) cause; markers.add(new DroolsBuildMarker(recogErr.getMessage(), recogErr.line)); //flick back the line number } } catch (Exception t) { String message = t.getMessage(); if (message == null || message.trim().equals("")) { message = "Error: " + t.getClass().getName(); } markers.add(new DroolsBuildMarker(message)); } return (DroolsBuildMarker[]) markers.toArray(new DroolsBuildMarker[markers.size()]); } private DroolsBuildMarker[] parseXLSFile(IFile file) { List markers = new ArrayList(); try { SpreadsheetCompiler converter = new SpreadsheetCompiler(); String drl = converter.compile(file.getContents(), InputType.XLS); DRLInfo drlInfo = DroolsEclipsePlugin.getDefault().parseXLSResource(drl, file); // parser errors markParseErrors(markers, drlInfo.getParserErrors()); markOtherErrors(markers, drlInfo.getBuilderErrors()); } catch (DroolsParserException e) { // we have an error thrown from DrlParser Throwable cause = e.getCause(); if (cause instanceof RecognitionException ) { RecognitionException recogErr = (RecognitionException) cause; markers.add(new DroolsBuildMarker(recogErr.getMessage(), recogErr.line)); //flick back the line number } } catch (Exception t) { String message = t.getMessage(); if (message == null || message.trim().equals( "" )) { message = "Error: " + t.getClass().getName(); } markers.add(new DroolsBuildMarker(message)); } return (DroolsBuildMarker[]) markers.toArray(new DroolsBuildMarker[markers.size()]); } private DroolsBuildMarker[] parseCSVFile(IFile file) { List markers = new ArrayList(); try { SpreadsheetCompiler converter = new SpreadsheetCompiler(); String drl = converter.compile(file.getContents(), InputType.CSV); DRLInfo drlInfo = DroolsEclipsePlugin.getDefault().parseXLSResource(drl, file); // parser errors markParseErrors(markers, drlInfo.getParserErrors()); markOtherErrors(markers, drlInfo.getBuilderErrors()); } catch (DroolsParserException e) { // we have an error thrown from DrlParser Throwable cause = e.getCause(); if (cause instanceof RecognitionException ) { RecognitionException recogErr = (RecognitionException) cause; markers.add(new DroolsBuildMarker(recogErr.getMessage(), recogErr.line)); //flick back the line number } } catch (Exception t) { String message = t.getMessage(); if (message == null || message.trim().equals( "" )) { message = "Error: " + t.getClass().getName(); } markers.add(new DroolsBuildMarker(message)); } return (DroolsBuildMarker[]) markers.toArray(new DroolsBuildMarker[markers.size()]); } private DroolsBuildMarker[] parseBRLFile(IFile file) { List markers = new ArrayList(); try { String brl = convertToString(file.getContents()); RuleModel model = BRXMLPersistence.getInstance().unmarshal(brl); String drl = BRDRLPersistence.getInstance().marshal(model); // TODO pass this through DSL converter in case brl is based on dsl DRLInfo drlInfo = DroolsEclipsePlugin.getDefault().parseBRLResource(drl, file); // parser errors markParseErrors(markers, drlInfo.getParserErrors()); markOtherErrors(markers, drlInfo.getBuilderErrors()); } catch (DroolsParserException e) { // we have an error thrown from DrlParser Throwable cause = e.getCause(); if (cause instanceof RecognitionException ) { RecognitionException recogErr = (RecognitionException) cause; markers.add(new DroolsBuildMarker(recogErr.getMessage(), recogErr.line)); //flick back the line number } } catch (Exception t) { String message = t.getMessage(); if (message == null || message.trim().equals( "" )) { message = "Error: " + t.getClass().getName(); } markers.add(new DroolsBuildMarker(message)); } return (DroolsBuildMarker[]) markers.toArray(new DroolsBuildMarker[markers.size()]); } protected DroolsBuildMarker[] parseRuleFlowFile(IFile file) { if (!file.exists()) { return new DroolsBuildMarker[0]; } List markers = new ArrayList(); try { String input = convertToString(file.getContents()); ProcessInfo processInfo = DroolsEclipsePlugin.getDefault().parseProcess(input, file); if (processInfo != null) { markParseErrors(markers, processInfo.getErrors()); } } catch (Exception t) { t.printStackTrace(); String message = t.getMessage(); if (message == null || message.trim().equals( "" )) { message = "Error: " + t.getClass().getName(); } markers.add(new DroolsBuildMarker(message)); } return (DroolsBuildMarker[]) markers.toArray(new DroolsBuildMarker[markers.size()]); } protected static String convertToString(final InputStream inputStream) throws IOException { Reader reader = new InputStreamReader(inputStream); final StringBuffer text = new StringBuffer(); final char[] buf = new char[1024]; int len = 0; while ((len = reader.read(buf)) >= 0) { text.append(buf, 0, len); } return text.toString(); } /** * This will create markers for parse errors. * Parse errors mean that antlr has picked up some major typos in the input source. */ protected void markParseErrors(List markers, List parserErrors) { for ( Iterator iter = parserErrors.iterator(); iter.hasNext(); ) { Object error = iter.next(); if (error instanceof ParserError) { ParserError err = (ParserError) error; markers.add(new DroolsBuildMarker(err.getMessage(), err.getRow())); } else if (error instanceof ExpanderException) { ExpanderException exc = (ExpanderException) error; // TODO line mapping is incorrect markers.add(new DroolsBuildMarker(exc.getMessage(), -1)); } else { markers.add(new DroolsBuildMarker(error.toString())); } } } /** * This will create markers for build errors that happen AFTER parsing. */ private void markOtherErrors(List markers, DroolsError[] buildErrors) { // TODO are there warnings too? for (int i = 0; i < buildErrors.length; i++ ) { DroolsError error = buildErrors[i]; if (error instanceof GlobalError) { GlobalError globalError = (GlobalError) error; markers.add(new DroolsBuildMarker("Global error: " + globalError.getGlobal(), -1)); } else if (error instanceof RuleBuildError) { RuleBuildError ruleError = (RuleBuildError) error; // TODO try to retrieve line number (or even character start-end) // disabled for now because line number are those of the rule class, // not the rule file itself if (ruleError.getObject() instanceof CompilationProblem[]) { CompilationProblem[] problems = (CompilationProblem[]) ruleError.getObject(); for (int j = 0; j < problems.length; j++) { markers.add(new DroolsBuildMarker(problems[j].getMessage(), ruleError.getLine())); } } else { markers.add(new DroolsBuildMarker(ruleError.getRule().getName() + ":" + ruleError.getMessage(), ruleError.getLine())); } } else if (error instanceof ParserError) { ParserError parserError = (ParserError) error; // TODO try to retrieve character start-end markers.add(new DroolsBuildMarker(parserError.getMessage(), parserError.getRow())); } else if (error instanceof FunctionError) { FunctionError functionError = (FunctionError) error; // TODO add line to function error // TODO try to retrieve character start-end if (functionError.getObject() instanceof CompilationProblem[]) { CompilationProblem[] problems = (CompilationProblem[]) functionError.getObject(); for (int j = 0; j < problems.length; j++) { markers.add(new DroolsBuildMarker(problems[j].getMessage(), functionError.getErrorLines()[j])); } } else { markers.add(new DroolsBuildMarker(functionError.getFunctionDescr().getName() + ":" + functionError.getMessage(), -1)); } } else if (error instanceof FieldTemplateError) { markers.add(new DroolsBuildMarker(error.getMessage(), ((FieldTemplateError) error).getLine())); } else if (error instanceof FactTemplateError) { markers.add(new DroolsBuildMarker(error.getMessage(), ((FactTemplateError) error).getLine())); } else if (error instanceof ImportError) { markers.add(new DroolsBuildMarker("ImportError: " + error.getMessage())); } else if (error instanceof DescrBuildError) { markers.add(new DroolsBuildMarker("BuildError: " + error.getMessage(), ((DescrBuildError) error).getLine())); } else { markers.add(new DroolsBuildMarker("Unknown DroolsError " + error.getClass() + ": " + error)); } } } protected void createMarker(final IResource res, final String message, final int lineNumber) { try { IWorkspaceRunnable r= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { IMarker marker = res .createMarker(IDroolsModelMarker.DROOLS_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, message); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LINE_NUMBER, lineNumber); } }; res.getWorkspace().run(r, null, IWorkspace.AVOID_UPDATE, null); } catch (CoreException e) { DroolsEclipsePlugin.log(e); } } protected void removeProblemsFor(IResource resource) { try { if (resource != null && resource.exists()) { resource.deleteMarkers( IDroolsModelMarker.DROOLS_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); } } catch (CoreException e) { DroolsEclipsePlugin.log(e); } } private IProject[] getRequiredProjects(IProject project) { IJavaProject javaProject = JavaCore.create(project); List projects = new ArrayList(); try { IClasspathEntry[] entries = javaProject.getResolvedClasspath(true); for (int i = 0, l = entries.length; i < l; i++) { IClasspathEntry entry = entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IProject p = project.getWorkspace().getRoot().getProject(entry.getPath().lastSegment()); // missing projects are considered too if (p != null && !projects.contains(p)) { projects.add(p); } } } } catch(JavaModelException e) { return new IProject[0]; } return (IProject[]) projects.toArray(new IProject[projects.size()]); } }
true
true
protected boolean parseResource(IResource res, boolean clean) { try { IJavaProject project = JavaCore.create(res.getProject()); // exclude files that are located in the output directory, // unless the ouput directory is the same as the project location if (!project.getOutputLocation().equals(project.getPath()) && project.getOutputLocation().isPrefixOf(res.getFullPath())) { return false; } } catch (JavaModelException e) { // do nothing } if (res instanceof IFile && ("drl".equals(res.getFileExtension()) || "dslr".equals(res.getFileExtension()) || ".package".equals(res.getName()))) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseDRLFile((IFile) res, new String(Util.getResourceContentsAsCharArray((IFile) res))); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "xls".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseXLSFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "csv".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseCSVFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "brl".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseBRLFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "rf".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseRuleFlowFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } return true; }
protected boolean parseResource(IResource res, boolean clean) { try { IJavaProject project = JavaCore.create(res.getProject()); // exclude files that are located in the output directory, // unless the ouput directory is the same as the project location if (!project.getOutputLocation().equals(project.getPath()) && project.getOutputLocation().isPrefixOf(res.getFullPath())) { return false; } } catch (JavaModelException e) { // do nothing } if (res instanceof IFile && ("drl".equals(res.getFileExtension()) || "dslr".equals(res.getFileExtension()) || ".package".equals(res.getName()))) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseDRLFile((IFile) res, new String(Util.getResourceContentsAsCharArray((IFile) res))); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { DroolsEclipsePlugin.log(t); createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "xls".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseXLSFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "csv".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseCSVFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "brl".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseBRLFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } else if (res instanceof IFile && "rf".equals(res.getFileExtension())) { removeProblemsFor(res); try { if (clean) { DroolsEclipsePlugin.getDefault().invalidateResource(res); } DroolsBuildMarker[] markers = parseRuleFlowFile((IFile) res); for (int i = 0; i < markers.length; i++) { createMarker(res, markers[i].getText(), markers[i].getLine()); } } catch (Throwable t) { createMarker(res, t.getMessage(), -1); } return false; } return true; }
diff --git a/src/main/java/org/odlabs/wiquery/ui/selectable/SelectableAjaxBehavior.java b/src/main/java/org/odlabs/wiquery/ui/selectable/SelectableAjaxBehavior.java index 02080173..6d60280c 100644 --- a/src/main/java/org/odlabs/wiquery/ui/selectable/SelectableAjaxBehavior.java +++ b/src/main/java/org/odlabs/wiquery/ui/selectable/SelectableAjaxBehavior.java @@ -1,424 +1,424 @@ /* * Copyright (c) 2009 WiQuery team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.odlabs.wiquery.ui.selectable; import java.util.StringTokenizer; import org.apache.wicket.Component; import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.odlabs.wiquery.core.javascript.JsScopeContext; import org.odlabs.wiquery.core.javascript.JsStatement; import org.odlabs.wiquery.core.options.Options; import org.odlabs.wiquery.core.util.MarkupIdVisitor; import org.odlabs.wiquery.ui.core.JsScopeUiEvent; import org.odlabs.wiquery.ui.selectable.SelectableBehavior.ToleranceEnum; /** * $Id: SelectableAjaxBehavior * <p> * Sets the attached component selectable behavior. When the user finished to * select some childs components,{@link #onSelection(Component[], AjaxRequestTarget)} * is called via Ajax. * </p> * * <p> * This behavior contains a {@link SelectableBehavior} which is used to control * the options of the selectable, including all the options and event of the * behavior. Example: * <pre> * SelectableAjaxBehavior selectable = new SelectableAjaxBehavior() { * public void onSelection(Component[] components, AjaxRequestTarget ajaxRequestTarget) { * ... * } * } * SelectableBehavior sb = selectable.getSelectableBehavior(); * sb.setTolerance(ToleranceEnum.FIT); * add(selectable); * </pre> * </p> * * @author Julien Roche * @since 1.0 */ public abstract class SelectableAjaxBehavior extends AbstractDefaultAjaxBehavior { /** * We override the behavior to deny the access of critical methods * * @author Julien Roche * */ private class InnerDroppableBehavior extends SelectableBehavior { // Constants /** Constant of serialization */ private static final long serialVersionUID = 5587258236214715234L; /** * {@inheritDoc} * @see org.odlabs.wiquery.ui.selectable.SelectableBehavior#getOptions() */ @Override protected Options getOptions() { throw new UnsupportedOperationException( "You can't call this method into the SelectableAjaxBehavior"); } /** * For framework internal use only. */ private void setInnerStopEvent(JsScopeUiEvent stop) { super.setStopEvent(stop); } /** * {@inheritDoc} * @see org.odlabs.wiquery.ui.selectable.SelectableBehavior#setStopEvent(org.odlabs.wiquery.ui.core.JsScopeUiEvent) */ @Override public SelectableBehavior setStopEvent(JsScopeUiEvent stop) { throw new UnsupportedOperationException( "You can't call this method into the SelectableAjaxBehavior"); } /** * {@inheritDoc} * @see org.odlabs.wiquery.ui.selectable.SelectableBehavior#statement() */ @Override public JsStatement statement() { selectableBehavior.setInnerStopEvent(new JsScopeUiEvent() { private static final long serialVersionUID = 1L; /** * {@inheritDoc} * @see org.odlabs.wiquery.core.javascript.JsScope#execute(org.odlabs.wiquery.core.javascript.JsScopeContext) */ @Override protected void execute(JsScopeContext scopeContext) { scopeContext.append("var selected = new Array();" + "jQuery.each($('#" + getComponent().getMarkupId(true) +"')" + - ".children(\"*[class*='ui-selected']\"), function(){" + + ".find(\".ui-selectee.ui-selected\"), function(){" + "selected.push($(this).attr('id'));});" + SelectableAjaxBehavior.this.getCallbackScript(true)); } }); return super.statement(); } } // Constants /** Constant of serialization */ private static final long serialVersionUID = 1L; /** * Adding the standard selectable JavaScript behavior */ private InnerDroppableBehavior selectableBehavior; /** Selection into the request */ private static final String SELECTED_ARRAY = "selectedArray"; /** * Default constructor */ public SelectableAjaxBehavior() { super(); selectableBehavior = new InnerDroppableBehavior(); } /** * We override super method to add the selected array to the URL. * Otherwise we use standard AbstractDefaultAjaxBehavior machinery to generate script: what way all the logic * regarding IAjaxCallDecorator or indicatorId will be added to the generated script. * This makes selectable AJAX behavior compatible with standard Wicket's AJAX call-backs. * * (non-Javadoc) * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#getCallbackUrl() */ @Override protected CharSequence getCallbackScript() { return generateCallbackScript("wicketAjaxGet('" + getCallbackUrl() + "&" + SELECTED_ARRAY + "='+ jQuery.unique(selected).toString()"); } /** * @return the standard Selectable JavaScript behavior */ public SelectableBehavior getSelectableBehavior() { return selectableBehavior; } /** * {@inheritDoc} * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#onBind() */ @Override protected void onBind() { getComponent().add(selectableBehavior); } /** * For framework internal use only. */ public final void onSelection(AjaxRequestTarget target) { String selected = this.getComponent().getRequest().getQueryParameters().getParameterValue(SELECTED_ARRAY).toString(); StringTokenizer tokenized = new StringTokenizer(selected, ","); Component[] components = new Component[tokenized.countTokens()]; Integer index = 0; MarkupIdVisitor visitorParent = null; while(tokenized.hasMoreTokens()){ visitorParent = new MarkupIdVisitor(tokenized.nextToken().trim()); this.getComponent().getPage().visitChildren(visitorParent); components[index] = visitorParent.getFoundComponent(); index++; } onSelection(components, target); } /** * onSelection is triggered at the end of a selection operation. * * @param components List of components selected * @param ajaxRequestTarget the Ajax target */ public abstract void onSelection(Component[] components, AjaxRequestTarget ajaxRequestTarget); /** * {@inheritDoc} * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#respond(org.apache.wicket.ajax.AjaxRequestTarget) */ @Override protected void respond(AjaxRequestTarget target) { onSelection(target); } /** * {@inheritDoc} * @see org.odlabs.wiquery.core.commons.IWiQueryPlugin#statement() */ protected JsStatement statement() { return selectableBehavior.statement(); } //////////////////////////////////////////////////////////////////////////// //// SHORTCUTS //// //////////////////////////////////////////////////////////////////////////// /** * @return the cancel option value */ public String getCancel() { return selectableBehavior.getCancel(); } /** * @return the delay option value */ public int getDelay() { return selectableBehavior.getDelay(); } /** * @return the distance option value */ public int getDistance() { return selectableBehavior.getDistance(); } /** * @return the cancel option value */ public String getFilter() { return selectableBehavior.getFilter(); } /** * @return the tolerance option enum */ public ToleranceEnum getTolerance() { return selectableBehavior.getTolerance(); } /** * @return the autoRefresh option enum */ public boolean isAutoRefresh() { return selectableBehavior.isAutoRefresh(); } /** This determines whether to refresh (recalculate) the position and size * of each selected at the beginning of each select operation. If you have * many many items, you may want to set this to false and call the * refresh method manually. * @param autoRefresh * @return instance of the current behavior */ public SelectableAjaxBehavior setAutoRefresh(boolean autoRefresh) { selectableBehavior.setAutoRefresh(autoRefresh); return this; } /**Disables (true) or enables (false) the selectable. Can be set when * initialising (first creating) the selectable. * @param disabled * @return instance of the current behavior */ public SelectableAjaxBehavior setDisabled(boolean disabled) { selectableBehavior.setDisabled(disabled); return this; } /** * @return the disabled option */ public boolean isDisabled() { return selectableBehavior.isDisabled(); } /** Set's the prevent selecting if you start on elements matching the selector * @param cancel Selector (default : ':input,option') * @return instance of the current behavior */ public SelectableAjaxBehavior setCancel(String cancel) { selectableBehavior.setCancel(cancel); return this; } /** Set's the delay (in milliseconds) to define when the selecting should start * @param delay * @return instance of the current behavior */ public SelectableAjaxBehavior setDelay(int delay) { selectableBehavior.setDelay(delay); return this; } /** Set's the tolerance in pixels * @param distance * @return instance of the current behavior */ public SelectableAjaxBehavior setDistance(int distance) { selectableBehavior.setDistance(distance); return this; } /** Set's the matching child to be selectable * @param filter Selector (default : '*') * @return instance of the current behavior */ public SelectableAjaxBehavior setFilter(String filter) { selectableBehavior.setFilter(filter); return this; } /** Set's the tolerance * <ul> * <li><b>fit</b>: draggable overlaps the droppable entirely</li> * <li><b>touch</b>: draggable overlaps the droppable any amount</li> * </ul> * @param tolerance * @return instance of the current behavior */ public SelectableAjaxBehavior setTolerance(ToleranceEnum tolerance) { selectableBehavior.setTolerance(tolerance); return this; } /*---- Methods section ----*/ /**Method to destroy * This will return the element back to its pre-init state. * @return the associated JsStatement */ public JsStatement destroy() { return selectableBehavior.destroy(); } /**Method to destroy within the ajax request * @param ajaxRequestTarget */ public void destroy(AjaxRequestTarget ajaxRequestTarget) { selectableBehavior.destroy(ajaxRequestTarget); } /**Method to disable * @return the associated JsStatement */ public JsStatement disable() { return selectableBehavior.disable(); } /**Method to disable within the ajax request * @param ajaxRequestTarget */ public void disable(AjaxRequestTarget ajaxRequestTarget) { selectableBehavior.disable(ajaxRequestTarget); } /**Method to enable * @return the associated JsStatement */ public JsStatement enable() { return selectableBehavior.enable(); } /**Method to enable within the ajax request * @param ajaxRequestTarget */ public void enable(AjaxRequestTarget ajaxRequestTarget) { selectableBehavior.enable(ajaxRequestTarget); } /**Method to refresh * @return the associated JsStatement */ public JsStatement refresh() { return selectableBehavior.refresh(); } /**Method to refresh within the ajax request * @param ajaxRequestTarget */ public void refresh(AjaxRequestTarget ajaxRequestTarget) { selectableBehavior.refresh(); } /**Method to returns the .ui-selectable element * @return the associated JsStatement */ public JsStatement widget() { return selectableBehavior.widget(); } /**Method to returns the .ui-selectable element within the ajax request * @param ajaxRequestTarget */ public void widget(AjaxRequestTarget ajaxRequestTarget) { selectableBehavior.widget(ajaxRequestTarget); } }
true
true
public JsStatement statement() { selectableBehavior.setInnerStopEvent(new JsScopeUiEvent() { private static final long serialVersionUID = 1L; /** * {@inheritDoc} * @see org.odlabs.wiquery.core.javascript.JsScope#execute(org.odlabs.wiquery.core.javascript.JsScopeContext) */ @Override protected void execute(JsScopeContext scopeContext) { scopeContext.append("var selected = new Array();" + "jQuery.each($('#" + getComponent().getMarkupId(true) +"')" + ".children(\"*[class*='ui-selected']\"), function(){" + "selected.push($(this).attr('id'));});" + SelectableAjaxBehavior.this.getCallbackScript(true)); } }); return super.statement(); }
public JsStatement statement() { selectableBehavior.setInnerStopEvent(new JsScopeUiEvent() { private static final long serialVersionUID = 1L; /** * {@inheritDoc} * @see org.odlabs.wiquery.core.javascript.JsScope#execute(org.odlabs.wiquery.core.javascript.JsScopeContext) */ @Override protected void execute(JsScopeContext scopeContext) { scopeContext.append("var selected = new Array();" + "jQuery.each($('#" + getComponent().getMarkupId(true) +"')" + ".find(\".ui-selectee.ui-selected\"), function(){" + "selected.push($(this).attr('id'));});" + SelectableAjaxBehavior.this.getCallbackScript(true)); } }); return super.statement(); }
diff --git a/src/Controller/CharacterController.java b/src/Controller/CharacterController.java index 275ba74..3ba7c0e 100644 --- a/src/Controller/CharacterController.java +++ b/src/Controller/CharacterController.java @@ -1,111 +1,112 @@ package controller; import model.Character; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Input; import view.CharacterView; import view.WorldView; public class CharacterController { private InGameController inGameController; private Character character; private CharacterView characterView; /*Default keyvalues*/ private int keyRight = Input.KEY_RIGHT; private int keyLeft = Input.KEY_LEFT; private int keyDown = Input.KEY_DOWN; private int keyUp = Input.KEY_UP; public CharacterController(InGameController inGameController) { this.inGameController = inGameController; this.character = new Character(400, 300); this.characterView = new CharacterView(character); } public Character getCharacter() { return character; } public CharacterView getCharacterView() { return characterView; } /*Getters for keypresses*/ public int getKeyRight() { return this.keyRight; } public int getKeyLeft() { return this.keyLeft; } public int getKeyUp() { return this.keyUp; } public int getKeyDown() { return this.keyDown; } /*Setters for keypresses*/ public void setKeyRight(int keyRight) { this.keyRight = keyRight; } public void setKeyLeft(int keyLeft) { this.keyLeft = keyLeft; } public void setKeyUp(int keyUp) { this.keyUp = keyUp; } public void setKeyDown(int keyDown) { this.keyDown = keyDown; } /*Check the key pressed matches the right key*/ public boolean isControllerRight(int key) { return this.keyRight == key; } public boolean isControllerLeft(int key) { return this.keyLeft == key; } public boolean isControllerUp(int key) { return this.keyUp == key; } public boolean isControllerDown(int key) { return this.keyUp == key; } //check which key is pressed //borde event-anropas från vyn public void keyPressedUpdate(GameContainer gc) { Input input = gc.getInput(); if(input.isKeyDown(Input.KEY_RIGHT)) { characterView.setColor(Color.blue); inGameController.getWorldController().moveBodyRight(); } if(input.isKeyDown(Input.KEY_LEFT)) { characterView.setColor(Color.green); inGameController.getWorldController().moveBodyLeft(); } if(isControllerDown(Input.KEY_DOWN)) { //plocka upp ett item TODO } - if(isControllerUp(Input.KEY_UP)) { + if(input.isKeyDown(Input.KEY_UP)) { + characterView.setColor(Color.red); inGameController.getWorldController().jumpBody(); } } }
true
true
public void keyPressedUpdate(GameContainer gc) { Input input = gc.getInput(); if(input.isKeyDown(Input.KEY_RIGHT)) { characterView.setColor(Color.blue); inGameController.getWorldController().moveBodyRight(); } if(input.isKeyDown(Input.KEY_LEFT)) { characterView.setColor(Color.green); inGameController.getWorldController().moveBodyLeft(); } if(isControllerDown(Input.KEY_DOWN)) { //plocka upp ett item TODO } if(isControllerUp(Input.KEY_UP)) { inGameController.getWorldController().jumpBody(); } }
public void keyPressedUpdate(GameContainer gc) { Input input = gc.getInput(); if(input.isKeyDown(Input.KEY_RIGHT)) { characterView.setColor(Color.blue); inGameController.getWorldController().moveBodyRight(); } if(input.isKeyDown(Input.KEY_LEFT)) { characterView.setColor(Color.green); inGameController.getWorldController().moveBodyLeft(); } if(isControllerDown(Input.KEY_DOWN)) { //plocka upp ett item TODO } if(input.isKeyDown(Input.KEY_UP)) { characterView.setColor(Color.red); inGameController.getWorldController().jumpBody(); } }
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java index fc1c1d06a..cec446f04 100644 --- a/src/com/android/launcher3/LauncherModel.java +++ b/src/com/android/launcher3/LauncherModel.java @@ -1,3074 +1,3074 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.app.SearchManager; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.*; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import android.util.Pair; import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons private final boolean mAppsCanBeOnRemoveableStorage; private final LauncherAppState mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private LoaderTask mLoaderTask; private boolean mIsLoaderTaskRunning; private volatile boolean mFlushingWorkerThread; // Specific runnable types that are run on the main thread deferred handler, this allows us to // clear all queued binding runnables when the Launcher activity is destroyed. private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0; private static final int MAIN_THREAD_BINDING_RUNNABLE = 1; private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); static { sWorkerThread.start(); } private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); // We start off with everything not loaded. After that, we assume that // our monitoring of the package manager provides all updates and we never // need to do a requery. These are only ever touched from the loader thread. private boolean mWorkspaceLoaded; private boolean mAllAppsLoaded; // When we are loading pages synchronously, we can't just post the binding of items on the side // pages as this delays the rotation process. Instead, we wait for a callback from the first // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start // a normal load, we also clear this set of Runnables. static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>(); private WeakReference<Callbacks> mCallbacks; // < only access in worker thread > private AllAppsList mBgAllAppsList; // The lock that must be acquired before referencing any static bg data structures. Unlike // other locks, this one can generally be held long-term because we never expect any of these // static data structures to be referenced outside of the worker thread except on the first // load after configuration change. static final Object sBgLock = new Object(); // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by // LauncherModel to their ids static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>(); // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts // created by LauncherModel that are directly on the home screen (however, no widgets or // shortcuts within folders). static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>(); // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>(); // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>(); // sBgWorkspaceScreens is the ordered set of workspace screens. static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>(); // </ only access in worker thread > private IconCache mIconCache; private Bitmap mDefaultIcon; private static int mCellCountX; private static int mCellCountY; protected int mPreviousConfigMcc; public interface Callbacks { public boolean setLoadOnResume(); public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end, boolean forceAnimateIcons); public void bindScreens(ArrayList<Long> orderedScreenIds); public void bindAddScreens(ArrayList<Long> orderedScreenIds); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(boolean upgradePath); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindComponentsRemoved(ArrayList<String> packageNames, ArrayList<ApplicationInfo> appInfos, boolean matchPackageNamesOnly); public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts); public void bindSearchablesChanged(); public void onPageBoundSynchronously(int page); } public interface ItemInfoFilter { public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn); } LauncherModel(LauncherAppState app, IconCache iconCache) { final Context context = app.getContext(); mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable(); mApp = app; mBgAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( mIconCache.getFullResDefaultActivityIcon(), context); final Resources res = context.getResources(); Configuration config = res.getConfiguration(); mPreviousConfigMcc = config.mcc; } /** Runs the specified runnable immediately if called from the main thread, otherwise it is * posted on the main thread handler. */ private void runOnMainThread(Runnable r) { runOnMainThread(r, 0); } private void runOnMainThread(Runnable r, int type) { if (sWorkerThread.getThreadId() == Process.myTid()) { // If we are on the worker thread, post onto the main handler mHandler.post(r); } else { r.run(); } } /** Runs the specified runnable immediately if called from the worker thread, otherwise it is * posted on the worker thread handler. */ private static void runOnWorkerThread(Runnable r) { if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { // If we are not on the worker thread, then post to the worker handler sWorker.post(r); } } static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy, long screen) { final int xCount = LauncherModel.getCellCountX(); final int yCount = LauncherModel.getCellCountY(); boolean[][] occupied = new boolean[xCount][yCount]; int cellX, cellY, spanX, spanY; for (int i = 0; i < items.size(); ++i) { final ItemInfo item = items.get(i); if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (item.screenId == screen) { cellX = item.cellX; cellY = item.cellY; spanX = item.spanX; spanY = item.spanY; for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) { for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) { occupied[x][y] = true; } } } } } return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied); } static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name, Intent launchIntent, int firstScreenIndex) { // Lock on the app so that we don't try and get the items while apps are being added LauncherAppState app = LauncherAppState.getInstance(); LauncherModel model = app.getModel(); boolean found = false; synchronized (app) { if (sWorkerThread.getThreadId() != Process.myTid()) { // Flush the LauncherModel worker thread, so that if we just did another // processInstallShortcut, we give it time for its shortcut to get added to the // database (getItemsInLocalCoordinates reads the database) model.flushWorkerThread(); } final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context); // Try adding to the workspace screens incrementally, starting at the default or center // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1)) firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size()); int count = sBgWorkspaceScreens.size(); for (int screen = firstScreenIndex; screen < count && !found; screen++) { int[] tmpCoordinates = new int[2]; if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates, sBgWorkspaceScreens.get(screen))) { // Update the Launcher db return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates); } } } return null; } public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added, final Callbacks callbacks) { if (added.isEmpty()) { throw new RuntimeException("EMPTY ADDED ARRAY?"); } // Process the newly added applications and add them to the database first Runnable r = new Runnable() { public void run() { final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>(); final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>(); synchronized(sBgLock) { Iterator<ItemInfo> iter = added.iterator(); while (iter.hasNext()) { ItemInfo a = iter.next(); final String name = a.title.toString(); final Intent launchIntent = a.getIntent(); // Short-circuit this logic if the icon exists somewhere on the workspace if (LauncherModel.shortcutExists(context, name, launchIntent)) { continue; } // Add this icon to the db, creating a new page if necessary int startSearchPageIndex = 1; Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context, name, launchIntent, startSearchPageIndex); if (coords == null) { LauncherAppState appState = LauncherAppState.getInstance(); LauncherProvider lp = appState.getLauncherProvider(); // If we can't find a valid position, then just add a new screen. // This takes time so we need to re-queue the add until the new // page is added. Create as many screens as necessary to satisfy // the startSearchPageIndex. int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 - sBgWorkspaceScreens.size()); while (numPagesToAdd > 0) { long screenId = lp.generateNewScreenId(); // Update the model sBgWorkspaceScreens.add(screenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Save the screen id for binding in the workspace addedWorkspaceScreensFinal.add(screenId); numPagesToAdd--; } // Find the coordinate again coords = LauncherModel.findNextAvailableIconSpace(context, name, launchIntent, startSearchPageIndex); } if (coords == null) { throw new RuntimeException("Coordinates should not be null"); } ShortcutInfo shortcutInfo; if (a instanceof ShortcutInfo) { shortcutInfo = (ShortcutInfo) a; } else if (a instanceof ApplicationInfo) { shortcutInfo = ((ApplicationInfo) a).makeShortcut(); } else { throw new RuntimeException("Unexpected info type"); } // Add the shortcut to the db addItemToDatabase(context, shortcutInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP, coords.first, coords.second[0], coords.second[1], false); // Save the ShortcutInfo for binding in the workspace addedShortcutsFinal.add(shortcutInfo); } } if (!addedShortcutsFinal.isEmpty()) { runOnMainThread(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAddScreens(addedWorkspaceScreensFinal); ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1); long lastScreenId = info.screenId; final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>(); for (ItemInfo i : addedShortcutsFinal) { if (i.screenId == lastScreenId) { addAnimated.add(i); } else { addNotAnimated.add(i); } } // We add the items without animation on non-visible pages, and with // animations on the new page (which we will try and snap to). if (!addNotAnimated.isEmpty()) { callbacks.bindItems(addNotAnimated, 0, addNotAnimated.size(), false); } if (!addAnimated.isEmpty()) { callbacks.bindItems(addAnimated, 0, addAnimated.size(), true); } } } }); } } }; runOnWorkerThread(r); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } public void unbindItemInfosAndClearQueuedBindRunnables() { if (sWorkerThread.getThreadId() == Process.myTid()) { throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " + "main thread"); } // Clear any deferred bind runnables mDeferredBindRunnables.clear(); // Remove any queued bind runnables mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE); // Unbind all the workspace items unbindWorkspaceItemsOnMainThread(); } /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */ void unbindWorkspaceItemsOnMainThread() { // Ensure that we don't use the same workspace items data structure on the main thread // by making a copy of workspace items first. final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>(); synchronized (sBgLock) { tmpWorkspaceItems.addAll(sBgWorkspaceItems); tmpAppWidgets.addAll(sBgAppWidgets); } Runnable r = new Runnable() { @Override public void run() { for (ItemInfo item : tmpWorkspaceItems) { item.unbind(); } for (ItemInfo item : tmpAppWidgets) { item.unbind(); } } }; runOnMainThread(r); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, long screenId, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screenId, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screenId, cellX, cellY); } } static void checkItemInfoLocked( final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) { ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem != null && item != modelItem) { // check all the data is consistent if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) { ShortcutInfo modelShortcut = (ShortcutInfo) modelItem; ShortcutInfo shortcut = (ShortcutInfo) item; if (modelShortcut.title.toString().equals(shortcut.title.toString()) && modelShortcut.intent.filterEquals(shortcut.intent) && modelShortcut.id == shortcut.id && modelShortcut.itemType == shortcut.itemType && modelShortcut.container == shortcut.container && modelShortcut.screenId == shortcut.screenId && modelShortcut.cellX == shortcut.cellX && modelShortcut.cellY == shortcut.cellY && modelShortcut.spanX == shortcut.spanX && modelShortcut.spanY == shortcut.spanY && ((modelShortcut.dropPos == null && shortcut.dropPos == null) || (modelShortcut.dropPos != null && shortcut.dropPos != null && modelShortcut.dropPos[0] == shortcut.dropPos[0] && modelShortcut.dropPos[1] == shortcut.dropPos[1]))) { // For all intents and purposes, this is the same object return; } } // the modelItem needs to match up perfectly with item if our model is // to be consistent with the database-- for now, just require // modelItem == item or the equality check above String msg = "item: " + ((item != null) ? item.toString() : "null") + "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + "Error: ItemInfo passed to checkItemInfo doesn't match original"; RuntimeException e = new RuntimeException(msg); if (stackTrace != null) { e.setStackTrace(stackTrace); } // TODO: something breaks this in the upgrade path //throw e; } } static void checkItemInfo(final ItemInfo item) { final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); final long itemId = item.id; Runnable r = new Runnable() { public void run() { synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); } } }; runOnWorkerThread(r); } static void updateItemInDatabaseHelper(Context context, final ContentValues values, final ItemInfo item, final String callingFunction) { final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { cr.update(uri, values, null, null); updateItemArrays(item, itemId, stackTrace); } }; runOnWorkerThread(r); } static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList, final ArrayList<ItemInfo> items, final String callingFunction) { final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); ContentValues values = valuesList.get(i); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); updateItemArrays(item, itemId, stackTrace); } try { cr.applyBatch(LauncherProvider.AUTHORITY, ops); } catch (Exception e) { e.printStackTrace(); } } }; runOnWorkerThread(r); } static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) { // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP && item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Item is in a folder, make sure this folder exists if (!sBgFolders.containsKey(item.container)) { // An items container is being set to a that of an item which is not in // the list of Folders. String msg = "item: " + item + " container being set to: " + item.container + ", not in the list of folders"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } // Items are added/removed from the corresponding FolderInfo elsewhere, such // as in Workspace.onDrop. Here, we just add/remove them from the list of items // that are on the desktop, as appropriate ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { switch (modelItem.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: if (!sBgWorkspaceItems.contains(modelItem)) { sBgWorkspaceItems.add(modelItem); } break; default: break; } } else { sBgWorkspaceItems.remove(modelItem); } } } public void flushWorkerThread() { mFlushingWorkerThread = true; Runnable waiter = new Runnable() { public void run() { synchronized (this) { notifyAll(); mFlushingWorkerThread = false; } } }; synchronized(waiter) { runOnWorkerThread(waiter); if (mLoaderTask != null) { synchronized(mLoaderTask) { mLoaderTask.notify(); } } boolean success = false; while (!success) { try { waiter.wait(); success = true; } catch (InterruptedException e) { } } } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY) { String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase"); } /** * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the * cellX, cellY have already been updated on the ItemInfos. */ static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items, final long container, final int screen) { ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); item.container = container; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX, item.cellY); } else { item.screenId = screen; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); contentValues.add(values); } updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase"); } /** * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY> */ static void modifyItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) { String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); item.cellX = cellX; item.cellY = cellY; item.spanX = spanX; item.spanY = spanY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SPANX, item.spanX); values.put(LauncherSettings.Favorites.SPANY, item.spanY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase"); } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase"); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Ensure that all the applications that are in the system are represented on the home // screen. if (!isUpgrade) { verifyApplications(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; - ArrayList<ApplicationInfo> added = new ArrayList<ApplicationInfo>(); + ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ApplicationInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (!isValidPackage(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the database Uri uri = LauncherSettings.Favorites.getContentUri(id, false); contentResolver.delete(uri, null, null); Log.e(TAG, "Invalid package removed in loadWorkspace: " + cn); } else { // If apps can be on external storage, then we just leave // them for the user to remove (maybe add treatment to it) Log.e(TAG, "Invalid package found in loadWorkspace: " + cn); } continue; } } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { if (c != null) { c.close(); } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState app = LauncherAppState.getInstance(); app.getLauncherProvider().updateMaxItemId(maxItemId); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; for (int i = 0; i < apps.size(); i++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); } final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, addedInfos, cb); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (ApplicationInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } else { for (ApplicationInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackage(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); if (!isValidPackage(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). final ShortcutInfo info = new ShortcutInfo(); Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
true
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Ensure that all the applications that are in the system are represented on the home // screen. if (!isUpgrade) { verifyApplications(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ApplicationInfo> added = new ArrayList<ApplicationInfo>(); synchronized (sBgLock) { for (ApplicationInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (!isValidPackage(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the database Uri uri = LauncherSettings.Favorites.getContentUri(id, false); contentResolver.delete(uri, null, null); Log.e(TAG, "Invalid package removed in loadWorkspace: " + cn); } else { // If apps can be on external storage, then we just leave // them for the user to remove (maybe add treatment to it) Log.e(TAG, "Invalid package found in loadWorkspace: " + cn); } continue; } } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { if (c != null) { c.close(); } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState app = LauncherAppState.getInstance(); app.getLauncherProvider().updateMaxItemId(maxItemId); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; for (int i = 0; i < apps.size(); i++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); } final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, addedInfos, cb); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (ApplicationInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } else { for (ApplicationInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackage(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); if (!isValidPackage(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). final ShortcutInfo info = new ShortcutInfo(); Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Ensure that all the applications that are in the system are represented on the home // screen. if (!isUpgrade) { verifyApplications(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ApplicationInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (!isValidPackage(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the database Uri uri = LauncherSettings.Favorites.getContentUri(id, false); contentResolver.delete(uri, null, null); Log.e(TAG, "Invalid package removed in loadWorkspace: " + cn); } else { // If apps can be on external storage, then we just leave // them for the user to remove (maybe add treatment to it) Log.e(TAG, "Invalid package found in loadWorkspace: " + cn); } continue; } } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { if (c != null) { c.close(); } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState app = LauncherAppState.getInstance(); app.getLauncherProvider().updateMaxItemId(maxItemId); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; for (int i = 0; i < apps.size(); i++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); } final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, addedInfos, cb); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (ApplicationInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } else { for (ApplicationInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackage(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); if (!isValidPackage(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). final ShortcutInfo info = new ShortcutInfo(); Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/keymap/vim/ConstructorWrappers.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/keymap/vim/ConstructorWrappers.java index 67b6555e..357a2f13 100644 --- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/keymap/vim/ConstructorWrappers.java +++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/keymap/vim/ConstructorWrappers.java @@ -1,428 +1,429 @@ package net.sourceforge.vrapper.keymap.vim; import static java.util.Arrays.asList; import static net.sourceforge.vrapper.keymap.StateUtils.union; import static net.sourceforge.vrapper.vim.commands.BorderPolicy.LINE_WISE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.sourceforge.vrapper.keymap.CovariantState; import net.sourceforge.vrapper.keymap.HashMapState; import net.sourceforge.vrapper.keymap.KeyBinding; import net.sourceforge.vrapper.keymap.KeyStroke; import net.sourceforge.vrapper.keymap.SimpleKeyBinding; import net.sourceforge.vrapper.keymap.SimpleTransition; import net.sourceforge.vrapper.keymap.SpecialKey; import net.sourceforge.vrapper.keymap.State; import net.sourceforge.vrapper.keymap.Transition; import net.sourceforge.vrapper.log.VrapperLog; import net.sourceforge.vrapper.utils.CaretType; import net.sourceforge.vrapper.utils.Function; import net.sourceforge.vrapper.vim.PerformOperationOnSearchResultCommand; import net.sourceforge.vrapper.vim.commands.ChangeCaretShapeCommand; import net.sourceforge.vrapper.vim.commands.ChangeModeCommand; import net.sourceforge.vrapper.vim.commands.ChangeToSearchModeCommand; import net.sourceforge.vrapper.vim.commands.Command; import net.sourceforge.vrapper.vim.commands.MotionTextObject; import net.sourceforge.vrapper.vim.commands.SelectionBasedTextObjectCommand; import net.sourceforge.vrapper.vim.commands.TextObject; import net.sourceforge.vrapper.vim.commands.TextOperation; import net.sourceforge.vrapper.vim.commands.TextOperationTextObjectCommand; import net.sourceforge.vrapper.vim.commands.motions.LineEndMotion; import net.sourceforge.vrapper.vim.commands.motions.Motion; import net.sourceforge.vrapper.vim.commands.motions.SearchResultMotion; import net.sourceforge.vrapper.vim.modes.commandline.CommandLineMode; /** * Static utility methods to construct keymaps. * These Java-ugliness-hiding static methods are intended to be statically imported. * @author Krzysiek Goj */ public class ConstructorWrappers { private static final Map<String, KeyStroke> keyNames = createKeyMap(); @SuppressWarnings("serial") static final Map<SpecialKey, String> specialKeyNames = Collections.unmodifiableMap(new HashMap<SpecialKey, String>() {{ for (SpecialKey key: SpecialKey.values()) { String keyName = key.toString(); put(key, "<"+keyName+">"); } put(SpecialKey.ARROW_LEFT, "<LEFT>"); put(SpecialKey.ARROW_RIGHT, "<RIGHT>"); put(SpecialKey.ARROW_UP, "<UP>"); put(SpecialKey.ARROW_DOWN, "<DOWN>"); }}); // private static final Pattern pattern = Pattern.compile("<(.+)>"); public static Iterable<KeyStroke> parseKeyStrokes(String s) { List<KeyStroke> result = new ArrayList<KeyStroke>(); for (int i = 0; i < s.length(); i++) { char input = s.charAt(i); if (input == '<') { StringBuilder sb = new StringBuilder(); if (i + 1 < s.length()) { sb.append('<'); i++; input = s.charAt(i); } while (i < s.length() && input != '>' && isSpecialKeyChar(input)) { sb.append(input); i++; if ( i < s.length()) { input = s.charAt(i); } } // sb must contain characters, otherwise we have found part of a > shift operator if (input == '>' && sb.length() > 1) { KeyStroke stroke = null; String key = sb.substring(1).toUpperCase(); if (key.length() > 0) { stroke = parseSpecialKey(key); } if (stroke == null) { VrapperLog.info("Key code <" + key + "> in mapping '" + s + "' is unknown." + " Ignoring."); } else { result.add(stroke); } } else { for (char c : sb.toString().toCharArray()) { result.add(key(c)); } if (i + 1 < s.length() && input == '<') { // Nested < chars. There might be a special key next up, recheck current i. i--; } else if (! isSpecialKeyChar(input)) { // Special char, not yet added to sb so append it manually. result.add(key(input)); } // else char is already in sb because i must have been incremented to s.length } } else { result.add(key(input)); } } return result; } private static boolean isSpecialKeyChar(char c) { return Character.isLetterOrDigit(c) || c == '-' || c == '_' || c == '@' || c == ']' || c == '[' || c == '\\' || c == '^'; } /** * Parse the KeyStoke found within '<' and '>' tags. * For example: * <Insert> * <Left> * <S-Home> * <A-X> * <M-Left> * @param key - String found within '<' and '>' * @return KeyStroke representing key's Key */ private static KeyStroke parseSpecialKey(String key) { KeyStroke stroke = null; //Sanity check for recursion. if (key.length() > 20 || key.length() == 0) { return null; } if(key.startsWith("S-")) { //Shift KeyStroke k = parseSpecialKey( key.substring(2) ); if(k != null) { if (k.getSpecialKey() == null && ! k.withCtrlKey() && k.getCharacter() > ' ') { //for combinations like A-S-x. Never convert S-C-x to uppercase! stroke = new SimpleKeyStroke(Character.toUpperCase(k.getCharacter()), true, k.withAltKey(), k.withCtrlKey()); } else { stroke = new SimpleKeyStroke(k, true, k.withAltKey(), k.withCtrlKey()); } } } else if(key.startsWith("A-") || key.startsWith("M-")) { //Alt (Meta) KeyStroke k = parseSpecialKey(key.substring(2)); if(k != null) { stroke = new SimpleKeyStroke(k, k.withShiftKey(), true, k.withCtrlKey()); } } else if (key.startsWith("C-")) { //Control KeyStroke k = parseSpecialKey(key.substring(2)); if (k != null) { stroke = new SimpleKeyStroke(k, k.withShiftKey(), k.withAltKey(), true); } } else if (keyNames.containsKey(key)) { stroke = keyNames.get(key); } else if (key.length() == 1 && key.charAt(0) >= ' ') { //normal character, not special key (e.g., <A-x>) //force lower-case, let the shift modifier convert it back to uppercase if needed. stroke = new SimpleKeyStroke(key.toLowerCase().charAt(0)); } // else we return null, maybe some unknown special key? return stroke; } public static String keyStrokesToString(Iterable<KeyStroke> strokes) { StringBuilder sb = new StringBuilder(); for (KeyStroke stroke : strokes) { sb.append(keyStrokeToString(stroke)); } return sb.toString(); } public static String keyStrokeToString(KeyStroke stroke) { if (stroke.getSpecialKey() == null) { String key = String.valueOf(stroke.getCharacter()); if (stroke.getCharacter() >= ' ') { switch (stroke.getCharacter()) { case '<': return "<LT>"; case '>': return "<GT>"; case ' ': return "<SPACE>"; default: return key; } } return "<C-"+key+">"; } return specialKeyNames.get(stroke.getSpecialKey()); } public static KeyStroke key(char key) { return new SimpleKeyStroke(key); } public static KeyStroke ctrlKey(char key) { return new SimpleKeyStroke(Character.toLowerCase(key), false, false, true); } public static KeyStroke key(SpecialKey key) { return new SimpleKeyStroke(key); } public static<T> KeyBinding<T> binding(char k, Transition<T> transition) { return new SimpleKeyBinding<T>(key(k), transition); } public static<T> KeyBinding<T> binding(SpecialKey k, Transition<T> transition) { return new SimpleKeyBinding<T>(key(k), transition); } public static<T> KeyBinding<T> binding(KeyStroke stroke, Transition<T> transition) { return new SimpleKeyBinding<T>(stroke, transition); } public static<T> Transition<T> leaf(T value) { return new SimpleTransition<T>(value); } public static<T> Transition<T> transition(State<T> state) { return new SimpleTransition<T>(state); } public static<T> Transition<T> transition(T value, State<T> state) { return new SimpleTransition<T>(value, state); } public static<T> State<T> state(KeyBinding<T>... bindings) { return new HashMapState<T>(asList(bindings)); } public static<T> KeyBinding<T> leafBind(KeyStroke k, T value) { return binding(k, leaf(value)); } public static<T> KeyBinding<T> leafBind(char k, T value) { return binding(k, leaf(value)); } public static<T> KeyBinding<T> leafBind(SpecialKey k, T value) { return binding(k, leaf(value)); } public static<T> KeyBinding<T> leafCtrlBind(char k, T value) { return binding(ctrlKey(k), leaf(value)); } public static<T> KeyBinding<T> transitionBind(char k, State<T> state) { return binding(k, transition(state)); } public static<T> KeyBinding<T> transitionBind(KeyStroke k, State<T> state) { return binding(k, transition(state)); } public static<T> KeyBinding<T> transitionBind(char k, T value, State<T> state) { return binding(k, transition(value, state)); } public static<T> KeyBinding<T> transitionBind(char k, KeyBinding<T>... bindings) { return binding(k, transition(state(bindings))); } @SuppressWarnings("unchecked") public static<T> State<T> leafState(char k, T value) { return state(leafBind(k, value)); } @SuppressWarnings("unchecked") public static<T> State<T> leafState(KeyStroke k, T value) { return state(leafBind(k, value)); } @SuppressWarnings("unchecked") public static<T> State<T> transitionState(char k, State<T> state) { return state(transitionBind(k, state)); } @SuppressWarnings("unchecked") public static<T> State<T> transitionState(KeyStroke k, State<T> state) { return state(transitionBind(k, state)); } public static SelectionBasedTextObjectCommand operatorMoveCmd(Command operator, Motion move) { return new SelectionBasedTextObjectCommand(operator, new MotionTextObject(move)); } public static State<Command> counted(State<Command> wrapped) { return CountingState.wrap(wrapped); } public static ChangeCaretShapeCommand changeCaret(CaretType caret) { return ChangeCaretShapeCommand.getInstance(caret); } @SuppressWarnings("unchecked") private static State<Command> operatorPendingState(char key, State<Command> doubleKey, State<Command> operatorCmds) { return state(binding(key, transition(changeCaret(CaretType.HALF_RECT), counted(union(doubleKey, operatorCmds))))); } @SuppressWarnings("unchecked") public static State<Command> operatorCmdsWithUpperCase(char key, TextOperation command, TextObject eolMotion, State<TextObject> textObjects) { assert Character.isLowerCase(key); Command doToEOL = new TextOperationTextObjectCommand(command, eolMotion); return union( leafState(Character.toUpperCase(key), doToEOL), // FIXME: was: counted(...) operatorCmds(key, command, textObjects)); } @SuppressWarnings("unchecked") public static State<Command> operatorCmds(char key, TextOperation command, State<TextObject> textObjects) { LineEndMotion lineEndMotion = new LineEndMotion(LINE_WISE); Command doLinewise = new TextOperationTextObjectCommand(command, new MotionTextObject(lineEndMotion)); State<Command> doubleKey = leafState(key, doLinewise); State<Command> operatorCmds = union( leafState('/', (Command) new ChangeToSearchModeCommand(false, new PerformOperationOnSearchResultCommand(command, SearchResultMotion.FORWARD))), leafState('?', (Command) new ChangeToSearchModeCommand(true, new PerformOperationOnSearchResultCommand(command, SearchResultMotion.FORWARD))), leafState(':', (Command) new ChangeModeCommand(CommandLineMode.NAME)), new OperatorCommandState(command, textObjects) ); return operatorPendingState(key, doubleKey, operatorCmds); } public static State<Command> operatorCmds(char key, Command operator, State<TextObject> textObjects) { Command doLinewise = operatorMoveCmd(operator, new LineEndMotion(LINE_WISE)); State<Command> doubleKey = leafState(key, doLinewise); State<Command> operatorCmds = new OperatorCommandState(operator, textObjects); return operatorPendingState(key, doubleKey, operatorCmds); } public static State<Command> prefixedOperatorCmds(char prefix, char key, TextOperation command, State<TextObject> textObjects) { LineEndMotion lineEndMotion = new LineEndMotion(LINE_WISE); Command doLinewise = new TextOperationTextObjectCommand(command, new MotionTextObject(lineEndMotion)); @SuppressWarnings("unchecked") State<Command> doubleKey = state( leafBind(key, doLinewise), // e.g. for 'g??' transitionBind(prefix, leafBind(key, doLinewise))); // e.g. for 'g?g?' State<Command> operatorCmds = new OperatorCommandState(command, textObjects); return transitionState(prefix, operatorPendingState(key, doubleKey, operatorCmds)); } public static State<Command> prefixedOperatorCmds(char prefix, char key, Command operator, State<TextObject> textObjects) { Command doLinewise = operatorMoveCmd(operator, new LineEndMotion(LINE_WISE)); @SuppressWarnings("unchecked") State<Command> doubleKey = state( leafBind(key, doLinewise), // e.g. for 'g??' transitionBind(prefix, leafBind(key, doLinewise))); // e.g. for 'g?g?' State<Command> operatorCmds = new OperatorCommandState(operator, textObjects); return transitionState(prefix, operatorPendingState(key, doubleKey, operatorCmds)); } public static <T> State<T> convertKeyStroke(Function<T, KeyStroke> converter, Set<KeyStroke> keystrokes) { return new KeyStrokeConvertingState<T>(converter, keystrokes); } public static<T1, T2 extends T1> State<T1> covariant(State<T2> wrapped) { return new CovariantState<T1, T2>(wrapped); } private static Map<String, KeyStroke> createKeyMap() { HashMap<String, KeyStroke> map = new HashMap<String, KeyStroke>(); // special keys for (SpecialKey key : SpecialKey.values()) { map.put(key.name().toUpperCase(), key(key)); } map.put("DEL", key(SpecialKey.DELETE)); map.put("INS", key(SpecialKey.INSERT)); map.put("BS", key(SpecialKey.BACKSPACE)); map.put("RETURN", key(SpecialKey.RETURN)); map.put("ENTER", map.get("RETURN")); map.put("CR", map.get("RETURN")); map.put("PAGEUP", key(SpecialKey.PAGE_UP)); map.put("PAGEDOWN",key(SpecialKey.PAGE_DOWN)); map.put("UP", key(SpecialKey.ARROW_UP)); map.put("DOWN", key(SpecialKey.ARROW_DOWN)); map.put("LEFT", key(SpecialKey.ARROW_LEFT)); map.put("RIGHT", key(SpecialKey.ARROW_RIGHT)); map.put("TAB", key(SpecialKey.TAB)); map.put("SPACE", key(' ')); map.put("GT", key('>')); map.put("LT", key('<')); + map.put("BAR", key('|')); // add these ctrl keys to keep parseSpecialKey working map.put("C-@", new SimpleKeyStroke('@', false, false, true)); map.put("C-A", new SimpleKeyStroke('a', false, false, true)); map.put("C-B", new SimpleKeyStroke('b', false, false, true)); map.put("C-C", new SimpleKeyStroke('c', false, false, true)); map.put("C-D", new SimpleKeyStroke('d', false, false, true)); map.put("C-E", new SimpleKeyStroke('e', false, false, true)); map.put("C-F", new SimpleKeyStroke('f', false, false, true)); map.put("C-G", new SimpleKeyStroke('g', false, false, true)); map.put("C-H", new SimpleKeyStroke('h', false, false, true)); map.put("C-I", new SimpleKeyStroke('i', false, false, true)); map.put("C-J", new SimpleKeyStroke('j', false, false, true)); map.put("C-K", new SimpleKeyStroke('k', false, false, true)); map.put("C-L", new SimpleKeyStroke('l', false, false, true)); map.put("C-M", new SimpleKeyStroke('m', false, false, true)); map.put("C-N", new SimpleKeyStroke('n', false, false, true)); map.put("C-O", new SimpleKeyStroke('o', false, false, true)); map.put("C-P", new SimpleKeyStroke('p', false, false, true)); map.put("C-Q", new SimpleKeyStroke('q', false, false, true)); map.put("C-R", new SimpleKeyStroke('r', false, false, true)); map.put("C-S", new SimpleKeyStroke('s', false, false, true)); map.put("C-T", new SimpleKeyStroke('t', false, false, true)); map.put("C-U", new SimpleKeyStroke('u', false, false, true)); map.put("C-V", new SimpleKeyStroke('v', false, false, true)); map.put("C-W", new SimpleKeyStroke('w', false, false, true)); map.put("C-X", new SimpleKeyStroke('x', false, false, true)); map.put("C-Y", new SimpleKeyStroke('y', false, false, true)); map.put("C-Z", new SimpleKeyStroke('z', false, false, true)); map.put("C-[", new SimpleKeyStroke('[', false, false, true)); map.put("C-\\",new SimpleKeyStroke('\\', false, false, true)); map.put("C-]", new SimpleKeyStroke(']', false, false, true)); map.put("C-^", new SimpleKeyStroke('^', false, false, true)); map.put("C-_", new SimpleKeyStroke('_', false, false, true)); map.put("C-SPACE", new SimpleKeyStroke(' ', false, false, true)); return map; } }
true
true
private static Map<String, KeyStroke> createKeyMap() { HashMap<String, KeyStroke> map = new HashMap<String, KeyStroke>(); // special keys for (SpecialKey key : SpecialKey.values()) { map.put(key.name().toUpperCase(), key(key)); } map.put("DEL", key(SpecialKey.DELETE)); map.put("INS", key(SpecialKey.INSERT)); map.put("BS", key(SpecialKey.BACKSPACE)); map.put("RETURN", key(SpecialKey.RETURN)); map.put("ENTER", map.get("RETURN")); map.put("CR", map.get("RETURN")); map.put("PAGEUP", key(SpecialKey.PAGE_UP)); map.put("PAGEDOWN",key(SpecialKey.PAGE_DOWN)); map.put("UP", key(SpecialKey.ARROW_UP)); map.put("DOWN", key(SpecialKey.ARROW_DOWN)); map.put("LEFT", key(SpecialKey.ARROW_LEFT)); map.put("RIGHT", key(SpecialKey.ARROW_RIGHT)); map.put("TAB", key(SpecialKey.TAB)); map.put("SPACE", key(' ')); map.put("GT", key('>')); map.put("LT", key('<')); // add these ctrl keys to keep parseSpecialKey working map.put("C-@", new SimpleKeyStroke('@', false, false, true)); map.put("C-A", new SimpleKeyStroke('a', false, false, true)); map.put("C-B", new SimpleKeyStroke('b', false, false, true)); map.put("C-C", new SimpleKeyStroke('c', false, false, true)); map.put("C-D", new SimpleKeyStroke('d', false, false, true)); map.put("C-E", new SimpleKeyStroke('e', false, false, true)); map.put("C-F", new SimpleKeyStroke('f', false, false, true)); map.put("C-G", new SimpleKeyStroke('g', false, false, true)); map.put("C-H", new SimpleKeyStroke('h', false, false, true)); map.put("C-I", new SimpleKeyStroke('i', false, false, true)); map.put("C-J", new SimpleKeyStroke('j', false, false, true)); map.put("C-K", new SimpleKeyStroke('k', false, false, true)); map.put("C-L", new SimpleKeyStroke('l', false, false, true)); map.put("C-M", new SimpleKeyStroke('m', false, false, true)); map.put("C-N", new SimpleKeyStroke('n', false, false, true)); map.put("C-O", new SimpleKeyStroke('o', false, false, true)); map.put("C-P", new SimpleKeyStroke('p', false, false, true)); map.put("C-Q", new SimpleKeyStroke('q', false, false, true)); map.put("C-R", new SimpleKeyStroke('r', false, false, true)); map.put("C-S", new SimpleKeyStroke('s', false, false, true)); map.put("C-T", new SimpleKeyStroke('t', false, false, true)); map.put("C-U", new SimpleKeyStroke('u', false, false, true)); map.put("C-V", new SimpleKeyStroke('v', false, false, true)); map.put("C-W", new SimpleKeyStroke('w', false, false, true)); map.put("C-X", new SimpleKeyStroke('x', false, false, true)); map.put("C-Y", new SimpleKeyStroke('y', false, false, true)); map.put("C-Z", new SimpleKeyStroke('z', false, false, true)); map.put("C-[", new SimpleKeyStroke('[', false, false, true)); map.put("C-\\",new SimpleKeyStroke('\\', false, false, true)); map.put("C-]", new SimpleKeyStroke(']', false, false, true)); map.put("C-^", new SimpleKeyStroke('^', false, false, true)); map.put("C-_", new SimpleKeyStroke('_', false, false, true)); map.put("C-SPACE", new SimpleKeyStroke(' ', false, false, true)); return map; }
private static Map<String, KeyStroke> createKeyMap() { HashMap<String, KeyStroke> map = new HashMap<String, KeyStroke>(); // special keys for (SpecialKey key : SpecialKey.values()) { map.put(key.name().toUpperCase(), key(key)); } map.put("DEL", key(SpecialKey.DELETE)); map.put("INS", key(SpecialKey.INSERT)); map.put("BS", key(SpecialKey.BACKSPACE)); map.put("RETURN", key(SpecialKey.RETURN)); map.put("ENTER", map.get("RETURN")); map.put("CR", map.get("RETURN")); map.put("PAGEUP", key(SpecialKey.PAGE_UP)); map.put("PAGEDOWN",key(SpecialKey.PAGE_DOWN)); map.put("UP", key(SpecialKey.ARROW_UP)); map.put("DOWN", key(SpecialKey.ARROW_DOWN)); map.put("LEFT", key(SpecialKey.ARROW_LEFT)); map.put("RIGHT", key(SpecialKey.ARROW_RIGHT)); map.put("TAB", key(SpecialKey.TAB)); map.put("SPACE", key(' ')); map.put("GT", key('>')); map.put("LT", key('<')); map.put("BAR", key('|')); // add these ctrl keys to keep parseSpecialKey working map.put("C-@", new SimpleKeyStroke('@', false, false, true)); map.put("C-A", new SimpleKeyStroke('a', false, false, true)); map.put("C-B", new SimpleKeyStroke('b', false, false, true)); map.put("C-C", new SimpleKeyStroke('c', false, false, true)); map.put("C-D", new SimpleKeyStroke('d', false, false, true)); map.put("C-E", new SimpleKeyStroke('e', false, false, true)); map.put("C-F", new SimpleKeyStroke('f', false, false, true)); map.put("C-G", new SimpleKeyStroke('g', false, false, true)); map.put("C-H", new SimpleKeyStroke('h', false, false, true)); map.put("C-I", new SimpleKeyStroke('i', false, false, true)); map.put("C-J", new SimpleKeyStroke('j', false, false, true)); map.put("C-K", new SimpleKeyStroke('k', false, false, true)); map.put("C-L", new SimpleKeyStroke('l', false, false, true)); map.put("C-M", new SimpleKeyStroke('m', false, false, true)); map.put("C-N", new SimpleKeyStroke('n', false, false, true)); map.put("C-O", new SimpleKeyStroke('o', false, false, true)); map.put("C-P", new SimpleKeyStroke('p', false, false, true)); map.put("C-Q", new SimpleKeyStroke('q', false, false, true)); map.put("C-R", new SimpleKeyStroke('r', false, false, true)); map.put("C-S", new SimpleKeyStroke('s', false, false, true)); map.put("C-T", new SimpleKeyStroke('t', false, false, true)); map.put("C-U", new SimpleKeyStroke('u', false, false, true)); map.put("C-V", new SimpleKeyStroke('v', false, false, true)); map.put("C-W", new SimpleKeyStroke('w', false, false, true)); map.put("C-X", new SimpleKeyStroke('x', false, false, true)); map.put("C-Y", new SimpleKeyStroke('y', false, false, true)); map.put("C-Z", new SimpleKeyStroke('z', false, false, true)); map.put("C-[", new SimpleKeyStroke('[', false, false, true)); map.put("C-\\",new SimpleKeyStroke('\\', false, false, true)); map.put("C-]", new SimpleKeyStroke(']', false, false, true)); map.put("C-^", new SimpleKeyStroke('^', false, false, true)); map.put("C-_", new SimpleKeyStroke('_', false, false, true)); map.put("C-SPACE", new SimpleKeyStroke(' ', false, false, true)); return map; }
diff --git a/src/de/questmaster/tudmensa/MensaMeals.java b/src/de/questmaster/tudmensa/MensaMeals.java index 0d01064..376abbb 100644 --- a/src/de/questmaster/tudmensa/MensaMeals.java +++ b/src/de/questmaster/tudmensa/MensaMeals.java @@ -1,474 +1,473 @@ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.questmaster.tudmensa; import java.util.Calendar; import com.admob.android.ads.AdManager; import com.admob.android.ads.AdView; import com.admob.android.ads.SimpleAdListener; import de.questmaster.tudmensa.R; import android.app.ExpandableListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.format.DateFormat; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.SimpleCursorTreeAdapter; import android.widget.TextView; import android.widget.Toast; public class MensaMeals extends ExpandableListActivity { private static final int UPDATE_ID = Menu.FIRST; private static final int TODAY_ID = Menu.FIRST + 1; private static final int SETTINGS_ID = Menu.FIRST + 2; public static final int ON_SETTINGS_CHANGE = 0; private MensaMealsSettings.Settings mSettings = new MensaMealsSettings.Settings(); protected MealsDbAdapter mDbHelper; private ProgressDialog mPDialog = null; private boolean mRestart = false; protected Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mPDialog.dismiss(); // updateView after update. Don't do it for an update after startup mRestart = true; fillData(); } }; private Calendar mToday = Calendar.getInstance(); protected Context mContext = this; private String mOldTheme; private AdView mAdView = null; private GestureDetector gestureDetector; /** * Copied from K9mail. * * */ public class MyGestureDetector extends SimpleOnGestureListener { private static final float SWIPE_MIN_DISTANCE_DIP = 130.0f; private static final float SWIPE_MAX_OFF_PATH_DIP = 250f; private static final float SWIPE_THRESHOLD_VELOCITY_DIP = 325f; @Override public boolean onDoubleTap(MotionEvent ev) { super.onDoubleTap(ev); if (mSettings.m_bGestures) { onClickTodayButton(null); } return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (mSettings.m_bGestures) { // Convert the dips to pixels final float mGestureScale = getResources().getDisplayMetrics().density; int min_distance = (int) (SWIPE_MIN_DISTANCE_DIP * mGestureScale + 0.5f); int min_velocity = (int) (SWIPE_THRESHOLD_VELOCITY_DIP * mGestureScale + 0.5f); int max_off_path = (int) (SWIPE_MAX_OFF_PATH_DIP * mGestureScale + 0.5f); try { if (Math.abs(e1.getY() - e2.getY()) > max_off_path) return false; // right to left swipe if (e1.getX() - e2.getX() > min_distance && Math.abs(velocityX) > min_velocity) { onClickNextButton(null); } else if (e2.getX() - e1.getX() > min_distance && Math.abs(velocityX) > min_velocity) { onClickPrevButton(null); } } catch (Exception e) { // nothing } } return false; } } public class CustomCursorTreeAdapter extends SimpleCursorTreeAdapter { public CustomCursorTreeAdapter(Context context, Cursor cursor, int groupLayout, String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom, int[] childTo) { super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom, childTo); } @Override protected Cursor getChildrenCursor(Cursor groupCursor) { String location = groupCursor.getString(groupCursor.getColumnIndex(MealsDbAdapter.KEY_LOCATION)); String date = groupCursor.getString(groupCursor.getColumnIndex(MealsDbAdapter.KEY_DATE)); String counter = groupCursor.getString(groupCursor.getColumnIndex(MealsDbAdapter.KEY_COUNTER)); Cursor c = new MealsDbCursorWrapper(mDbHelper.fetchMealsOfGroupDay(location, date, counter), mContext); startManagingCursor(c); return c; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { // Read settings mSettings.ReadSettings(this); // Setup Theme if (mSettings.m_sThemes.equals("dark")) { setTheme(R.style.myTheme); } else if (mSettings.m_sThemes.equals("light")) { setTheme(R.style.myThemeLight); } // Set Content super.onCreate(savedInstanceState); setContentView(R.layout.meals_list); // Init Database mDbHelper = new MealsDbAdapter(this); mDbHelper.open(); // Setup date mToday = Calendar.getInstance(); if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { mToday.add(Calendar.DAY_OF_YEAR, 2); } else if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { mToday.add(Calendar.DAY_OF_YEAR, 1); } // Capture our buttons from layout and set them up Button buttonPrev = (Button) findViewById(R.id.btn_prev); Button buttonNext = (Button) findViewById(R.id.btn_next); buttonPrev.setBackgroundResource(R.drawable.ic_menu_back); buttonNext.setBackgroundResource(R.drawable.ic_menu_forward); updateButtonText(); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); // Init Ads + hide them after 7 secs mAdView = (AdView) findViewById(R.id.ad); + if (!mSettings.m_bAds) { mAdView.setAdListener( new SimpleAdListener() { public void onReceiveAd(com.admob.android.ads.AdView adView) { - System.out.println("done.\n"); adView.postDelayed(new Runnable() { @Override public void run() { // ScaleAnimation animation = new ScaleAnimation (1.0f, 0.0f, 1.0f, 0.0f, // Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1.0f); // animation.setDuration(400); // animation.setFillAfter(true); // animation.setInterpolator(new AccelerateInterpolator()); // mAdView.startAnimation(animation); - if (!mSettings.m_bAds) { mAdView.setVisibility(View.GONE); - } } }, 7000); super.onReceiveAd(adView); } } ); - mAdView.setKeywords("mensa menu meals"); + } + mAdView.setKeywords("mensa menu meals"); mAdView.setRequestInterval(15); mAdView.requestFreshAd(); // Fade the ad in over 4/10 of a second. AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(400); animation.setFillAfter(true); animation.setInterpolator(new AccelerateInterpolator()); mAdView.startAnimation(animation); // // hide ads if deactivated // if (mSettings.m_bAds) { -// mAdView.setVisibility(View.VISIBLE); + mAdView.setVisibility(View.VISIBLE); // } else { // mAdView.setVisibility(View.GONE); // } AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR, // Android emulator // "E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone }); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { super.dispatchTouchEvent(ev); return gestureDetector.onTouchEvent(ev); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); MenuItem mItem = null; mItem = menu.add(0, UPDATE_ID, 0, R.string.menu_update); mItem.setIcon(R.drawable.ic_menu_refresh); mItem = menu.add(0, TODAY_ID, 1, R.string.menu_today); mItem.setIcon(android.R.drawable.ic_menu_today); mItem = menu.add(0, SETTINGS_ID, 2, R.string.menu_settings); mItem.setIcon(android.R.drawable.ic_menu_preferences); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case UPDATE_ID: getData(); fillData(); break; case TODAY_ID: onClickTodayButton(null); break; case SETTINGS_ID: Intent iSettings = new Intent(); iSettings.setClass(this, MensaMealsSettings.class); startActivityForResult(iSettings, ON_SETTINGS_CHANGE); // To be able to check for new data if mensa changed. mRestart = false; // Store old theme mOldTheme = mSettings.m_sThemes; break; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case ON_SETTINGS_CHANGE: mSettings.ReadSettings(this); // WORKAROUND: restart activity FIXME may have side-effects in froyo if (!mOldTheme.equals(mSettings.m_sThemes)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } // (un)hide Ads AdView av = (AdView) findViewById(R.id.ad); if (mSettings.m_bAds) { av.setVisibility(View.VISIBLE); } else { av.setVisibility(View.GONE); } // Reread data and display it updateButtonText(); fillData(); break; } } @Override public void onGroupCollapse(int groupPosition) { // keep the Groups expanded getExpandableListView().expandGroup(groupPosition); } public void onClickTodayButton(View v) { mToday = Calendar.getInstance(); if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { mToday.add(Calendar.DAY_OF_YEAR, 2); } else if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { mToday.add(Calendar.DAY_OF_YEAR, 1); } updateButtonText(); fillData(); } public void onClickNextButton(View v) { // Setup date mToday.add(Calendar.DAY_OF_YEAR, 1); if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { mToday.add(Calendar.DAY_OF_YEAR, 2); } else if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { mToday.add(Calendar.DAY_OF_YEAR, 1); } updateButtonText(); fillData(); } public void onClickPrevButton(View v) { // Setup date mToday.add(Calendar.DAY_OF_YEAR, -1); if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { mToday.add(Calendar.DAY_OF_YEAR, -1); } else if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { mToday.add(Calendar.DAY_OF_YEAR, -2); } updateButtonText(); fillData(); } @Override protected void onDestroy() { super.onDestroy(); // close database mDbHelper.close(); } @Override protected void onResume() { super.onResume(); // expand groups fillData(); } @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // show Type and legend information Cursor c = mDbHelper.fetchMeal(id); startManagingCursor(c); // get info date String info = c.getString(c.getColumnIndex(MealsDbAdapter.KEY_INFO)); if (!info.equals("")) // Display Toast message Toast.makeText(this, info, Toast.LENGTH_SHORT).show(); return false; } private void updateButtonText() { // Prepare times Calendar cPrev = (Calendar) mToday.clone(); Calendar cNext = (Calendar) mToday.clone(); cPrev.add(Calendar.DAY_OF_YEAR, -1); cNext.add(Calendar.DAY_OF_YEAR, 1); // check weekends if (cPrev.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { cPrev.add(Calendar.DAY_OF_YEAR, -1); } else if (cPrev.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { cPrev.add(Calendar.DAY_OF_YEAR, -2); } if (cNext.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { cNext.add(Calendar.DAY_OF_YEAR, 2); } else if (cNext.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { cNext.add(Calendar.DAY_OF_YEAR, 1); } // // Update Text Prev // Button buttonPrev = (Button) findViewById(R.id.btn_prev); // String textPrev = // DateFormat.getDateFormat(this).format(cPrev.getTime()); // buttonPrev.setText(textPrev.substring(0, textPrev.length() - 5)); // // // Update Text Next // Button buttonNext = (Button) findViewById(R.id.btn_next); // String textNext = // DateFormat.getDateFormat(this).format(cNext.getTime()); // buttonNext.setText(textNext.substring(0, textNext.length() - 5)); // Set new title int pos = 0; for (String s : getResources().getStringArray(R.array.MensaLocationsValues)) { if (s.equals(mSettings.m_sMensaLocation)) { break; } else pos++; } // Update label TextView labelDay = (TextView) findViewById(R.id.txt_date); labelDay.setText(getResources().getStringArray(R.array.MensaLocations)[pos] + "\n" + DateFormat.format("EEEE", mToday.getTime()) + ", " + DateFormat.getDateFormat(this).format(mToday.getTime())); } private void fillData() { // prepare date string String date = (String) DateFormat.format("yyyyMMdd", mToday); // Get all of the notes from the database and create the item list Cursor c = mDbHelper.fetchGroupsOfDay(mSettings.m_sMensaLocation, date); // if none found start a new query automatically if (mSettings.m_bAutoUpdate && c.getCount() == 0 && !mRestart) { mRestart = true; getData(); return; } startManagingCursor(c); String[] group_from = new String[] { MealsDbAdapter.KEY_COUNTER }; int[] group_to = new int[] { R.id.counter }; String[] child_from = new String[] { MealsDbAdapter.KEY_NAME, MealsDbAdapter.KEY_PRICE, MealsDbAdapter.KEY_TYPE }; int[] child_to = new int[] { R.id.meal, R.id.price, R.id.meal_type }; // Now create an array adapter and set it to display using our row CustomCursorTreeAdapter meals = new CustomCursorTreeAdapter(this, c, R.layout.simple_expandable_list_item_1, group_from, group_to, R.layout.simple_expandable_list_item_2, child_from, child_to); setListAdapter(meals); // expand all items for (int i = 0; i < c.getCount(); i++) { getExpandableListView().expandGroup(i); } } private void getData() { mPDialog = ProgressDialog.show(this, null, getResources().getString(R.string.dialog_updating_text), true, true); // get data DataExtractor de = new DataExtractor(this, mSettings.m_sMensaLocation); Thread t = new Thread(de); t.start(); } }
false
true
public void onCreate(Bundle savedInstanceState) { // Read settings mSettings.ReadSettings(this); // Setup Theme if (mSettings.m_sThemes.equals("dark")) { setTheme(R.style.myTheme); } else if (mSettings.m_sThemes.equals("light")) { setTheme(R.style.myThemeLight); } // Set Content super.onCreate(savedInstanceState); setContentView(R.layout.meals_list); // Init Database mDbHelper = new MealsDbAdapter(this); mDbHelper.open(); // Setup date mToday = Calendar.getInstance(); if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { mToday.add(Calendar.DAY_OF_YEAR, 2); } else if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { mToday.add(Calendar.DAY_OF_YEAR, 1); } // Capture our buttons from layout and set them up Button buttonPrev = (Button) findViewById(R.id.btn_prev); Button buttonNext = (Button) findViewById(R.id.btn_next); buttonPrev.setBackgroundResource(R.drawable.ic_menu_back); buttonNext.setBackgroundResource(R.drawable.ic_menu_forward); updateButtonText(); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); // Init Ads + hide them after 7 secs mAdView = (AdView) findViewById(R.id.ad); mAdView.setAdListener( new SimpleAdListener() { public void onReceiveAd(com.admob.android.ads.AdView adView) { System.out.println("done.\n"); adView.postDelayed(new Runnable() { @Override public void run() { // ScaleAnimation animation = new ScaleAnimation (1.0f, 0.0f, 1.0f, 0.0f, // Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1.0f); // animation.setDuration(400); // animation.setFillAfter(true); // animation.setInterpolator(new AccelerateInterpolator()); // mAdView.startAnimation(animation); if (!mSettings.m_bAds) { mAdView.setVisibility(View.GONE); } } }, 7000); super.onReceiveAd(adView); } } ); mAdView.setKeywords("mensa menu meals"); mAdView.setRequestInterval(15); mAdView.requestFreshAd(); // Fade the ad in over 4/10 of a second. AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(400); animation.setFillAfter(true); animation.setInterpolator(new AccelerateInterpolator()); mAdView.startAnimation(animation); // // hide ads if deactivated // if (mSettings.m_bAds) { // mAdView.setVisibility(View.VISIBLE); // } else { // mAdView.setVisibility(View.GONE); // } AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR, // Android emulator // "E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone }); }
public void onCreate(Bundle savedInstanceState) { // Read settings mSettings.ReadSettings(this); // Setup Theme if (mSettings.m_sThemes.equals("dark")) { setTheme(R.style.myTheme); } else if (mSettings.m_sThemes.equals("light")) { setTheme(R.style.myThemeLight); } // Set Content super.onCreate(savedInstanceState); setContentView(R.layout.meals_list); // Init Database mDbHelper = new MealsDbAdapter(this); mDbHelper.open(); // Setup date mToday = Calendar.getInstance(); if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { mToday.add(Calendar.DAY_OF_YEAR, 2); } else if (mToday.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { mToday.add(Calendar.DAY_OF_YEAR, 1); } // Capture our buttons from layout and set them up Button buttonPrev = (Button) findViewById(R.id.btn_prev); Button buttonNext = (Button) findViewById(R.id.btn_next); buttonPrev.setBackgroundResource(R.drawable.ic_menu_back); buttonNext.setBackgroundResource(R.drawable.ic_menu_forward); updateButtonText(); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); // Init Ads + hide them after 7 secs mAdView = (AdView) findViewById(R.id.ad); if (!mSettings.m_bAds) { mAdView.setAdListener( new SimpleAdListener() { public void onReceiveAd(com.admob.android.ads.AdView adView) { adView.postDelayed(new Runnable() { @Override public void run() { // ScaleAnimation animation = new ScaleAnimation (1.0f, 0.0f, 1.0f, 0.0f, // Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1.0f); // animation.setDuration(400); // animation.setFillAfter(true); // animation.setInterpolator(new AccelerateInterpolator()); // mAdView.startAnimation(animation); mAdView.setVisibility(View.GONE); } }, 7000); super.onReceiveAd(adView); } } ); } mAdView.setKeywords("mensa menu meals"); mAdView.setRequestInterval(15); mAdView.requestFreshAd(); // Fade the ad in over 4/10 of a second. AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(400); animation.setFillAfter(true); animation.setInterpolator(new AccelerateInterpolator()); mAdView.startAnimation(animation); // // hide ads if deactivated // if (mSettings.m_bAds) { mAdView.setVisibility(View.VISIBLE); // } else { // mAdView.setVisibility(View.GONE); // } AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR, // Android emulator // "E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone }); }
diff --git a/src/java/org/infoglue/deliver/util/PublicationThread.java b/src/java/org/infoglue/deliver/util/PublicationThread.java index 68430d42b..8bbb449dd 100755 --- a/src/java/org/infoglue/deliver/util/PublicationThread.java +++ b/src/java/org/infoglue/deliver/util/PublicationThread.java @@ -1,85 +1,85 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.deliver.util; import org.apache.log4j.Logger; import org.infoglue.cms.util.CmsPropertyHandler; /** * @author mattias * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class PublicationThread extends Thread { public final static Logger logger = Logger.getLogger(PublicationThread.class.getName()); public synchronized void run() { logger.info("setting block"); RequestAnalyser.getRequestAnalyser().setBlockRequests(true); try { int publicationDelay = 5000; String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay(); if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1) publicationDelay = Integer.parseInt(publicationThreadDelay); logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n"); sleep(publicationDelay); logger.info("\n\n\nUpdating all caches as this was a publishing-update\n\n\n"); CacheController.clearCastorCaches(); logger.info("\n\n\nclearing all except page cache as we are in publish mode..\n\n\n"); - CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition"}); + CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition", "JNDIAuthorizationCache", "WebServiceAuthorizationCache"}); logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n"); CacheController.cacheCentralCastorCaches(); logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n"); CacheController.clearCache("ServerNodeProperties"); CacheController.clearCache("serverNodePropertiesCache"); CacheController.clearCache("pageCache"); CacheController.clearCache("componentCache"); CacheController.clearCache("NavigationCache"); CacheController.clearCache("pagePathCache"); CacheController.clearCache("pageCacheParentSiteNodeCache"); CacheController.clearCache("pageCacheLatestSiteNodeVersions"); CacheController.clearCache("pageCacheSiteNodeTypeDefinition"); CacheController.renameCache("newPagePathCache", "pagePathCache"); } catch (Exception e) { logger.error("An error occurred in the PublicationThread:" + e.getMessage(), e); } logger.info("released block \n\n DONE---"); RequestAnalyser.getRequestAnalyser().setBlockRequests(false); } }
true
true
public synchronized void run() { logger.info("setting block"); RequestAnalyser.getRequestAnalyser().setBlockRequests(true); try { int publicationDelay = 5000; String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay(); if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1) publicationDelay = Integer.parseInt(publicationThreadDelay); logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n"); sleep(publicationDelay); logger.info("\n\n\nUpdating all caches as this was a publishing-update\n\n\n"); CacheController.clearCastorCaches(); logger.info("\n\n\nclearing all except page cache as we are in publish mode..\n\n\n"); CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition"}); logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n"); CacheController.cacheCentralCastorCaches(); logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n"); CacheController.clearCache("ServerNodeProperties"); CacheController.clearCache("serverNodePropertiesCache"); CacheController.clearCache("pageCache"); CacheController.clearCache("componentCache"); CacheController.clearCache("NavigationCache"); CacheController.clearCache("pagePathCache"); CacheController.clearCache("pageCacheParentSiteNodeCache"); CacheController.clearCache("pageCacheLatestSiteNodeVersions"); CacheController.clearCache("pageCacheSiteNodeTypeDefinition"); CacheController.renameCache("newPagePathCache", "pagePathCache"); } catch (Exception e) { logger.error("An error occurred in the PublicationThread:" + e.getMessage(), e); } logger.info("released block \n\n DONE---"); RequestAnalyser.getRequestAnalyser().setBlockRequests(false); }
public synchronized void run() { logger.info("setting block"); RequestAnalyser.getRequestAnalyser().setBlockRequests(true); try { int publicationDelay = 5000; String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay(); if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1) publicationDelay = Integer.parseInt(publicationThreadDelay); logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n"); sleep(publicationDelay); logger.info("\n\n\nUpdating all caches as this was a publishing-update\n\n\n"); CacheController.clearCastorCaches(); logger.info("\n\n\nclearing all except page cache as we are in publish mode..\n\n\n"); CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition", "JNDIAuthorizationCache", "WebServiceAuthorizationCache"}); logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n"); CacheController.cacheCentralCastorCaches(); logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n"); CacheController.clearCache("ServerNodeProperties"); CacheController.clearCache("serverNodePropertiesCache"); CacheController.clearCache("pageCache"); CacheController.clearCache("componentCache"); CacheController.clearCache("NavigationCache"); CacheController.clearCache("pagePathCache"); CacheController.clearCache("pageCacheParentSiteNodeCache"); CacheController.clearCache("pageCacheLatestSiteNodeVersions"); CacheController.clearCache("pageCacheSiteNodeTypeDefinition"); CacheController.renameCache("newPagePathCache", "pagePathCache"); } catch (Exception e) { logger.error("An error occurred in the PublicationThread:" + e.getMessage(), e); } logger.info("released block \n\n DONE---"); RequestAnalyser.getRequestAnalyser().setBlockRequests(false); }
diff --git a/genlab.gui/src/genlab/gui/views/MessagesViewAbstract.java b/genlab.gui/src/genlab/gui/views/MessagesViewAbstract.java index e6e6606..7b51b1b 100644 --- a/genlab.gui/src/genlab/gui/views/MessagesViewAbstract.java +++ b/genlab.gui/src/genlab/gui/views/MessagesViewAbstract.java @@ -1,603 +1,609 @@ package genlab.gui.views; import genlab.core.usermachineinteraction.IListOfMessagesListener; import genlab.core.usermachineinteraction.ITextMessage; import genlab.core.usermachineinteraction.ListOfMessages; import genlab.core.usermachineinteraction.ListsOfMessages; import genlab.gui.VisualResources; import genlab.gui.actions.ClearMessagesAction; import java.io.PrintWriter; import java.io.StringWriter; import java.text.DateFormat; import java.util.Locale; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.part.ViewPart; /** * Displays messages as a table. * Listens for general messages. * * TODO add exportation to a text file ?! * * @author Samuel Thiriot * */ public abstract class MessagesViewAbstract extends ViewPart { /** * Datetime format used to display the "when" column */ public static final DateFormat DATE_FORMAT = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.getDefault()); /** * Comparator for the table viewer (sorts info) */ private MyViewerComparator comparator = null; /** * The table viewer; we use a virtual one (meaning, it does only display what is visible), * but not a lazy loader, because loading data is not coslty for us. */ protected TableViewer viewer = null; /** * The listener which monitors the changes in the list of messages */ protected IListOfMessagesListener listener = null; /** * The list of messages we are listening to */ protected ListOfMessages messages = null; /** * The part composite of the view (if of use ?) */ private Composite parent; private Display display; public MessagesViewAbstract() { } /** * In charge of refreshing the view as soon as possible, * but not too often * @author Samuel Thiriot * */ class ThreadMessageUpdate extends Thread { private boolean cancel = false; private boolean contentToDisplay = false; private boolean updateInProgress = false; /** * Minimum delay between two refresh (avoids to update in continuous) */ private long minPeriodMs = 100; private boolean longSleep = false; private Runnable runnable = null; public ThreadMessageUpdate() { setDaemon(true); setPriority(MIN_PRIORITY); setName("glUpdateMessages"); runnable = new Runnable() { @Override public void run() { if (parent.isDisposed() && listener != null) { ListsOfMessages.getGenlabMessages().removeListener(listener); return; } try { viewer.getControl().setRedraw(false); //viewer.setInput("toto"); viewer.refresh(false); viewer.getControl().setRedraw(true); } catch (RuntimeException e) { // TODO manage disposed exception e.printStackTrace(); } updateInProgress = false; } }; } public void cancel() { cancel = true; if (longSleep) interrupt(); } public void notifySomethingToDisplay() { if (updateInProgress) return; // ignore if we are aleady updating contentToDisplay = true; if (longSleep) interrupt(); } protected void refreshDisplay() { if (updateInProgress) return; if (display == null || display.isDisposed()) { this.cancel(); if (messages != null) messages.removeListener(listener); } updateInProgress = true; //long timestampStart = System.currentTimeMillis(); //System.err.println("update display: begin"); display.syncExec(runnable); //System.err.println("time to update display : "+(System.currentTimeMillis()-timestampStart)); } @Override public void run() { while (!cancel) { // update display if (contentToDisplay) { refreshDisplay(); contentToDisplay = false; // now sleep (short) longSleep = false; try { Thread.sleep(minPeriodMs); } catch (InterruptedException e) { } } else { longSleep = true; try { Thread.sleep(1000*60*60); } catch (InterruptedException e) { } longSleep = false; } } } } private ThreadMessageUpdate updateThread = null; class MessagesContentProvider implements IStructuredContentProvider { private final ListOfMessages list; public MessagesContentProvider(ListOfMessages list) { this.list = list; } @Override public void dispose() { } @Override public void inputChanged(Viewer pviewer, Object oldInput, Object newInput) { // nothing to do (read only !) } @Override public Object[] getElements(Object inputElement) { //System.err.println("get elements called; "+list.getSize()+" vs. "+viewer.getTable().getItemCount()); Object[] res = null; res = list.asArray(); return res; } } /** * Basic label provider that manages colors * * @author Samuel Thiriot * */ protected class ColorColumnProvider extends ColumnLabelProvider { @Override public Color getForeground(Object element) { ITextMessage message = (ITextMessage)element; switch (message.getLevel()) { case DEBUG: case TRACE: return VisualResources.COLOR_GRAY; case ERROR: return VisualResources.COLOR_RED; default: return null; } } } /** * Provides comparison for sorting. * */ public class MyViewerComparator extends ViewerComparator { private int propertyIndex; private static final int DESCENDING = 1; private int direction = DESCENDING; public MyViewerComparator() { this.propertyIndex = 2; // sort by date by default direction = DESCENDING; } public int getDirection() { return direction == 1 ? SWT.DOWN : SWT.UP; } public void setColumn(int column) { if (column == this.propertyIndex) { // Same column as last sort; toggle the direction direction = 1 - direction; } else { // New column; do an ascending sort this.propertyIndex = column; direction = DESCENDING; } } @Override public int compare(Viewer viewer, Object e1, Object e2) { ITextMessage p1 = (ITextMessage) e1; ITextMessage p2 = (ITextMessage) e2; int rc = 0; switch (propertyIndex) { case 0: rc = p1.getLevel().compareTo(p2.getLevel()); break; case 1: rc = p1.getAudience().compareTo(p2.getAudience()); break; case 2: rc = p1.getTimestamp().compareTo(p2.getTimestamp()); break; case 3: rc = p1.getEmitter().getCanonicalName().compareTo(p2.getEmitter().getCanonicalName()); break; case 4: rc = p1.getMessage().compareTo(p2.getMessage()); break; default: System.err.println("default ! :-("); rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; } } /** * Listens for click events on the table, and changes sorting * @param column * @param index * @return */ private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index) { SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (comparator == null || viewer == null) return; comparator.setColumn(index); int dir = comparator.getDirection(); viewer.getTable().setSortDirection(dir); viewer.refresh(); } }; return selectionAdapter; } /** * Returns the list of messages tracked by this view * @return */ public ListOfMessages getListOfMessages() { return messages; } @Override public void createPartControl(final Composite parent) { this.parent = parent; this.display = parent.getDisplay(); viewer = new TableViewer( parent, //SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER | SWT.READ_ONLY | SWT.VIRTUAL ); viewer.setUseHashlookup(true); ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE); // configure viewer comparator = new MyViewerComparator(); viewer.setComparator(comparator); // ... columns { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("Level"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getLevel().toString(); } @Override public Image getImage(Object element) { ITextMessage message = (ITextMessage)element; switch (message.getLevel()) { case TRACE: case DEBUG: return VisualResources.ICON_DEBUG; case TIP: return VisualResources.ICON_TIP; case ERROR: return VisualResources.ICON_ERROR; case INFO: return VisualResources.ICON_INFO; case WARNING: return VisualResources.ICON_WARNING; default: return null; } } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 0)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("Audience"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getAudience().toString(); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 1)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("When"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return DATE_FORMAT.format(message.getDate()); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 2)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(300); col.getColumn().setText("From"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getToolTipText(Object element) { ITextMessage message = (ITextMessage)element; return message.getEmitter().getCanonicalName(); } public int getToolTipDisplayDelayTime(Object object) { return 50; } public int getToolTipTimeDisplayed(Object object) { return 10000; } @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getEmitter().getCanonicalName(); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 3)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(400); col.getColumn().setText("Message"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getToolTipText(Object element) { ITextMessage message = (ITextMessage)element; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); - pw.println(message.getMessage()); + String msg = message.getMessage(); + if (msg.length() > 10000) { + pw.print(message.getMessage().substring(0, 10000)); + pw.println("[...]"); + } else { + pw.println(message.getMessage()); + } if (message.getException() != null) message.getException().printStackTrace(pw); return sw.toString(); } public int getToolTipDisplayDelayTime(Object object) { return 100; } public int getToolTipTimeDisplayed(Object object) { return 40000; } @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; if (message.getCount() > 1) { StringBuffer sb = new StringBuffer(); return sb .append("(") //$NON-NLS-1$ .append(message.getCount()) .append(" times") .append(") ") //$NON-NLS-1$ .append(message.getMessageFirstLine()) .toString(); } else return message.getMessageFirstLine(); } }); //col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 4)); } // configure table final Table table = viewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); updateThread = new ThreadMessageUpdate(); listener = new IListOfMessagesListener() { @Override public void contentChanged(ListOfMessages list) { if (viewer == null || viewer.getControl().isDisposed()) { messages.removeListener(this); return; } updateThread.notifySomethingToDisplay(); } @Override public void messageAdded(ListOfMessages list, ITextMessage message) { } }; updateThread.start(); listenMessages(); // add actions getViewSite().getActionBars().getToolBarManager().add(new ClearMessagesAction()); } @Override public void setFocus() { // nothing to do (?) } protected abstract void listenMessages(); @Override public void dispose() { if (updateThread != null) updateThread.cancel(); if (listener != null && messages != null) messages.removeListener(listener); super.dispose(); } }
true
true
public void createPartControl(final Composite parent) { this.parent = parent; this.display = parent.getDisplay(); viewer = new TableViewer( parent, //SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER | SWT.READ_ONLY | SWT.VIRTUAL ); viewer.setUseHashlookup(true); ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE); // configure viewer comparator = new MyViewerComparator(); viewer.setComparator(comparator); // ... columns { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("Level"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getLevel().toString(); } @Override public Image getImage(Object element) { ITextMessage message = (ITextMessage)element; switch (message.getLevel()) { case TRACE: case DEBUG: return VisualResources.ICON_DEBUG; case TIP: return VisualResources.ICON_TIP; case ERROR: return VisualResources.ICON_ERROR; case INFO: return VisualResources.ICON_INFO; case WARNING: return VisualResources.ICON_WARNING; default: return null; } } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 0)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("Audience"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getAudience().toString(); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 1)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("When"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return DATE_FORMAT.format(message.getDate()); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 2)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(300); col.getColumn().setText("From"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getToolTipText(Object element) { ITextMessage message = (ITextMessage)element; return message.getEmitter().getCanonicalName(); } public int getToolTipDisplayDelayTime(Object object) { return 50; } public int getToolTipTimeDisplayed(Object object) { return 10000; } @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getEmitter().getCanonicalName(); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 3)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(400); col.getColumn().setText("Message"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getToolTipText(Object element) { ITextMessage message = (ITextMessage)element; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(message.getMessage()); if (message.getException() != null) message.getException().printStackTrace(pw); return sw.toString(); } public int getToolTipDisplayDelayTime(Object object) { return 100; } public int getToolTipTimeDisplayed(Object object) { return 40000; } @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; if (message.getCount() > 1) { StringBuffer sb = new StringBuffer(); return sb .append("(") //$NON-NLS-1$ .append(message.getCount()) .append(" times") .append(") ") //$NON-NLS-1$ .append(message.getMessageFirstLine()) .toString(); } else return message.getMessageFirstLine(); } }); //col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 4)); } // configure table final Table table = viewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); updateThread = new ThreadMessageUpdate(); listener = new IListOfMessagesListener() { @Override public void contentChanged(ListOfMessages list) { if (viewer == null || viewer.getControl().isDisposed()) { messages.removeListener(this); return; } updateThread.notifySomethingToDisplay(); } @Override public void messageAdded(ListOfMessages list, ITextMessage message) { } }; updateThread.start(); listenMessages(); // add actions getViewSite().getActionBars().getToolBarManager().add(new ClearMessagesAction()); }
public void createPartControl(final Composite parent) { this.parent = parent; this.display = parent.getDisplay(); viewer = new TableViewer( parent, //SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER | SWT.READ_ONLY | SWT.VIRTUAL ); viewer.setUseHashlookup(true); ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE); // configure viewer comparator = new MyViewerComparator(); viewer.setComparator(comparator); // ... columns { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("Level"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getLevel().toString(); } @Override public Image getImage(Object element) { ITextMessage message = (ITextMessage)element; switch (message.getLevel()) { case TRACE: case DEBUG: return VisualResources.ICON_DEBUG; case TIP: return VisualResources.ICON_TIP; case ERROR: return VisualResources.ICON_ERROR; case INFO: return VisualResources.ICON_INFO; case WARNING: return VisualResources.ICON_WARNING; default: return null; } } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 0)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("Audience"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getAudience().toString(); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 1)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(100); col.getColumn().setText("When"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return DATE_FORMAT.format(message.getDate()); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 2)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(300); col.getColumn().setText("From"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getToolTipText(Object element) { ITextMessage message = (ITextMessage)element; return message.getEmitter().getCanonicalName(); } public int getToolTipDisplayDelayTime(Object object) { return 50; } public int getToolTipTimeDisplayed(Object object) { return 10000; } @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; return message.getEmitter().getCanonicalName(); } }); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 3)); } { TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE); col.getColumn().setWidth(400); col.getColumn().setText("Message"); col.setLabelProvider(new ColorColumnProvider() { @Override public String getToolTipText(Object element) { ITextMessage message = (ITextMessage)element; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String msg = message.getMessage(); if (msg.length() > 10000) { pw.print(message.getMessage().substring(0, 10000)); pw.println("[...]"); } else { pw.println(message.getMessage()); } if (message.getException() != null) message.getException().printStackTrace(pw); return sw.toString(); } public int getToolTipDisplayDelayTime(Object object) { return 100; } public int getToolTipTimeDisplayed(Object object) { return 40000; } @Override public String getText(Object element) { ITextMessage message = (ITextMessage)element; if (message.getCount() > 1) { StringBuffer sb = new StringBuffer(); return sb .append("(") //$NON-NLS-1$ .append(message.getCount()) .append(" times") .append(") ") //$NON-NLS-1$ .append(message.getMessageFirstLine()) .toString(); } else return message.getMessageFirstLine(); } }); //col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 4)); } // configure table final Table table = viewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); updateThread = new ThreadMessageUpdate(); listener = new IListOfMessagesListener() { @Override public void contentChanged(ListOfMessages list) { if (viewer == null || viewer.getControl().isDisposed()) { messages.removeListener(this); return; } updateThread.notifySomethingToDisplay(); } @Override public void messageAdded(ListOfMessages list, ITextMessage message) { } }; updateThread.start(); listenMessages(); // add actions getViewSite().getActionBars().getToolBarManager().add(new ClearMessagesAction()); }
diff --git a/easysoa-registry-v1/easysoa-registry-doctypes-core/src/main/java/org/easysoa/registry/dbb/ResourceDownloadServiceImpl.java b/easysoa-registry-v1/easysoa-registry-doctypes-core/src/main/java/org/easysoa/registry/dbb/ResourceDownloadServiceImpl.java index 80b570a8..0f08a7d2 100644 --- a/easysoa-registry-v1/easysoa-registry-doctypes-core/src/main/java/org/easysoa/registry/dbb/ResourceDownloadServiceImpl.java +++ b/easysoa-registry-v1/easysoa-registry-doctypes-core/src/main/java/org/easysoa/registry/dbb/ResourceDownloadServiceImpl.java @@ -1,213 +1,215 @@ /** * */ package org.easysoa.registry.dbb; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.util.Properties; import org.easysoa.registry.DocumentService; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.model.ComponentContext; import org.nuxeo.runtime.model.DefaultComponent; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import java.text.SimpleDateFormat; import java.util.Date; import org.easysoa.registry.types.ResourceDownloadInfo; /** * Impl of ResourceDownloadService for Nuxeo components. * * Makes the global ResourceDownloadService available in Nuxeo, * but if not available or timeout at activation, disables it and does instead * a local synchronous download (using HttpDownloaderServiceImpl). * * Default configuration (change it in nxserver/config/easysoa.properties ) : * * ResourceDownloadServiceImpl.delegateResourceDownloadServiceUrl = http://localhost:7080/get * * Reuses a single Jersey client (rather than creating one per download which costs too much). * * TODO LATER better : * test delegate async at start * called by ResourceUpdate within async using Nuxeo Work * * @author jguillemotte, mdutoo * */ public class ResourceDownloadServiceImpl extends DefaultComponent implements ResourceDownloadService { private String delegateResourceDownloadServiceUrl; // caches private Client client = null; private boolean isDelegatedDownloadDisabled = false; @Override public void activate(ComponentContext context) throws Exception { super.activate(context); // Configuration (following ex. SchedulerImpl) // TODO LATER maybe rather as an extension point / contribution ?? try { DocumentService documentService = Framework.getService(DocumentService.class); Properties props = documentService.getProperties(); if (props != null) { delegateResourceDownloadServiceUrl = props.getProperty( "ResourceDownloadServiceImpl.delegateResourceDownloadServiceUrl", "http://localhost:7080/get"); } } catch (Exception e) { throw new RuntimeException("Unable to get DocumentService", e); } // Create reusable Jersey client, rather than creating one per download else costs too much // (ex. lots of threads at SignatureParser l. 79 within annotation parsing). // TODO LATER better : called by ResourceUpdate within async using Nuxeo Work client = Client.create(); client.setConnectTimeout(3000); // Set timeout to 3 seconds TODO LATER make it configurable // TODO LATER start async Work that tests delegated download and sets isDelegatedDownloadDisabled } @Override public void deactivate(ComponentContext context) throws Exception { client = null; super.deactivate(context); } @Override public ResourceDownloadInfo get(URL url) throws Exception { ResourceDownloadInfoImpl resourceDownloadInfo = new ResourceDownloadInfoImpl(); File file = null; if (!isDelegatedDownloadDisabled) { // First try : Connect to FraSCAti studio download service (TODO : this service must be exposed as REST service ...) try { //return delegatedDownload(url); file = delegatedDownload(url); } catch(Exception ex){ // Error or timeout, try the second donwload method isDelegatedDownloadDisabled = true; - // If no response : Use local downloader service - file = localDownload(url); } - } - //return localDownload(url); + } else { + // If no response : Use local downloader service + file = localDownload(url); + } // Compute timestamp - Date date = new Date(); - SimpleDateFormat sdf = new SimpleDateFormat(ResourceDownloadInfo.TIMESTAMP_DATETIME_PATTERN); - resourceDownloadInfo.setTimestamp(sdf.format(date)); - resourceDownloadInfo.setFile(file); + if(file != null){ + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat(ResourceDownloadInfo.TIMESTAMP_DATETIME_PATTERN); + resourceDownloadInfo.setTimestamp(sdf.format(date)); + resourceDownloadInfo.setFile(file); + } return resourceDownloadInfo; } /** * * @param url * @return * @throws Exception */ private File delegatedDownload(URL url) throws Exception { WebResource webResource = client.resource(delegateResourceDownloadServiceUrl); // NB. reuses Jersey client rather than creating one per download else costs too much // (ex. lots of threads at SignatureParser l. 79 within annotation parsing) // TODO LATER better : called by ResourceUpdate within async using Nuxeo Work // TODO for frascati service side : Add a parameter to pass the url webResource.setProperty("fileURL", url.toURI().toString()); // Get the resource File resourceFile = webResource.get(File.class); return resourceFile; } /** * * @param url * @return * @throws Exception */ private File localDownload(URL url) throws Exception{ HttpDownloaderService httpDownloaderService = new HttpDownloaderServiceImpl(); HttpDownloader fileDownloader = httpDownloaderService.createHttpDownloader(url); fileDownloader.download(); return fileDownloader.getFile(); } /** * Read data from File * @param file * @return */ @Override public String getData(File file) throws Exception { String data; FileInputStream fis = null; try { if (file == null) { // ex. if site root url returns something else than 200 (ex. 403) return ""; // else cleaner.clean(siteRootFile) throws NullPointerException } fis = new FileInputStream(file); StringBuilder dataBuffer = new StringBuilder(); int c; while ((c = fis.read()) != -1) { dataBuffer.append((char) c); } data = dataBuffer.toString(); } catch (Exception e) { data = null; } finally { if (fis != null) { fis.close(); } } return data; } //@Reference //protected List<UrlPatternWebResourceDownloadService> downloadServices; /* (non-Javadoc) * @see org.easysoa.registry.rest.integration.resources.RoutingWebResourceDownloadService#get(java.net.URL) */ /*@Override @Path("/get/") @GET public File get(URL url, PreferencesManagerItf preferences) throws Exception { // - Sort the list, to have the webResourceDownloadServices in the specified order // Need to be sorted manually because FraSCAti doesn't provide a native way to specify an execution order Collections.sort(downloadServices, new DownloadServicesComparator()); for(UrlPatternWebResourceDownloadService service : downloadServices){ if(service.matchUrl(url)){ // file type is always WSDL ?? File localTempFolder = new File(tempFolder + "tempWsdl"); if(!localTempFolder.exists()){ localTempFolder.mkdir(); } File localWsdlFile = new File(tempFolder + "tempWsdl/temp_" + System.currentTimeMillis() + ".wsdl"); if (!localWsdlFile.createNewFile()) { throw new IOException("Unable to create local WSDL file at " + localWsdlFile.getAbsolutePath()); } // TODO closes ? IOUtils.write(service.get(url), new FileOutputStream(localWsdlFile)); return localWsdlFile; //return Response.ok(service.get(url)).type("text/xml").build(); } } //return Response.serverError().build(); return null; } */ }
false
true
public ResourceDownloadInfo get(URL url) throws Exception { ResourceDownloadInfoImpl resourceDownloadInfo = new ResourceDownloadInfoImpl(); File file = null; if (!isDelegatedDownloadDisabled) { // First try : Connect to FraSCAti studio download service (TODO : this service must be exposed as REST service ...) try { //return delegatedDownload(url); file = delegatedDownload(url); } catch(Exception ex){ // Error or timeout, try the second donwload method isDelegatedDownloadDisabled = true; // If no response : Use local downloader service file = localDownload(url); } } //return localDownload(url); // Compute timestamp Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(ResourceDownloadInfo.TIMESTAMP_DATETIME_PATTERN); resourceDownloadInfo.setTimestamp(sdf.format(date)); resourceDownloadInfo.setFile(file); return resourceDownloadInfo; }
public ResourceDownloadInfo get(URL url) throws Exception { ResourceDownloadInfoImpl resourceDownloadInfo = new ResourceDownloadInfoImpl(); File file = null; if (!isDelegatedDownloadDisabled) { // First try : Connect to FraSCAti studio download service (TODO : this service must be exposed as REST service ...) try { //return delegatedDownload(url); file = delegatedDownload(url); } catch(Exception ex){ // Error or timeout, try the second donwload method isDelegatedDownloadDisabled = true; } } else { // If no response : Use local downloader service file = localDownload(url); } // Compute timestamp if(file != null){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(ResourceDownloadInfo.TIMESTAMP_DATETIME_PATTERN); resourceDownloadInfo.setTimestamp(sdf.format(date)); resourceDownloadInfo.setFile(file); } return resourceDownloadInfo; }
diff --git a/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/user/IndividuController.java b/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/user/IndividuController.java index 8a95ee3b..c469bb9f 100644 --- a/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/user/IndividuController.java +++ b/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/user/IndividuController.java @@ -1,1680 +1,1681 @@ /** * */ package org.esupportail.opi.web.controllers.user; import fj.*; import fj.data.Option; import fj.data.Stream; import org.apache.commons.lang.StringUtils; import org.esupportail.commons.services.ldap.LdapUser; import org.esupportail.commons.services.ldap.LdapUserService; import org.esupportail.commons.services.logging.Logger; import org.esupportail.commons.services.logging.LoggerImpl; import org.esupportail.commons.utils.Assert; import org.esupportail.opi.domain.beans.etat.EtatIndividu; import org.esupportail.opi.domain.beans.parameters.AccesSelectif; import org.esupportail.opi.domain.beans.parameters.Campagne; import org.esupportail.opi.domain.beans.parameters.Transfert; import org.esupportail.opi.domain.beans.parameters.TypeDecision; import org.esupportail.opi.domain.beans.parameters.TypeTraitement; import org.esupportail.opi.domain.beans.references.commission.Commission; import org.esupportail.opi.domain.beans.references.commission.TraitementCmi; import org.esupportail.opi.domain.beans.references.rendezvous.IndividuDate; import org.esupportail.opi.domain.beans.user.Adresse; import org.esupportail.opi.domain.beans.user.Gestionnaire; import org.esupportail.opi.domain.beans.user.Individu; import org.esupportail.opi.domain.beans.user.User; import org.esupportail.opi.domain.beans.user.candidature.IndFormulaire; import org.esupportail.opi.domain.beans.user.candidature.IndVoeu; import org.esupportail.opi.domain.beans.user.candidature.VersionEtpOpi; import org.esupportail.opi.domain.beans.user.indcursus.IndBac; import org.esupportail.opi.domain.beans.user.indcursus.IndCursusScol; import org.esupportail.opi.domain.beans.user.situation.IndSituation; import org.esupportail.opi.utils.Constantes; import org.esupportail.opi.utils.GenNumDosOPI; import org.esupportail.opi.web.beans.beanEnum.ActionEnum; import org.esupportail.opi.web.beans.paginator.IndividuPaginator; import org.esupportail.opi.web.beans.parameters.FormationContinue; import org.esupportail.opi.web.beans.parameters.FormationInitiale; import org.esupportail.opi.web.beans.parameters.RegimeInscription; import org.esupportail.opi.web.beans.pojo.IndRechPojo; import org.esupportail.opi.web.beans.pojo.IndividuPojo; import org.esupportail.opi.web.beans.utils.NavigationRulesConst; import org.esupportail.opi.web.beans.utils.Utilitaires; import org.esupportail.opi.web.controllers.AbstractAccessController; import org.esupportail.opi.web.controllers.SessionController; import org.esupportail.opi.web.controllers.formation.FormulairesController; import org.esupportail.opi.web.utils.fj.Conversions; import org.esupportail.opi.web.utils.fj.Functions; import org.esupportail.opi.web.utils.paginator.LazyDataModel; import org.primefaces.model.SortOrder; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static fj.Effect.f; import static fj.data.Option.*; import static fj.data.Option.fromString; import static fj.data.Stream.*; import static fj.data.Stream.join; import static org.esupportail.opi.domain.beans.etat.EtatIndividu.EtatComplet; import static org.esupportail.opi.domain.beans.etat.EtatIndividu.EtatIncomplet; import static org.esupportail.opi.utils.primefaces.PFFilters.pfFilters; import static org.esupportail.opi.web.utils.paginator.LazyDataModel.lazyModel; /** * @author cleprous */ public class IndividuController extends AbstractAccessController { /** * The serialization id. */ private static final long serialVersionUID = 1739075202274589002L; /** * The number of character for the NumDosOPI code. */ private static final int NB_CHAR_CODE = 8; /** * */ private static final int NB_YEAR_FIRST = 10; /** * */ private static final int NB_YEAR_LAST = 100; /** * Current Year Used By default for birth dates(). */ private static final int DEFAULT_CURRENT_YEAR = 2010; /** * can no be null. */ private static final String CAN_NO_BE_NULL = "can not be null"; /** * The state when create a dossier. */ private static final String DOSSIER_CREATE = "DOSSIER_CREATE"; /** * The state when update a dossier. */ private static final String DOSSIER_UPDATE = "DOSSIER_UPDATE"; /** * Static list used to store the years which can be used for the birthdates. */ private static List<SelectItem> listeAnneeNaissance = new ArrayList<>(); /** * At true if call in ENT. * Default value : false. */ private boolean isRecupCursus; /** * At true if call in ENT. * Default value : false. */ private boolean isRecupBac; /** * At true if call in ENT. * Default value : false. */ private boolean isRecupInfos; /** * access to the ldap Service */ LdapUserService ldapUserService; /** * A logger. */ private final Logger log = new LoggerImpl(getClass()); /* ******************* PROPERTIES ******************* */ /** * The Individu. */ private IndividuPojo pojoIndividu; /** * The actionEnum. */ private ActionEnum actionEnum; /** * see {@link AdressController}. */ private AdressController adressController; /** * see {@link CursusController}. */ private CursusController cursusController; /** * see {@link AdressController}. */ private IndBacController indBacController; /** * see {@link SituationController}. */ private SituationController situationController; /** * see {@link IndividuPaginator}. */ private IndividuPaginator individuPaginator; /** * see {@link FormulairesController}. */ private FormulairesController formulairesController; /** * State of the dossier (create or update). */ private String etatDossier; /** * Used to Store the birth day. */ private String jourNaissance; /** * Used to store the birth month. */ private String moisNaissance; /** * Use to store the birth Year. */ private String anneeNaissance; /** * Variable to check the mail address. */ private String checkEmail; private Collection<TypeTraitement> typeTraitements; private boolean renderTable = false; private Effect<String> applyPut(String key, Map<String, String> map) { return f(Functions.<String, Map<String, String>, Unit>apply2(key, map).o(Functions.<String, String>put_())); } private final LazyDataModel<Individu> indLDM = lazyModel( new F5<Integer, Integer, String, SortOrder, Map<String, String>, P2<Long, Stream<Individu>>>() { public P2<Long, Stream<Individu>> f(final Integer first, final Integer pageSize, final String sortField, final SortOrder sortOrder, final Map<String, String> filters) { // le gestionnaire courant SessionController sessionCont = getSessionController(); User user = sessionCont.getCurrentUser(); Gestionnaire gest = !(user instanceof Gestionnaire) ? sessionCont.getManager() : (Gestionnaire) user; // les filtres : IndRechPojo indRechPojo = individuPaginator.getIndRechPojo(); // 1. les numdossier, nom, prenom fromString(indRechPojo.getNumDossierOpiRecherche()) .foreach(applyPut("numDossierOpi", filters)); fromString(indRechPojo.getNomRecherche()) .foreach(applyPut("nomPatronymique", filters)); fromString(indRechPojo.getPrenomRecherche()) .foreach(applyPut("prenom", filters)); // Hack pour filtrer ou non les individus sans voeux : // indRechPojo.useVoeuFilter est positionné dans les vues par f:event iif(indRechPojo.isUseVoeuFilter(), "true") .foreach(applyPut("useVoeuFilter", filters)); // 2. le ou les types de décision final List<TypeDecision> typesDec = indRechPojo.getTypesDec(); // 3. les étapes (TraitementCmi) de la commission Integer idCom = indRechPojo.getIdCmi(); Option<Stream<Commission>> cmis = iif(idCom != null && idCom > 0, idCom) .map(new F<Integer, Stream<Commission>>() { public Stream<Commission> f(Integer idCmi) { return single(getParameterService().getCommission(idCmi, null)); }}) .orElse(iif(indRechPojo.isUseGestCommsFilter(), // (Hack : isUseGestCommsFilter est positionné par f:event) iterableStream(fromNull(getDomainApoService().getListCommissionsByRight(gest, true)) .orSome(new HashSet<Commission>())))); final Option<Set<TraitementCmi>> trtCmis = cmis.map(new F<Stream<Commission>, Stream<TraitementCmi>>() { public Stream<TraitementCmi> f(Stream<Commission> commissions) { return commissions.bind(new F<Commission, Stream<TraitementCmi>>() { public Stream<TraitementCmi> f(Commission com) { return join(fromNull(com.getTraitementCmi()) .toStream() .map(Conversions.<TraitementCmi>setToStream_())); } }); } }.andThen(Conversions.<TraitementCmi>streamToSet_())); // 4. les régimes d'inscription final Set<Integer> listCodesRI = new HashSet<>( iterableStream(fromNull(indRechPojo.getListeRI()) .orSome(Collections.<RegimeInscription>emptySet())) .map(new F<RegimeInscription, Integer>() { public Integer f(RegimeInscription ri) { return ri.getCode(); } }).toCollection()); // 5. caractère 'traité' ou non du voeu Boolean excludeTreated = indRechPojo.getExcludeWishProcessed(); final Option<Boolean> wishTreated = iif(excludeTreated != null && excludeTreated, false); // 6. caratère 'validé' ou non du voeu final Option<Boolean> validWish = fromNull(indRechPojo.getSelectValid()); // 7. le type de traitement (Hack : indRechPojo.useTypeTrtFilter est positionné dans les vues par f:event) final Collection<TypeTraitement> typeTrtmts = indRechPojo.isUseTypeTrtFilter() ? typeTraitements : Collections.<TypeTraitement>emptyList(); // 8. Date de création des voeux final Option<Date> dateCrea = fromNull(indRechPojo.getDateCreationVoeuRecherchee()); // 9. le ou les types de traitement des étapes Boolean useTypeTrtVetFilter = indRechPojo.isUseTypeTrtVetFilter(); final Option<List<String>> typesTrtVet = iif(useTypeTrtVetFilter != null && useTypeTrtVetFilter, indRechPojo.getTypesTrtVet()); return getDomainService().sliceOfInd( pfFilters((long) first, (long) pageSize, sortField, sortOrder, filters), typesDec, validWish, wishTreated, dateCrea, typeTrtmts, trtCmis, listCodesRI, typesTrtVet); } }, new F2<String, Individu, Boolean>() { public Boolean f(String rowKey, Individu individu) { return individu.getId().toString().equals(rowKey); } } ); // ******************* INIT ************************* /** * @see org.esupportail.opi.web.controllers.AbstractDomainAwareBean#reset() */ @Override public void reset() { actionEnum = new ActionEnum(); pojoIndividu = new IndividuPojo(); pojoIndividu.getIndividu().setCodPayNaissance(Constantes.CODEFRANCE); pojoIndividu.getIndividu().setCodPayNationalite(Constantes.CODEFRANCE); checkEmail = ""; jourNaissance = ""; moisNaissance = ""; anneeNaissance = ""; adressController.reset(); cursusController.reset(); indBacController.reset(); situationController.reset(); } /** * @see org.esupportail.opi.web.controllers.AbstractContextAwareController#afterPropertiesSetInternal() */ @Override public void afterPropertiesSetInternal() { super.afterPropertiesSetInternal(); Assert.notNull(this.adressController, "property adressController of class " + this.getClass().getName() + CAN_NO_BE_NULL); Assert.notNull(this.cursusController, "property cursusController of class " + this.getClass().getName() + CAN_NO_BE_NULL); Assert.notNull(this.indBacController, "property indBacController of class " + this.getClass().getName() + CAN_NO_BE_NULL); Assert.notNull(this.situationController, "property situationController of class " + this.getClass().getName() + CAN_NO_BE_NULL); Assert.notNull(this.individuPaginator, "property individuPaginator of class " + this.getClass().getName() + CAN_NO_BE_NULL); Assert.notNull(this.formulairesController, "property formulairesController of class " + this.getClass().getName() + CAN_NO_BE_NULL); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "IndividuController#" + hashCode() + "[pojoIndividu =" + pojoIndividu + "]"; } /* ******************* CALLBACK ********************** */ /** * Callback to search a Rennes1 student with his NNE code. * * @return String */ public String goSearchEtuR1() { reset(); resetRoadMap(); pojoIndividu.getIndividu().setCodPayNaissance(""); pojoIndividu.getIndividu().setCodPayNationalite(""); if (!getManagedCalendar().getCalInsIsOpen()) { //les calendriers sont fermes return NavigationRulesConst.INSCRIPTION_CLOSE; } getSessionController().setRegimeInsUser( getSessionController().getRegimeIns().get(FormationInitiale.CODE)); addTheCurrentRoad(NavigationRulesConst.SEARCH_ETU_R1, getString("INDIVIDU.SEARCH"), getString("INDIVIDU.SEARCH.DESC")); return NavigationRulesConst.SEARCH_ETU_R1; } /** * Callback to find a Rennes1 student in Apogee with his NNE code. * * @return String */ public String goFindEtuR1() { if (log.isDebugEnabled()) { log.debug("entering goFindEtuR1()"); } etatDossier = DOSSIER_CREATE; /** * Règles d'accès à la création d'un dossier : * - soit l'étudiant vient de l'ENT auquel cas on l'identifie avec son codEtu depuis Apogée * - soit il vient de la page de recherche : * - si il a saisit son code INE, on le recherche dans Apogée * - si il a cliqué sur "Création d'un dossier", on remet à zero le pojoIndividu * - si il a fait une recherche, on lui affiche son dossier prérempli avec ses coordonnées * éventuellement bloquées si les données existent déjà dans Apogée */ //isCodEtu signifie qu'1 etudiant de Rennes1 se connecte pour la premiere fois sur OPI Boolean isCodEtu = StringUtils.isNotBlank(getSessionController().getCodEtu()); if (isCodEtu || (!pojoIndividu.getDoNotHaveCodeNne() && !pojoIndividu.getIsUsingSearch())) { Individu ind = pojoIndividu.getIndividu(); Individu individuOPI; Individu individuApogee; if (!isCodEtu) { // Check NNE fields if (!StringUtils.isNotBlank(ind.getCodeNNE()) || !StringUtils.isNotBlank(ind.getCodeClefNNE())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.NUM_NNE")); return null; } // Get the student data from Base individuOPI = getDomainService().getIndividuINE(ind.getCodeNNE(), ind.getCodeClefNNE()); // Get the student data from Apogee individuApogee = getDomainApoService().getIndividuFromApogee( ind.getCodeNNE(), ind.getCodeClefNNE().toUpperCase(), null, null, null, null); } else { // Get the student data from Base individuOPI = getDomainService().getIndividuCodEtu(getSessionController().getCodEtu()); // Get the student data from Apogee individuApogee = getDomainApoService().getIndividuFromApogee( null, null, getSessionController().getCodEtu(), null, null, null); // cas d'un individu déjà enregistré sans codEtu mais présent dans OPI // récup grace au num ine dans apogée if (individuOPI == null && individuApogee != null) { List<Individu> indResSearch = getDomainService().getIndividuSearch( individuApogee.getNomPatronymique(), individuApogee.getPrenom(), individuApogee.getDateNaissance(), individuApogee.getCodPayNaissance(), individuApogee.getCodDepPaysNaissance()); // si on a une liste de plus d'un individu, on informe le candidat // et on arrête sa candidature if (indResSearch.size() > 1) { // si on a plusieurs résultats, cas d'une homonymie en base, // dans ce cas, on informe le candidat de contacter la scol addErrorMessage(null, "ERROR.SEARCH_IND.HOMONYME"); return null; } else if (!indResSearch.isEmpty()) { individuOPI = indResSearch.get(0); } } } if (individuApogee == null && individuOPI == null) { addErrorMessage(null, "ERROR.FIELD.NNE_KO"); } else { initIndividuFromApogee(individuOPI, individuApogee); } } else if (pojoIndividu.getIsUsingSearch()) { // cas où l'utilisateur fait une recherche // on recherche l'individu if (ctrlSearch()) { Individu searchInd = toUpperCaseAnyAttributs(pojoIndividu.getIndividu()); List<Individu> indResSearch = getDomainService().getIndividuSearch( searchInd.getNomPatronymique(), searchInd.getPrenom(), searchInd.getDateNaissance(), searchInd.getCodPayNaissance(), searchInd.getCodDepPaysNaissance()); // on réinitialise le controller dans tous les cas reset(); if (indResSearch.isEmpty()) { // si le résultat est vide, on informe le candidat addErrorMessage(null, "ERROR.SEARCH_IND.EMPTY"); return null; } else if (indResSearch.size() > 1) { // si on a plusieurs résultats, cas d'une homonymie en base, // dans ce cas, on informe le candidat de contacter la scol addErrorMessage(null, "ERROR.SEARCH_IND.HOMONYME"); return null; } else { // on a récupéré le dossier puis on récupère ses infos depuis Apogée Individu individuOPI = indResSearch.get(0); SimpleDateFormat dateFormat = new SimpleDateFormat(Constantes.DATE_FORMAT); Individu individuApogee = getDomainApoService().getIndividuFromApogee( null, null, null, individuOPI.getNomPatronymique(), individuOPI.getPrenom(), dateFormat.format(individuOPI.getDateNaissance())); initIndividuFromApogee(individuOPI, individuApogee); } } else { return null; } } else { reset(); } return goAddAccount(); } /** * Callback to see account details for the current connected user. * * @return String */ public String goSeeAccount() { pojoIndividu = getCurrentInd(); actionEnum.setWhatAction(ActionEnum.READ_ACTION); //init individu initIndividuPojo(); checkEmail = pojoIndividu.getIndividu().getAdressMail(); initChampsSelectAnneeNaissance(); // init adress if (pojoIndividu.getIndividu().getAdresses().get(Constantes.ADR_FIX) != null) { adressController.init( pojoIndividu.getIndividu() .getAdresses().get(Constantes.ADR_FIX), false); } return NavigationRulesConst.SEE_ACCOUNT; } /** * Callback to see cursus details for the current connected user. * * @return String */ public String goSeeCursus() { pojoIndividu = getCurrentInd(); indBacController.initIndBac( new ArrayList<>( pojoIndividu.getIndividu().getIndBac()), false); return NavigationRulesConst.SEE_CURSUS; } /** * Callback to add a account. * * @return String */ public String goAddAccount() { // on mémorise le codeRI présent en session pojoIndividu.setRegimeInscription(getSessionController().getRegimeInsUser()); addTheCurrentRoad(NavigationRulesConst.ADD_ACCOUNT, getString("INDIVIDU.COORD"), getString("INDIVIDU.COORD")); initChampsSelectAnneeNaissance(); return NavigationRulesConst.ADD_ACCOUNT; } /** * Callback to add ind bac or a situation. * * @return String */ public String goAddIndBacOrSituation() { if (ctrlEnter() && ctrlUnicite()) { if (pojoIndividu.getRegimeInscription() instanceof FormationContinue) { situationController.getActionEnum().setWhatAction(ActionEnum.ADD_ACTION); situationController.setIndividuPojo(pojoIndividu); situationController.cancelSituation(); addTheCurrentRoad(NavigationRulesConst.ADD_SITUATION, getString("INDIVIDU.SITUATION"), getString("INDIVIDU.SITUATION")); return NavigationRulesConst.ADD_SITUATION; } addTheCurrentRoad(NavigationRulesConst.ADD_IND_BAC, getString("INDIVIDU.BAC"), getString("INDIVIDU.BAC")); return NavigationRulesConst.ADD_IND_BAC; } return null; } /** * Callback to accueilCandidat for a manager. * * @return String */ public String goSeeOneIndividu() { //put true boolean isManager attribute in indPojo //put the boolean canUpdateStudent atttribute in indPojo Set<Commission> rightOnCmi = new HashSet<Commission>(getDomainApoService().getListCommissionsByRight( getCurrentGest(), true)); pojoIndividu.setIndividu(getDomainService().getIndividu( pojoIndividu.getIndividu().getNumDossierOpi(), pojoIndividu.getIndividu().getDateNaissance())); getSessionController().initCurrentInd( pojoIndividu.getIndividu().getNumDossierOpi(), pojoIndividu.getIndividu().getDateNaissance(), true, getDomainService().hasGestionnaireRightsOnStudent( pojoIndividu.getIndividu().getVoeux(), rightOnCmi)); getCurrentInd(); if (getCurrentInd().getEtat() == EtatIncomplet) { //on informe l'individu qu'il doit completer sur dossier avant de deposer de voeux if (!getSessionController() .getCurrentInd() .getRegimeInscription() .getDisplayInfoFC()) addInfoMessage(null, "INFO.CANDIDAT.ETAT_INCOMPLET.1"); else addInfoMessage(null, "INFO.CANDIDAT.ETAT_INCOMPLET.1.FC"); addInfoMessage(null, "INFO.CANDIDAT.ETAT_INCOMPLET.2"); } // initialisation de la situation de l'individu si FC if (getCurrentInd().getRegimeInscription() instanceof FormationContinue) getSituationController().setIndSituation( getDomainService().getIndSituation(getCurrentInd().getIndividu())); formulairesController.reset(); return NavigationRulesConst.ACCUEIL_CANDIDAT; } /** * Go to generate numero Dossier. * * @return String */ public String goSaveDossier() { addTheCurrentRoad(NavigationRulesConst.SAVE_DOSSIER, getString("INDIVIDU.INIT.CANDI"), getString("INDIVIDU.INIT.CANDI")); if (etatDossier != null && etatDossier.equals(DOSSIER_CREATE)) { // Get a random alphanumeric string for NumDosOPI GenNumDosOPI genNumDosOPI = new GenNumDosOPI(NB_CHAR_CODE); String newNumDosOPI = genNumDosOPI.generate(); while (getDomainService().getIndividu(newNumDosOPI, null) != null) { newNumDosOPI = genNumDosOPI.generate(); } this.pojoIndividu.getIndividu().setNumDossierOpi(newNumDosOPI); } return NavigationRulesConst.SAVE_DOSSIER; } /** * Go numero Dossier. * * @return String */ public String goGetNumDossier() { return NavigationRulesConst.GET_NUM_DOSSIER; } /** * Callback to see all sutdents. * * @return String */ public String goSeeAllEtudiants() { return NavigationRulesConst.DISPLAY_STUDENT; } /** * Callback to add a student. * * @return String */ public String goAddEtudiant() { reset(); // on initialise le régime d'inscription du candidat selon // le régime du gestionnaire Gestionnaire gest = (Gestionnaire) getSessionController().getCurrentUser(); int codeRI = gest.getProfile().getCodeRI(); pojoIndividu.setRegimeInscription(getRegimeIns().get(codeRI)); initChampsSelectAnneeNaissance(); return NavigationRulesConst.ADD_STUDENT; } /** * Callback to list of a students (Gestionnaire). * * @return String */ public String goSendMailStudent() { pojoIndividu.getRegimeInscription().sendCreateDos(pojoIndividu.getIndividu()); addInfoMessage(null, "INFO.CANDIDAT.MAIL_OK"); return NavigationRulesConst.DISPLAY_STUDENT; } /* ******************* METHODS ********************** */ /** * add a student (by a gestionnaire manager). * * @return String */ public String addIndGestionnaire() { if (log.isDebugEnabled()) { log.debug("entering goAddIndGestionnaire() "); } if (ctrlEnterMinimum()) { // Get a random alphanumeric string for NumDosOPI GenNumDosOPI genNumDosOPI = new GenNumDosOPI(NB_CHAR_CODE); String newNumDosOPI = genNumDosOPI.generate(); while (getDomainService().getIndividu(newNumDosOPI, null) != null) { newNumDosOPI = genNumDosOPI.generate(); } this.pojoIndividu.getIndividu().setNumDossierOpi(newNumDosOPI); //pojoIndividu.setRegimeInscription(getRegimeIns() // .get(Utilitaires.getCodeRIIndividu(pojoIndividu.getIndividu()))); // put add action this.actionEnum.setWhatAction(this.actionEnum.getAddAction()); } return null; } /** * @param attributName * @param attribut * @return a List de user ldap si ils sont enregistrés dans LDAP */ public List<LdapUser> isInLdap(String attributName, String attribut) { //make filter String filter = "(" + attributName + "=" + attribut + ")"; List<LdapUser> ldapManagers = ldapUserService.getLdapUsersFromFilter(filter); return ldapManagers; } /** * Initialisation de l'individu à partir de l'individu Apogée. * Si on a un individu dans Opi * * @param individuOPI * @param individuApogee */ public void initIndividuFromApogee(final Individu individuOPI, final Individu individuApogee) { if (log.isDebugEnabled()) { log.debug("entering initIndividuFromApogee(individuOPI " + individuOPI + ", individuApogee " + individuApogee + " ) "); } if (individuOPI != null) { // si individuOPI != null, on est dans un cas de mise à jour de dossier etatDossier = DOSSIER_UPDATE; if (individuApogee != null && isRecupInfos) { String id = individuApogee.getCodeNNE(); id += individuApogee.getCodeClefNNE(); List<LdapUser> ldapManagers = isInLdap("supannCodeINE", id); // on met à jour individuOPI avec les données d'Apogée individuOPI.setCodeEtu(individuApogee.getCodeEtu()); individuOPI.setCodeNNE(individuApogee.getCodeNNE()); individuOPI.setCodeClefNNE(individuApogee.getCodeClefNNE()); if (StringUtils.isNotBlank(individuApogee.getAdressMail())) { individuOPI.setAdressMail(individuApogee.getAdressMail()); } //On ne remplie pas l'email institutionnel ([email protected]) si étudiant pas dans ldap car il ne sera plus valide et retournera une erreur au moment de l'envoi bug 7693 if (StringUtils.isNotBlank(individuApogee.getEmailAnnuaire()) && !ldapManagers.isEmpty()) { individuOPI.setEmailAnnuaire(individuApogee.getEmailAnnuaire()); } else { individuOPI.setEmailAnnuaire(null); } if (StringUtils.isNotBlank(individuApogee.getNumeroTelPortable())) { individuOPI.setNumeroTelPortable(individuApogee.getNumeroTelPortable()); } // mise à jour de l'adresse Adresse adresseOPI = individuOPI.getAdresses().get(Constantes.ADR_FIX); Adresse adresseApo = individuApogee.getAdresses().get(Constantes.ADR_FIX); adresseOPI.setAdr1(adresseApo.getAdr1()); adresseOPI.setAdr2(adresseApo.getAdr2()); adresseOPI.setAdr3(adresseApo.getAdr3()); adresseOPI.setCodPays(adresseApo.getCodPays()); adresseOPI.setCodCommune(adresseApo.getCodCommune()); adresseOPI.setLibComEtr(adresseApo.getLibComEtr()); adresseOPI.setCodBdi(adresseApo.getCodBdi()); } pojoIndividu.setIndividu(individuOPI); //TODO faire de mm si on n'est pas en maj de dossier ? + //Better use Option<IndividuPojo> here or even better a NullObject patten on IndividuPojo to avoid returning null all the time if (getSessionController().getCurrentInd() == null){ getSessionController().initCurrentInd(individuOPI.getNumDossierOpi(), individuApogee.getDateNaissance(), false, false); } } else { addInfoMessage(null, "INFO.CANDIDAT.FIND.ETU_R1"); if (isRecupInfos) { String id = individuApogee.getCodeNNE(); id += individuApogee.getCodeClefNNE(); List<LdapUser> ldapManagers = isInLdap("supannCodeINE", id); //On vide l'email institutionnel ([email protected]) si étudiant pas dans ldap car il ne sera plus valide et retournera une erreur au moment de l'envoi bug 7693 if (StringUtils.isNotBlank(individuApogee.getEmailAnnuaire()) && ldapManagers.isEmpty()) { individuApogee.setEmailAnnuaire(null); } pojoIndividu.setIndividu(individuApogee); } else { reset(); return; } } Individu individu = pojoIndividu.getIndividu(); adressController.getFixAdrPojo().setAdresse( individu.getAdresses().get(Constantes.ADR_FIX)); adressController.selectCpFix(); //afin de pouvoir enregistrer l'individu separement des adresses //pojoIndividu.getIndividu().setAdresses(null); //init POJO initIndividuPojo(); if (isRecupInfos && isRecupBac) { //bug 7428 Correction du bug empechant la recherche dossier côté candidat String codeClefNNE = individu.getCodeClefNNE(); if (codeClefNNE != null) codeClefNNE = codeClefNNE.toUpperCase(); // Get the IndBac data from Apogee List<IndBac> indBacs = getDomainApoService().getIndBacFromApogee( individu.getCodeNNE(), codeClefNNE, getSessionController().getCodEtu()); if (indBacs != null) { indBacController.initIndBac(indBacs, true); } else if (individuOPI != null) { List<IndBac> indBacsOPI = new ArrayList<IndBac>(); indBacsOPI.addAll(individuOPI.getIndBac()); indBacController.initIndBac(indBacsOPI, false); } } else if (individuOPI != null) { List<IndBac> indBacsOPI = new ArrayList<IndBac>(); indBacsOPI.addAll(individuOPI.getIndBac()); indBacController.initIndBac(indBacsOPI, false); } if (isRecupInfos && isRecupCursus) { if (individuOPI == null) { List<IndCursusScol> indCurScol = getDomainApoService() .getIndCursusScolFromApogee(individu); if (indCurScol != null) { cursusController.initCursusList(indCurScol); } } else { if (individuOPI.getCursusScol() != null) { cursusController.initCursusListFromApogee(individuOPI); } } } else if (individuOPI != null) { List<IndCursusScol> indCurScol = new ArrayList<IndCursusScol>(); indCurScol.addAll(individuOPI.getCursusScol()); cursusController.initCursusList(indCurScol); } } public void initIndRechPojo() { if (!FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) { final IndRechPojo indRechPojo = new IndRechPojo(); final SessionController sessionController = getSessionController(); final User user = sessionController.getCurrentUser(); if (user != null && user instanceof Gestionnaire) { Gestionnaire gest = (Gestionnaire) user; int codeRI = gest.getProfile().getCodeRI(); RegimeInscription regimeIns = sessionController.getRegimeIns().get(codeRI); indRechPojo.getListeRI().add(regimeIns); indRechPojo.setCanModifyRISearch(regimeIns.canModifyRISearch()); } individuPaginator.setIndRechPojo(indRechPojo); } } public void useVoeuFilter(Boolean bool) { individuPaginator.getIndRechPojo().setUseVoeuFilter(bool); } public void useTypeTrtFilter(Boolean bool) { individuPaginator.getIndRechPojo().setUseTypeTrtFilter(bool); } public void useTypeTrtVetFilter(Boolean bool) { individuPaginator.getIndRechPojo().setUseTypeTrtVetFilter(bool); } public void useGestCommsFilter(Boolean bool) { individuPaginator.getIndRechPojo().setUseGestCommsFilter(bool); } public void excludeWishProcessed(Boolean bool) { individuPaginator.getIndRechPojo().setExcludeWishProcessed(bool); } /** * Charge les attributes des individus Pojo. */ public void initIndividuPojo() { pojoIndividu.setDepartement(getDomainApoService().getDepartement( pojoIndividu.getIndividu().getCodDepPaysNaissance())); pojoIndividu.setPays(getDomainApoService().getPays( pojoIndividu.getIndividu().getCodPayNaissance())); pojoIndividu.setNationalite(getDomainApoService().getPays( pojoIndividu.getIndividu().getCodPayNationalite())); } /** * Charge les attribut des Pojo de pojoIndividu, d'adresse et de cursus et indBac. */ public void initAllPojo() { //init individu initIndividuPojo(); // init adress Adresse a = pojoIndividu.getIndividu() .getAdresses().get(Constantes.ADR_FIX); if (a != null) { adressController.init(a, false); } //init cursus Pro cursusController.initCursus(pojoIndividu.getIndividu().getCursus()); cursusController.initCursusList( new ArrayList<IndCursusScol>( pojoIndividu.getIndividu().getCursusScol())); //init indBac indBacController.initIndBac(new ArrayList<IndBac>(pojoIndividu.getIndividu().getIndBac()), false); } /** * Méthode utilisée pour initialiser la liste des années de naissance. */ private void initListeAnneeNaissance() { Campagne campEnCours; int anneeEnCours = DEFAULT_CURRENT_YEAR; if (pojoIndividu.getRegimeInscription() != null) { int codeRI = pojoIndividu.getRegimeInscription().getCode(); campEnCours = getParameterService().getCampagneEnServ(codeRI); anneeEnCours = Integer.parseInt(campEnCours.getCodAnu()); } listeAnneeNaissance.add(new SelectItem("", "")); for (int i = anneeEnCours - NB_YEAR_FIRST; i > anneeEnCours - (NB_YEAR_FIRST + NB_YEAR_LAST); i--) { listeAnneeNaissance.add(new SelectItem(String.valueOf(i), String .valueOf(i))); } } /** * Méthode permettant d'initialiser les champs Select utilisés pour la * saisie de la date de naissance d' un individu. */ private void initChampsSelectAnneeNaissance() { //On initialise la liste des années de naissance si elle est vide. if (listeAnneeNaissance.isEmpty()) { initListeAnneeNaissance(); } // Si l'individu a déja une date de naissance on initialise les champs // select avec celle-ci. if (getPojoIndividu().getIndividu().getDateNaissance() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(pojoIndividu .getIndividu().getDateNaissance()); jourNaissance = StringUtils.leftPad(String.valueOf(calendar .get(Calendar.DAY_OF_MONTH)), 2, '0'); moisNaissance = StringUtils.leftPad(String.valueOf(calendar .get(Calendar.MONTH) + 1), 2, '0'); anneeNaissance = String.valueOf(calendar.get(Calendar.YEAR)); } } /** * Changes the regime d'inscription du candidat. */ public void modifyRegimeInscription() { pojoIndividu = getCurrentInd(); int codeRI = pojoIndividu.getRegimeInscription().getCode(); // on retire la campagne en cours pour l'ancien régime Campagne camp = pojoIndividu.getCampagneEnServ(getDomainService()); pojoIndividu.getIndividu().getCampagnes().remove(camp); // on ajoute celle du nouveau régime pojoIndividu.getIndividu().getCampagnes().add( getParameterService().getCampagneEnServ(codeRI)); // on supprime les formulaires Map<VersionEtpOpi, IndFormulaire> indF = getParameterService().getIndFormulaires(pojoIndividu.getIndividu()); if (indF != null && !indF.isEmpty()) { for (Map.Entry<VersionEtpOpi, IndFormulaire> vOpi : indF.entrySet()) { getParameterService().deleteIndFormulaire(vOpi.getValue(), pojoIndividu.getIndividu().getNumDossierOpi(), pojoIndividu.getRegimeInscription().getShortLabel()); } } getDomainService().updateUser(pojoIndividu.getIndividu()); // on supprime les voeux qu'il avait fait sur l'ancien régime for (IndVoeu voeu : pojoIndividu.getIndividu().getVoeux()) { getDomainService().deleteIndVoeu(voeu); } } /** * Save the individu only. */ public void add() { if (log.isDebugEnabled()) { log.debug("entering add with individu = " + pojoIndividu.getIndividu()); } pojoIndividu.setIndividu( getDomainService().add(pojoIndividu.getIndividu(), pojoIndividu.getIndividu().getNumDossierOpi())); int codeRI = pojoIndividu.getRegimeInscription().getCode(); if (!StringUtils.isNotBlank(pojoIndividu.getIndividu().getState())) { //slt si l'etat est vide if (pojoIndividu.getRegimeInscription() .getControlField().control(pojoIndividu.getIndividu())) { pojoIndividu.getIndividu().setState(EtatComplet.getCodeLabel()); } else { pojoIndividu.getIndividu().setState(EtatIncomplet.getCodeLabel()); } } // affiliation à la campagne en cours pojoIndividu.getIndividu().getCampagnes().add( getParameterService().getCampagneEnServ(codeRI)); pojoIndividu.setIndividu(toUpperCaseAnyAttributs(pojoIndividu.getIndividu())); getDomainService().addUser(pojoIndividu.getIndividu()); log.info("save to database the individu with the num dossier = " + pojoIndividu.getIndividu().getNumDossierOpi()); } /** * Save the individu, his adress and cursus. * * @return to accueil */ public String addFullInd() { if (log.isDebugEnabled()) { log.debug("entering addFullInd with individu = " + pojoIndividu.getIndividu()); } // getDomainService().initOneProxyHib(pojoIndividu.getIndividu(), // pojoIndividu.getIndividu().getCampagnes(), Campagne.class); //l'etat est forcement complet //On teste si le dossier n'a pas déja été créé. if (getDomainService().getIndividu( pojoIndividu.getIndividu().getNumDossierOpi(), pojoIndividu.getIndividu().getDateNaissance()) != null) { addErrorMessage(null, "ERROR.ACTION.DOSSIER.EXIST", pojoIndividu .getIndividu().getNumDossierOpi()); return NavigationRulesConst.GET_NUM_DOSSIER; } pojoIndividu.getIndividu().setState(EtatComplet.getCodeLabel()); if (etatDossier != null && etatDossier.equals(DOSSIER_CREATE)) { add(); adressController.addAdrFix(pojoIndividu.getIndividu()); indBacController.add(pojoIndividu.getIndividu()); } else { getActionEnum().setWhatAction(ActionEnum.UPDATE_ACTION); adressController.getActionEnum().setWhatAction(ActionEnum.UPDATE_ACTION); update(); adressController.update(adressController.getFixAdrPojo()); if (isRecupInfos && isRecupCursus) { cursusController.deleteCursusR1(); } } cursusController.add(pojoIndividu.getIndividu()); situationController.add(pojoIndividu.getIndividu()); //Send email pojoIndividu.getRegimeInscription() .sendCreateDos(pojoIndividu.getIndividu()); getSessionController().initCurrentInd( pojoIndividu.getIndividu().getNumDossierOpi(), pojoIndividu.getIndividu().getDateNaissance(), false, false); addInfoMessage(null, "INFO.CANDIDAT.SAVE_OK"); addInfoMessage(null, "INFO.CANDIDAT.SEND_MAIL.NUM_DOS"); if (log.isDebugEnabled()) { log.debug("leaving add"); } return NavigationRulesConst.GET_NUM_DOSSIER; } /** * Initialisation de l'adresse. */ public void initAdresse() { if (pojoIndividu.getIndividu().getAdresses().get(Constantes.ADR_FIX) != null) { adressController.init( pojoIndividu.getIndividu() .getAdresses().get(Constantes.ADR_FIX), false); } } /** * Update the individu. */ public void update() { if (getActionEnum().getWhatAction().equals(ActionEnum.UPDATE_ACTION) && ctrlEnterMinimum()) { boolean haveToInit = false; if ((StringUtils.isNotBlank(pojoIndividu.getIndividu() .getCodDepPaysNaissance())) || StringUtils.isNotBlank(pojoIndividu.getIndividu() .getCodPayNaissance())) { haveToInit = true; } pojoIndividu.setIndividu(toUpperCaseAnyAttributs(pojoIndividu.getIndividu())); // on ajoute éventuellement la nouvelle campagne correspondant au régime d'inscription if (pojoIndividu.getRegimeInscription() != null) { int codeRI = pojoIndividu.getRegimeInscription().getCode(); Campagne campEnCours = getParameterService().getCampagneEnServ(codeRI); Campagne campDel = null; for (Campagne camp : pojoIndividu.getIndividu().getCampagnes()) { if (camp.getCodAnu().equals(campEnCours.getCodAnu())) { campDel = camp; } } if (campDel == null) { pojoIndividu.getIndividu().getCampagnes().add(campEnCours); } else { if (campDel.equals(campEnCours)) { // on retire la campagne en cours pour l'ancien régime pojoIndividu.getIndividu().getCampagnes().remove(campDel); // on ajoute celle du nouveau régime pojoIndividu.getIndividu().getCampagnes().add(campEnCours); } } } // on le met en service dans tous les cas pojoIndividu.getIndividu().setTemoinEnService(true); getDomainService().updateUser(pojoIndividu.getIndividu()); // on remet à jour l'authenticator dans le cas où la date de naissance est modifié // si modification de la date de naissance, perte du currentUser getSessionController().getAuthenticator().storeManager( getSessionController().getAuthenticator().getManager(), pojoIndividu.getIndividu().getNumDossierOpi(), pojoIndividu.getIndividu().getDateNaissance()); if (haveToInit) { initIndividuPojo(); } actionEnum.setWhatAction(ActionEnum.READ_ACTION); } // Update current Adress si champs ok if (adressController.getActionEnum() .getWhatAction().equals(ActionEnum.UPDATE_ACTION) && adressController.ctrlEnter(adressController .getFixAdrPojo().getAdresse(), true) && ctrlEnterMail()) { // maj de l'individu pour enregistrer son adresse mail getDomainService().updateUser(pojoIndividu.getIndividu()); if (pojoIndividu.getIndividu() .getAdresses().get(Constantes.ADR_FIX) == null) { adressController.addAdrFix(pojoIndividu.getIndividu()); } else { adressController.update(adressController.getFixAdrPojo()); } } } /** * Delete the individu. */ public void delete() { if (log.isDebugEnabled()) { log.debug("entering delete with individu = " + pojoIndividu.getIndividu()); } // on supprime les formulaires Map<VersionEtpOpi, IndFormulaire> indF = getParameterService().getIndFormulaires(pojoIndividu.getIndividu()); RegimeInscription regime = getRegimeIns().get( Utilitaires.getCodeRIIndividu(pojoIndividu.getIndividu(), getDomainService())); if (indF != null && !indF.isEmpty()) { for (Map.Entry<VersionEtpOpi, IndFormulaire> vOpi : indF.entrySet()) { getParameterService().deleteIndFormulaire(vOpi.getValue(), pojoIndividu.getIndividu().getNumDossierOpi(), regime.getShortLabel()); } } // on supprime les rendez vous s'il y en a //init hib proxy adresse getDomainService().initOneProxyHib(pojoIndividu.getIndividu(), pojoIndividu.getIndividu().getVoeux(), IndVoeu.class); for (IndVoeu indVoeu : pojoIndividu.getIndividu().getVoeux()) { IndividuDate individuDate = getDomainService().getIndividuDate(indVoeu); if (individuDate != null) { getDomainService().deleteIndividuDate(individuDate); } } // de même pour les voeux archivés for (IndVoeu indVoeu : pojoIndividu.getIndividu().getArchVoeux()) { IndividuDate individuDate = getDomainService().getIndividuDate(indVoeu); if (individuDate != null) { getDomainService().deleteIndividuDate(individuDate); } } // on supprime la situation de l'individu si FC IndSituation indSituation = getDomainService().getIndSituation(pojoIndividu.getIndividu()); if (indSituation != null) { getDomainService().deleteIndSituation(indSituation); } getDomainService().deleteUser(pojoIndividu.getIndividu()); reset(); addInfoMessage(null, "INFO.DELETE.SUCCESS"); if (log.isDebugEnabled()) { log.debug("leaving delete"); } } /** * Return the civility items. * * @return List<SelectItem> */ public List<SelectItem> getCiviliteItems() { List<SelectItem> s = new ArrayList<SelectItem>(); s.add(new SelectItem("", "")); s.add(new SelectItem(Constantes.COD_SEXE_FEMININ, getString(Constantes.I18N_CIV_MM))); s.add(new SelectItem(Constantes.COD_SEXE_MASCULIN, getString(Constantes.I18N_CIV_MR))); return s; } /** * The selected pays. */ public void selectPay() { String codePay = pojoIndividu.getIndividu().getCodPayNaissance(); //SI Pays != france on remet à null le département. if (!StringUtils.equals(codePay, adressController.getCodeFrance())) { pojoIndividu.getIndividu().setCodDepPaysNaissance(null); } //modification de la nationalite pojoIndividu.getIndividu().setCodPayNationalite(codePay); } /* ### ALL CONTROL ####*/ /** * Control the pojoIndividu attributes. * @deprecated for form validation should migrate to JSR-303 and JSF2.x mechanism * cf: * http://fr.slideshare.net/martyhall/jsf-2-tutorial-validating-user-input-form-field-validation * http://www.javacodegeeks.com/2012/12/easier-multi-field-validation-with-jsf-2-0.html * http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/} * * * @return Boolean */ private Boolean ctrlEnterMinimum() { Boolean ctrlOk = true; // Check individu's fields Individu ind = pojoIndividu.getIndividu(); if (ind.getSexe() == null || ind.getSexe().isEmpty()) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.CIVILITE")); ctrlOk = false; } if (!StringUtils.isNotBlank(ind.getNomPatronymique())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.NOM")); ctrlOk = false; } if (!StringUtils.isNotBlank(ind.getPrenom())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.PRENOM")); ctrlOk = false; } if (!(StringUtils.isNotBlank(jourNaissance) && StringUtils.isNotBlank(moisNaissance) && StringUtils .isNotBlank(anneeNaissance))) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.DATE_NAI_COURT")); ctrlOk = false; } else { SimpleDateFormat sdf = new SimpleDateFormat(Constantes.DATE_SHORT_FORMAT); sdf.setLenient(false); try { ind.setDateNaissance(sdf.parse(jourNaissance + moisNaissance + anneeNaissance)); } catch (ParseException e) { addErrorMessage(null, "ERROR.FIELD.DAT_NAISS.INEXIST"); ctrlOk = false; } } // check individu mail fields if (!ctrlEnterMail()) { ctrlOk = false; } return ctrlOk; } /** * Control the pojoIndividu attributes. * @deprecated for form validation should migrate to JSR-303 and JSF2.x mechanism * cf: * http://fr.slideshare.net/martyhall/jsf-2-tutorial-validating-user-input-form-field-validation * http://www.javacodegeeks.com/2012/12/easier-multi-field-validation-with-jsf-2-0.html * http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/} * * * * @return Boolean */ private Boolean ctrlEnterMail() { Boolean ctrlOk = true; // Check individu's fields Individu ind = pojoIndividu.getIndividu(); if (!StringUtils.isNotBlank(ind.getAdressMail())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("FIELD_LABEL.MAIL")); ctrlOk = false; } else if (!Utilitaires.isFormatEmailValid(ind.getAdressMail())) { addErrorMessage(null, "ERROR.FIELD.EMAIL"); ctrlOk = false; } else if (!getDomainService().emailIsUnique(ind)) { //adress mail doit etre unique addErrorMessage(null, "ERROR.FIELD.EMAIL.EXIST"); ctrlOk = false; } // controle sur la double saisie du mail if (!StringUtils.isNotBlank(checkEmail)) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("FIELD_LABEL.MAIL_CHECK")); ctrlOk = false; } else if (ind.getAdressMail().compareTo(checkEmail) != 0) { addErrorMessage(null, "ERROR.FIELD.EMAIL.BAD_CHECK"); ctrlOk = false; } return ctrlOk; } /** * @deprecated for form validation should migrate to JSR-303 and JSF2.x mechanism * cf: * http://fr.slideshare.net/martyhall/jsf-2-tutorial-validating-user-input-form-field-validation * http://www.javacodegeeks.com/2012/12/easier-multi-field-validation-with-jsf-2-0.html * http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/} * * * @return Boolean */ private Boolean ctrlEnter() { Boolean ctrlOk = ctrlEnterMinimum(); // Check individu's other fields Individu ind = pojoIndividu.getIndividu(); if (!StringUtils.isNotBlank(ind.getCodPayNaissance())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.PAY_NAI")); ctrlOk = false; } if (ind.getCodPayNaissance().equals(Constantes.CODEFRANCE) && !StringUtils.isNotBlank(ind.getCodDepPaysNaissance())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.DEP_NAI")); ctrlOk = false; } if (!StringUtils.isNotBlank(ind.getVilleNaissance())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.VIL_NAI")); ctrlOk = false; } if (!StringUtils.isNotBlank(ind.getCodPayNationalite())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.NAT")); ctrlOk = false; } // Check fix adress fields if (!adressController.ctrlEnter(adressController.getFixAdrPojo().getAdresse(), true)) { ctrlOk = false; } return ctrlOk; } /** * Control if the added user is unique. * @deprecated for form validation should migrate to JSR-303 and JSF2.x mechanism * cf: * http://fr.slideshare.net/martyhall/jsf-2-tutorial-validating-user-input-form-field-validation * http://www.javacodegeeks.com/2012/12/easier-multi-field-validation-with-jsf-2-0.html * http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/} * * * */ private Boolean ctrlUnicite() { Boolean ctrlOk = true; // Check individu's other fields if (etatDossier != null && etatDossier.equals(DOSSIER_CREATE)) { Individu individu = pojoIndividu.getIndividu(); if (!getDomainService().canInsertIndividu(individu)) { addErrorMessage(null, "ERROR.INDIVIDU_NOT_UNIQUE"); ctrlOk = false; } } return ctrlOk; } /** * Control the pojoIndividu attributes. * @deprecated for form validation should migrate to JSR-303 and JSF2.x mechanism * cf: * http://fr.slideshare.net/martyhall/jsf-2-tutorial-validating-user-input-form-field-validation * http://www.javacodegeeks.com/2012/12/easier-multi-field-validation-with-jsf-2-0.html * http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/} * * * @return Boolean */ private Boolean ctrlSearch() { Boolean ctrlOk = true; // Check individu's fields Individu ind = pojoIndividu.getIndividu(); if (StringUtils.isBlank(ind.getNomPatronymique())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.NOM")); ctrlOk = false; } if (StringUtils.isBlank(ind.getPrenom())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.PRENOM")); ctrlOk = false; } if (ind.getDateNaissance() == null) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.DATE_NAI")); ctrlOk = false; } if (StringUtils.isBlank(ind.getCodPayNaissance())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.PAY_NAI")); ctrlOk = false; }else { if (ind.getCodPayNaissance().equals(Constantes.CODEFRANCE) && StringUtils.isBlank(ind.getCodDepPaysNaissance())) { addErrorMessage(null, Constantes.I18N_EMPTY, getString("INDIVIDU.DEP_NAI")); ctrlOk = false; } } return ctrlOk; } /** * Upper any attributs in Individu. * * @return Individu */ private Individu toUpperCaseAnyAttributs(final Individu i) { //UPPER CASE any attributs if (StringUtils.isNotBlank(i.getNomPatronymique())) { i.setNomPatronymique(i.getNomPatronymique().toUpperCase()); } if (StringUtils.isNotBlank(i.getNomUsuel())) { i.setNomUsuel(i.getNomUsuel().toUpperCase()); } i.setPrenom(i.getPrenom().toUpperCase()); if (StringUtils.isNotBlank(i.getPrenom2())) { i.setPrenom2(i.getPrenom2().toUpperCase()); } if (StringUtils.isNotBlank(i.getVilleNaissance())) { i.setVilleNaissance( i.getVilleNaissance().toUpperCase()); } if (StringUtils.isNotBlank(i.getCodeClefNNE())) { i.setCodeClefNNE( i.getCodeClefNNE().toUpperCase()); } return i; } public IndividuPojo getPojoIndividu() { return pojoIndividu; } public void setPojoIndividu(final IndividuPojo pojoIndividu) { this.pojoIndividu = pojoIndividu; } public void setAdressController(final AdressController adressController) { this.adressController = adressController; } public void setCursusController(final CursusController cursusController) { this.cursusController = cursusController; } public void setIndBacController(final IndBacController indBacController) { this.indBacController = indBacController; } public ActionEnum getActionEnum() { return actionEnum; } public void setActionEnum(final ActionEnum actionEnum) { this.actionEnum = actionEnum; } public IndividuPaginator getIndividuPaginator() { return individuPaginator; } public void setIndividuPaginator(final IndividuPaginator individuPaginator) { this.individuPaginator = individuPaginator; } public AdressController getAdressController() { return adressController; } public CursusController getCursusController() { return cursusController; } public IndBacController getIndBacController() { return indBacController; } public SituationController getSituationController() { return situationController; } public void setSituationController(final SituationController situationController) { this.situationController = situationController; } public void setFormulairesController(final FormulairesController formulairesController) { this.formulairesController = formulairesController; } public String getEtatDossier() { return etatDossier; } public void setEtatDossier(final String etatDossier) { this.etatDossier = etatDossier; } public boolean getIsRecupInfos() { return isRecupInfos; } public void setIsRecupInfos(final boolean isRecupInfos) { this.isRecupInfos = isRecupInfos; } public boolean getIsRecupCursus() { return isRecupCursus; } public void setIsRecupCursus(final boolean isRecupCursus) { this.isRecupCursus = isRecupCursus; } public boolean getIsRecupBac() { return isRecupBac; } public void setIsRecupBac(final boolean isRecupBac) { this.isRecupBac = isRecupBac; } public String getJourNaissance() { return jourNaissance; } public void setJourNaissance(final String jourNaissance) { this.jourNaissance = jourNaissance; } public String getMoisNaissance() { return moisNaissance; } public void setMoisNaissance(final String moisNaissance) { this.moisNaissance = moisNaissance; } public String getAnneeNaissance() { return anneeNaissance; } public void setAnneeNaissance(final String anneeNaissance) { this.anneeNaissance = anneeNaissance; } public List<SelectItem> getListeAnneeNaissance() { return listeAnneeNaissance; } public String getCheckEmail() { return checkEmail; } public void setCheckEmail(final String checkEmail) { this.checkEmail = checkEmail; } public LdapUserService getLdapUserService() { return ldapUserService; } public Collection<TypeTraitement> getTypeTraitements() { return typeTraitements; } public void setTypeTraitements(Collection<TypeTraitement> typeTraitements) { this.typeTraitements = typeTraitements; } public void setLdapUserService(LdapUserService ldapUserService) { this.ldapUserService = ldapUserService; } public LazyDataModel<Individu> getIndLDM() { return indLDM; } public boolean isRenderTable() { return renderTable; } public void setRenderTable(boolean renderTable) { this.renderTable = renderTable; } public void doRenderTable() { renderTable = true; } }
true
true
public void initIndividuFromApogee(final Individu individuOPI, final Individu individuApogee) { if (log.isDebugEnabled()) { log.debug("entering initIndividuFromApogee(individuOPI " + individuOPI + ", individuApogee " + individuApogee + " ) "); } if (individuOPI != null) { // si individuOPI != null, on est dans un cas de mise à jour de dossier etatDossier = DOSSIER_UPDATE; if (individuApogee != null && isRecupInfos) { String id = individuApogee.getCodeNNE(); id += individuApogee.getCodeClefNNE(); List<LdapUser> ldapManagers = isInLdap("supannCodeINE", id); // on met à jour individuOPI avec les données d'Apogée individuOPI.setCodeEtu(individuApogee.getCodeEtu()); individuOPI.setCodeNNE(individuApogee.getCodeNNE()); individuOPI.setCodeClefNNE(individuApogee.getCodeClefNNE()); if (StringUtils.isNotBlank(individuApogee.getAdressMail())) { individuOPI.setAdressMail(individuApogee.getAdressMail()); } //On ne remplie pas l'email institutionnel ([email protected]) si étudiant pas dans ldap car il ne sera plus valide et retournera une erreur au moment de l'envoi bug 7693 if (StringUtils.isNotBlank(individuApogee.getEmailAnnuaire()) && !ldapManagers.isEmpty()) { individuOPI.setEmailAnnuaire(individuApogee.getEmailAnnuaire()); } else { individuOPI.setEmailAnnuaire(null); } if (StringUtils.isNotBlank(individuApogee.getNumeroTelPortable())) { individuOPI.setNumeroTelPortable(individuApogee.getNumeroTelPortable()); } // mise à jour de l'adresse Adresse adresseOPI = individuOPI.getAdresses().get(Constantes.ADR_FIX); Adresse adresseApo = individuApogee.getAdresses().get(Constantes.ADR_FIX); adresseOPI.setAdr1(adresseApo.getAdr1()); adresseOPI.setAdr2(adresseApo.getAdr2()); adresseOPI.setAdr3(adresseApo.getAdr3()); adresseOPI.setCodPays(adresseApo.getCodPays()); adresseOPI.setCodCommune(adresseApo.getCodCommune()); adresseOPI.setLibComEtr(adresseApo.getLibComEtr()); adresseOPI.setCodBdi(adresseApo.getCodBdi()); } pojoIndividu.setIndividu(individuOPI); //TODO faire de mm si on n'est pas en maj de dossier ? if (getSessionController().getCurrentInd() == null){ getSessionController().initCurrentInd(individuOPI.getNumDossierOpi(), individuApogee.getDateNaissance(), false, false); } } else { addInfoMessage(null, "INFO.CANDIDAT.FIND.ETU_R1"); if (isRecupInfos) { String id = individuApogee.getCodeNNE(); id += individuApogee.getCodeClefNNE(); List<LdapUser> ldapManagers = isInLdap("supannCodeINE", id); //On vide l'email institutionnel ([email protected]) si étudiant pas dans ldap car il ne sera plus valide et retournera une erreur au moment de l'envoi bug 7693 if (StringUtils.isNotBlank(individuApogee.getEmailAnnuaire()) && ldapManagers.isEmpty()) { individuApogee.setEmailAnnuaire(null); } pojoIndividu.setIndividu(individuApogee); } else { reset(); return; } } Individu individu = pojoIndividu.getIndividu(); adressController.getFixAdrPojo().setAdresse( individu.getAdresses().get(Constantes.ADR_FIX)); adressController.selectCpFix(); //afin de pouvoir enregistrer l'individu separement des adresses //pojoIndividu.getIndividu().setAdresses(null); //init POJO initIndividuPojo(); if (isRecupInfos && isRecupBac) { //bug 7428 Correction du bug empechant la recherche dossier côté candidat String codeClefNNE = individu.getCodeClefNNE(); if (codeClefNNE != null) codeClefNNE = codeClefNNE.toUpperCase(); // Get the IndBac data from Apogee List<IndBac> indBacs = getDomainApoService().getIndBacFromApogee( individu.getCodeNNE(), codeClefNNE, getSessionController().getCodEtu()); if (indBacs != null) { indBacController.initIndBac(indBacs, true); } else if (individuOPI != null) { List<IndBac> indBacsOPI = new ArrayList<IndBac>(); indBacsOPI.addAll(individuOPI.getIndBac()); indBacController.initIndBac(indBacsOPI, false); } } else if (individuOPI != null) { List<IndBac> indBacsOPI = new ArrayList<IndBac>(); indBacsOPI.addAll(individuOPI.getIndBac()); indBacController.initIndBac(indBacsOPI, false); } if (isRecupInfos && isRecupCursus) { if (individuOPI == null) { List<IndCursusScol> indCurScol = getDomainApoService() .getIndCursusScolFromApogee(individu); if (indCurScol != null) { cursusController.initCursusList(indCurScol); } } else { if (individuOPI.getCursusScol() != null) { cursusController.initCursusListFromApogee(individuOPI); } } } else if (individuOPI != null) { List<IndCursusScol> indCurScol = new ArrayList<IndCursusScol>(); indCurScol.addAll(individuOPI.getCursusScol()); cursusController.initCursusList(indCurScol); } }
public void initIndividuFromApogee(final Individu individuOPI, final Individu individuApogee) { if (log.isDebugEnabled()) { log.debug("entering initIndividuFromApogee(individuOPI " + individuOPI + ", individuApogee " + individuApogee + " ) "); } if (individuOPI != null) { // si individuOPI != null, on est dans un cas de mise à jour de dossier etatDossier = DOSSIER_UPDATE; if (individuApogee != null && isRecupInfos) { String id = individuApogee.getCodeNNE(); id += individuApogee.getCodeClefNNE(); List<LdapUser> ldapManagers = isInLdap("supannCodeINE", id); // on met à jour individuOPI avec les données d'Apogée individuOPI.setCodeEtu(individuApogee.getCodeEtu()); individuOPI.setCodeNNE(individuApogee.getCodeNNE()); individuOPI.setCodeClefNNE(individuApogee.getCodeClefNNE()); if (StringUtils.isNotBlank(individuApogee.getAdressMail())) { individuOPI.setAdressMail(individuApogee.getAdressMail()); } //On ne remplie pas l'email institutionnel ([email protected]) si étudiant pas dans ldap car il ne sera plus valide et retournera une erreur au moment de l'envoi bug 7693 if (StringUtils.isNotBlank(individuApogee.getEmailAnnuaire()) && !ldapManagers.isEmpty()) { individuOPI.setEmailAnnuaire(individuApogee.getEmailAnnuaire()); } else { individuOPI.setEmailAnnuaire(null); } if (StringUtils.isNotBlank(individuApogee.getNumeroTelPortable())) { individuOPI.setNumeroTelPortable(individuApogee.getNumeroTelPortable()); } // mise à jour de l'adresse Adresse adresseOPI = individuOPI.getAdresses().get(Constantes.ADR_FIX); Adresse adresseApo = individuApogee.getAdresses().get(Constantes.ADR_FIX); adresseOPI.setAdr1(adresseApo.getAdr1()); adresseOPI.setAdr2(adresseApo.getAdr2()); adresseOPI.setAdr3(adresseApo.getAdr3()); adresseOPI.setCodPays(adresseApo.getCodPays()); adresseOPI.setCodCommune(adresseApo.getCodCommune()); adresseOPI.setLibComEtr(adresseApo.getLibComEtr()); adresseOPI.setCodBdi(adresseApo.getCodBdi()); } pojoIndividu.setIndividu(individuOPI); //TODO faire de mm si on n'est pas en maj de dossier ? //Better use Option<IndividuPojo> here or even better a NullObject patten on IndividuPojo to avoid returning null all the time if (getSessionController().getCurrentInd() == null){ getSessionController().initCurrentInd(individuOPI.getNumDossierOpi(), individuApogee.getDateNaissance(), false, false); } } else { addInfoMessage(null, "INFO.CANDIDAT.FIND.ETU_R1"); if (isRecupInfos) { String id = individuApogee.getCodeNNE(); id += individuApogee.getCodeClefNNE(); List<LdapUser> ldapManagers = isInLdap("supannCodeINE", id); //On vide l'email institutionnel ([email protected]) si étudiant pas dans ldap car il ne sera plus valide et retournera une erreur au moment de l'envoi bug 7693 if (StringUtils.isNotBlank(individuApogee.getEmailAnnuaire()) && ldapManagers.isEmpty()) { individuApogee.setEmailAnnuaire(null); } pojoIndividu.setIndividu(individuApogee); } else { reset(); return; } } Individu individu = pojoIndividu.getIndividu(); adressController.getFixAdrPojo().setAdresse( individu.getAdresses().get(Constantes.ADR_FIX)); adressController.selectCpFix(); //afin de pouvoir enregistrer l'individu separement des adresses //pojoIndividu.getIndividu().setAdresses(null); //init POJO initIndividuPojo(); if (isRecupInfos && isRecupBac) { //bug 7428 Correction du bug empechant la recherche dossier côté candidat String codeClefNNE = individu.getCodeClefNNE(); if (codeClefNNE != null) codeClefNNE = codeClefNNE.toUpperCase(); // Get the IndBac data from Apogee List<IndBac> indBacs = getDomainApoService().getIndBacFromApogee( individu.getCodeNNE(), codeClefNNE, getSessionController().getCodEtu()); if (indBacs != null) { indBacController.initIndBac(indBacs, true); } else if (individuOPI != null) { List<IndBac> indBacsOPI = new ArrayList<IndBac>(); indBacsOPI.addAll(individuOPI.getIndBac()); indBacController.initIndBac(indBacsOPI, false); } } else if (individuOPI != null) { List<IndBac> indBacsOPI = new ArrayList<IndBac>(); indBacsOPI.addAll(individuOPI.getIndBac()); indBacController.initIndBac(indBacsOPI, false); } if (isRecupInfos && isRecupCursus) { if (individuOPI == null) { List<IndCursusScol> indCurScol = getDomainApoService() .getIndCursusScolFromApogee(individu); if (indCurScol != null) { cursusController.initCursusList(indCurScol); } } else { if (individuOPI.getCursusScol() != null) { cursusController.initCursusListFromApogee(individuOPI); } } } else if (individuOPI != null) { List<IndCursusScol> indCurScol = new ArrayList<IndCursusScol>(); indCurScol.addAll(individuOPI.getCursusScol()); cursusController.initCursusList(indCurScol); } }
diff --git a/cpk-pentaho/src/pt/webdetails/cpk/elements/impl/DashboardElement.java b/cpk-pentaho/src/pt/webdetails/cpk/elements/impl/DashboardElement.java index 9868180..c953f63 100644 --- a/cpk-pentaho/src/pt/webdetails/cpk/elements/impl/DashboardElement.java +++ b/cpk-pentaho/src/pt/webdetails/cpk/elements/impl/DashboardElement.java @@ -1,147 +1,147 @@ /*! * Copyright 2002 - 2013 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.cpk.elements.impl; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import pt.webdetails.cpf.Util; import pt.webdetails.cpk.CpkEngine; import pt.webdetails.cpk.InterPluginBroker; import pt.webdetails.cpk.elements.Element; import pt.webdetails.cpk.elements.IElement; import java.util.HashMap; import pt.webdetails.cpf.utils.IPluginUtils; public class DashboardElement extends Element { private IPluginUtils pluginUtils; public DashboardElement() { } @Override public boolean isRenderable() { return true; } @Override public void processRequest( Map<String, Map<String, Object>> bloatedMap ) { try { // element = (DashboardElement) element; callCDE( bloatedMap ); } catch ( Exception ex ) { logger.error( "Error while calling CDE: " + Util.getExceptionDescription( ex ) ); } } protected void callCDE( Map<String, Map<String, Object>> bloatedMap ) throws UnsupportedEncodingException, IOException { String path = CpkEngine.getInstance().getEnvironment().getPluginUtils().getPluginRelativeDirectory(this.getLocation(), true); ServletRequest wrapper = (HttpServletRequest) bloatedMap.get( "path" ).get( "httprequest" ); HttpServletResponse response = (HttpServletResponse) bloatedMap.get( "path" ).get( "httpresponse" ); OutputStream out = response.getOutputStream(); String root = wrapper.getScheme() + "://" + wrapper.getServerName() + ":" + wrapper.getServerPort(); Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> requestParams = bloatedMap.get( "request" ); path = FilenameUtils.separatorsToUnix( FilenameUtils.normalize( path ) ); params.put( "solution", "system" ); params.put( "path", path ); if ( requestParams.containsKey( "mode" ) && requestParams.get( "mode" ).equals( "preview" ) ) { - params.put( "file", this.getId() + "_tmp.cdfde" ); + params.put( "file", this.getName() + "_tmp.cdfde" ); } else { - params.put( "file", this.getId() + ".wcdf" ); + params.put( "file", this.getName() + ".wcdf" ); } params.put( "absolute", "true" ); params.put( "inferScheme", "false" ); params.put( "root", root ); //PluginUtils.copyParametersFromProvider( params, requestParams ); Iterator<String> it = requestParams.keySet().iterator(); while ( it.hasNext() ) { String name = it.next(); params.put( name, requestParams.get( name ) ); } if ( requestParams.containsKey( "mode" ) && requestParams.get( "mode" ).equals( "edit" ) ) { redirectToCdeEditor( response, params ); return; } InterPluginBroker.run( params, response, out ); } private void redirectToCdeEditor( HttpServletResponse response, Map<String, Object> params ) throws IOException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append( "../pentaho-cdf-dd/edit" ); if ( params.size() > 0 ) { urlBuilder.append( "?" ); } List<String> paramArray = new ArrayList<String>(); for ( String key : params.keySet() ) { Object value = params.get( key ); if ( value instanceof String ) { paramArray.add( key + "=" + URLEncoder.encode( (String) value, "utf-8" ) ); } } urlBuilder.append( StringUtils.join( paramArray, "&" ) ); if ( response == null ) { logger.error( "response not found" ); return; } try { response.sendRedirect( urlBuilder.toString() ); } catch ( IOException e ) { logger.error( "could not redirect", e ); } } /* @Override protected ElementInfo createElementInfo() { return new ElementInfo( "text/html" ); } */ }
false
true
protected void callCDE( Map<String, Map<String, Object>> bloatedMap ) throws UnsupportedEncodingException, IOException { String path = CpkEngine.getInstance().getEnvironment().getPluginUtils().getPluginRelativeDirectory(this.getLocation(), true); ServletRequest wrapper = (HttpServletRequest) bloatedMap.get( "path" ).get( "httprequest" ); HttpServletResponse response = (HttpServletResponse) bloatedMap.get( "path" ).get( "httpresponse" ); OutputStream out = response.getOutputStream(); String root = wrapper.getScheme() + "://" + wrapper.getServerName() + ":" + wrapper.getServerPort(); Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> requestParams = bloatedMap.get( "request" ); path = FilenameUtils.separatorsToUnix( FilenameUtils.normalize( path ) ); params.put( "solution", "system" ); params.put( "path", path ); if ( requestParams.containsKey( "mode" ) && requestParams.get( "mode" ).equals( "preview" ) ) { params.put( "file", this.getId() + "_tmp.cdfde" ); } else { params.put( "file", this.getId() + ".wcdf" ); } params.put( "absolute", "true" ); params.put( "inferScheme", "false" ); params.put( "root", root ); //PluginUtils.copyParametersFromProvider( params, requestParams ); Iterator<String> it = requestParams.keySet().iterator(); while ( it.hasNext() ) { String name = it.next(); params.put( name, requestParams.get( name ) ); } if ( requestParams.containsKey( "mode" ) && requestParams.get( "mode" ).equals( "edit" ) ) { redirectToCdeEditor( response, params ); return; } InterPluginBroker.run( params, response, out ); }
protected void callCDE( Map<String, Map<String, Object>> bloatedMap ) throws UnsupportedEncodingException, IOException { String path = CpkEngine.getInstance().getEnvironment().getPluginUtils().getPluginRelativeDirectory(this.getLocation(), true); ServletRequest wrapper = (HttpServletRequest) bloatedMap.get( "path" ).get( "httprequest" ); HttpServletResponse response = (HttpServletResponse) bloatedMap.get( "path" ).get( "httpresponse" ); OutputStream out = response.getOutputStream(); String root = wrapper.getScheme() + "://" + wrapper.getServerName() + ":" + wrapper.getServerPort(); Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> requestParams = bloatedMap.get( "request" ); path = FilenameUtils.separatorsToUnix( FilenameUtils.normalize( path ) ); params.put( "solution", "system" ); params.put( "path", path ); if ( requestParams.containsKey( "mode" ) && requestParams.get( "mode" ).equals( "preview" ) ) { params.put( "file", this.getName() + "_tmp.cdfde" ); } else { params.put( "file", this.getName() + ".wcdf" ); } params.put( "absolute", "true" ); params.put( "inferScheme", "false" ); params.put( "root", root ); //PluginUtils.copyParametersFromProvider( params, requestParams ); Iterator<String> it = requestParams.keySet().iterator(); while ( it.hasNext() ) { String name = it.next(); params.put( name, requestParams.get( name ) ); } if ( requestParams.containsKey( "mode" ) && requestParams.get( "mode" ).equals( "edit" ) ) { redirectToCdeEditor( response, params ); return; } InterPluginBroker.run( params, response, out ); }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/BasicMetrics.java b/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/BasicMetrics.java index ed5e54a0..ba48a626 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/BasicMetrics.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/BasicMetrics.java @@ -1,221 +1,221 @@ package org.jboss.as.console.client.shared.runtime.jpa; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.shared.help.HelpSystem; import org.jboss.as.console.client.shared.runtime.RuntimeBaseAddress; import org.jboss.as.console.client.shared.runtime.charts.Column; import org.jboss.as.console.client.shared.runtime.charts.NumberColumn; import org.jboss.as.console.client.shared.runtime.charts.TextColumn; import org.jboss.as.console.client.shared.runtime.jpa.model.JPADeployment; import org.jboss.as.console.client.shared.runtime.plain.PlainColumnView; import org.jboss.as.console.client.shared.viewframework.builder.OneToOneLayout; import org.jboss.ballroom.client.widgets.tools.ToolButton; import org.jboss.ballroom.client.widgets.tools.ToolStrip; import org.jboss.dmr.client.ModelDescriptionConstants; import org.jboss.dmr.client.ModelNode; /** * @author Heiko Braun * @date 1/19/12 */ public class BasicMetrics { private JPAMetricPresenter presenter; private JPADeployment currentUnit; private HTML title; private PlainColumnView queryCacheSampler; private PlainColumnView txSampler; private PlainColumnView queryExecSampler; private PlainColumnView secondLevelSampler; private PlainColumnView connectionSampler; private String[] tokens; private HTML slowQuery; public BasicMetrics(JPAMetricPresenter presenter) { this.presenter = presenter; } Widget asWidget() { final ToolStrip toolStrip = new ToolStrip(); toolStrip.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_refresh(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.loadMetrics(tokens); } })); // ------ NumberColumn txCount = new NumberColumn("completed-transaction-count","Completed"); Column[] cols = new Column[] { txCount.setBaseline(true), new NumberColumn("successful-transaction-count","Successful").setComparisonColumn(txCount) }; final HelpSystem.AddressCallback addressCallback = new HelpSystem.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = new ModelNode(); address.get(ModelDescriptionConstants.ADDRESS).set(RuntimeBaseAddress.get()); address.get(ModelDescriptionConstants.ADDRESS).add("deployment", "*"); address.get(ModelDescriptionConstants.ADDRESS).add("subsystem", "jpa"); address.get(ModelDescriptionConstants.ADDRESS).add("hibernate-persistence-unit", "*"); return address; } }; txSampler = new PlainColumnView("Transactions", addressCallback) .setColumns(cols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn queryCount = new NumberColumn("query-cache-put-count","Query Put Count"); Column[] queryCols = new Column[] { queryCount.setBaseline(true), new NumberColumn("query-cache-hit-count","Query Hit Count").setComparisonColumn(queryCount), new NumberColumn("query-cache-miss-count","Query Miss Count").setComparisonColumn(queryCount) }; queryCacheSampler = new PlainColumnView("Query Cache", addressCallback) .setColumns(queryCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn queryExecCount = new NumberColumn("query-execution-count","Query Execution Count"); Column[] queryExecCols = new Column[] { queryExecCount, new NumberColumn("query-execution-max-time","Exec Max Time") }; queryExecSampler = new PlainColumnView("Query Execution", addressCallback) .setColumns(queryExecCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn secondLevelCount = new NumberColumn("second-level-cache-put-count","Put Count"); Column[] secondLevelCols = new Column[] { secondLevelCount.setBaseline(true), new NumberColumn("second-level-cache-hit-count","Hit Count").setComparisonColumn(secondLevelCount), new TextColumn("second-level-cache-miss-count","Miss Count").setComparisonColumn(secondLevelCount) }; secondLevelSampler = new PlainColumnView("Second Level Cache", addressCallback) .setColumns(secondLevelCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn sessionOpenCount = new NumberColumn("session-open-count", "Session Open Count"); Column[] connectionCols = new Column[] { sessionOpenCount.setBaseline(true), - new TextColumn("session-close-count","Sesison Close Count").setComparisonColumn(sessionOpenCount), + new TextColumn("session-close-count","Session Close Count").setComparisonColumn(sessionOpenCount), new NumberColumn("connect-count","Connection Count") }; connectionSampler = new PlainColumnView("Connections", addressCallback) .setColumns(connectionCols) .setWidth(100, Style.Unit.PCT); // ---- title = new HTML(); title.setStyleName("content-header-label"); // ------- VerticalPanel connectionPanel = new VerticalPanel(); connectionPanel.setStyleName("fill-layout-width"); connectionPanel.add(connectionSampler.asWidget()); VerticalPanel txPanel = new VerticalPanel(); txPanel.setStyleName("fill-layout-width"); txPanel.add(txSampler.asWidget()); VerticalPanel queryPanel = new VerticalPanel(); queryPanel.setStyleName("fill-layout-width"); queryPanel.add(queryCacheSampler.asWidget()); queryPanel.add(queryExecSampler.asWidget()); slowQuery = new HTML(); slowQuery.setStyleName("help-panel-open"); slowQuery.getElement().setAttribute("style", "padding:5px"); queryPanel.add(slowQuery); VerticalPanel secondPanel = new VerticalPanel(); secondPanel.setStyleName("fill-layout-width"); secondPanel.add(secondLevelSampler.asWidget()); OneToOneLayout layout = new OneToOneLayout() .setPlain(true) .setTopLevelTools(toolStrip.asWidget()) .setHeadlineWidget(title) .setDescription(Console.CONSTANTS.subsys_jpa_basicMetric_desc()) .addDetail("Connections", connectionPanel) .addDetail("Transactions", txPanel) .addDetail("Queries", queryPanel) .addDetail("Second Level Cache", secondPanel); return layout.build(); } public void setUnit(JPADeployment unit) { this.currentUnit = unit; } public void setContextName(String[] tokens) { this.tokens = tokens; title.setText("Persistence Unit Metrics: "+tokens[0]+"#"+tokens[1]); } public void updateMetric(UnitMetric unitMetric) { txSampler.addSample(unitMetric.getTxMetric()); queryCacheSampler.addSample(unitMetric.getQueryMetric()); queryExecSampler.addSample(unitMetric.getQueryExecMetric()); slowQuery.setHTML("<b>Max Time Query</b>: "+ unitMetric.getQueryExecMetric().get(2)); secondLevelSampler.addSample(unitMetric.getSecondLevelCacheMetric()); connectionSampler.addSample(unitMetric.getConnectionMetric()); } public void clearValues() { txSampler.clearSamples(); queryCacheSampler.clearSamples(); queryExecSampler.clearSamples(); slowQuery.setHTML("<b>Max Time Query</b>: "); secondLevelSampler.clearSamples(); connectionSampler.clearSamples(); } }
true
true
Widget asWidget() { final ToolStrip toolStrip = new ToolStrip(); toolStrip.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_refresh(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.loadMetrics(tokens); } })); // ------ NumberColumn txCount = new NumberColumn("completed-transaction-count","Completed"); Column[] cols = new Column[] { txCount.setBaseline(true), new NumberColumn("successful-transaction-count","Successful").setComparisonColumn(txCount) }; final HelpSystem.AddressCallback addressCallback = new HelpSystem.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = new ModelNode(); address.get(ModelDescriptionConstants.ADDRESS).set(RuntimeBaseAddress.get()); address.get(ModelDescriptionConstants.ADDRESS).add("deployment", "*"); address.get(ModelDescriptionConstants.ADDRESS).add("subsystem", "jpa"); address.get(ModelDescriptionConstants.ADDRESS).add("hibernate-persistence-unit", "*"); return address; } }; txSampler = new PlainColumnView("Transactions", addressCallback) .setColumns(cols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn queryCount = new NumberColumn("query-cache-put-count","Query Put Count"); Column[] queryCols = new Column[] { queryCount.setBaseline(true), new NumberColumn("query-cache-hit-count","Query Hit Count").setComparisonColumn(queryCount), new NumberColumn("query-cache-miss-count","Query Miss Count").setComparisonColumn(queryCount) }; queryCacheSampler = new PlainColumnView("Query Cache", addressCallback) .setColumns(queryCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn queryExecCount = new NumberColumn("query-execution-count","Query Execution Count"); Column[] queryExecCols = new Column[] { queryExecCount, new NumberColumn("query-execution-max-time","Exec Max Time") }; queryExecSampler = new PlainColumnView("Query Execution", addressCallback) .setColumns(queryExecCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn secondLevelCount = new NumberColumn("second-level-cache-put-count","Put Count"); Column[] secondLevelCols = new Column[] { secondLevelCount.setBaseline(true), new NumberColumn("second-level-cache-hit-count","Hit Count").setComparisonColumn(secondLevelCount), new TextColumn("second-level-cache-miss-count","Miss Count").setComparisonColumn(secondLevelCount) }; secondLevelSampler = new PlainColumnView("Second Level Cache", addressCallback) .setColumns(secondLevelCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn sessionOpenCount = new NumberColumn("session-open-count", "Session Open Count"); Column[] connectionCols = new Column[] { sessionOpenCount.setBaseline(true), new TextColumn("session-close-count","Sesison Close Count").setComparisonColumn(sessionOpenCount), new NumberColumn("connect-count","Connection Count") }; connectionSampler = new PlainColumnView("Connections", addressCallback) .setColumns(connectionCols) .setWidth(100, Style.Unit.PCT); // ---- title = new HTML(); title.setStyleName("content-header-label"); // ------- VerticalPanel connectionPanel = new VerticalPanel(); connectionPanel.setStyleName("fill-layout-width"); connectionPanel.add(connectionSampler.asWidget()); VerticalPanel txPanel = new VerticalPanel(); txPanel.setStyleName("fill-layout-width"); txPanel.add(txSampler.asWidget()); VerticalPanel queryPanel = new VerticalPanel(); queryPanel.setStyleName("fill-layout-width"); queryPanel.add(queryCacheSampler.asWidget()); queryPanel.add(queryExecSampler.asWidget()); slowQuery = new HTML(); slowQuery.setStyleName("help-panel-open"); slowQuery.getElement().setAttribute("style", "padding:5px"); queryPanel.add(slowQuery); VerticalPanel secondPanel = new VerticalPanel(); secondPanel.setStyleName("fill-layout-width"); secondPanel.add(secondLevelSampler.asWidget()); OneToOneLayout layout = new OneToOneLayout() .setPlain(true) .setTopLevelTools(toolStrip.asWidget()) .setHeadlineWidget(title) .setDescription(Console.CONSTANTS.subsys_jpa_basicMetric_desc()) .addDetail("Connections", connectionPanel) .addDetail("Transactions", txPanel) .addDetail("Queries", queryPanel) .addDetail("Second Level Cache", secondPanel); return layout.build(); }
Widget asWidget() { final ToolStrip toolStrip = new ToolStrip(); toolStrip.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_refresh(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.loadMetrics(tokens); } })); // ------ NumberColumn txCount = new NumberColumn("completed-transaction-count","Completed"); Column[] cols = new Column[] { txCount.setBaseline(true), new NumberColumn("successful-transaction-count","Successful").setComparisonColumn(txCount) }; final HelpSystem.AddressCallback addressCallback = new HelpSystem.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = new ModelNode(); address.get(ModelDescriptionConstants.ADDRESS).set(RuntimeBaseAddress.get()); address.get(ModelDescriptionConstants.ADDRESS).add("deployment", "*"); address.get(ModelDescriptionConstants.ADDRESS).add("subsystem", "jpa"); address.get(ModelDescriptionConstants.ADDRESS).add("hibernate-persistence-unit", "*"); return address; } }; txSampler = new PlainColumnView("Transactions", addressCallback) .setColumns(cols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn queryCount = new NumberColumn("query-cache-put-count","Query Put Count"); Column[] queryCols = new Column[] { queryCount.setBaseline(true), new NumberColumn("query-cache-hit-count","Query Hit Count").setComparisonColumn(queryCount), new NumberColumn("query-cache-miss-count","Query Miss Count").setComparisonColumn(queryCount) }; queryCacheSampler = new PlainColumnView("Query Cache", addressCallback) .setColumns(queryCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn queryExecCount = new NumberColumn("query-execution-count","Query Execution Count"); Column[] queryExecCols = new Column[] { queryExecCount, new NumberColumn("query-execution-max-time","Exec Max Time") }; queryExecSampler = new PlainColumnView("Query Execution", addressCallback) .setColumns(queryExecCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn secondLevelCount = new NumberColumn("second-level-cache-put-count","Put Count"); Column[] secondLevelCols = new Column[] { secondLevelCount.setBaseline(true), new NumberColumn("second-level-cache-hit-count","Hit Count").setComparisonColumn(secondLevelCount), new TextColumn("second-level-cache-miss-count","Miss Count").setComparisonColumn(secondLevelCount) }; secondLevelSampler = new PlainColumnView("Second Level Cache", addressCallback) .setColumns(secondLevelCols) .setWidth(100, Style.Unit.PCT); // ------ NumberColumn sessionOpenCount = new NumberColumn("session-open-count", "Session Open Count"); Column[] connectionCols = new Column[] { sessionOpenCount.setBaseline(true), new TextColumn("session-close-count","Session Close Count").setComparisonColumn(sessionOpenCount), new NumberColumn("connect-count","Connection Count") }; connectionSampler = new PlainColumnView("Connections", addressCallback) .setColumns(connectionCols) .setWidth(100, Style.Unit.PCT); // ---- title = new HTML(); title.setStyleName("content-header-label"); // ------- VerticalPanel connectionPanel = new VerticalPanel(); connectionPanel.setStyleName("fill-layout-width"); connectionPanel.add(connectionSampler.asWidget()); VerticalPanel txPanel = new VerticalPanel(); txPanel.setStyleName("fill-layout-width"); txPanel.add(txSampler.asWidget()); VerticalPanel queryPanel = new VerticalPanel(); queryPanel.setStyleName("fill-layout-width"); queryPanel.add(queryCacheSampler.asWidget()); queryPanel.add(queryExecSampler.asWidget()); slowQuery = new HTML(); slowQuery.setStyleName("help-panel-open"); slowQuery.getElement().setAttribute("style", "padding:5px"); queryPanel.add(slowQuery); VerticalPanel secondPanel = new VerticalPanel(); secondPanel.setStyleName("fill-layout-width"); secondPanel.add(secondLevelSampler.asWidget()); OneToOneLayout layout = new OneToOneLayout() .setPlain(true) .setTopLevelTools(toolStrip.asWidget()) .setHeadlineWidget(title) .setDescription(Console.CONSTANTS.subsys_jpa_basicMetric_desc()) .addDetail("Connections", connectionPanel) .addDetail("Transactions", txPanel) .addDetail("Queries", queryPanel) .addDetail("Second Level Cache", secondPanel); return layout.build(); }
diff --git a/src/haven/GLFrameBuffer.java b/src/haven/GLFrameBuffer.java index c0dcbefa..6ba006ae 100644 --- a/src/haven/GLFrameBuffer.java +++ b/src/haven/GLFrameBuffer.java @@ -1,176 +1,177 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import javax.media.opengl.*; public class GLFrameBuffer extends GLState { public static final Slot<GLFrameBuffer> slot = new Slot<GLFrameBuffer>(Slot.Type.SYS, GLFrameBuffer.class, HavenPanel.global); private final TexGL[] color; private final TexGL depth; private final RenderBuffer altdepth; private FBO fbo; public static class FBO extends GLObject { public final int id; public FBO(GL gl) { super(gl); int[] buf = new int[1]; gl.glGenFramebuffersEXT(1, buf, 0); this.id = buf[0]; GOut.checkerr(gl); } protected void delete() { int[] buf = {id}; gl.glDeleteFramebuffersEXT(1, buf, 0); GOut.checkerr(gl); } } public static class RenderBuffer { public final Coord sz; public final int fmt; private RBO rbo; public RenderBuffer(Coord sz, int fmt) { this.sz = sz; this.fmt = fmt; } public int glid(GL gl) { if((rbo != null) && (rbo.gl != gl)) dispose(); if(rbo == null) { rbo = new RBO(gl); gl.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, rbo.id); gl.glRenderbufferStorageEXT(GL.GL_RENDERBUFFER_EXT, fmt, sz.x, sz.y); } return(rbo.id); } public void dispose() { synchronized(this) { if(rbo != null) { rbo.dispose(); rbo = null; } } } public static class RBO extends GLObject { public final int id; public RBO(GL gl) { super(gl); int[] buf = new int[1]; gl.glGenRenderbuffersEXT(1, buf, 0); this.id = buf[0]; GOut.checkerr(gl); } protected void delete() { int[] buf = {id}; gl.glDeleteRenderbuffersEXT(1, buf, 0); GOut.checkerr(gl); } } } public GLFrameBuffer(TexGL color, TexGL depth) { if(color == null) this.color = new TexGL[0]; else this.color = new TexGL[] {color}; if((this.depth = depth) == null) { if(this.color.length == 0) throw(new RuntimeException("Cannot create a framebuffer with neither color nor depth")); this.altdepth = new RenderBuffer(this.color[0].tdim, GL.GL_DEPTH_COMPONENT); } else { this.altdepth = null; } } public Coord sz() { /* This is not perfect, but there's no current (or probably * sane) situation where it would fail. */ if(depth != null) return(depth.sz()); else return(altdepth.sz); } public void apply(GOut g) { GL gl = g.gl; synchronized(this) { if((fbo != null) && (fbo.gl != gl)) dispose(); if(fbo == null) { fbo = new FBO(gl); gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id); for(int i = 0; i < color.length; i++) gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT + i, GL.GL_TEXTURE_2D, color[i].glid(g), 0); if(depth != null) gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_TEXTURE_2D, depth.glid(g), 0); else gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, altdepth.glid(gl)); + GOut.checkerr(gl); int st = gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT); if(st != GL.GL_FRAMEBUFFER_COMPLETE_EXT) throw(new RuntimeException("FBO failed completeness test: " + st)); } else { gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id); } if(color.length == 0) { gl.glDrawBuffer(GL.GL_NONE); gl.glReadBuffer(GL.GL_NONE); } } } public void unapply(GOut g) { GL gl = g.gl; gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0); if(color.length == 0) { gl.glDrawBuffer(GL.GL_BACK); gl.glReadBuffer(GL.GL_BACK); } } public void prep(Buffer buf) { buf.put(slot, this); } public void dispose() { synchronized(this) { if(fbo != null) { fbo.dispose(); fbo = null; } } } }
true
true
public void apply(GOut g) { GL gl = g.gl; synchronized(this) { if((fbo != null) && (fbo.gl != gl)) dispose(); if(fbo == null) { fbo = new FBO(gl); gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id); for(int i = 0; i < color.length; i++) gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT + i, GL.GL_TEXTURE_2D, color[i].glid(g), 0); if(depth != null) gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_TEXTURE_2D, depth.glid(g), 0); else gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, altdepth.glid(gl)); int st = gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT); if(st != GL.GL_FRAMEBUFFER_COMPLETE_EXT) throw(new RuntimeException("FBO failed completeness test: " + st)); } else { gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id); } if(color.length == 0) { gl.glDrawBuffer(GL.GL_NONE); gl.glReadBuffer(GL.GL_NONE); } } }
public void apply(GOut g) { GL gl = g.gl; synchronized(this) { if((fbo != null) && (fbo.gl != gl)) dispose(); if(fbo == null) { fbo = new FBO(gl); gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id); for(int i = 0; i < color.length; i++) gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT + i, GL.GL_TEXTURE_2D, color[i].glid(g), 0); if(depth != null) gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_TEXTURE_2D, depth.glid(g), 0); else gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, altdepth.glid(gl)); GOut.checkerr(gl); int st = gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT); if(st != GL.GL_FRAMEBUFFER_COMPLETE_EXT) throw(new RuntimeException("FBO failed completeness test: " + st)); } else { gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id); } if(color.length == 0) { gl.glDrawBuffer(GL.GL_NONE); gl.glReadBuffer(GL.GL_NONE); } } }
diff --git a/src/main/java/suite/algo/LempelZivWelch.java b/src/main/java/suite/algo/LempelZivWelch.java index 9ada1cca2..8682601fb 100644 --- a/src/main/java/suite/algo/LempelZivWelch.java +++ b/src/main/java/suite/algo/LempelZivWelch.java @@ -1,86 +1,86 @@ package suite.algo; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import suite.util.FunUtil.Sink; import suite.util.FunUtil.Source; import suite.util.Util; public class LempelZivWelch<Unit> { private List<Unit> units; private class Trie { private Integer index; private Map<Unit, Trie> branches = new HashMap<>(); private Trie(Integer index) { this.index = index; } } public LempelZivWelch(List<Unit> units) { this.units = units; } public void encode(Source<Unit> source, Sink<Integer> sink) { Trie root = new Trie(null); int index = 0; for (Unit unit : units) root.branches.put(unit, new Trie(index++)); Trie trie = root; Unit unit; while ((unit = source.source()) != null) { if (!trie.branches.containsKey(unit)) { sink.sink(trie.index); trie.branches.put(unit, new Trie(index++)); trie = root; } trie = trie.branches.get(unit); } if (trie != root) sink.sink(trie.index); } public void decode(Source<Integer> source, Sink<Unit> sink) { List<List<Unit>> dict = new ArrayList<>(); for (Unit unit : units) dict.add(Arrays.asList(unit)); Integer index; if ((index = source.source()) != null) { List<Unit> word; for (Unit unit : word = dict.get(index)) sink.sink(unit); while ((index = source.source()) != null) { List<Unit> w0 = word; List<Unit> newWord; if (index < dict.size()) - newWord = Util.add(w0, word = dict.get(index)); + newWord = Util.add(w0, Util.left(word = dict.get(index), 1)); else newWord = word = Util.add(w0, Util.left(w0, 1)); if (!w0.isEmpty()) dict.add(newWord); for (Unit unit : word) sink.sink(unit); } } } }
true
true
public void decode(Source<Integer> source, Sink<Unit> sink) { List<List<Unit>> dict = new ArrayList<>(); for (Unit unit : units) dict.add(Arrays.asList(unit)); Integer index; if ((index = source.source()) != null) { List<Unit> word; for (Unit unit : word = dict.get(index)) sink.sink(unit); while ((index = source.source()) != null) { List<Unit> w0 = word; List<Unit> newWord; if (index < dict.size()) newWord = Util.add(w0, word = dict.get(index)); else newWord = word = Util.add(w0, Util.left(w0, 1)); if (!w0.isEmpty()) dict.add(newWord); for (Unit unit : word) sink.sink(unit); } } }
public void decode(Source<Integer> source, Sink<Unit> sink) { List<List<Unit>> dict = new ArrayList<>(); for (Unit unit : units) dict.add(Arrays.asList(unit)); Integer index; if ((index = source.source()) != null) { List<Unit> word; for (Unit unit : word = dict.get(index)) sink.sink(unit); while ((index = source.source()) != null) { List<Unit> w0 = word; List<Unit> newWord; if (index < dict.size()) newWord = Util.add(w0, Util.left(word = dict.get(index), 1)); else newWord = word = Util.add(w0, Util.left(w0, 1)); if (!w0.isEmpty()) dict.add(newWord); for (Unit unit : word) sink.sink(unit); } } }
diff --git a/drools-wb-jcr2vfs-migration/drools-wb-jcr2vfs-migration-core/src/main/java/org/drools/workbench/jcr2vfsmigration/config/MigrationConfig.java b/drools-wb-jcr2vfs-migration/drools-wb-jcr2vfs-migration-core/src/main/java/org/drools/workbench/jcr2vfsmigration/config/MigrationConfig.java index 8270fabf7..2ac433585 100644 --- a/drools-wb-jcr2vfs-migration/drools-wb-jcr2vfs-migration-core/src/main/java/org/drools/workbench/jcr2vfsmigration/config/MigrationConfig.java +++ b/drools-wb-jcr2vfs-migration/drools-wb-jcr2vfs-migration-core/src/main/java/org/drools/workbench/jcr2vfsmigration/config/MigrationConfig.java @@ -1,126 +1,126 @@ /* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.workbench.jcr2vfsmigration.config; import java.io.File; import java.io.IOException; import java.util.Arrays; import javax.enterprise.context.ApplicationScoped; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ApplicationScoped public class MigrationConfig { protected static final Logger logger = LoggerFactory.getLogger(MigrationConfig.class); public static String formatstr = "runMigration [options...]"; private File inputJcrRepository; private File outputVfsRepository; private boolean forceOverwriteOutputVfsRepository; public File getInputJcrRepository() { return inputJcrRepository; } public File getOutputVfsRepository() { return outputVfsRepository; } // ************************************************************************ // Configuration methods // ************************************************************************ public boolean parseArgs(String[] args) { Options options = new Options(); options.addOption("h", "help", false, "help for the command."); options.addOption("i", "inputJcrRepository", true, "The Guvnor 5 JCR repository"); options.addOption("o", "outputVfsRepository", true, "The Guvnor 6 VFS repository"); options.addOption("f", "forceOverwriteOutputVfsRepository", false, "Force overwriting the Guvnor 6 VFS repository"); CommandLine commandLine; HelpFormatter formatter = new HelpFormatter(); try { commandLine = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp( formatstr, options ); return false; } if (commandLine.hasOption("h")) { formatter.printHelp(formatstr, options); return false; } return (parseArgInputJcrRepository(commandLine, formatter, options) && parseArgOutputVfsRepository(commandLine, formatter, options)); } private boolean parseArgInputJcrRepository(CommandLine commandLine, HelpFormatter formatter, Options options) { inputJcrRepository = new File(commandLine.getOptionValue("i", "inputJcr")); if (!inputJcrRepository.exists()) { System.out.println("The inputJcrRepository (" + inputJcrRepository.getAbsolutePath() + ") does not exist."); return false; } try { inputJcrRepository = inputJcrRepository.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("The inputJcrRepository (" + inputJcrRepository + ") has issues.", e); } return true; } private boolean parseArgOutputVfsRepository(CommandLine commandLine, HelpFormatter formatter, Options options) { outputVfsRepository = new File(commandLine.getOptionValue("o", "outputVfs")); - forceOverwriteOutputVfsRepository = Boolean.parseBoolean(commandLine.getOptionValue("f", "false")); + forceOverwriteOutputVfsRepository = commandLine.hasOption("f"); if (outputVfsRepository.exists()) { if (forceOverwriteOutputVfsRepository) { try { FileUtils.deleteDirectory(outputVfsRepository); } catch (IOException e) { throw new IllegalStateException("Force deleting outputVfsRepository (" + outputVfsRepository.getAbsolutePath() + ") failed.", e); } } else { System.out.println("The outputVfsRepository (" + outputVfsRepository.getAbsolutePath() + ") already exists."); return false; } } try { outputVfsRepository = outputVfsRepository.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("The outputVfsRepository (" + outputVfsRepository + ") has issues.", e); } outputVfsRepository.mkdirs(); return true; } }
true
true
private boolean parseArgOutputVfsRepository(CommandLine commandLine, HelpFormatter formatter, Options options) { outputVfsRepository = new File(commandLine.getOptionValue("o", "outputVfs")); forceOverwriteOutputVfsRepository = Boolean.parseBoolean(commandLine.getOptionValue("f", "false")); if (outputVfsRepository.exists()) { if (forceOverwriteOutputVfsRepository) { try { FileUtils.deleteDirectory(outputVfsRepository); } catch (IOException e) { throw new IllegalStateException("Force deleting outputVfsRepository (" + outputVfsRepository.getAbsolutePath() + ") failed.", e); } } else { System.out.println("The outputVfsRepository (" + outputVfsRepository.getAbsolutePath() + ") already exists."); return false; } } try { outputVfsRepository = outputVfsRepository.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("The outputVfsRepository (" + outputVfsRepository + ") has issues.", e); } outputVfsRepository.mkdirs(); return true; }
private boolean parseArgOutputVfsRepository(CommandLine commandLine, HelpFormatter formatter, Options options) { outputVfsRepository = new File(commandLine.getOptionValue("o", "outputVfs")); forceOverwriteOutputVfsRepository = commandLine.hasOption("f"); if (outputVfsRepository.exists()) { if (forceOverwriteOutputVfsRepository) { try { FileUtils.deleteDirectory(outputVfsRepository); } catch (IOException e) { throw new IllegalStateException("Force deleting outputVfsRepository (" + outputVfsRepository.getAbsolutePath() + ") failed.", e); } } else { System.out.println("The outputVfsRepository (" + outputVfsRepository.getAbsolutePath() + ") already exists."); return false; } } try { outputVfsRepository = outputVfsRepository.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("The outputVfsRepository (" + outputVfsRepository + ") has issues.", e); } outputVfsRepository.mkdirs(); return true; }
diff --git a/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java b/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java index 311410d096..96a01e7f38 100644 --- a/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java +++ b/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java @@ -1,272 +1,282 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.vfny.geoserver.action; import com.vividsolutions.jts.geom.Envelope; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import org.geoserver.feature.FeatureSourceUtils; import org.geoserver.util.ReaderUtils; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import org.vfny.geoserver.global.ConfigurationException; import org.vfny.geoserver.global.CoverageInfo; import org.vfny.geoserver.global.Data; import org.vfny.geoserver.global.FeatureTypeInfo; import org.vfny.geoserver.global.WMS; import org.vfny.geoserver.util.requests.CapabilitiesRequest; import org.vfny.geoserver.wms.servlets.Capabilities; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <b>MapPreviewAction</b><br> Sep 26, 2005<br> * <b>Purpose:</b><br> * Gathers up all the FeatureTypes in use and returns the informaion to the * .jsp .<br> * It will also generate requests to the WMS "openlayers" output format. <br> * This will communicate to a .jsp and return it three arrays of strings that contain:<br> * - The Featuretype's name<br> * - The DataStore name of the FeatureType<br> * - The bounding box of the FeatureType<br> * To change what data is output to the .jsp, you must change <b>struts-config.xml</b>.<br> * Look for the line:<br> * &lt;form-bean <br> * name="mapPreviewForm"<br> * * @author Brent Owens (The Open Planning Project) * @version */ public class MapPreviewAction extends GeoServerAction { /* (non-Javadoc) * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList dsList = new ArrayList(); ArrayList ftList = new ArrayList(); ArrayList bboxList = new ArrayList(); ArrayList srsList = new ArrayList(); ArrayList ftnsList = new ArrayList(); ArrayList widthList = new ArrayList(); ArrayList heightList = new ArrayList(); // 1) get the capabilities info so we can find out our feature types WMS wms = getWMS(request); Capabilities caps = new Capabilities(wms); CapabilitiesRequest capRequest = new CapabilitiesRequest("WMS", caps); capRequest.setHttpServletRequest(request); Data catalog = wms.getData(); List ftypes = new ArrayList(catalog.getFeatureTypeInfos().values()); + for (Iterator it = ftypes.iterator(); it.hasNext();) { + FeatureTypeInfo ft = (FeatureTypeInfo) it.next(); + if(!ft.isEnabled()) + it.remove(); + } Collections.sort(ftypes, new FeatureTypeInfoNameComparator()); List ctypes = new ArrayList(catalog.getCoverageInfos().values()); + for (Iterator it = ctypes.iterator(); it.hasNext();) { + CoverageInfo ci = (CoverageInfo) it.next(); + if(!ci.isEnabled()) + it.remove(); + } Collections.sort(ctypes, new CoverageInfoNameComparator()); // 2) delete any existing generated files in the generation directory ServletContext sc = request.getSession().getServletContext(); //File rootDir = GeoserverDataDirectory.getGeoserverDataDirectory(sc); //File previewDir = new File(sc.getRealPath("data/generated")); if (sc.getRealPath("preview") == null) { //There's a problem here, since we can't get a real path for the "preview" directory. //On tomcat this happens when "unpackWars=false" is set for this context. throw new RuntimeException( "Couldn't populate preview directory...is the war running in unpacked mode?"); } File previewDir = new File(sc.getRealPath("preview")); //File previewDir = new File(rootDir, "data/generated"); if (!previewDir.exists()) { previewDir.mkdirs(); } // We need to create a 4326 CRS for comparison to layer's crs CoordinateReferenceSystem latLonCrs = null; try { // get the CRS object for lat/lon 4326 latLonCrs = CRS.decode("EPSG:" + 4326); } catch (NoSuchAuthorityCodeException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } catch (FactoryException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } // 3) Go through each *FeatureType* and collect information && write out config files for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo layer = (FeatureTypeInfo) it.next(); if (!layer.isEnabled() || layer.isGeometryless()) { continue; // if it isn't enabled, move to the next layer } CoordinateReferenceSystem layerCrs = layer.getDeclaredCRS(); /* A quick and efficient way to grab the bounding box is to get it * from the featuretype info where the lat/lon bbox is loaded * from the DTO. We do this with layer.getLatLongBoundingBox(). * We need to reproject the bounding box from lat/lon to the layer crs * for display */ Envelope orig_bbox = layer.getLatLongBoundingBox(); if ((orig_bbox.getWidth() == 0) || (orig_bbox.getHeight() == 0)) { orig_bbox.expandBy(0.1); } ReferencedEnvelope bbox = new ReferencedEnvelope(orig_bbox, latLonCrs); if (!CRS.equalsIgnoreMetadata(layerCrs, latLonCrs)) { try { // reproject the bbox to the layer crs bbox = bbox.transform(layerCrs, true); } catch (TransformException e) { e.printStackTrace(); } catch (FactoryException e) { e.printStackTrace(); } } // we now have a bounding box in the same CRS as the layer if ((bbox.getWidth() == 0) || (bbox.getHeight() == 0)) { bbox.expandBy(0.1); } if (layer.isEnabled()) { // prepare strings for web output ftList.add(layer.getNameSpace().getPrefix() + "_" + layer.getFeatureType().getTypeName()); // FeatureType name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + layer.getFeatureType().getTypeName()); dsList.add(layer.getDataStoreInfo().getId()); // DataStore info // bounding box of the FeatureType // expand bbox by 5% to allow large symbolizers to fit the map bbox.expandBy(bbox.getWidth() / 20, bbox.getHeight() / 20); bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add("EPSG:" + layer.getSRS()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 3.5) Go through each *Coverage* and collect its info for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo layer = (CoverageInfo) it.next(); // upper right corner? lower left corner? Who knows?! Better naming conventions needed guys. double[] lowerLeft = layer.getEnvelope().getLowerCorner().getCoordinates(); double[] upperRight = layer.getEnvelope().getUpperCorner().getCoordinates(); Envelope bbox = new Envelope(lowerLeft[0], upperRight[0], lowerLeft[1], upperRight[1]); if (layer.isEnabled()) { // prepare strings for web output String shortLayerName = layer.getName().split(":")[1]; // we don't want the namespace prefix ftList.add(layer.getNameSpace().getPrefix() + "_" + shortLayerName); // Coverage name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + shortLayerName); dsList.add(layer.getFormatInfo().getId()); // DataStore info // bounding box of the Coverage bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add(layer.getSrsName()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 4) send off gathered information to the .jsp DynaActionForm myForm = (DynaActionForm) form; myForm.set("DSNameList", dsList.toArray(new String[dsList.size()])); myForm.set("FTNameList", ftList.toArray(new String[ftList.size()])); myForm.set("BBoxList", bboxList.toArray(new String[bboxList.size()])); myForm.set("SRSList", srsList.toArray(new String[srsList.size()])); myForm.set("WidthList", widthList.toArray(new String[widthList.size()])); myForm.set("HeightList", heightList.toArray(new String[heightList.size()])); myForm.set("FTNamespaceList", ftnsList.toArray(new String[ftnsList.size()])); return mapping.findForward("success"); } private int[] getMapWidthHeight(Envelope bbox) { int width; int height; double ratio = bbox.getHeight() / bbox.getWidth(); if (ratio < 1) { width = 750; height = (int) Math.round(750 * ratio); } else { width = (int) Math.round(550 / ratio); height = 550; } // make sure we reach some minimal dimensions (300 pixels is more or less // the height of the zoom bar) if (width < 300) { width = 300; } if (height < 300) { height = 300; } // add 50 pixels horizontally to account for the zoom bar return new int[] { width + 50, height }; } private static class FeatureTypeInfoNameComparator implements Comparator { public int compare(Object o1, Object o2) { FeatureTypeInfo ft1 = (FeatureTypeInfo) o1; FeatureTypeInfo ft2 = (FeatureTypeInfo) o2; String ft1Name = ft1.getNameSpace().getPrefix() + ft1.getName(); String ft2Name = ft2.getNameSpace().getPrefix() + ft2.getName(); return ft1Name.compareTo(ft2Name); } } private static class CoverageInfoNameComparator implements Comparator { public int compare(Object o1, Object o2) { CoverageInfo c1 = (CoverageInfo) o1; CoverageInfo c2 = (CoverageInfo) o2; String ft1Name = c1.getNameSpace().getPrefix() + c1.getName(); String ft2Name = c2.getNameSpace().getPrefix() + c2.getName(); return ft1Name.compareTo(ft2Name); } } }
false
true
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList dsList = new ArrayList(); ArrayList ftList = new ArrayList(); ArrayList bboxList = new ArrayList(); ArrayList srsList = new ArrayList(); ArrayList ftnsList = new ArrayList(); ArrayList widthList = new ArrayList(); ArrayList heightList = new ArrayList(); // 1) get the capabilities info so we can find out our feature types WMS wms = getWMS(request); Capabilities caps = new Capabilities(wms); CapabilitiesRequest capRequest = new CapabilitiesRequest("WMS", caps); capRequest.setHttpServletRequest(request); Data catalog = wms.getData(); List ftypes = new ArrayList(catalog.getFeatureTypeInfos().values()); Collections.sort(ftypes, new FeatureTypeInfoNameComparator()); List ctypes = new ArrayList(catalog.getCoverageInfos().values()); Collections.sort(ctypes, new CoverageInfoNameComparator()); // 2) delete any existing generated files in the generation directory ServletContext sc = request.getSession().getServletContext(); //File rootDir = GeoserverDataDirectory.getGeoserverDataDirectory(sc); //File previewDir = new File(sc.getRealPath("data/generated")); if (sc.getRealPath("preview") == null) { //There's a problem here, since we can't get a real path for the "preview" directory. //On tomcat this happens when "unpackWars=false" is set for this context. throw new RuntimeException( "Couldn't populate preview directory...is the war running in unpacked mode?"); } File previewDir = new File(sc.getRealPath("preview")); //File previewDir = new File(rootDir, "data/generated"); if (!previewDir.exists()) { previewDir.mkdirs(); } // We need to create a 4326 CRS for comparison to layer's crs CoordinateReferenceSystem latLonCrs = null; try { // get the CRS object for lat/lon 4326 latLonCrs = CRS.decode("EPSG:" + 4326); } catch (NoSuchAuthorityCodeException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } catch (FactoryException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } // 3) Go through each *FeatureType* and collect information && write out config files for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo layer = (FeatureTypeInfo) it.next(); if (!layer.isEnabled() || layer.isGeometryless()) { continue; // if it isn't enabled, move to the next layer } CoordinateReferenceSystem layerCrs = layer.getDeclaredCRS(); /* A quick and efficient way to grab the bounding box is to get it * from the featuretype info where the lat/lon bbox is loaded * from the DTO. We do this with layer.getLatLongBoundingBox(). * We need to reproject the bounding box from lat/lon to the layer crs * for display */ Envelope orig_bbox = layer.getLatLongBoundingBox(); if ((orig_bbox.getWidth() == 0) || (orig_bbox.getHeight() == 0)) { orig_bbox.expandBy(0.1); } ReferencedEnvelope bbox = new ReferencedEnvelope(orig_bbox, latLonCrs); if (!CRS.equalsIgnoreMetadata(layerCrs, latLonCrs)) { try { // reproject the bbox to the layer crs bbox = bbox.transform(layerCrs, true); } catch (TransformException e) { e.printStackTrace(); } catch (FactoryException e) { e.printStackTrace(); } } // we now have a bounding box in the same CRS as the layer if ((bbox.getWidth() == 0) || (bbox.getHeight() == 0)) { bbox.expandBy(0.1); } if (layer.isEnabled()) { // prepare strings for web output ftList.add(layer.getNameSpace().getPrefix() + "_" + layer.getFeatureType().getTypeName()); // FeatureType name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + layer.getFeatureType().getTypeName()); dsList.add(layer.getDataStoreInfo().getId()); // DataStore info // bounding box of the FeatureType // expand bbox by 5% to allow large symbolizers to fit the map bbox.expandBy(bbox.getWidth() / 20, bbox.getHeight() / 20); bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add("EPSG:" + layer.getSRS()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 3.5) Go through each *Coverage* and collect its info for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo layer = (CoverageInfo) it.next(); // upper right corner? lower left corner? Who knows?! Better naming conventions needed guys. double[] lowerLeft = layer.getEnvelope().getLowerCorner().getCoordinates(); double[] upperRight = layer.getEnvelope().getUpperCorner().getCoordinates(); Envelope bbox = new Envelope(lowerLeft[0], upperRight[0], lowerLeft[1], upperRight[1]); if (layer.isEnabled()) { // prepare strings for web output String shortLayerName = layer.getName().split(":")[1]; // we don't want the namespace prefix ftList.add(layer.getNameSpace().getPrefix() + "_" + shortLayerName); // Coverage name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + shortLayerName); dsList.add(layer.getFormatInfo().getId()); // DataStore info // bounding box of the Coverage bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add(layer.getSrsName()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 4) send off gathered information to the .jsp DynaActionForm myForm = (DynaActionForm) form; myForm.set("DSNameList", dsList.toArray(new String[dsList.size()])); myForm.set("FTNameList", ftList.toArray(new String[ftList.size()])); myForm.set("BBoxList", bboxList.toArray(new String[bboxList.size()])); myForm.set("SRSList", srsList.toArray(new String[srsList.size()])); myForm.set("WidthList", widthList.toArray(new String[widthList.size()])); myForm.set("HeightList", heightList.toArray(new String[heightList.size()])); myForm.set("FTNamespaceList", ftnsList.toArray(new String[ftnsList.size()])); return mapping.findForward("success"); }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList dsList = new ArrayList(); ArrayList ftList = new ArrayList(); ArrayList bboxList = new ArrayList(); ArrayList srsList = new ArrayList(); ArrayList ftnsList = new ArrayList(); ArrayList widthList = new ArrayList(); ArrayList heightList = new ArrayList(); // 1) get the capabilities info so we can find out our feature types WMS wms = getWMS(request); Capabilities caps = new Capabilities(wms); CapabilitiesRequest capRequest = new CapabilitiesRequest("WMS", caps); capRequest.setHttpServletRequest(request); Data catalog = wms.getData(); List ftypes = new ArrayList(catalog.getFeatureTypeInfos().values()); for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo ft = (FeatureTypeInfo) it.next(); if(!ft.isEnabled()) it.remove(); } Collections.sort(ftypes, new FeatureTypeInfoNameComparator()); List ctypes = new ArrayList(catalog.getCoverageInfos().values()); for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo ci = (CoverageInfo) it.next(); if(!ci.isEnabled()) it.remove(); } Collections.sort(ctypes, new CoverageInfoNameComparator()); // 2) delete any existing generated files in the generation directory ServletContext sc = request.getSession().getServletContext(); //File rootDir = GeoserverDataDirectory.getGeoserverDataDirectory(sc); //File previewDir = new File(sc.getRealPath("data/generated")); if (sc.getRealPath("preview") == null) { //There's a problem here, since we can't get a real path for the "preview" directory. //On tomcat this happens when "unpackWars=false" is set for this context. throw new RuntimeException( "Couldn't populate preview directory...is the war running in unpacked mode?"); } File previewDir = new File(sc.getRealPath("preview")); //File previewDir = new File(rootDir, "data/generated"); if (!previewDir.exists()) { previewDir.mkdirs(); } // We need to create a 4326 CRS for comparison to layer's crs CoordinateReferenceSystem latLonCrs = null; try { // get the CRS object for lat/lon 4326 latLonCrs = CRS.decode("EPSG:" + 4326); } catch (NoSuchAuthorityCodeException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } catch (FactoryException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } // 3) Go through each *FeatureType* and collect information && write out config files for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo layer = (FeatureTypeInfo) it.next(); if (!layer.isEnabled() || layer.isGeometryless()) { continue; // if it isn't enabled, move to the next layer } CoordinateReferenceSystem layerCrs = layer.getDeclaredCRS(); /* A quick and efficient way to grab the bounding box is to get it * from the featuretype info where the lat/lon bbox is loaded * from the DTO. We do this with layer.getLatLongBoundingBox(). * We need to reproject the bounding box from lat/lon to the layer crs * for display */ Envelope orig_bbox = layer.getLatLongBoundingBox(); if ((orig_bbox.getWidth() == 0) || (orig_bbox.getHeight() == 0)) { orig_bbox.expandBy(0.1); } ReferencedEnvelope bbox = new ReferencedEnvelope(orig_bbox, latLonCrs); if (!CRS.equalsIgnoreMetadata(layerCrs, latLonCrs)) { try { // reproject the bbox to the layer crs bbox = bbox.transform(layerCrs, true); } catch (TransformException e) { e.printStackTrace(); } catch (FactoryException e) { e.printStackTrace(); } } // we now have a bounding box in the same CRS as the layer if ((bbox.getWidth() == 0) || (bbox.getHeight() == 0)) { bbox.expandBy(0.1); } if (layer.isEnabled()) { // prepare strings for web output ftList.add(layer.getNameSpace().getPrefix() + "_" + layer.getFeatureType().getTypeName()); // FeatureType name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + layer.getFeatureType().getTypeName()); dsList.add(layer.getDataStoreInfo().getId()); // DataStore info // bounding box of the FeatureType // expand bbox by 5% to allow large symbolizers to fit the map bbox.expandBy(bbox.getWidth() / 20, bbox.getHeight() / 20); bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add("EPSG:" + layer.getSRS()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 3.5) Go through each *Coverage* and collect its info for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo layer = (CoverageInfo) it.next(); // upper right corner? lower left corner? Who knows?! Better naming conventions needed guys. double[] lowerLeft = layer.getEnvelope().getLowerCorner().getCoordinates(); double[] upperRight = layer.getEnvelope().getUpperCorner().getCoordinates(); Envelope bbox = new Envelope(lowerLeft[0], upperRight[0], lowerLeft[1], upperRight[1]); if (layer.isEnabled()) { // prepare strings for web output String shortLayerName = layer.getName().split(":")[1]; // we don't want the namespace prefix ftList.add(layer.getNameSpace().getPrefix() + "_" + shortLayerName); // Coverage name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + shortLayerName); dsList.add(layer.getFormatInfo().getId()); // DataStore info // bounding box of the Coverage bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add(layer.getSrsName()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 4) send off gathered information to the .jsp DynaActionForm myForm = (DynaActionForm) form; myForm.set("DSNameList", dsList.toArray(new String[dsList.size()])); myForm.set("FTNameList", ftList.toArray(new String[ftList.size()])); myForm.set("BBoxList", bboxList.toArray(new String[bboxList.size()])); myForm.set("SRSList", srsList.toArray(new String[srsList.size()])); myForm.set("WidthList", widthList.toArray(new String[widthList.size()])); myForm.set("HeightList", heightList.toArray(new String[heightList.size()])); myForm.set("FTNamespaceList", ftnsList.toArray(new String[ftnsList.size()])); return mapping.findForward("success"); }
diff --git a/src/com/agodwin/hideseek/Main.java b/src/com/agodwin/hideseek/Main.java index b3594d0..6cfa787 100644 --- a/src/com/agodwin/hideseek/Main.java +++ b/src/com/agodwin/hideseek/Main.java @@ -1,246 +1,246 @@ package com.agodwin.hideseek; import java.util.HashMap; import java.util.logging.Level; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin { private String wiki = "http://pornhub.com/"; public static String helper = ChatColor.GOLD + "[H&S Helper]" + ChatColor.RED + " "; public String info = ChatColor.GOLD + "[H&S info]" + ChatColor.AQUA + " "; public final static HashMap<String, Arena> inArena = new HashMap<String, Arena>(); public static int maxArenas = 100; // public final static String[] arenaNames = new String[maxArenas]; // public final Location[] arenaLobby = new Location[maxArenas]; // public final static Location[] arenaSpawnSeek = new Location[maxArenas]; // public final Location[] arenaSpawnHide = new Location[maxArenas]; // public final Location[] arenaLeave = new Location[maxArenas]; // public final int[] players = new int[maxArenas]; private HashMap<String, Arena> arenas = new HashMap<String, Arena>(); public int arenaCounter = 0; private Events events; private static Plugin p = null; @Override public void onEnable() { getConfig().options().copyDefaults(true); saveConfig(); events = new Events(); register(); getLogger().log(Level.SEVERE, "Sup, nigga bitch?"); p = this; } @Override public void onDisable() { } public void register() { this.getServer().getPluginManager().registerEvents(events, this); } @Override public boolean onCommand(CommandSender sender, Command command, String CommandLabel, String[] args) { Player p = (Player) sender; if (CommandLabel.equalsIgnoreCase("hns")) { if (args.length == 0) { p.sendMessage(info + "Welcome to Hide and Seek version " + this.getDescription().getVersion()); p.sendMessage(info + "Do /hns help to get basic commands"); } else if (args[0].equalsIgnoreCase("help")) { p.sendMessage(ChatColor.GOLD + "****************************************************"); p.sendMessage(ChatColor.GREEN + "do /hns join <arena> to play Hide and Seek"); p.sendMessage(ChatColor.GREEN + "do /hns leave to leave Hide and Seek"); p.sendMessage(ChatColor.GREEN + "do /hns list to see areanas"); p.sendMessage(ChatColor.GREEN + "Visit the Wiki here: " + ChatColor.BLUE + wiki + ChatColor.GREEN + " for more advanced commands"); p.sendMessage(ChatColor.GOLD + "****************************************************"); } else if (args[0].equalsIgnoreCase("join")) { if (inArena.containsKey(p.getName())) { p.sendMessage(helper + "You must leave this game before you can join another!"); } else { if (args.length == 1) { p.sendMessage(helper + "Please enter an arena to join."); } else { // for (int i = 0; i < arenaNames.length;) { // String requestedName = arenaNames[i]; // if (args[1].equalsIgnoreCase(requestedName)) { // Location lobbyLocation = arenaLobby[i]; // Location test = arenaSpawnHide[i]; // p.teleport(lobbyLocation); // p.sendMessage(info + "You chose to join: " + // ChatColor.GOLD + args[1]); // inArena.put(p.getName(), arenaNames[i]); // players[i]++; // p.sendMessage(info+"There are "+ChatColor.GOLD+players[i]+"/10"+ChatColor.AQUA+"players"); // if (players[i] == 2) { // players[i] = 0; // for(Player player : Bukkit.getOnlinePlayers()){ // if(inArena.containsKey(player.getName())){ // player.teleport(test); // player.setMetadata("team", new // FixedMetadataValue(this, "hider")); // } // } // // break; // } // break; // } else { // p.sendMessage(helper + "That is not a valid name"); // break; // } // } if (arenas.containsKey(args[1])) { // put them in the arena Arena joining = arenas.get(args[1]); if (!joining.arenaInProgress()) { joining.addPlayer(p); inArena.put(p.getName(), joining); p.teleport(joining.getLobbyLocation()); p.sendMessage(info + "You chose to join: " + ChatColor.GOLD + joining.getArenaName()); p.sendMessage(info + "There are " + ChatColor.GOLD + joining.getNumPlayers() + "/" + joining.getMaxPlayers() + ChatColor.AQUA + " players"); if (joining.getNumPlayers() >= 2) { joining.startArena(); } } else { p.sendMessage(helper + "That arena is in progress. Please try another arena or wait for the game to finish."); } } else { p.sendMessage(helper + "That is not a valid arena name. Please try again."); for (String name : arenas.keySet()) { if (Utils.similar(name, args[1]) > .8D) { p.sendMessage("You may have meant: " + name + "."); } } } } } } else if (args[0].equalsIgnoreCase("list")) { String message = ""; for (String name : arenas.keySet()) { message += name + ", "; } if (!message.isEmpty()) p.sendMessage(info + message.substring(0, message.lastIndexOf((int) ','))); } else if (args[0].equalsIgnoreCase("leave")) { if (inArena.containsKey(p.getName())) { if (inArena.get(p.getName()).arenaInProgress()) { inArena.get(p.getName()).safelyRemovePlayer(p); } } } else if (args[0].equalsIgnoreCase("create")) { if (args.length == 1) { p.sendMessage(helper + "You must enter an arena name!"); } else if (args.length == 2) { p.sendMessage(info + "You created an arena with the name: " + ChatColor.GOLD + args[1]); p.sendMessage(info + "To setup " + ChatColor.GOLD + args[1] + ChatColor.AQUA + ", Enter the commands " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); arenas.put(args[1], new Arena(args[1])); } else { p.sendMessage(helper + "You have entered the command incorrectly. You are a dumb shit."); } } else if (args[0].equalsIgnoreCase("markpoint")) { if (args.length != 3) { p.sendMessage(helper + "Try like this: " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); return false; } String arg = args[2]; String arenaName = args[1]; - if (!arenas.containsKey(args[1])) { - if (arenas.containsKey(args[2])) { + if (!arenas.containsKey(arenaName)) { + if (arenas.containsKey(arg)) { // they switched that shit up arg = args[1]; arenaName = args[2]; + } else { + p.sendMessage(helper + + "I was unable to determine the arena. \nTry like this: " + + ChatColor.RED + + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); + return false; } - } else { - p.sendMessage(helper - + "I was unable to determine the arena. \nTry like this: " - + ChatColor.RED - + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); - return false; } Arena a = arenas.get(arenaName); if (arg.equalsIgnoreCase("lobby")) { p.sendMessage(info + "You marked the lobby location"); a.setLobbyLocation(p.getLocation()); } else if (arg.equalsIgnoreCase("hidespawn")) { p.sendMessage(info + "You marked the Hider Spawn location"); a.setHiderSpawnLoc(p.getLocation()); } else if (arg.equalsIgnoreCase("seekspawn")) { p.sendMessage(info + "You marked the Seeker Spawn location"); a.setSeekerSpawnLoc(p.getLocation()); } else if (arg.equalsIgnoreCase("leave")) { p.sendMessage(info + "You marked the Leave location"); a.setLeaveLoc(p.getLocation()); } else { p.sendMessage(helper + "Unknown argument"); } } else { p.sendMessage(helper + "Unknown command do /hns help"); } } return false; } public Location loc(Player pl) { Location loc = null; for (Arena a : arenas.values()) { if (a.playerInArena(pl)) return a.getSeekerSpawnLoc(); } return loc; } public static Plugin getPlugin() { return p; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String CommandLabel, String[] args) { Player p = (Player) sender; if (CommandLabel.equalsIgnoreCase("hns")) { if (args.length == 0) { p.sendMessage(info + "Welcome to Hide and Seek version " + this.getDescription().getVersion()); p.sendMessage(info + "Do /hns help to get basic commands"); } else if (args[0].equalsIgnoreCase("help")) { p.sendMessage(ChatColor.GOLD + "****************************************************"); p.sendMessage(ChatColor.GREEN + "do /hns join <arena> to play Hide and Seek"); p.sendMessage(ChatColor.GREEN + "do /hns leave to leave Hide and Seek"); p.sendMessage(ChatColor.GREEN + "do /hns list to see areanas"); p.sendMessage(ChatColor.GREEN + "Visit the Wiki here: " + ChatColor.BLUE + wiki + ChatColor.GREEN + " for more advanced commands"); p.sendMessage(ChatColor.GOLD + "****************************************************"); } else if (args[0].equalsIgnoreCase("join")) { if (inArena.containsKey(p.getName())) { p.sendMessage(helper + "You must leave this game before you can join another!"); } else { if (args.length == 1) { p.sendMessage(helper + "Please enter an arena to join."); } else { // for (int i = 0; i < arenaNames.length;) { // String requestedName = arenaNames[i]; // if (args[1].equalsIgnoreCase(requestedName)) { // Location lobbyLocation = arenaLobby[i]; // Location test = arenaSpawnHide[i]; // p.teleport(lobbyLocation); // p.sendMessage(info + "You chose to join: " + // ChatColor.GOLD + args[1]); // inArena.put(p.getName(), arenaNames[i]); // players[i]++; // p.sendMessage(info+"There are "+ChatColor.GOLD+players[i]+"/10"+ChatColor.AQUA+"players"); // if (players[i] == 2) { // players[i] = 0; // for(Player player : Bukkit.getOnlinePlayers()){ // if(inArena.containsKey(player.getName())){ // player.teleport(test); // player.setMetadata("team", new // FixedMetadataValue(this, "hider")); // } // } // // break; // } // break; // } else { // p.sendMessage(helper + "That is not a valid name"); // break; // } // } if (arenas.containsKey(args[1])) { // put them in the arena Arena joining = arenas.get(args[1]); if (!joining.arenaInProgress()) { joining.addPlayer(p); inArena.put(p.getName(), joining); p.teleport(joining.getLobbyLocation()); p.sendMessage(info + "You chose to join: " + ChatColor.GOLD + joining.getArenaName()); p.sendMessage(info + "There are " + ChatColor.GOLD + joining.getNumPlayers() + "/" + joining.getMaxPlayers() + ChatColor.AQUA + " players"); if (joining.getNumPlayers() >= 2) { joining.startArena(); } } else { p.sendMessage(helper + "That arena is in progress. Please try another arena or wait for the game to finish."); } } else { p.sendMessage(helper + "That is not a valid arena name. Please try again."); for (String name : arenas.keySet()) { if (Utils.similar(name, args[1]) > .8D) { p.sendMessage("You may have meant: " + name + "."); } } } } } } else if (args[0].equalsIgnoreCase("list")) { String message = ""; for (String name : arenas.keySet()) { message += name + ", "; } if (!message.isEmpty()) p.sendMessage(info + message.substring(0, message.lastIndexOf((int) ','))); } else if (args[0].equalsIgnoreCase("leave")) { if (inArena.containsKey(p.getName())) { if (inArena.get(p.getName()).arenaInProgress()) { inArena.get(p.getName()).safelyRemovePlayer(p); } } } else if (args[0].equalsIgnoreCase("create")) { if (args.length == 1) { p.sendMessage(helper + "You must enter an arena name!"); } else if (args.length == 2) { p.sendMessage(info + "You created an arena with the name: " + ChatColor.GOLD + args[1]); p.sendMessage(info + "To setup " + ChatColor.GOLD + args[1] + ChatColor.AQUA + ", Enter the commands " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); arenas.put(args[1], new Arena(args[1])); } else { p.sendMessage(helper + "You have entered the command incorrectly. You are a dumb shit."); } } else if (args[0].equalsIgnoreCase("markpoint")) { if (args.length != 3) { p.sendMessage(helper + "Try like this: " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); return false; } String arg = args[2]; String arenaName = args[1]; if (!arenas.containsKey(args[1])) { if (arenas.containsKey(args[2])) { // they switched that shit up arg = args[1]; arenaName = args[2]; } } else { p.sendMessage(helper + "I was unable to determine the arena. \nTry like this: " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); return false; } Arena a = arenas.get(arenaName); if (arg.equalsIgnoreCase("lobby")) { p.sendMessage(info + "You marked the lobby location"); a.setLobbyLocation(p.getLocation()); } else if (arg.equalsIgnoreCase("hidespawn")) { p.sendMessage(info + "You marked the Hider Spawn location"); a.setHiderSpawnLoc(p.getLocation()); } else if (arg.equalsIgnoreCase("seekspawn")) { p.sendMessage(info + "You marked the Seeker Spawn location"); a.setSeekerSpawnLoc(p.getLocation()); } else if (arg.equalsIgnoreCase("leave")) { p.sendMessage(info + "You marked the Leave location"); a.setLeaveLoc(p.getLocation()); } else { p.sendMessage(helper + "Unknown argument"); } } else { p.sendMessage(helper + "Unknown command do /hns help"); } } return false; }
public boolean onCommand(CommandSender sender, Command command, String CommandLabel, String[] args) { Player p = (Player) sender; if (CommandLabel.equalsIgnoreCase("hns")) { if (args.length == 0) { p.sendMessage(info + "Welcome to Hide and Seek version " + this.getDescription().getVersion()); p.sendMessage(info + "Do /hns help to get basic commands"); } else if (args[0].equalsIgnoreCase("help")) { p.sendMessage(ChatColor.GOLD + "****************************************************"); p.sendMessage(ChatColor.GREEN + "do /hns join <arena> to play Hide and Seek"); p.sendMessage(ChatColor.GREEN + "do /hns leave to leave Hide and Seek"); p.sendMessage(ChatColor.GREEN + "do /hns list to see areanas"); p.sendMessage(ChatColor.GREEN + "Visit the Wiki here: " + ChatColor.BLUE + wiki + ChatColor.GREEN + " for more advanced commands"); p.sendMessage(ChatColor.GOLD + "****************************************************"); } else if (args[0].equalsIgnoreCase("join")) { if (inArena.containsKey(p.getName())) { p.sendMessage(helper + "You must leave this game before you can join another!"); } else { if (args.length == 1) { p.sendMessage(helper + "Please enter an arena to join."); } else { // for (int i = 0; i < arenaNames.length;) { // String requestedName = arenaNames[i]; // if (args[1].equalsIgnoreCase(requestedName)) { // Location lobbyLocation = arenaLobby[i]; // Location test = arenaSpawnHide[i]; // p.teleport(lobbyLocation); // p.sendMessage(info + "You chose to join: " + // ChatColor.GOLD + args[1]); // inArena.put(p.getName(), arenaNames[i]); // players[i]++; // p.sendMessage(info+"There are "+ChatColor.GOLD+players[i]+"/10"+ChatColor.AQUA+"players"); // if (players[i] == 2) { // players[i] = 0; // for(Player player : Bukkit.getOnlinePlayers()){ // if(inArena.containsKey(player.getName())){ // player.teleport(test); // player.setMetadata("team", new // FixedMetadataValue(this, "hider")); // } // } // // break; // } // break; // } else { // p.sendMessage(helper + "That is not a valid name"); // break; // } // } if (arenas.containsKey(args[1])) { // put them in the arena Arena joining = arenas.get(args[1]); if (!joining.arenaInProgress()) { joining.addPlayer(p); inArena.put(p.getName(), joining); p.teleport(joining.getLobbyLocation()); p.sendMessage(info + "You chose to join: " + ChatColor.GOLD + joining.getArenaName()); p.sendMessage(info + "There are " + ChatColor.GOLD + joining.getNumPlayers() + "/" + joining.getMaxPlayers() + ChatColor.AQUA + " players"); if (joining.getNumPlayers() >= 2) { joining.startArena(); } } else { p.sendMessage(helper + "That arena is in progress. Please try another arena or wait for the game to finish."); } } else { p.sendMessage(helper + "That is not a valid arena name. Please try again."); for (String name : arenas.keySet()) { if (Utils.similar(name, args[1]) > .8D) { p.sendMessage("You may have meant: " + name + "."); } } } } } } else if (args[0].equalsIgnoreCase("list")) { String message = ""; for (String name : arenas.keySet()) { message += name + ", "; } if (!message.isEmpty()) p.sendMessage(info + message.substring(0, message.lastIndexOf((int) ','))); } else if (args[0].equalsIgnoreCase("leave")) { if (inArena.containsKey(p.getName())) { if (inArena.get(p.getName()).arenaInProgress()) { inArena.get(p.getName()).safelyRemovePlayer(p); } } } else if (args[0].equalsIgnoreCase("create")) { if (args.length == 1) { p.sendMessage(helper + "You must enter an arena name!"); } else if (args.length == 2) { p.sendMessage(info + "You created an arena with the name: " + ChatColor.GOLD + args[1]); p.sendMessage(info + "To setup " + ChatColor.GOLD + args[1] + ChatColor.AQUA + ", Enter the commands " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); arenas.put(args[1], new Arena(args[1])); } else { p.sendMessage(helper + "You have entered the command incorrectly. You are a dumb shit."); } } else if (args[0].equalsIgnoreCase("markpoint")) { if (args.length != 3) { p.sendMessage(helper + "Try like this: " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); return false; } String arg = args[2]; String arenaName = args[1]; if (!arenas.containsKey(arenaName)) { if (arenas.containsKey(arg)) { // they switched that shit up arg = args[1]; arenaName = args[2]; } else { p.sendMessage(helper + "I was unable to determine the arena. \nTry like this: " + ChatColor.RED + "/hns markpoint <arena name> <lobby, hidespawn, seekspawn, leave>"); return false; } } Arena a = arenas.get(arenaName); if (arg.equalsIgnoreCase("lobby")) { p.sendMessage(info + "You marked the lobby location"); a.setLobbyLocation(p.getLocation()); } else if (arg.equalsIgnoreCase("hidespawn")) { p.sendMessage(info + "You marked the Hider Spawn location"); a.setHiderSpawnLoc(p.getLocation()); } else if (arg.equalsIgnoreCase("seekspawn")) { p.sendMessage(info + "You marked the Seeker Spawn location"); a.setSeekerSpawnLoc(p.getLocation()); } else if (arg.equalsIgnoreCase("leave")) { p.sendMessage(info + "You marked the Leave location"); a.setLeaveLoc(p.getLocation()); } else { p.sendMessage(helper + "Unknown argument"); } } else { p.sendMessage(helper + "Unknown command do /hns help"); } } return false; }
diff --git a/src/net/sf/freecol/client/control/InGameController.java b/src/net/sf/freecol/client/control/InGameController.java index 1c299ae31..46f6399c7 100644 --- a/src/net/sf/freecol/client/control/InGameController.java +++ b/src/net/sf/freecol/client/control/InGameController.java @@ -1,3873 +1,3874 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.control; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import net.sf.freecol.FreeCol; import net.sf.freecol.client.ClientOptions; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.client.gui.Canvas.MissionaryAction; import net.sf.freecol.client.gui.Canvas.ScoutAction; import net.sf.freecol.client.gui.GUI; import net.sf.freecol.client.gui.InGameMenuBar; import net.sf.freecol.client.gui.action.BuildColonyAction; import net.sf.freecol.client.gui.animation.Animation; import net.sf.freecol.client.gui.animation.UnitMoveAnimation; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.client.gui.option.FreeColActionUI; import net.sf.freecol.client.gui.panel.ChoiceItem; import net.sf.freecol.client.gui.panel.EventPanel; import net.sf.freecol.client.gui.panel.ReportTurnPanel; import net.sf.freecol.client.gui.sound.SfxLibrary; import net.sf.freecol.client.gui.sound.SoundLibrary.SoundEffect; import net.sf.freecol.client.networking.Client; import net.sf.freecol.common.Specification; import net.sf.freecol.common.model.AbstractGoods; import net.sf.freecol.common.model.BuildableType; import net.sf.freecol.common.model.Building; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.CombatModel.CombatResult; import net.sf.freecol.common.model.CombatModel.CombatResultType; import net.sf.freecol.common.model.DiplomaticTrade; import net.sf.freecol.common.model.EquipmentType; import net.sf.freecol.common.model.Europe; import net.sf.freecol.common.model.ExportData; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.GoalDecider; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsContainer; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.IndianSettlement; import net.sf.freecol.common.model.Location; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Tension; import net.sf.freecol.common.model.Map.Direction; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Nameable; import net.sf.freecol.common.model.Ownable; import net.sf.freecol.common.model.PathNode; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Player.Stance; import net.sf.freecol.common.model.Region; import net.sf.freecol.common.model.Settlement; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.TileImprovement; import net.sf.freecol.common.model.TileImprovementType; import net.sf.freecol.common.model.TileItemContainer; import net.sf.freecol.common.model.TradeRoute; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Unit.MoveType; import net.sf.freecol.common.model.Unit.UnitState; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.model.WorkLocation; import net.sf.freecol.common.model.Map.Position; import net.sf.freecol.common.model.TradeRoute.Stop; import net.sf.freecol.common.networking.BuyLandMessage; import net.sf.freecol.common.networking.Message; import net.sf.freecol.common.networking.NetworkConstants; import net.sf.freecol.common.networking.StealLandMessage; import net.sf.freecol.common.networking.StatisticsMessage; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * The controller that will be used while the game is played. */ public final class InGameController implements NetworkConstants { private static final Logger logger = Logger.getLogger(InGameController.class.getName()); private final FreeColClient freeColClient; /** * Sets that the turn will be ended when all going-to units have been moved. */ private boolean endingTurn = false; /** * If true, then at least one unit has been active and the turn may automatically be ended. */ private boolean canAutoEndTurn = false; /** * Sets that all going-to orders should be executed. */ private boolean executeGoto = false; /** * A hash map of messages to be ignored. */ private HashMap<String, Integer> messagesToIgnore = new HashMap<String, Integer>(); /** * A list of save game files. */ private ArrayList<File> allSaveGames = new ArrayList<File>(); /** * The constructor to use. * * @param freeColClient The main controller. */ public InGameController(FreeColClient freeColClient) { this.freeColClient = freeColClient; } /** * Opens a dialog where the user should specify the filename and saves the * game. */ public void saveGame() { final Canvas canvas = freeColClient.getCanvas(); String fileName = freeColClient.getMyPlayer().getName() + "_" + freeColClient.getMyPlayer().getNationAsString() + "_" + freeColClient.getGame().getTurn().toSaveGameString(); fileName = fileName.replaceAll(" ", "_"); if (freeColClient.getMyPlayer().isAdmin() && freeColClient.getFreeColServer() != null) { final File file = canvas.showSaveDialog(FreeCol.getSaveDirectory(), fileName); if (file != null) { FreeCol.setSaveDirectory(file.getParentFile()); saveGame(file); } } } /** * Saves the game to the given file. * * @param file The <code>File</code>. */ public void saveGame(final File file) { final Canvas canvas = freeColClient.getCanvas(); canvas.showStatusPanel(Messages.message("status.savingGame")); Thread t = new Thread() { public void run() { try { freeColClient.getFreeColServer().saveGame(file, freeColClient.getMyPlayer().getName()); SwingUtilities.invokeLater(new Runnable() { public void run() { canvas.closeStatusPanel(); canvas.requestFocusInWindow(); } }); } catch (IOException e) { SwingUtilities.invokeLater(new Runnable() { public void run() { canvas.errorMessage("couldNotSaveGame"); } }); } } }; t.start(); } /** * Opens a dialog where the user should specify the filename and loads the * game. */ public void loadGame() { Canvas canvas = freeColClient.getCanvas(); File file = canvas.showLoadDialog(FreeCol.getSaveDirectory()); if (file == null) { return; } if (!file.isFile()) { canvas.errorMessage("fileNotFound"); return; } if (!canvas.showConfirmDialog("stopCurrentGame.text", "stopCurrentGame.yes", "stopCurrentGame.no")) { return; } freeColClient.getConnectController().quitGame(true); canvas.removeInGameComponents(); freeColClient.getConnectController().loadGame(file); } /** * Sets the "debug mode" to be active or not. Calls * {@link FreeCol#setInDebugMode(boolean)} and reinitialize the * <code>FreeColMenuBar</code>. * * @param debug Should be set to <code>true</code> in order to enable * debug mode. */ public void setInDebugMode(boolean debug) { FreeCol.setInDebugMode(debug); freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient)); freeColClient.getCanvas().updateJMenuBar(); } /** * Declares independence for the home country. */ public void declareIndependence() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); if (freeColClient.getMyPlayer().getSoL() < 50) { canvas.showInformationMessage("declareIndependence.notMajority", FreeCol.getSpecification().getGoodsType("model.goods.bells"), "%percentage%", Integer.toString(freeColClient.getMyPlayer().getSoL())); return; } if (!canvas.showConfirmDialog("declareIndependence.areYouSure.text", "declareIndependence.areYouSure.yes", "declareIndependence.areYouSure.no")) { return; } Element declareIndependenceElement = Message.createNewRootElement("declareIndependence"); freeColClient.getMyPlayer().declareIndependence(); freeColClient.getActionManager().update(); freeColClient.getClient().sendAndWait(declareIndependenceElement); canvas.showDeclarationDialog(); } /** * Sends a public chat message. * * @param message The chat message. */ public void sendChat(String message) { Element chatElement = Message.createNewRootElement("chat"); chatElement.setAttribute("message", message); chatElement.setAttribute("privateChat", "false"); freeColClient.getClient().sendAndWait(chatElement); } /** * Sets <code>player</code> as the new <code>currentPlayer</code> of the * game. * * @param currentPlayer The player. */ public void setCurrentPlayer(Player currentPlayer) { logger.finest("Setting current player " + currentPlayer.getName()); Game game = freeColClient.getGame(); game.setCurrentPlayer(currentPlayer); if (freeColClient.getMyPlayer().equals(currentPlayer)) { // Autosave the game: if (freeColClient.getFreeColServer() != null) { final int turnNumber = freeColClient.getGame().getTurn().getNumber(); final int savegamePeriod = freeColClient.getClientOptions().getInteger(ClientOptions.AUTOSAVE_PERIOD); if (savegamePeriod == 1 || (savegamePeriod != 0 && turnNumber % savegamePeriod == 0)) { final String filename = Messages.message("clientOptions.savegames.autosave.fileprefix") + '-' + freeColClient.getGame().getTurn().toSaveGameString() + ".fsg"; File saveGameFile = new File(FreeCol.getAutosaveDirectory(), filename); saveGame(saveGameFile); int generations = freeColClient.getClientOptions().getInteger(ClientOptions.AUTOSAVE_GENERATIONS); if (generations > 0) { allSaveGames.add(saveGameFile); if (allSaveGames.size() > generations) { File fileToDelete = allSaveGames.remove(0); fileToDelete.delete(); } } } } removeUnitsOutsideLOS(); if (currentPlayer.checkEmigrate()) { if (currentPlayer.hasAbility("model.ability.selectRecruit") && currentPlayer.getEurope().recruitablesDiffer()) { emigrateUnitInEurope(freeColClient.getCanvas().showEmigrationPanel()); } else { emigrateUnitInEurope(0); } } if (!freeColClient.isSingleplayer()) { freeColClient.playSound(currentPlayer.getNation().getAnthem()); } checkTradeRoutesInEurope(); displayModelMessages(true); nextActiveUnit(); } logger.finest("Exiting method setCurrentPlayer()"); } /** * Renames a <code>Renameable</code>. * * @param object The object to rename. */ public void rename(Nameable object) { if (!(object instanceof Ownable) || ((Ownable) object).getOwner() != freeColClient.getMyPlayer()) { return; } String name = null; if (object instanceof Colony) { name = freeColClient.getCanvas().showInputDialog("renameColony.text", object.getName(), "renameColony.yes", "renameColony.no"); if (name==null || name.length()==0) { // user canceled return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", "%name%", name); return; } } else if (object instanceof Unit) { name = freeColClient.getCanvas().showInputDialog("renameUnit.text", object.getName(), "renameUnit.yes", "renameUnit.no"); } else { return; } object.setName(name); Element renameElement = Message.createNewRootElement("rename"); renameElement.setAttribute("nameable", ((FreeColGameObject) object).getId()); renameElement.setAttribute("name", name); freeColClient.getClient().sendAndWait(renameElement); } /** * Removes the units we cannot see anymore from the map. */ private void removeUnitsOutsideLOS() { Player player = freeColClient.getMyPlayer(); Map map = freeColClient.getGame().getMap(); player.resetCanSeeTiles(); Iterator<Position> tileIterator = map.getWholeMapIterator(); while (tileIterator.hasNext()) { Tile t = map.getTile(tileIterator.next()); if (t != null && !player.canSee(t) && t.getFirstUnit() != null) { if (t.getFirstUnit().getOwner() == player) { logger.warning("Could not see one of my own units!"); } t.disposeAllUnits(); } } player.resetCanSeeTiles(); } /** * Uses the active unit to build a colony. */ public void buildColony() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); GUI gui = freeColClient.getGUI(); Unit unit = freeColClient.getGUI().getActiveUnit(); if (unit == null || !unit.canBuildColony()) { return; } Tile tile = unit.getTile(); if (tile == null) { return; } if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) { boolean landLocked = true; boolean ownedByEuropeans = false; boolean ownedBySelf = false; boolean ownedByIndians = false; java.util.Map<GoodsType, Integer> goodsMap = new HashMap<GoodsType, Integer>(); for (GoodsType goodsType : FreeCol.getSpecification().getGoodsTypeList()) { if (goodsType.isFoodType()) { int potential = 0; if (tile.primaryGoods() == goodsType) { potential = tile.potential(goodsType); } goodsMap.put(goodsType, new Integer(potential)); } else if (goodsType.isBuildingMaterial()) { while (goodsType.isRefined()) { goodsType = goodsType.getRawMaterial(); } int potential = 0; if (tile.secondaryGoods() == goodsType) { potential = tile.potential(goodsType); } goodsMap.put(goodsType, new Integer(potential)); } } Map map = game.getMap(); Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition()); while (tileIterator.hasNext()) { Tile newTile = map.getTile(tileIterator.next()); if (newTile.isLand()) { for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { entry.setValue(entry.getValue().intValue() + newTile.potential(entry.getKey())); } Player tileOwner = newTile.getOwner(); if (tileOwner == unit.getOwner()) { if (newTile.getOwningSettlement() != null) { // we are using newTile ownedBySelf = true; } else { Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition()); while (ownTileIt.hasNext()) { Colony colony = map.getTile(ownTileIt.next()).getColony(); if (colony != null && colony.getOwner() == unit.getOwner()) { // newTile can be used from an own colony ownedBySelf = true; break; } } } } else if (tileOwner != null && tileOwner.isEuropean()) { ownedByEuropeans = true; } else if (tileOwner != null) { ownedByIndians = true; } } else { landLocked = false; } } int food = 0; for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { if (entry.getKey().isFoodType()) { food += entry.getValue().intValue(); } } ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); if (landLocked) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.fish"), "buildColony.landLocked")); } if (food < 8) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.food"), "buildColony.noFood")); } for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { if (!entry.getKey().isFoodType() && entry.getValue().intValue() < 4) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, entry.getKey(), "buildColony.noBuildingMaterials", "%goods%", entry.getKey().getName())); } } if (ownedBySelf) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.ownLand")); } if (ownedByEuropeans) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.EuropeanLand")); } if (ownedByIndians) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.IndianLand")); } if (messages.size() > 0) { ModelMessage[] modelMessages = messages.toArray(new ModelMessage[0]); if (!freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes", "buildColony.no")) { return; } } } String name = freeColClient.getCanvas().showInputDialog("nameColony.text", freeColClient.getMyPlayer().getDefaultColonyName(), "nameColony.yes", "nameColony.no"); if (name == null) { // The user canceled the action. return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", "%name%", name); return; } Element buildColonyElement = Message.createNewRootElement("buildColony"); buildColonyElement.setAttribute("name", name); buildColonyElement.setAttribute("unit", unit.getId()); Element reply = client.ask(buildColonyElement); if (reply.getTagName().equals("buildColonyConfirmed")) { Element updateElement = getChildElement(reply, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().update(updateElement); } Element colonyElement = (Element) reply.getFirstChild(); Colony colony = (Colony) game.getFreeColGameObject(colonyElement.getAttribute("ID")); if (colony == null) { colony = new Colony(game, colonyElement); } else { colony.readFromXMLElement(colonyElement); } changeWorkType(unit, Goods.FOOD); unit.buildColony(colony); - for(Unit unitInTile : tile.getUnitList()) { + ArrayList<Unit> units = new ArrayList<Unit>(tile.getUnitList()); + for(Unit unitInTile : units) { if (unitInTile.canCarryTreasure()) { checkCashInTreasureTrain(unitInTile); } } gui.setActiveUnit(null); gui.setSelectedTile(colony.getTile().getPosition()); } else { // Handle error message. } } /** * Moves the active unit in a specified direction. This may result in an * attack, move... action. * * @param direction The direction in which to move the Unit. */ public void moveActiveUnit(Direction direction) { Unit unit = freeColClient.getGUI().getActiveUnit(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (unit != null) { clearGotoOrders(unit); move(unit, direction); // centers unit if option "always center" is active // A few checks need to be remade, as the unit may no longer exist //or no longer be on the map boolean alwaysCenter = freeColClient.getClientOptions().getBoolean(ClientOptions.ALWAYS_CENTER); if(alwaysCenter && unit != null && unit.getTile() != null){ Position unitPosition = unit.getTile().getPosition(); freeColClient.getGUI().setFocus(unitPosition); } } // else: nothing: There is no active unit that can be moved. } /** * Selects a destination for this unit. Europe and the player's colonies are * valid destinations. * * @param unit The unit for which to select a destination. */ public void selectDestination(Unit unit) { final Player player = freeColClient.getMyPlayer(); Map map = freeColClient.getGame().getMap(); final ArrayList<ChoiceItem> destinations = new ArrayList<ChoiceItem>(); if (unit.isNaval() && unit.getOwner().canMoveToEurope()) { PathNode path = map.findPathToEurope(unit, unit.getTile()); if (path != null) { int turns = path.getTotalTurns(); destinations.add(new ChoiceItem(player.getEurope() + " (" + turns + ")", player.getEurope())); } else if (unit.getTile() != null && (unit.getTile().getType().canSailToEurope() || map.isAdjacentToMapEdge(unit.getTile()))) { destinations.add(new ChoiceItem(player.getEurope() + " (0)", player.getEurope())); } } final Settlement inSettlement = (unit.getTile() != null) ? unit.getTile().getSettlement() : null; // Search for destinations we can reach: map.search(unit, new GoalDecider() { public PathNode getGoal() { return null; } public boolean check(Unit u, PathNode p) { if (p.getTile().getSettlement() != null && p.getTile().getSettlement().getOwner() == player && p.getTile().getSettlement() != inSettlement) { Settlement s = p.getTile().getSettlement(); int turns = p.getTurns(); destinations.add(new ChoiceItem(s.toString() + " (" + turns + ")", s)); } return false; } public boolean hasSubGoals() { return false; } }, Integer.MAX_VALUE); Canvas canvas = freeColClient.getCanvas(); ChoiceItem choice = (ChoiceItem) canvas .showChoiceDialog(Messages.message("selectDestination.text"), Messages.message("selectDestination.cancel"), destinations.toArray(new ChoiceItem[0])); if (choice == null) { // user aborted return; } Location destination = (Location) choice.getObject(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { setDestination(unit, destination); return; } if (destination instanceof Europe && unit.getTile() != null && (unit.getTile().getType().canSailToEurope() || map.isAdjacentToMapEdge(unit.getTile()))) { moveToEurope(unit); nextActiveUnit(); } else { setDestination(unit, destination); moveToDestination(unit); } } /** * Sets the destination of the given unit and send the server a message for this action. * * @param unit The <code>Unit</code>. * @param destination The <code>Location</code>. * @see Unit#setDestination(Location) */ public void setDestination(Unit unit, Location destination) { Element setDestinationElement = Message.createNewRootElement("setDestination"); setDestinationElement.setAttribute("unit", unit.getId()); if (destination != null) { setDestinationElement.setAttribute("destination", destination.getId()); } unit.setDestination(destination); freeColClient.getClient().sendAndWait(setDestinationElement); } /** * Moves the given unit towards the destination given by * {@link Unit#getDestination()}. * * @param unit The unit to move. */ public void moveToDestination(Unit unit) { final Canvas canvas = freeColClient.getCanvas(); final Map map = freeColClient.getGame().getMap(); final Location destination = unit.getDestination(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { canvas.showInformationMessage("notYourTurn"); return; } // Trade unit is at current stop if (unit.getTradeRoute() != null && unit.getLocation().getTile() == unit.getCurrentStop().getLocation().getTile()){ logger.info("Trade unit " + unit.getId() + " in route " + unit.getTradeRoute().getName() + " is at " + unit.getCurrentStop().getLocation().getLocationName()); followTradeRoute(unit); return; } if(unit.getTradeRoute() != null){ logger.info("Unit " + unit.getId() + " is a trade unit in route " + unit.getTradeRoute().getName() + ", going to " + unit.getCurrentStop().getLocation().getLocationName()); } else logger.info("Moving unit " + unit.getId() + " to position " + unit.getDestination().getLocationName()); PathNode path; if (destination instanceof Europe) { path = map.findPathToEurope(unit, unit.getTile()); } else { if (destination.getTile() == null) { // Destination is an abandoned colony, for example clearGotoOrders(unit); return; } path = map.findPath(unit, unit.getTile(), destination.getTile()); } if (path == null) { canvas.showInformationMessage("selectDestination.failed", unit, "%destination%", destination.getLocationName()); setDestination(unit, null); return; } boolean knownEnemyOnLastTile = path != null && path.getLastNode() != null && ((path.getLastNode().getTile().getFirstUnit() != null && path.getLastNode().getTile().getFirstUnit() .getOwner() != freeColClient.getMyPlayer()) || (path.getLastNode().getTile().getSettlement() != null && path .getLastNode().getTile().getSettlement().getOwner() != freeColClient.getMyPlayer())); while (path != null) { MoveType mt = unit.getMoveType(path.getDirection()); switch (mt) { case MOVE: reallyMove(unit, path.getDirection()); break; case EXPLORE_LOST_CITY_RUMOUR: exploreLostCityRumour(unit, path.getDirection()); if (unit.isDisposed()) return; break; case MOVE_HIGH_SEAS: if (destination instanceof Europe) { moveToEurope(unit); path = null; } else if (path == path.getLastNode()) { move(unit, path.getDirection()); path = null; } else { reallyMove(unit, path.getDirection()); } break; case DISEMBARK: disembark(unit, path.getDirection()); path = null; break; default: if (path == path.getLastNode() && mt != MoveType.ILLEGAL_MOVE && (mt != MoveType.ATTACK || knownEnemyOnLastTile)) { move(unit, path.getDirection()); } else { Tile target = map.getNeighbourOrNull(path.getDirection(), unit.getTile()); int moveCost = unit.getMoveCost(target); if (unit.getMovesLeft() == 0 || (moveCost > unit.getMovesLeft() && (target.getFirstUnit() == null || target.getFirstUnit().getOwner() == unit .getOwner()) && (target.getSettlement() == null || target.getSettlement() .getOwner() == unit.getOwner()))) { // we can't go there now, but we don't want to wake up unit.setMovesLeft(0); nextActiveUnit(); return; } else { // Active unit to show path and permit to move it // manually freeColClient.getGUI().setActiveUnit(unit); return; } } } if (path != null) { path = path.next; } } if (unit.getTile() != null && destination instanceof Europe && map.isAdjacentToMapEdge(unit.getTile())) { moveToEurope(unit); } // we have reached our destination // if in a trade route, unload and update next stop if (unit.getTradeRoute() == null) { setDestination(unit, null); } else{ followTradeRoute(unit); } // Display a "cash in"-dialog if a treasure train have been // moved into a coastal colony: if (unit.canCarryTreasure() && checkCashInTreasureTrain(unit)) { unit = null; } if (unit != null && unit.getMovesLeft() > 0 && unit.getTile() != null) { freeColClient.getGUI().setActiveUnit(unit); } else if (freeColClient.getGUI().getActiveUnit() == unit) { nextActiveUnit(); } return; } private void checkTradeRoutesInEurope() { Europe europe = freeColClient.getMyPlayer().getEurope(); if (europe == null) { return; } List<Unit> units = europe.getUnitList(); for(Unit unit : units) { // Process units that have a trade route and //are actually in Europe, not bound to/from if (unit.getTradeRoute() != null && unit.isInEurope()) { followTradeRoute(unit); } } } private void followTradeRoute(Unit unit) { Stop stop = unit.getCurrentStop(); if (stop == null) { return; } boolean inEurope = unit.isInEurope(); boolean stopIsEurope = (stop.getLocation().getId() == freeColClient.getMyPlayer().getEurope().getId()); // ship has not arrived in europe yet if(stopIsEurope && !inEurope) return; // Unit was already in this location at the beginning of the turn // Allow loading if(unit.getInitialMovesLeft() == unit.getMovesLeft()){ Stop oldStop = unit.getCurrentStop(); if(inEurope) buyTradeGoodsFromEurope(unit); else loadTradeGoodsFromColony(unit); updateCurrentStop(unit); // It may happen that the unit may need to wait // (Not enough goods in warehouse to load yet) if(oldStop.getLocation().getTile() == unit.getCurrentStop().getLocation().getTile()){ unit.setMovesLeft(0); } } else { // Has only just arrived, unload and stop here, //no more moves allowed logger.info("Trade unit " + unit.getId() + " in route " + unit.getTradeRoute().getName() + " arrives at " + unit.getCurrentStop().getLocation().getLocationName()); if(inEurope) sellTradeGoodsInEurope(unit); else unloadTradeGoodsToColony(unit); unit.setMovesLeft(0); } } private void loadTradeGoodsFromColony(Unit unit){ Stop stop = unit.getCurrentStop(); Location location = unit.getColony(); logger.info("Trade unit " + unit.getId() + " loading in " + location.getLocationName()); GoodsContainer warehouse = location.getGoodsContainer(); if (warehouse == null) { throw new IllegalStateException("No warehouse in a stop's location"); } ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo(); Iterator<Goods> goodsIterator = unit.getGoodsIterator(); // First, finish loading partially empty slots while (goodsIterator.hasNext()) { Goods goods = goodsIterator.next(); if (goods.getAmount() < 100) { for (int index = 0; index < goodsTypesToLoad.size(); index++) { GoodsType goodsType = goodsTypesToLoad.get(index); ExportData exportData = unit.getColony().getExportData(goodsType); if (goods.getType() == goodsType) { // complete goods until 100 units // respect the lower limit for TradeRoute int amountPresent = warehouse.getGoodsCount(goodsType) - exportData.getExportLevel(); if (amountPresent > 0) { logger.finest("Automatically loading goods " + goods.getName()); int amountToLoad = Math.min(100 - goods.getAmount(), amountPresent); loadCargo(new Goods(freeColClient.getGame(), location, goods.getType(), amountToLoad), unit); } } // remove item: other items of the same type // may or may not be present goodsTypesToLoad.remove(index); break; } } } // load rest of the cargo that should be on board //while space is available for (GoodsType goodsType : goodsTypesToLoad) { // no more space left if (unit.getSpaceLeft() == 0) { break; } // respect the lower limit for TradeRoute ExportData exportData = unit.getColony().getExportData(goodsType); int amountPresent = warehouse.getGoodsCount(goodsType) - exportData.getExportLevel(); if(amountPresent > 0){ logger.finest("Automatically loading goods " + goodsType.getName()); loadCargo(new Goods(freeColClient.getGame(), location, goodsType, Math.min( amountPresent, 100)), unit); } } } private void unloadTradeGoodsToColony(Unit unit){ Stop stop = unit.getCurrentStop(); Location location = unit.getColony(); logger.info("Trade unit " + unit.getId() + " unloading in " + location.getLocationName()); GoodsContainer warehouse = location.getGoodsContainer(); if (warehouse == null) { throw new IllegalStateException("No warehouse in a stop's location"); } ArrayList<GoodsType> goodsTypesToKeep = stop.getCargo(); Iterator<Goods> goodsIterator = unit.getGoodsIterator(); while (goodsIterator.hasNext()) { Goods goods = goodsIterator.next(); boolean toKeep = false; for (int index = 0; index < goodsTypesToKeep.size(); index++) { GoodsType goodsType = goodsTypesToKeep.get(index); if (goods.getType() == goodsType) { // remove item: other items of the same type // may or may not be present goodsTypesToKeep.remove(index); toKeep = true; break; } } // Cargo should be kept if(toKeep) continue; // do not unload more than the warehouse can store int capacity = ((Colony) location).getWarehouseCapacity() - warehouse.getGoodsCount(goods.getType()); if (capacity < goods.getAmount() && !freeColClient.getCanvas().showConfirmDialog(Messages.message("traderoute.warehouseCapacity", "%unit%", unit.getName(), "%colony%", ((Colony) location).getName(), "%amount%", String.valueOf(goods.getAmount() - capacity), "%goods%", goods.getName()), "yes", "no")) { logger.finest("Automatically unloading " + capacity + " " + goods.getName()); unloadCargo(new Goods(freeColClient.getGame(), unit, goods.getType(), capacity)); } else { logger.finest("Automatically unloading " + goods.getAmount() + " " + goods.getName()); unloadCargo(goods); } } } private void sellTradeGoodsInEurope(Unit unit) { Stop stop = unit.getCurrentStop(); // unload cargo that should not be on board ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo(); Iterator<Goods> goodsIterator = unit.getGoodsIterator(); while (goodsIterator.hasNext()) { Goods goods = goodsIterator.next(); boolean toKeep = false; for (int index = 0; index < goodsTypesToLoad.size(); index++) { GoodsType goodsType = goodsTypesToLoad.get(index); if (goods.getType() == goodsType) { // remove item: other items of the same type // may or may not be present goodsTypesToLoad.remove(index); toKeep = true; break; } } if(toKeep) continue; // this type of goods was not in the cargo list logger.finest("Automatically unloading " + goods.getName()); sellGoods(goods); } } private void buyTradeGoodsFromEurope(Unit unit) { Stop stop = unit.getCurrentStop(); // First, finish loading partially empty slots ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo(); Iterator<Goods> goodsIterator = unit.getGoodsIterator(); while (goodsIterator.hasNext()) { Goods goods = goodsIterator.next(); for (int index = 0; index < goodsTypesToLoad.size(); index++) { GoodsType goodsType = goodsTypesToLoad.get(index); if (goods.getType() == goodsType) { if (goods.getAmount() < 100) { logger.finest("Automatically loading goods " + goods.getName()); buyGoods(goods.getType(), (100 - goods.getAmount()), unit); } // remove item: other items of the same type // may or may not be present goodsTypesToLoad.remove(index); break; } } } // load rest of cargo that should be on board for (GoodsType goodsType : goodsTypesToLoad) { if (unit.getSpaceLeft() > 0) { logger.finest("Automatically loading goods " + goodsType.getName()); buyGoods(goodsType, 100, unit); } } } private void updateCurrentStop(Unit unit) { // Set destination to next stop's location Element updateCurrentStopElement = Message.createNewRootElement("updateCurrentStop"); updateCurrentStopElement.setAttribute("unit", unit.getId()); freeColClient.getClient().sendAndWait(updateCurrentStopElement); Stop stop = unit.nextStop(); // go to next stop, unit can already be there waiting to load if (stop != null && stop.getLocation() != unit.getColony()) { if (unit.isInEurope()) { moveToAmerica(unit); } else { moveToDestination(unit); } } } /** * Moves the specified unit in a specified direction. This may result in an * attack, move... action. * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ public void move(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } // Be certain the tile we are about to move into has been updated by the // server: // Can be removed if we use 'client.ask' when moving: /* * try { while (game.getMap().getNeighbourOrNull(direction, * unit.getTile()) != null && * game.getMap().getNeighbourOrNull(direction, unit.getTile()).getType() == * Tile.UNEXPLORED) { Thread.sleep(5); } } catch (InterruptedException * ie) {} */ MoveType move = unit.getMoveType(direction); switch (move) { case MOVE: reallyMove(unit, direction); break; case ATTACK: attack(unit, direction); break; case DISEMBARK: disembark(unit, direction); break; case EMBARK: embark(unit, direction); break; case MOVE_HIGH_SEAS: moveHighSeas(unit, direction); break; case ENTER_INDIAN_VILLAGE_WITH_SCOUT: scoutIndianSettlement(unit, direction); break; case ENTER_INDIAN_VILLAGE_WITH_MISSIONARY: useMissionary(unit, direction); break; case ENTER_INDIAN_VILLAGE_WITH_FREE_COLONIST: learnSkillAtIndianSettlement(unit, direction); break; case ENTER_FOREIGN_COLONY_WITH_SCOUT: scoutForeignColony(unit, direction); break; case ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS: //TODO: unify trade and negotiations Map map = freeColClient.getGame().getMap(); Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement(); if (settlement instanceof Colony) { negotiate(unit, direction); } else { tradeWithSettlement(unit, direction); } break; case EXPLORE_LOST_CITY_RUMOUR: exploreLostCityRumour(unit, direction); break; case ILLEGAL_MOVE: freeColClient.playSound(SoundEffect.ILLEGAL_MOVE); break; default: throw new RuntimeException("unrecognised move: " + move); } // Display a "cash in"-dialog if a treasure train have been moved into a // colony: if (unit.canCarryTreasure()) { checkCashInTreasureTrain(unit); if (unit.isDisposed()) { nextActiveUnit(); } } nextModelMessage(); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getActionManager().update(); freeColClient.getCanvas().updateJMenuBar(); } }); } /** * Initiates a negotiation with a foreign power. The player * creates a DiplomaticTrade with the NegotiationDialog. The * DiplomaticTrade is sent to the other player. If the other * player accepts the offer, the trade is concluded. If not, this * method returns, since the next offer must come from the other * player. * * @param unit an <code>Unit</code> value * @param direction an <code>int</code> value */ private void negotiate(Unit unit, Direction direction) { Map map = freeColClient.getGame().getMap(); Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement(); Element spyElement = Message.createNewRootElement("spySettlement"); spyElement.setAttribute("unit", unit.getId()); spyElement.setAttribute("direction", String.valueOf(direction)); Element reply = freeColClient.getClient().ask(spyElement); if (reply != null) { settlement.readFromXMLElement((Element) reply.getFirstChild()); } DiplomaticTrade agreement = freeColClient.getCanvas().showNegotiationDialog(unit, settlement, null); if (agreement != null) { unit.setMovesLeft(0); String nation = agreement.getRecipient().getNationAsString(); reply = null; do { Element diplomaticElement = Message.createNewRootElement("diplomaticTrade"); diplomaticElement.setAttribute("unit", unit.getId()); diplomaticElement.setAttribute("direction", String.valueOf(direction)); diplomaticElement.appendChild(agreement.toXMLElement(null, diplomaticElement.getOwnerDocument())); reply = freeColClient.getClient().ask(diplomaticElement); if (reply != null) { String accept = reply.getAttribute("accept"); if ("accept".equals(accept)) { freeColClient.getCanvas().showInformationMessage("negotiationDialog.offerAccepted", "%nation%", nation); agreement.makeTrade(); return; } else { Element childElement = (Element) reply.getFirstChild(); DiplomaticTrade proposal = new DiplomaticTrade(freeColClient.getGame(), childElement); agreement = freeColClient.getCanvas().showNegotiationDialog(unit, settlement, proposal); } } else if (agreement.isAccept()) { // We have accepted the contra-proposal agreement.makeTrade(); return; } } while (reply != null); freeColClient.getCanvas().showInformationMessage("negotiationDialog.offerRejected", "%nation%", nation); } } /** * Enter in a foreign colony to spy it. * * @param unit an <code>Unit</code> value * @param direction an <code>int</code> value */ private void spy(Unit unit, Direction direction) { Game game = freeColClient.getGame(); Colony colony = game.getMap().getNeighbourOrNull(direction, unit.getTile()).getColony(); Element spyElement = Message.createNewRootElement("spySettlement"); spyElement.setAttribute("unit", unit.getId()); spyElement.setAttribute("direction", String.valueOf(direction)); Element reply = freeColClient.getClient().ask(spyElement); if (reply != null) { unit.setMovesLeft(0); NodeList childNodes = reply.getChildNodes(); colony.readFromXMLElement((Element) childNodes.item(0)); Tile tile = colony.getTile(); for(int i=1; i < childNodes.getLength(); i++) { Element unitElement = (Element) childNodes.item(i); Unit foreignUnit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (foreignUnit == null) { foreignUnit = new Unit(game, unitElement); } else { foreignUnit.readFromXMLElement(unitElement); } tile.add(foreignUnit); } freeColClient.getCanvas().showColonyPanel(colony); } } /** * Ask for explore a lost city rumour, and move unit if player accepts * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ private void exploreLostCityRumour(Unit unit, Direction direction) { if (freeColClient.getCanvas().showConfirmDialog("exploreLostCityRumour.text", "exploreLostCityRumour.yes", "exploreLostCityRumour.no")) { reallyMove(unit, direction); } } /** * Buys the given land from the indians. * * @param tile The land which should be bought from the indians. */ public void buyLand(Tile tile) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Element buyLandElement = new BuyLandMessage(tile).toXMLElement(); freeColClient.getMyPlayer().buyLand(tile); freeColClient.getClient().sendAndWait(buyLandElement); freeColClient.getCanvas().updateGoldLabel(); } /** * Steals the given land from the indians. * * @param tile The land which should be stolen from the indians. * @param colony a <code>Colony</code> value */ public void stealLand(Tile tile, Colony colony) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Element stealLandElement = new StealLandMessage(tile, colony).toXMLElement(); freeColClient.getClient().sendAndWait(stealLandElement); tile.takeOwnership(freeColClient.getMyPlayer(), colony); } /** * Uses the given unit to trade with a <code>Settlement</code> in the * given direction. * * @param unit The <code>Unit</code> that is a carrier containing goods. * @param direction The direction the unit could move in order to enter the * <code>Settlement</code>. * @exception IllegalArgumentException if the unit is not a carrier, or if * there is no <code>Settlement</code> in the given * direction. * @see Settlement */ private void tradeWithSettlement(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); Client client = freeColClient.getClient(); if (!unit.isCarrier()) { throw new IllegalArgumentException("The unit has to be a carrier in order to trade!"); } Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement(); if (settlement == null) { throw new IllegalArgumentException("No settlement in given direction!"); } if (unit.getGoodsCount() == 0) { canvas.errorMessage("noGoodsOnboard"); return; } Goods goods = (Goods) canvas.showChoiceDialog(Messages.message("tradeProposition.text"), Messages.message("tradeProposition.cancel"), unit.getGoodsIterator()); if (goods == null) { // == Trade aborted by the player. return; } Element tradePropositionElement = Message.createNewRootElement("tradeProposition"); tradePropositionElement.setAttribute("unit", unit.getId()); tradePropositionElement.setAttribute("settlement", settlement.getId()); tradePropositionElement.appendChild(goods.toXMLElement(null, tradePropositionElement.getOwnerDocument())); Element reply = client.ask(tradePropositionElement); while (reply != null) { if (!reply.getTagName().equals("tradePropositionAnswer")) { logger.warning("Illegal reply."); throw new IllegalStateException(); } int gold = Integer.parseInt(reply.getAttribute("gold")); if (gold == NO_NEED_FOR_THE_GOODS) { canvas.showInformationMessage("noNeedForTheGoods", "%goods%", goods.getName()); return; } else if (gold <= NO_TRADE) { canvas.showInformationMessage("noTrade"); return; } else { String text = Messages.message("trade.text", "%nation%", settlement.getOwner().getNationAsString(), "%goods%", goods.getName(), "%gold%", Integer.toString(gold)); ChoiceItem ci = (ChoiceItem) canvas .showChoiceDialog(text, Messages.message("trade.cancel"), new ChoiceItem(Messages.message("trade.takeOffer"), 1), new ChoiceItem(Messages.message("trade.moreGold"), 2), new ChoiceItem(Messages.message("trade.gift", "%goods%", goods.getName()), 0)); if (ci == null) { // == Trade aborted by the player. return; } int ret = ci.getChoice(); if (ret == 1) { tradeWithSettlement(unit, settlement, goods, gold); return; } else if (ret == 0) { deliverGiftToSettlement(unit, settlement, goods); return; } } // Ask for more gold (ret == 2): tradePropositionElement = Message.createNewRootElement("tradeProposition"); tradePropositionElement.setAttribute("unit", unit.getId()); tradePropositionElement.setAttribute("settlement", settlement.getId()); tradePropositionElement.appendChild(goods.toXMLElement(null, tradePropositionElement.getOwnerDocument())); tradePropositionElement.setAttribute("gold", Integer.toString((gold * 11) / 10)); reply = client.ask(tradePropositionElement); } if (reply == null) { logger.warning("reply == null"); } } /** * Trades the given goods. The goods gets transferred from the given * <code>Unit</code> to the given <code>Settlement</code>, and the * {@link Unit#getOwner unit's owner} collects the payment. */ private void tradeWithSettlement(Unit unit, Settlement settlement, Goods goods, int gold) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element tradeElement = Message.createNewRootElement("trade"); tradeElement.setAttribute("unit", unit.getId()); tradeElement.setAttribute("settlement", settlement.getId()); tradeElement.setAttribute("gold", Integer.toString(gold)); tradeElement.appendChild(goods.toXMLElement(null, tradeElement.getOwnerDocument())); Element reply = client.ask(tradeElement); unit.trade(settlement, goods, gold); freeColClient.getCanvas().updateGoldLabel(); if (reply != null) { if (!reply.getTagName().equals("sellProposition")) { logger.warning("Illegal reply."); throw new IllegalStateException(); } ArrayList<Goods> goodsOffered = new ArrayList<Goods>(); NodeList childNodes = reply.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { goodsOffered.add(new Goods(freeColClient.getGame(), (Element) childNodes.item(i))); } Goods goodsToBuy = (Goods) freeColClient.getCanvas().showChoiceDialog(Messages.message("buyProposition.text"), Messages.message("buyProposition.cancel"), goodsOffered.iterator()); if (goodsToBuy != null) { buyFromSettlement(unit, goodsToBuy); } } nextActiveUnit(unit.getTile()); } /** * Uses the given unit to try buying the given goods from an * <code>IndianSettlement</code>. */ private void buyFromSettlement(Unit unit, Goods goods) { Canvas canvas = freeColClient.getCanvas(); Client client = freeColClient.getClient(); Element buyPropositionElement = Message.createNewRootElement("buyProposition"); buyPropositionElement.setAttribute("unit", unit.getId()); buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument())); Element reply = client.ask(buyPropositionElement); while (reply != null) { if (!reply.getTagName().equals("buyPropositionAnswer")) { logger.warning("Illegal reply."); throw new IllegalStateException(); } int gold = Integer.parseInt(reply.getAttribute("gold")); if (gold <= NO_TRADE) { canvas.showInformationMessage("noTrade"); return; } else { IndianSettlement settlement = (IndianSettlement) goods.getLocation(); String text = Messages.message("buy.text", "%nation%", settlement.getOwner().getNationAsString(), "%goods%", goods.getName(), "%gold%", Integer.toString(gold)); ChoiceItem ci = (ChoiceItem) canvas .showChoiceDialog(text, Messages.message("buy.cancel"), new ChoiceItem(Messages.message("buy.takeOffer"), 1), new ChoiceItem(Messages.message("buy.moreGold"), 2)); if (ci == null) { // == Trade aborted by the player. return; } int ret = ci.getChoice(); if (ret == 1) { buyFromSettlement(unit, goods, gold); return; } } // Ask for more gold (ret == 2): buyPropositionElement = Message.createNewRootElement("buyProposition"); buyPropositionElement.setAttribute("unit", unit.getId()); buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument())); buyPropositionElement.setAttribute("gold", Integer.toString((gold * 9) / 10)); reply = client.ask(buyPropositionElement); } } /** * Trades the given goods. The goods gets transferred from their location * to the given <code>Unit</code>, and the {@link Unit#getOwner unit's owner} * pays the given gold. */ private void buyFromSettlement(Unit unit, Goods goods, int gold) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element buyElement = Message.createNewRootElement("buy"); buyElement.setAttribute("unit", unit.getId()); buyElement.setAttribute("gold", Integer.toString(gold)); buyElement.appendChild(goods.toXMLElement(null, buyElement.getOwnerDocument())); client.ask(buyElement); IndianSettlement settlement = (IndianSettlement) goods.getLocation(); // add goods to settlement in order to client will be able to transfer the goods settlement.add(goods); unit.buy(settlement, goods, gold); freeColClient.getCanvas().updateGoldLabel(); } /** * Trades the given goods. The goods gets transferred from the given * <code>Unit</code> to the given <code>Settlement</code>. */ private void deliverGiftToSettlement(Unit unit, Settlement settlement, Goods goods) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element deliverGiftElement = Message.createNewRootElement("deliverGift"); deliverGiftElement.setAttribute("unit", unit.getId()); deliverGiftElement.setAttribute("settlement", settlement.getId()); deliverGiftElement.appendChild(goods.toXMLElement(null, deliverGiftElement.getOwnerDocument())); client.sendAndWait(deliverGiftElement); unit.deliverGift(settlement, goods); nextActiveUnit(unit.getTile()); } /** * Transfers the gold carried by this unit to the {@link Player owner}. * * @exception IllegalStateException if this unit is not a treasure train. or * if it cannot be cashed in at it's current location. */ private boolean checkCashInTreasureTrain(Unit unit) { Canvas canvas = freeColClient.getCanvas(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { canvas.showInformationMessage("notYourTurn"); return false; } Client client = freeColClient.getClient(); if (unit.canCashInTreasureTrain()) { boolean cash; if (unit.getOwner().getEurope() == null) { canvas.showInformationMessage("cashInTreasureTrain.text.independence", "%nation%", unit.getOwner().getNationAsString()); cash = true; } else { int transportFee = unit.getTransportFee(); String message = (transportFee == 0) ? "cashInTreasureTrain.text.free" : "cashInTreasureTrain.text.pay"; cash = canvas.showConfirmDialog(message, "cashInTreasureTrain.yes", "cashInTreasureTrain.no"); } if (cash) { // Inform the server: Element cashInTreasureTrainElement = Message.createNewRootElement("cashInTreasureTrain"); cashInTreasureTrainElement.setAttribute("unit", unit.getId()); client.sendAndWait(cashInTreasureTrainElement); unit.cashInTreasureTrain(); freeColClient.getCanvas().updateGoldLabel(); return true; } } return false; } /** * Actually moves a unit in a specified direction. * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ private void reallyMove(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Client client = freeColClient.getClient(); // Inform the server: Element moveElement = Message.createNewRootElement("move"); moveElement.setAttribute("unit", unit.getId()); moveElement.setAttribute("direction", direction.toString()); // TODO: server can actually fail (illegal move)! // Play an animation showing the unit movement if (freeColClient.getClientOptions().getBoolean(ClientOptions.DISPLAY_ANIMATIONS)) { new UnitMoveAnimation(canvas, unit, direction).animate(); } // move before ask to server, to be in new tile in case there is a // rumours unit.move(direction); Region region = unit.getTile().getRegion(); if (region!=null && region.isDiscoverable()) { String name = freeColClient.getCanvas().showInputDialog("nameRegion.text", "", "ok", "cancel", "%name%", region.getDisplayName()); moveElement.setAttribute("regionName", name); } // reply is an "update" Element Element reply = client.ask(moveElement); freeColClient.getInGameInputHandler().handle(client.getConnection(), reply); if (reply.hasAttribute("movesSlowed")) { // ship slowed unit.setMovesLeft(unit.getMovesLeft() - Integer.parseInt(reply.getAttribute("movesSlowed"))); Unit slowedBy = (Unit) freeColClient.getGame().getFreeColGameObject(reply.getAttribute("slowedBy")); canvas.showInformationMessage("model.unit.slowed", "%unit%", unit.getName(), "%enemyUnit%", slowedBy.getName(), "%enemyNation%", slowedBy.getOwner().getNationAsString()); } // set location again in order to meet with people player don't see // before move if (!unit.isDisposed()) { unit.setLocation(unit.getTile()); } if (unit.getTile().isLand() && !unit.getOwner().isNewLandNamed()) { String newLandName = canvas.showInputDialog("newLand.text", unit.getOwner().getNewLandName(), "newLand.yes", null); unit.getOwner().setNewLandName(newLandName); Element setNewLandNameElement = Message.createNewRootElement("setNewLandName"); setNewLandNameElement.setAttribute("newLandName", newLandName); client.sendAndWait(setNewLandNameElement); canvas.showEventDialog(EventPanel.FIRST_LANDING); final Player player = freeColClient.getMyPlayer(); final BuildColonyAction bca = (BuildColonyAction) freeColClient.getActionManager() .getFreeColAction(BuildColonyAction.id); final KeyStroke keyStroke = bca.getAccelerator(); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.TUTORIAL, player, "tutorial.buildColony", "%build_colony_key%", FreeColActionUI.getHumanKeyStrokeText(keyStroke), "%build_colony_menu_item%", Messages.message("unit.state.7"), "%orders_menu_item%", Messages.message("menuBar.orders"))); nextModelMessage(); } if (unit.getTile().getSettlement() != null && unit.isCarrier() && unit.getTradeRoute() == null && (unit.getDestination() == null || unit.getDestination().getTile() == unit.getTile())) { canvas.showColonyPanel((Colony) unit.getTile().getSettlement()); } else if (unit.getMovesLeft() <= 0 || unit.isDisposed()) { nextActiveUnit(unit.getTile()); } nextModelMessage(); } /** * Ask for attack or demand a tribute when attacking an indian settlement, * attack in other cases * * @param unit The unit to perform the attack. * @param direction The direction in which to attack. */ private void attack(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Tile target = freeColClient.getGame().getMap().getNeighbourOrNull(direction, unit.getTile()); if (target.getSettlement() != null && target.getSettlement() instanceof IndianSettlement && unit.isArmed()) { IndianSettlement settlement = (IndianSettlement) target.getSettlement(); switch (freeColClient.getCanvas().showArmedUnitIndianSettlementDialog(settlement)) { case INDIAN_SETTLEMENT_ATTACK: if (confirmHostileAction(unit, target) && confirmPreCombat(unit, target)) { reallyAttack(unit, direction); } return; case CANCEL: return; case INDIAN_SETTLEMENT_TRIBUTE: Element demandMessage = Message.createNewRootElement("armedUnitDemandTribute"); demandMessage.setAttribute("unit", unit.getId()); demandMessage.setAttribute("direction", direction.toString()); Element reply = freeColClient.getClient().ask(demandMessage); if (reply != null && reply.getTagName().equals("armedUnitDemandTributeResult")) { String result = reply.getAttribute("result"); if (result.equals("agree")) { String amount = reply.getAttribute("amount"); unit.getOwner().modifyGold(Integer.parseInt(amount)); freeColClient.getCanvas().updateGoldLabel(); freeColClient.getCanvas().showInformationMessage("scoutSettlement.tributeAgree", settlement, "%replace%", amount); } else if (result.equals("disagree")) { freeColClient.getCanvas().showInformationMessage("scoutSettlement.tributeDisagree", settlement); } unit.setMovesLeft(0); } else { logger.warning("Server gave an invalid reply to an armedUnitDemandTribute message"); return; } nextActiveUnit(unit.getTile()); break; default: logger.warning("Incorrect response returned from Canvas.showArmedUnitIndianSettlementDialog()"); return; } } else { if (confirmHostileAction(unit, target) && confirmPreCombat(unit, target)) { reallyAttack(unit, direction); } return; } } /** * Check if an attack results in a transition from peace or cease fire to * war and, if so, warn the player. * * @param attacker The potential attacker. * @param target The target tile. * @return true to attack, false to abort. */ private boolean confirmHostileAction(Unit attacker, Tile target) { if (!attacker.hasAbility("model.ability.piracy")) { Player enemy; if (target.getSettlement() != null) { enemy = target.getSettlement().getOwner(); } else { Unit defender = target.getDefendingUnit(attacker); if (defender == null) { logger.warning("Attacking, but no defender - will try!"); return true; } if (defender.hasAbility("model.ability.piracy")) { // Privateers can be attacked and remain at peace return true; } enemy = defender.getOwner(); } // TODO: this really should not be necessary if (attacker.getOwner().getStance(enemy) == null) { return true; } else { switch (attacker.getOwner().getStance(enemy)) { case CEASE_FIRE: return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.ceaseFire", "model.diplomacy.attack.confirm", "cancel", "%replace%", enemy.getNationAsString()); case PEACE: return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.peace", "model.diplomacy.attack.confirm", "cancel", "%replace%", enemy.getNationAsString()); case ALLIANCE: freeColClient.playSound(SoundEffect.ILLEGAL_MOVE); freeColClient.getCanvas().showInformationMessage("model.diplomacy.attack.alliance", "%replace%", enemy.getNationAsString()); return false; case WAR: logger.finest("Player at war, no confirmation needed"); return true; default: logger.warning("Unknown stance " + attacker.getOwner().getStance(enemy)); return true; } } } else { // Privateers can attack and remain at peace return true; } } /** * If the client options include a pre-combat dialog, allow the user to view * the odds and possibly cancel the attack. * * @param attacker The attacker. * @param target The target tile. * @return true to attack, false to abort. */ private boolean confirmPreCombat(Unit attacker, Tile target) { if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_PRECOMBAT)) { Settlement settlementOrNull = target.getSettlement(); // Don't tell the player how a settlement is defended! Unit defenderOrNull = settlementOrNull != null ? null : target.getDefendingUnit(attacker); return freeColClient.getCanvas().showPreCombatDialog(attacker, defenderOrNull, settlementOrNull); } return true; } /** * Performs an attack in a specified direction. Note that the server handles * the attack calculations here. * * @param unit The unit to perform the attack. * @param direction The direction in which to attack. */ private void reallyAttack(Unit unit, Direction direction) { Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); Tile target = game.getMap().getNeighbourOrNull(direction, unit.getTile()); if (unit.hasAbility("model.ability.bombard") || unit.isNaval()) { freeColClient.playSound(SoundEffect.ARTILLERY); } Element attackElement = Message.createNewRootElement("attack"); attackElement.setAttribute("unit", unit.getId()); attackElement.setAttribute("direction", direction.toString()); // Get the result of the attack from the server: Element attackResultElement = client.ask(attackElement); if (attackResultElement != null && attackResultElement.getTagName().equals("attackResult")) { // process the combat result CombatResultType result = Enum.valueOf(CombatResultType.class, attackResultElement.getAttribute("result")); int damage = Integer.parseInt(attackResultElement.getAttribute("damage")); int plunderGold = Integer.parseInt(attackResultElement.getAttribute("plunderGold")); // If a successful attack against a colony, we need to update the // tile: Element utElement = getChildElement(attackResultElement, Tile.getXMLElementTagName()); if (utElement != null) { Tile updateTile = (Tile) game.getFreeColGameObject(utElement.getAttribute("ID")); updateTile.readFromXMLElement(utElement); } // If there are captured goods, add to unit NodeList capturedGoods = attackResultElement.getElementsByTagName("capturedGoods"); for (int i = 0; i < capturedGoods.getLength(); ++i) { Element goods = (Element) capturedGoods.item(i); GoodsType type = FreeCol.getSpecification().getGoodsType(goods.getAttribute("type")); int amount = Integer.parseInt(goods.getAttribute("amount")); unit.getGoodsContainer().addGoods(type, amount); } // Get the defender: Element unitElement = getChildElement(attackResultElement, Unit.getXMLElementTagName()); Unit defender; if (unitElement != null) { defender = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (defender == null) { defender = new Unit(game, unitElement); } else { defender.readFromXMLElement(unitElement); } defender.setLocation(target); } else { // TODO: Erik - ensure this cannot happen! logger.log(Level.SEVERE, "Server reallyAttack did not return a defender!"); defender = target.getDefendingUnit(unit); if (defender == null) { throw new IllegalStateException("No defender available!"); } } if (!unit.isNaval()) { Unit winner; if (result == CombatResultType.WIN || result == CombatResultType.GREAT_WIN) { winner = unit; } else { winner = defender; } if (winner.isArmed()) { if (winner.isMounted()) { if (winner.getOwner().isIndian()) { freeColClient.playSound(SoundEffect.MUSKETS_HORSES); } else { freeColClient.playSound(SoundEffect.DRAGOON); } } else { freeColClient.playSound(SoundEffect.ATTACK); } } else if (winner.isMounted()) { freeColClient.playSound(SoundEffect.DRAGOON); } } else { if (result == CombatResultType.GREAT_WIN || result == CombatResultType.GREAT_LOSS) { freeColClient.playSound(SoundEffect.SUNK); } } try { game.getCombatModel().attack(unit, defender, new CombatResult(result, damage), plunderGold); } catch (Exception e) { // Ignore the exception (the update further down will fix any // problems). LogRecord lr = new LogRecord(Level.WARNING, "Exception in reallyAttack"); lr.setThrown(e); logger.log(lr); } // Get the convert: Element convertElement = getChildElement(attackResultElement, "convert"); Unit convert; if (convertElement != null) { unitElement = (Element) convertElement.getFirstChild(); convert = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (convert == null) { convert = new Unit(game, unitElement); } else { convert.readFromXMLElement(unitElement); } convert.setLocation(convert.getLocation()); String nation = defender.getOwner().getNationAsString(); ModelMessage message = new ModelMessage(convert, "model.unit.newConvertFromAttack", new String[][] {{"%nation%", nation}}, ModelMessage.MessageType.UNIT_ADDED); freeColClient.getMyPlayer().addModelMessage(message); nextModelMessage(); } if (defender.canCarryTreasure() && (result == CombatResultType.WIN || result == CombatResultType.GREAT_WIN)) { checkCashInTreasureTrain(defender); } if (!defender.isDisposed() && ((result == CombatResultType.DONE_SETTLEMENT && unitElement != null) || defender.getLocation() == null || !defender.isVisibleTo(freeColClient.getMyPlayer()))) { defender.dispose(); } Element updateElement = getChildElement(attackResultElement, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().handle(client.getConnection(), updateElement); } if (unit.getMovesLeft() <= 0) { nextActiveUnit(unit.getTile()); } freeColClient.getCanvas().refresh(); } else { logger.log(Level.SEVERE, "Server returned null from reallyAttack!"); } } /** * Disembarks the specified unit in a specified direction. * * @param unit The unit to be disembarked. * @param direction The direction in which to disembark the Unit. */ private void disembark(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } // Make sure it is a carrier. if (!unit.isCarrier()) { throw new RuntimeException("Programming error: disembark called on non carrier."); } // Check if user wants to disembark. Canvas canvas = freeColClient.getCanvas(); if (!canvas.showConfirmDialog("disembark.text", "disembark.yes", "disembark.no")) { return; } Game game = freeColClient.getGame(); Tile destinationTile = game.getMap().getNeighbourOrNull(direction, unit.getTile()); unit.setStateToAllChildren(UnitState.ACTIVE); // Disembark only the first unit. Unit toDisembark = unit.getFirstUnit(); if (toDisembark.getMovesLeft() > 0) { if (destinationTile.hasLostCityRumour()) { exploreLostCityRumour(toDisembark, direction); } else { reallyMove(toDisembark, direction); } } } /** * Embarks the specified unit in a specified direction. * * @param unit The unit to be embarked. * @param direction The direction in which to embark the Unit. */ private void embark(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Game game = freeColClient.getGame(); Client client = freeColClient.getClient(); GUI gui = freeColClient.getGUI(); Canvas canvas = freeColClient.getCanvas(); // Animate the units movement new UnitMoveAnimation(canvas, unit, direction).animate(); Tile destinationTile = game.getMap().getNeighbourOrNull(direction, unit.getTile()); Unit destinationUnit = null; if (destinationTile.getUnitCount() == 1) { destinationUnit = destinationTile.getFirstUnit(); } else { ArrayList<Unit> choices = new ArrayList<Unit>(); for (Unit nextUnit : destinationTile.getUnitList()) { if (nextUnit.getSpaceLeft() >= unit.getType().getSpaceTaken()) { choices.add(nextUnit); } } if (choices.size() == 1) { destinationUnit = choices.get(0); } else if (choices.size() == 0) { throw new IllegalStateException(); } else { destinationUnit = (Unit) canvas.showChoiceDialog(Messages.message("embark.text"), Messages .message("embark.cancel"), choices.iterator()); if (destinationUnit == null) { // == user cancelled return; } } } unit.embark(destinationUnit); if (destinationUnit.getMovesLeft() > 0) { gui.setActiveUnit(destinationUnit); } else { nextActiveUnit(destinationUnit.getTile()); } Element embarkElement = Message.createNewRootElement("embark"); embarkElement.setAttribute("unit", unit.getId()); embarkElement.setAttribute("direction", direction.toString()); embarkElement.setAttribute("embarkOnto", destinationUnit.getId()); client.sendAndWait(embarkElement); } /** * Boards a specified unit onto a carrier. The carrier should be at the same * tile as the boarding unit. * * @param unit The unit who is going to board the carrier. * @param carrier The carrier. * @return <i>true</i> if the <code>unit</code> actually gets on the * <code>carrier</code>. */ public boolean boardShip(Unit unit, Unit carrier) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); throw new IllegalStateException("Not your turn."); } if (unit == null) { logger.warning("unit == null"); return false; } if (carrier == null) { logger.warning("Trying to load onto a non-existent carrier."); return false; } Client client = freeColClient.getClient(); if (unit.isCarrier()) { logger.warning("Trying to load a carrier onto another carrier."); return false; } freeColClient.playSound(SoundEffect.LOAD_CARGO); Element boardShipElement = Message.createNewRootElement("boardShip"); boardShipElement.setAttribute("unit", unit.getId()); boardShipElement.setAttribute("carrier", carrier.getId()); unit.boardShip(carrier); client.sendAndWait(boardShipElement); return true; } /** * Clear the speciality of a <code>Unit</code>. That is, makes it a * <code>Unit.FREE_COLONIST</code>. * * @param unit The <code>Unit</code> to clear the speciality of. */ public void clearSpeciality(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element clearSpecialityElement = Message.createNewRootElement("clearSpeciality"); clearSpecialityElement.setAttribute("unit", unit.getId()); unit.clearSpeciality(); client.sendAndWait(clearSpecialityElement); } /** * Leave a ship. This method should only be invoked if the ship is in a * harbour. * * @param unit The unit who is going to leave the ship where it is located. */ public void leaveShip(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); unit.leaveShip(); Element leaveShipElement = Message.createNewRootElement("leaveShip"); leaveShipElement.setAttribute("unit", unit.getId()); client.sendAndWait(leaveShipElement); } /** * Loads a cargo onto a carrier. * * @param goods The goods which are going aboard the carrier. * @param carrier The carrier. */ public void loadCargo(Goods goods, Unit carrier) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (carrier == null) { throw new NullPointerException(); } freeColClient.playSound(SoundEffect.LOAD_CARGO); Client client = freeColClient.getClient(); goods.adjustAmount(); Element loadCargoElement = Message.createNewRootElement("loadCargo"); loadCargoElement.setAttribute("carrier", carrier.getId()); loadCargoElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), loadCargoElement .getOwnerDocument())); goods.loadOnto(carrier); client.sendAndWait(loadCargoElement); } /** * Unload cargo. If the unit carrying the cargo is not in a * harbour, the goods will be dumped. * * @param goods The goods which are going to leave the ship where it is * located. */ public void unloadCargo(Goods goods) { unloadCargo(goods, false); } /** * Unload cargo. If the unit carrying the cargo is not in a * harbour, or if the given boolean is true, the goods will be * dumped. * * @param goods The goods which are going to leave the ship where it is * located. * @param dump a <code>boolean</code> value */ public void unloadCargo(Goods goods, boolean dump) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); goods.adjustAmount(); Element unloadCargoElement = Message.createNewRootElement("unloadCargo"); unloadCargoElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), unloadCargoElement .getOwnerDocument())); if (!dump && goods.getLocation() instanceof Unit && ((Unit) goods.getLocation()).getColony() != null) { goods.unload(); } else { goods.setLocation(null); } client.sendAndWait(unloadCargoElement); } /** * Buys goods in Europe. The amount of goods is adjusted if there is lack of * space in the <code>carrier</code>. * * @param type The type of goods to buy. * @param amount The amount of goods to buy. * @param carrier The carrier. */ public void buyGoods(GoodsType type, int amount, Unit carrier) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player myPlayer = freeColClient.getMyPlayer(); Canvas canvas = freeColClient.getCanvas(); if (carrier == null) { throw new NullPointerException(); } if (carrier.getOwner() != myPlayer || (carrier.getSpaceLeft() <= 0 && (carrier.getGoodsContainer().getGoodsCount(type) % 100 == 0))) { return; } if (carrier.getSpaceLeft() <= 0) { amount = Math.min(amount, 100 - carrier.getGoodsContainer().getGoodsCount(type) % 100); } if (myPlayer.getMarket().getBidPrice(type, amount) > myPlayer.getGold()) { canvas.errorMessage("notEnoughGold"); return; } freeColClient.playSound(SoundEffect.LOAD_CARGO); Element buyGoodsElement = Message.createNewRootElement("buyGoods"); buyGoodsElement.setAttribute("carrier", carrier.getId()); buyGoodsElement.setAttribute("type", type.getId()); buyGoodsElement.setAttribute("amount", Integer.toString(amount)); carrier.buyGoods(type, amount); freeColClient.getCanvas().updateGoldLabel(); client.sendAndWait(buyGoodsElement); } /** * Sells goods in Europe. * * @param goods The goods to be sold. */ public void sellGoods(Goods goods) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player player = freeColClient.getMyPlayer(); freeColClient.playSound(SoundEffect.SELL_CARGO); goods.adjustAmount(); Element sellGoodsElement = Message.createNewRootElement("sellGoods"); sellGoodsElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), sellGoodsElement .getOwnerDocument())); player.getMarket().sell(goods, player); freeColClient.getCanvas().updateGoldLabel(); client.sendAndWait(sellGoodsElement); } /** * Sets the export settings of the custom house. * * @param colony The colony with the custom house. * @param goodsType The goods for which to set the settings. */ public void setGoodsLevels(Colony colony, GoodsType goodsType) { Client client = freeColClient.getClient(); ExportData data = colony.getExportData(goodsType); Element setGoodsLevelsElement = Message.createNewRootElement("setGoodsLevels"); setGoodsLevelsElement.setAttribute("colony", colony.getId()); setGoodsLevelsElement.appendChild(data.toXMLElement(colony.getOwner(), setGoodsLevelsElement .getOwnerDocument())); client.sendAndWait(setGoodsLevelsElement); } /** * Equips or unequips a <code>Unit</code> with a certain type of * <code>Goods</code>. * * @param unit The <code>Unit</code>. * @param type an <code>EquipmentType</code> value * @param amount How many of these goods the unit should have. */ public void equipUnit(Unit unit, EquipmentType type, int amount) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (amount == 0) { // no changes return; } Client client = freeColClient.getClient(); Player myPlayer = freeColClient.getMyPlayer(); Unit carrier = null; if (unit.getLocation() instanceof Unit) { carrier = (Unit) unit.getLocation(); leaveShip(unit); } Element equipUnitElement = Message.createNewRootElement("equipUnit"); equipUnitElement.setAttribute("unit", unit.getId()); equipUnitElement.setAttribute("type", type.getId()); equipUnitElement.setAttribute("amount", Integer.toString(amount)); if (amount > 0) { for (AbstractGoods requiredGoods : type.getGoodsRequired()) { GoodsType goodsType = requiredGoods.getType(); if (unit.isInEurope()) { if (!myPlayer.canTrade(goodsType)) { payArrears(goodsType); if (!myPlayer.canTrade(goodsType)) { return; // The user cancelled the action. } } } } for (int count = 0; count < amount; count++) { unit.equipWith(type); } } else { for (int count = 0; count > amount; count--) { unit.removeEquipment(type); } } freeColClient.getCanvas().updateGoldLabel(); client.sendAndWait(equipUnitElement); if (unit.getLocation() instanceof Colony || unit.getLocation() instanceof Building || unit.getLocation() instanceof ColonyTile) { putOutsideColony(unit); } else if (carrier != null) { boardShip(unit, carrier); } } /** * Moves a <code>Unit</code> to a <code>WorkLocation</code>. * * @param unit The <code>Unit</code>. * @param workLocation The <code>WorkLocation</code>. */ public void work(Unit unit, WorkLocation workLocation) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element workElement = Message.createNewRootElement("work"); workElement.setAttribute("unit", unit.getId()); workElement.setAttribute("workLocation", workLocation.getId()); unit.work(workLocation); client.sendAndWait(workElement); } /** * Puts the specified unit outside the colony. * * @param unit The <code>Unit</code> * @return <i>true</i> if the unit was successfully put outside the colony. */ public boolean putOutsideColony(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); throw new IllegalStateException("Not your turn."); } Element putOutsideColonyElement = Message.createNewRootElement("putOutsideColony"); putOutsideColonyElement.setAttribute("unit", unit.getId()); unit.putOutsideColony(); Client client = freeColClient.getClient(); client.sendAndWait(putOutsideColonyElement); return true; } /** * Changes the work type of this <code>Unit</code>. * * @param unit The <code>Unit</code> * @param workType The new <code>GoodsType</code> to produce. */ public void changeWorkType(Unit unit, GoodsType workType) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element changeWorkTypeElement = Message.createNewRootElement("changeWorkType"); changeWorkTypeElement.setAttribute("unit", unit.getId()); changeWorkTypeElement.setAttribute("workType", workType.getId()); unit.setWorkType(workType); client.sendAndWait(changeWorkTypeElement); } /** * Changes the work type of this <code>Unit</code>. * * @param unit The <code>Unit</code> * @param improvementType a <code>TileImprovementType</code> value */ public void changeWorkType(Unit unit, TileImprovementType improvementType) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Element changeWorkTypeElement = Message.createNewRootElement("workImprovement"); changeWorkTypeElement.setAttribute("unit", unit.getId()); changeWorkTypeElement.setAttribute("improvementType", improvementType.getId()); Element reply = freeColClient.getClient().ask(changeWorkTypeElement); Element containerElement = getChildElement(reply, TileItemContainer.getXMLElementTagName()); if (containerElement != null) { TileItemContainer container = (TileItemContainer) freeColClient.getGame() .getFreeColGameObject(containerElement.getAttribute("ID")); if (container == null) { container = new TileItemContainer(freeColClient.getGame(), unit.getTile(), containerElement); unit.getTile().setTileItemContainer(container); } else { container.readFromXMLElement(containerElement); } } Element improvementElement = getChildElement(reply, TileImprovement.getXMLElementTagName()); if (improvementElement != null) { TileImprovement improvement = (TileImprovement) freeColClient.getGame() .getFreeColGameObject(improvementElement.getAttribute("ID")); if (improvement == null) { improvement = new TileImprovement(freeColClient.getGame(), improvementElement); unit.getTile().add(improvement); } else { improvement.readFromXMLElement(improvementElement); } unit.work(improvement); } } /** * Assigns a unit to a teacher <code>Unit</code>. * * @param student an <code>Unit</code> value * @param teacher an <code>Unit</code> value */ public void assignTeacher(Unit student, Unit teacher) { Player player = freeColClient.getMyPlayer(); if (freeColClient.getGame().getCurrentPlayer() != player) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (!student.canBeStudent(teacher)) { throw new IllegalStateException("Unit can not be student!"); } if (!teacher.getColony().canTrain(teacher)) { throw new IllegalStateException("Unit can not be teacher!"); } if (student.getOwner() != player) { throw new IllegalStateException("Student is not your unit!"); } if (teacher.getOwner() != player) { throw new IllegalStateException("Teacher is not your unit!"); } if (student.getColony() != teacher.getColony()) { throw new IllegalStateException("Student and teacher are not in the same colony!"); } if (!(student.getLocation() instanceof WorkLocation)) { throw new IllegalStateException("Student is not in a WorkLocation!"); } Element assignTeacherElement = Message.createNewRootElement("assignTeacher"); assignTeacherElement.setAttribute("student", student.getId()); assignTeacherElement.setAttribute("teacher", teacher.getId()); if (student.getTeacher() != null) { student.getTeacher().setStudent(null); } student.setTeacher(teacher); if (teacher.getStudent() != null) { teacher.getStudent().setTeacher(null); } teacher.setStudent(student); freeColClient.getClient().sendAndWait(assignTeacherElement); } /** * Changes the current construction project of a <code>Colony</code>. * * @param colony The <code>Colony</code> * @param type The new type of building to build. */ public void setCurrentlyBuilding(Colony colony, BuildableType type) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); colony.setCurrentlyBuilding(type); Element setCurrentlyBuildingElement = Message.createNewRootElement("setCurrentlyBuilding"); setCurrentlyBuildingElement.setAttribute("colony", colony.getId()); setCurrentlyBuildingElement.setAttribute("type", type.getId()); client.sendAndWait(setCurrentlyBuildingElement); } /** * Changes the state of this <code>Unit</code>. * * @param unit The <code>Unit</code> * @param state The state of the unit. */ public void changeState(Unit unit, UnitState state) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); Canvas canvas = freeColClient.getCanvas(); if (!(unit.checkSetState(state))) { return; // Don't bother (and don't log, this is not exceptional) } if (state == UnitState.IMPROVING) { int price = unit.getOwner().getLandPrice(unit.getTile()); if (price > 0) { Player nation = unit.getTile().getOwner(); ChoiceItem ci = (ChoiceItem) canvas .showChoiceDialog(Messages.message("indianLand.text", "%player%", nation.getName()), Messages.message("indianLand.cancel"), new ChoiceItem(Messages.message("indianLand.pay" ,"%amount%", Integer.toString(price)), 1), new ChoiceItem(Messages.message("indianLand.take"), 2)); if (ci == null) { return; } else if (ci.getChoice() == 1) { if (price > freeColClient.getMyPlayer().getGold()) { canvas.errorMessage("notEnoughGold"); return; } buyLand(unit.getTile()); } } } else if (state == UnitState.FORTIFYING && unit.isOffensiveUnit() && !unit.hasAbility("model.ability.piracy")) { // check if it's going to occupy a work tile Tile tile = unit.getTile(); if (tile != null && tile.getOwningSettlement() != null) { // check stance with settlement's owner Player myPlayer = unit.getOwner(); Player enemy = tile.getOwningSettlement().getOwner(); if (myPlayer != enemy && myPlayer.getStance(enemy) != Stance.ALLIANCE && !confirmHostileAction(unit, tile.getOwningSettlement().getTile())) { // player has aborted return; } } } unit.setState(state); // NOTE! The call to nextActiveUnit below can lead to the dreaded // "not your turn" error, so let's finish networking first. Element changeStateElement = Message.createNewRootElement("changeState"); changeStateElement.setAttribute("unit", unit.getId()); changeStateElement.setAttribute("state", state.toString()); client.sendAndWait(changeStateElement); if (!freeColClient.getCanvas().isShowingSubPanel() && (unit.getMovesLeft() == 0 || unit.getState() == UnitState.SENTRY || unit.getState() == UnitState.SKIPPED)) { nextActiveUnit(); } else { freeColClient.getCanvas().refresh(); } } /** * Clears the orders of the given <code>Unit</code> The orders are cleared * by making the unit {@link UnitState#ACTIVE} and setting a null destination * * @param unit The <code>Unit</code>. */ public void clearOrders(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (unit == null) { return; } /* * report to server, in order not to restore destination if it's * received in a update message */ clearGotoOrders(unit); assignTradeRoute(unit, TradeRoute.NO_TRADE_ROUTE); changeState(unit, UnitState.ACTIVE); } /** * Clears the orders of the given <code>Unit</code>. The orders are * cleared by making the unit {@link UnitState#ACTIVE}. * * @param unit The <code>Unit</code>. */ public void clearGotoOrders(Unit unit) { if (unit == null) { return; } /* * report to server, in order not to restore destination if it's * received in a update message */ if (unit.getDestination() != null) setDestination(unit, null); } /** * Moves the specified unit in the "high seas" in a specified direction. * This may result in an ordinary move, no move or a move to europe. * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ private void moveHighSeas(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); // getTile() == null : Unit in europe if (!unit.isAlreadyOnHighSea() && (unit.getTile() == null || canvas.showConfirmDialog("highseas.text", "highseas.yes", "highseas.no"))) { moveToEurope(unit); nextActiveUnit(); } else if (map.getNeighbourOrNull(direction, unit.getTile()) != null) { reallyMove(unit, direction); } } /** * Moves the specified free colonist into an Indian settlement to learn a * skill. Of course, the colonist won't physically get into the village, it * will just stay where it is and gain the skill. * * @param unit The unit to learn the skill. * @param direction The direction in which the Indian settlement lies. */ private void learnSkillAtIndianSettlement(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()) .getSettlement(); if (settlement.getLearnableSkill() != null || !settlement.hasBeenVisited()) { unit.setMovesLeft(0); String skillName; Element askSkill = Message.createNewRootElement("askSkill"); askSkill.setAttribute("unit", unit.getId()); askSkill.setAttribute("direction", direction.toString()); Element reply = client.ask(askSkill); UnitType skill = null; if (reply.getTagName().equals("provideSkill")) { String skillStr = reply.getAttribute("skill"); if (skillStr == null) { skillName = null; } else { skill = FreeCol.getSpecification().getUnitType(skillStr); skillName = skill.getName(); } } else { logger.warning("Server gave an invalid reply to an askSkill message"); return; } settlement.setLearnableSkill(skill); settlement.setVisited(unit.getOwner()); if (skillName == null) { canvas.errorMessage("indianSettlement.noMoreSkill"); } else if (!unit.getType().canBeUpgraded(skill, UnitType.UpgradeType.NATIVES)) { canvas.showInformationMessage("indianSettlement.cantLearnSkill", settlement, "%unit%", unit.getName(), "%skill%", skillName); } else { Element learnSkill = Message.createNewRootElement("learnSkillAtSettlement"); learnSkill.setAttribute("unit", unit.getId()); learnSkill.setAttribute("direction", direction.toString()); if (!canvas.showConfirmDialog("learnSkill.text", "learnSkill.yes", "learnSkill.no", "%replace%", skillName)) { // the player declined to learn the skill learnSkill.setAttribute("action", "cancel"); } Element reply2 = freeColClient.getClient().ask(learnSkill); String result = reply2.getAttribute("result"); if (result.equals("die")) { unit.dispose(); canvas.showInformationMessage("learnSkill.die"); } else if (result.equals("leave")) { canvas.showInformationMessage("learnSkill.leave"); } else if (result.equals("success")) { unit.setType(skill); if (!settlement.isCapital()) settlement.setLearnableSkill(null); } else if (result.equals("cancelled")) { // do nothing } else { logger.warning("Server gave an invalid reply to an learnSkillAtSettlement message"); } } } else if (unit.getDestination() != null) { setDestination(unit, null); } nextActiveUnit(unit.getTile()); } /** * Ask for spy the foreign colony, negotiate with the foreign power * or attack the colony * * @param unit The unit that will spy, negotiate or attack. * @param direction The direction in which the foreign colony lies. */ private void scoutForeignColony(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); Tile tile = map.getNeighbourOrNull(direction, unit.getTile()); Colony colony = tile.getColony(); ScoutAction userAction = canvas.showScoutForeignColonyDialog(colony, unit); switch (userAction) { case CANCEL: break; case FOREIGN_COLONY_ATTACK: attack(unit, direction); break; case FOREIGN_COLONY_NEGOTIATE: negotiate(unit, direction); break; case FOREIGN_COLONY_SPY: spy(unit, direction); break; default: logger.warning("Incorrect response returned from Canvas.showScoutForeignColonyDialog()"); return; } } /** * Moves the specified scout into an Indian settlement to speak with the * chief or demand a tribute etc. Of course, the scout won't physically get * into the village, it will just stay where it is. * * @param unit The unit that will speak, attack or ask tribute. * @param direction The direction in which the Indian settlement lies. */ private void scoutIndianSettlement(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); Tile tile = map.getNeighbourOrNull(direction, unit.getTile()); IndianSettlement settlement = (IndianSettlement) tile.getSettlement(); // The scout loses his moves because the skill data and tradeable goods // data is fetched // from the server and the moves are the price we have to pay to obtain // that data. unit.setMovesLeft(0); Element scoutMessage = Message.createNewRootElement("scoutIndianSettlement"); scoutMessage.setAttribute("unit", unit.getId()); scoutMessage.setAttribute("direction", direction.toString()); scoutMessage.setAttribute("action", "basic"); Element reply = client.ask(scoutMessage); if (reply.getTagName().equals("scoutIndianSettlementResult")) { UnitType skill = null; String skillStr = reply.getAttribute("skill"); // TODO: find out how skillStr can be empty if (skillStr != null && !skillStr.equals("")) { skill = FreeCol.getSpecification().getUnitType(skillStr); } settlement.setLearnableSkill(skill); settlement.setWantedGoods(0, FreeCol.getSpecification().getGoodsType(reply.getAttribute("highlyWantedGoods"))); settlement.setWantedGoods(1, FreeCol.getSpecification().getGoodsType(reply.getAttribute("wantedGoods1"))); settlement.setWantedGoods(2, FreeCol.getSpecification().getGoodsType(reply.getAttribute("wantedGoods2"))); settlement.setVisited(unit.getOwner()); settlement.getOwner().setNumberOfSettlements(Integer.parseInt(reply.getAttribute("numberOfCamps"))); freeColClient.getInGameInputHandler().update(reply); } else { logger.warning("Server gave an invalid reply to an askSkill message"); return; } ScoutAction userAction = canvas.showScoutIndianSettlementDialog(settlement); switch (userAction) { case INDIAN_SETTLEMENT_ATTACK: scoutMessage.setAttribute("action", "attack"); // The movesLeft has been set to 0 when the scout initiated its // action.If it wants to attack then it can and it will need some // moves to do it. unit.setMovesLeft(1); client.sendAndWait(scoutMessage); // TODO: Check if this dialog is needed, one has just been displayed if (confirmPreCombat(unit, tile)) { reallyAttack(unit, direction); } return; case CANCEL: scoutMessage.setAttribute("action", "cancel"); client.sendAndWait(scoutMessage); return; case INDIAN_SETTLEMENT_SPEAK: scoutMessage.setAttribute("action", "speak"); reply = client.ask(scoutMessage); break; case INDIAN_SETTLEMENT_TRIBUTE: scoutMessage.setAttribute("action", "tribute"); reply = client.ask(scoutMessage); break; default: logger.warning("Incorrect response returned from Canvas.showScoutIndianSettlementDialog()"); return; } if (reply.getTagName().equals("scoutIndianSettlementResult")) { String result = reply.getAttribute("result"), action = scoutMessage.getAttribute("action"); if (result.equals("die")) { // unit killed unit.dispose(); canvas.showInformationMessage("scoutSettlement.speakDie", settlement); } else if (action.equals("speak") && result.equals("tales")) { // receive an update of the surrounding tiles. Element updateElement = getChildElement(reply, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().handle(client.getConnection(), updateElement); } canvas.showInformationMessage("scoutSettlement.speakTales", settlement); } else if (action.equals("speak") && result.equals("beads")) { // receive a small gift of gold String amount = reply.getAttribute("amount"); unit.getOwner().modifyGold(Integer.parseInt(amount)); freeColClient.getCanvas().updateGoldLabel(); canvas.showInformationMessage("scoutSettlement.speakBeads", settlement, "%replace%", amount); } else if (action.equals("speak") && result.equals("nothing")) { // nothing special canvas.showInformationMessage("scoutSettlement.speakNothing", settlement); } else if (action.equals("tribute") && result.equals("agree")) { // receive a tribute String amount = reply.getAttribute("amount"); unit.getOwner().modifyGold(Integer.parseInt(amount)); freeColClient.getCanvas().updateGoldLabel(); canvas.showInformationMessage("scoutSettlement.tributeAgree", settlement, "%replace%", amount); } else if (action.equals("tribute") && result.equals("disagree")) { // no tribute canvas.showInformationMessage("scoutSettlement.tributeDisagree", settlement); } } else { logger.warning("Server gave an invalid reply to an scoutIndianSettlement message"); return; } nextActiveUnit(unit.getTile()); } /** * Moves a missionary into an indian settlement. * * @param unit The unit that will enter the settlement. * @param direction The direction in which the Indian settlement lies. */ private void useMissionary(Unit unit, Direction direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()) .getSettlement(); List<Object> response = canvas.showUseMissionaryDialog(settlement); MissionaryAction action = (MissionaryAction) response.get(0); Element missionaryMessage = Message.createNewRootElement("missionaryAtSettlement"); missionaryMessage.setAttribute("unit", unit.getId()); missionaryMessage.setAttribute("direction", direction.toString()); Element reply = null; unit.setMovesLeft(0); String success = ""; switch (action) { case CANCEL: missionaryMessage.setAttribute("action", "cancel"); client.sendAndWait(missionaryMessage); break; case ESTABLISH_MISSION: missionaryMessage.setAttribute("action", "establish"); reply = client.ask(missionaryMessage); if (!reply.getTagName().equals("missionaryReply")) { logger.warning("Server gave an invalid reply to a missionaryAtSettlement message"); return; } success = reply.getAttribute("success"); Tension.Level tension = Tension.Level.valueOf(reply.getAttribute("tension")); String missionResponse = null; String[] data = new String [] {"%nation%",settlement.getOwner().getNationAsString() }; if (success.equals("true")) { settlement.setMissionary(unit); missionResponse = settlement.getResponseToMissionaryAttempt(tension, success); canvas.showInformationMessage(missionResponse,settlement,data); } else{ missionResponse = settlement.getResponseToMissionaryAttempt(tension, success); canvas.showInformationMessage(missionResponse,settlement,data); unit.dispose(); } nextActiveUnit(); // At this point: unit.getTile() == null return; case DENOUNCE_HERESY: missionaryMessage.setAttribute("action", "heresy"); reply = client.ask(missionaryMessage); if (!reply.getTagName().equals("missionaryReply")) { logger.warning("Server gave an invalid reply to a missionaryAtSettlement message"); return; } success = reply.getAttribute("success"); if (success.equals("true")) { settlement.setMissionary(unit); nextActiveUnit(); // At this point: unit.getTile() == null } else { unit.dispose(); nextActiveUnit(); // At this point: unit == null } return; case INCITE_INDIANS: missionaryMessage.setAttribute("action", "incite"); missionaryMessage.setAttribute("incite", ((Player) response.get(1)).getId()); reply = client.ask(missionaryMessage); if (reply.getTagName().equals("missionaryReply")) { int amount = Integer.parseInt(reply.getAttribute("amount")); boolean confirmed = canvas.showInciteDialog((Player) response.get(1), amount); if (confirmed && unit.getOwner().getGold() < amount) { canvas.showInformationMessage("notEnoughGold"); confirmed = false; } Element inciteMessage = Message.createNewRootElement("inciteAtSettlement"); inciteMessage.setAttribute("unit", unit.getId()); inciteMessage.setAttribute("direction", direction.toString()); inciteMessage.setAttribute("confirmed", confirmed ? "true" : "false"); inciteMessage.setAttribute("enemy", ((Player) response.get(1)).getId()); if (confirmed) { unit.getOwner().modifyGold(-amount); // Maybe at this point we can keep track of the fact that // the indian is now at // war with the chosen european player, but is this really // necessary at the client // side? settlement.getOwner().setStance((Player) response.get(1), Stance.WAR); ((Player) response.get(1)).setStance(settlement.getOwner(), Stance.WAR); } client.sendAndWait(inciteMessage); } else { logger.warning("Server gave an invalid reply to a missionaryAtSettlement message"); return; } } nextActiveUnit(unit.getTile()); } /** * Moves the specified unit to Europe. * * @param unit The unit to be moved to Europe. */ public void moveToEurope(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); unit.moveToEurope(); Element moveToEuropeElement = Message.createNewRootElement("moveToEurope"); moveToEuropeElement.setAttribute("unit", unit.getId()); client.sendAndWait(moveToEuropeElement); } /** * Moves the specified unit to America. * * @param unit The unit to be moved to America. */ public void moveToAmerica(Unit unit) { final Canvas canvas = freeColClient.getCanvas(); final Player player = freeColClient.getMyPlayer(); if (freeColClient.getGame().getCurrentPlayer() != player) { canvas.showInformationMessage("notYourTurn"); return; } final Client client = freeColClient.getClient(); final ClientOptions co = canvas.getClient().getClientOptions(); // Ask for autoload emigrants if (unit.getLocation() instanceof Europe) { final boolean autoload = co.getBoolean(ClientOptions.AUTOLOAD_EMIGRANTS); if (autoload) { int spaceLeft = unit.getSpaceLeft(); List<Unit> unitsInEurope = new ArrayList<Unit>(unit.getLocation().getUnitList()); for (Unit possiblePassenger : unitsInEurope) { if (possiblePassenger.isNaval()) { continue; } if (possiblePassenger.getType().getSpaceTaken() <= spaceLeft) { boardShip(possiblePassenger, unit); spaceLeft -= possiblePassenger.getType().getSpaceTaken(); } else { break; } } } } unit.moveToAmerica(); Element moveToAmericaElement = Message.createNewRootElement("moveToAmerica"); moveToAmericaElement.setAttribute("unit", unit.getId()); client.sendAndWait(moveToAmericaElement); } /** * Trains a unit of a specified type in Europe. * * @param unitType The type of unit to be trained. */ public void trainUnitInEurope(UnitType unitType) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Game game = freeColClient.getGame(); Player myPlayer = freeColClient.getMyPlayer(); Europe europe = myPlayer.getEurope(); if (myPlayer.getGold() < europe.getUnitPrice(unitType)) { canvas.errorMessage("notEnoughGold"); return; } Element trainUnitInEuropeElement = Message.createNewRootElement("trainUnitInEurope"); trainUnitInEuropeElement.setAttribute("unitType", unitType.getId()); Element reply = client.ask(trainUnitInEuropeElement); if (reply.getTagName().equals("trainUnitInEuropeConfirmed")) { Element unitElement = (Element) reply.getFirstChild(); Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(game, unitElement); } else { unit.readFromXMLElement(unitElement); } europe.train(unit); } else { logger.warning("Could not train unit in europe."); return; } freeColClient.getCanvas().updateGoldLabel(); } /** * Buys the remaining hammers and tools for the {@link Building} currently * being built in the given <code>Colony</code>. * * @param colony The {@link Colony} where the building should be bought. */ public void payForBuilding(Colony colony) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (!freeColClient.getCanvas() .showConfirmDialog("payForBuilding.text", "payForBuilding.yes", "payForBuilding.no", "%replace%", Integer.toString(colony.getPriceForBuilding()))) { return; } if (colony.getPriceForBuilding() > freeColClient.getMyPlayer().getGold()) { freeColClient.getCanvas().errorMessage("notEnoughGold"); return; } Element payForBuildingElement = Message.createNewRootElement("payForBuilding"); payForBuildingElement.setAttribute("colony", colony.getId()); colony.payForBuilding(); freeColClient.getClient().sendAndWait(payForBuildingElement); } /** * Recruit a unit from a specified "slot" in Europe. * * @param slot The slot to recruit the unit from. Either 1, 2 or 3. */ public void recruitUnitInEurope(int slot) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Game game = freeColClient.getGame(); Player myPlayer = freeColClient.getMyPlayer(); Europe europe = myPlayer.getEurope(); if (myPlayer.getGold() < myPlayer.getRecruitPrice()) { canvas.errorMessage("notEnoughGold"); return; } Element recruitUnitInEuropeElement = Message.createNewRootElement("recruitUnitInEurope"); recruitUnitInEuropeElement.setAttribute("slot", Integer.toString(slot)); Element reply = client.ask(recruitUnitInEuropeElement); if (reply.getTagName().equals("recruitUnitInEuropeConfirmed")) { Element unitElement = (Element) reply.getFirstChild(); Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(game, unitElement); } else { unit.readFromXMLElement(unitElement); } String unitId = reply.getAttribute("newRecruitable"); UnitType unitType = FreeCol.getSpecification().getUnitType(unitId); europe.recruit(slot, unit, unitType); } else { logger.warning("Could not recruit the specified unit in europe."); return; } freeColClient.getCanvas().updateGoldLabel(); } /** * Cause a unit to emigrate from a specified "slot" in Europe. If the player * doesn't have William Brewster in the congress then the value of the slot * parameter is not important (it won't be used). * * @param slot The slot from which the unit emigrates. Either 1, 2 or 3 if * William Brewster is in the congress. */ private void emigrateUnitInEurope(int slot) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); Player myPlayer = freeColClient.getMyPlayer(); Europe europe = myPlayer.getEurope(); Element emigrateUnitInEuropeElement = Message.createNewRootElement("emigrateUnitInEurope"); if (myPlayer.hasAbility("model.ability.selectRecruit")) { emigrateUnitInEuropeElement.setAttribute("slot", Integer.toString(slot)); } Element reply = client.ask(emigrateUnitInEuropeElement); if (reply == null || !reply.getTagName().equals("emigrateUnitInEuropeConfirmed")) { logger.warning("Could not recruit unit: " + myPlayer.getCrosses() + "/" + myPlayer.getCrossesRequired()); throw new IllegalStateException(); } if (!myPlayer.hasAbility("model.ability.selectRecruit")) { slot = Integer.parseInt(reply.getAttribute("slot")); } Element unitElement = (Element) reply.getFirstChild(); Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(game, unitElement); } else { unit.readFromXMLElement(unitElement); } String unitId = reply.getAttribute("newRecruitable"); UnitType newRecruitable = FreeCol.getSpecification().getUnitType(unitId); europe.emigrate(slot, unit, newRecruitable); freeColClient.getCanvas().updateGoldLabel(); } /** * Updates a trade route. * * @param route The trade route to update. */ public void updateTradeRoute(TradeRoute route) { logger.finest("Entering method updateTradeRoute"); /* * if (freeColClient.getGame().getCurrentPlayer() != * freeColClient.getMyPlayer()) { * freeColClient.getCanvas().showInformationMessage("notYourTurn"); * return; } */ Element tradeRouteElement = Message.createNewRootElement("updateTradeRoute"); tradeRouteElement.appendChild(route.toXMLElement(null, tradeRouteElement.getOwnerDocument())); freeColClient.getClient().sendAndWait(tradeRouteElement); } /** * Sets the trade routes for this player * * @param routes The trade routes to set. */ public void setTradeRoutes(List<TradeRoute> routes) { Player myPlayer = freeColClient.getMyPlayer(); myPlayer.setTradeRoutes(routes); /* * if (freeColClient.getGame().getCurrentPlayer() != * freeColClient.getMyPlayer()) { * freeColClient.getCanvas().showInformationMessage("notYourTurn"); * return; } */ Element tradeRoutesElement = Message.createNewRootElement("setTradeRoutes"); for(TradeRoute route : routes) { Element routeElement = tradeRoutesElement.getOwnerDocument().createElement(TradeRoute.getXMLElementTagName()); routeElement.setAttribute("id", route.getId()); tradeRoutesElement.appendChild(routeElement); } freeColClient.getClient().sendAndWait(tradeRoutesElement); } /** * Assigns a trade route to a unit. * * @param unit The unit to assign a trade route to. */ public void assignTradeRoute(Unit unit) { assignTradeRoute(unit, freeColClient.getCanvas().showTradeRouteDialog(unit.getTradeRoute())); } public void assignTradeRoute(Unit unit, TradeRoute tradeRoute) { if (tradeRoute != null) { Element assignTradeRouteElement = Message.createNewRootElement("assignTradeRoute"); assignTradeRouteElement.setAttribute("unit", unit.getId()); if (tradeRoute == TradeRoute.NO_TRADE_ROUTE) { unit.setTradeRoute(null); freeColClient.getClient().sendAndWait(assignTradeRouteElement); setDestination(unit, null); } else { unit.setTradeRoute(tradeRoute); assignTradeRouteElement.setAttribute("tradeRoute", tradeRoute.getId()); freeColClient.getClient().sendAndWait(assignTradeRouteElement); Location location = unit.getLocation(); if (location instanceof Tile) location = ((Tile) location).getColony(); if (tradeRoute.getStops().get(0).getLocation() == location) { followTradeRoute(unit); } else if (freeColClient.getGame().getCurrentPlayer() == freeColClient.getMyPlayer()) { moveToDestination(unit); } } } } /** * Pays the tax arrears on this type of goods. * * @param goods The goods for which to pay arrears. */ public void payArrears(Goods goods) { payArrears(goods.getType()); } /** * Pays the tax arrears on this type of goods. * * @param type The type of goods for which to pay arrears. */ public void payArrears(GoodsType type) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player player = freeColClient.getMyPlayer(); int arrears = player.getArrears(type); if (player.getGold() >= arrears) { if (freeColClient.getCanvas().showConfirmDialog("model.europe.payArrears", "ok", "cancel", "%replace%", String.valueOf(arrears))) { player.modifyGold(-arrears); freeColClient.getCanvas().updateGoldLabel(); player.resetArrears(type); // send to server Element payArrearsElement = Message.createNewRootElement("payArrears"); payArrearsElement.setAttribute("goodsType", type.getId()); client.sendAndWait(payArrearsElement); } } else { freeColClient.getCanvas().showInformationMessage("model.europe.cantPayArrears", "%amount%", String.valueOf(arrears)); } } /** * Purchases a unit of a specified type in Europe. * * @param unitType The type of unit to be purchased. */ public void purchaseUnitFromEurope(UnitType unitType) { trainUnitInEurope(unitType); } /** * Gathers information about opponents. */ public Element getForeignAffairsReport() { return freeColClient.getClient().ask(Message.createNewRootElement("foreignAffairs")); } /** * Gathers information about the REF. */ public Element getREFUnits() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return null; } Element reply = freeColClient.getClient().ask(Message.createNewRootElement("getREFUnits")); return reply; } /** * Disbands the active unit. */ public void disbandActiveUnit() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } GUI gui = freeColClient.getGUI(); Unit unit = gui.getActiveUnit(); Client client = freeColClient.getClient(); if (unit == null) { return; } if (!freeColClient.getCanvas().showConfirmDialog("disbandUnit.text", "disbandUnit.yes", "disbandUnit.no")) { return; } Element disbandUnit = Message.createNewRootElement("disbandUnit"); disbandUnit.setAttribute("unit", unit.getId()); unit.dispose(); client.sendAndWait(disbandUnit); nextActiveUnit(); } /** * Centers the map on the selected tile. */ public void centerActiveUnit() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } GUI gui = freeColClient.getGUI(); if (gui.getActiveUnit() != null && gui.getActiveUnit().getTile() != null) { gui.setFocus(gui.getActiveUnit().getTile().getPosition()); } } /** * Executes the units' goto orders. */ public void executeGotoOrders() { executeGoto = true; nextActiveUnit(null); } /** * Makes a new unit active. */ public void nextActiveUnit() { nextActiveUnit(null); } /** * Makes a new unit active. Displays any new <code>ModelMessage</code>s * (uses {@link #nextModelMessage}). * * @param tile The tile to select if no new unit can be made active. */ public void nextActiveUnit(Tile tile) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } nextModelMessage(); Canvas canvas = freeColClient.getCanvas(); Player myPlayer = freeColClient.getMyPlayer(); if (endingTurn || executeGoto) { while (!freeColClient.getCanvas().isShowingSubPanel() && myPlayer.hasNextGoingToUnit()) { Unit unit = myPlayer.getNextGoingToUnit(); moveToDestination(unit); nextModelMessage(); if (unit.getMovesLeft() > 0) { if (endingTurn) { unit.setMovesLeft(0); } else { return; } } } if (!myPlayer.hasNextGoingToUnit() && !freeColClient.getCanvas().isShowingSubPanel()) { if (endingTurn) { canvas.getGUI().setActiveUnit(null); endingTurn = false; Element endTurnElement = Message.createNewRootElement("endTurn"); freeColClient.getClient().send(endTurnElement); return; } else { executeGoto = false; } } } GUI gui = freeColClient.getGUI(); Unit nextActiveUnit = myPlayer.getNextActiveUnit(); if (nextActiveUnit != null) { canAutoEndTurn = true; gui.setActiveUnit(nextActiveUnit); } else { // no more active units, so we can move the others nextActiveUnit = myPlayer.getNextGoingToUnit(); if (nextActiveUnit != null) { moveToDestination(nextActiveUnit); } else if (tile != null) { Position p = tile.getPosition(); if (p != null) { // this really shouldn't happen gui.setSelectedTile(p); } gui.setActiveUnit(null); } else { gui.setActiveUnit(null); } if (canAutoEndTurn && !endingTurn && freeColClient.getClientOptions().getBoolean(ClientOptions.AUTO_END_TURN)) { endTurn(); } } } /** * Ignore this ModelMessage from now on until it is not generated in a turn. * * @param message a <code>ModelMessage</code> value * @param flag whether to ignore the ModelMessage or not */ public synchronized void ignoreMessage(ModelMessage message, boolean flag) { String key = message.getSource().getId(); String[] data = message.getData(); for (int index = 0; index < data.length; index += 2) { if (data[index].equals("%goods%")) { key += data[index + 1]; break; } } if (flag) { startIgnoringMessage(key, freeColClient.getGame().getTurn().getNumber()); } else { stopIgnoringMessage(key); } } /** * Displays the next <code>ModelMessage</code>. * * @see net.sf.freecol.common.model.ModelMessage ModelMessage */ public void nextModelMessage() { displayModelMessages(false); } public void displayModelMessages(final boolean allMessages) { int thisTurn = freeColClient.getGame().getTurn().getNumber(); final ArrayList<ModelMessage> messageList = new ArrayList<ModelMessage>(); Collection<ModelMessage> inputList; if (allMessages) { inputList = freeColClient.getMyPlayer().getModelMessages(); } else { inputList = freeColClient.getMyPlayer().getNewModelMessages(); } for (ModelMessage message : inputList) { if (shouldAllowMessage(message)) { if (message.getType() == ModelMessage.MessageType.WAREHOUSE_CAPACITY) { String key = message.getSource().getId(); String[] data = message.getData(); for (int index = 0; index < data.length; index += 2) { if (data[index].equals("%goods%")) { key += data[index + 1]; break; } } Integer turn = getTurnForMessageIgnored(key); if (turn != null && turn.intValue() == thisTurn - 1) { startIgnoringMessage(key, thisTurn); message.setBeenDisplayed(true); continue; } } messageList.add(message); } // flag all messages delivered as "beenDisplayed". message.setBeenDisplayed(true); } purgeOldMessagesFromMessagesToIgnore(thisTurn); final ModelMessage[] messages = messageList.toArray(new ModelMessage[0]); Runnable uiTask = new Runnable() { public void run() { Canvas canvas = freeColClient.getCanvas(); if (messageList.size() > 0) { if (allMessages || messageList.size() > 5) { canvas.showPanel(new ReportTurnPanel(canvas, messages)); } else { canvas.showModelMessages(messages); } } freeColClient.getActionManager().update(); } }; if (SwingUtilities.isEventDispatchThread()) { uiTask.run(); } else { try { SwingUtilities.invokeAndWait(uiTask); } catch (InterruptedException e) { // Ignore } catch (InvocationTargetException e) { // Ignore } } } private synchronized Integer getTurnForMessageIgnored(String key) { return messagesToIgnore.get(key); } private synchronized void startIgnoringMessage(String key, int turn) { logger.finer("Ignoring model message with key " + key); messagesToIgnore.put(key, new Integer(turn)); } private synchronized void stopIgnoringMessage(String key) { logger.finer("Removing model message with key " + key + " from ignored messages."); messagesToIgnore.remove(key); } private synchronized void purgeOldMessagesFromMessagesToIgnore(int thisTurn) { List<String> keysToRemove = new ArrayList<String>(); for (Entry<String, Integer> entry : messagesToIgnore.entrySet()) { if (entry.getValue().intValue() < thisTurn - 1) { if (logger.isLoggable(Level.FINER)) { logger.finer("Removing old model message with key " + entry.getKey() + " from ignored messages."); } keysToRemove.add(entry.getKey()); } } for (String key : keysToRemove) { stopIgnoringMessage(key); } } /** * Provides an opportunity to filter the messages delivered to the canvas. * * @param message the message that is candidate for delivery to the canvas * @return true if the message should be delivered */ private boolean shouldAllowMessage(ModelMessage message) { switch (message.getType()) { case DEFAULT: return true; case WARNING: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_WARNING); case SONS_OF_LIBERTY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_SONS_OF_LIBERTY); case GOVERNMENT_EFFICIENCY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_GOVERNMENT_EFFICIENCY); case WAREHOUSE_CAPACITY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_WAREHOUSE_CAPACITY); case UNIT_IMPROVED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_IMPROVED); case UNIT_DEMOTED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_DEMOTED); case UNIT_LOST: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_LOST); case UNIT_ADDED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_ADDED); case BUILDING_COMPLETED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_BUILDING_COMPLETED); case FOREIGN_DIPLOMACY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_FOREIGN_DIPLOMACY); case MARKET_PRICES: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_MARKET_PRICES); case MISSING_GOODS: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_MISSING_GOODS); case TUTORIAL: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_TUTORIAL); default: return true; } } /** * End the turn. */ public void endTurn() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } endingTurn = true; canAutoEndTurn = false; nextActiveUnit(null); } /** * Convenience method: returns the first child element with the specified * tagname. * * @param element The <code>Element</code> to search for the child * element. * @param tagName The tag name of the child element to be found. * @return The child of the given <code>Element</code> with the given * <code>tagName</code> or <code>null</code> if no such child * exists. */ protected Element getChildElement(Element element, String tagName) { NodeList n = element.getChildNodes(); for (int i = 0; i < n.getLength(); i++) { if (((Element) n.item(i)).getTagName().equals(tagName)) { return (Element) n.item(i); } } return null; } /** * Abandon a colony with no units * * @param colony The colony to be abandoned */ public void abandonColony(Colony colony) { if (colony == null) { return; } Client client = freeColClient.getClient(); Element abandonColony = Message.createNewRootElement("abandonColony"); abandonColony.setAttribute("colony", colony.getId()); colony.dispose(); client.sendAndWait(abandonColony); } /** * Retrieves server statistics */ public StatisticsMessage getServerStatistics() { Element request = Message.createNewRootElement(StatisticsMessage.getXMLElementTagName()); Element reply = freeColClient.getClient().ask(request); StatisticsMessage m = new StatisticsMessage(reply); return m; } }
true
true
public void buildColony() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); GUI gui = freeColClient.getGUI(); Unit unit = freeColClient.getGUI().getActiveUnit(); if (unit == null || !unit.canBuildColony()) { return; } Tile tile = unit.getTile(); if (tile == null) { return; } if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) { boolean landLocked = true; boolean ownedByEuropeans = false; boolean ownedBySelf = false; boolean ownedByIndians = false; java.util.Map<GoodsType, Integer> goodsMap = new HashMap<GoodsType, Integer>(); for (GoodsType goodsType : FreeCol.getSpecification().getGoodsTypeList()) { if (goodsType.isFoodType()) { int potential = 0; if (tile.primaryGoods() == goodsType) { potential = tile.potential(goodsType); } goodsMap.put(goodsType, new Integer(potential)); } else if (goodsType.isBuildingMaterial()) { while (goodsType.isRefined()) { goodsType = goodsType.getRawMaterial(); } int potential = 0; if (tile.secondaryGoods() == goodsType) { potential = tile.potential(goodsType); } goodsMap.put(goodsType, new Integer(potential)); } } Map map = game.getMap(); Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition()); while (tileIterator.hasNext()) { Tile newTile = map.getTile(tileIterator.next()); if (newTile.isLand()) { for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { entry.setValue(entry.getValue().intValue() + newTile.potential(entry.getKey())); } Player tileOwner = newTile.getOwner(); if (tileOwner == unit.getOwner()) { if (newTile.getOwningSettlement() != null) { // we are using newTile ownedBySelf = true; } else { Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition()); while (ownTileIt.hasNext()) { Colony colony = map.getTile(ownTileIt.next()).getColony(); if (colony != null && colony.getOwner() == unit.getOwner()) { // newTile can be used from an own colony ownedBySelf = true; break; } } } } else if (tileOwner != null && tileOwner.isEuropean()) { ownedByEuropeans = true; } else if (tileOwner != null) { ownedByIndians = true; } } else { landLocked = false; } } int food = 0; for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { if (entry.getKey().isFoodType()) { food += entry.getValue().intValue(); } } ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); if (landLocked) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.fish"), "buildColony.landLocked")); } if (food < 8) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.food"), "buildColony.noFood")); } for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { if (!entry.getKey().isFoodType() && entry.getValue().intValue() < 4) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, entry.getKey(), "buildColony.noBuildingMaterials", "%goods%", entry.getKey().getName())); } } if (ownedBySelf) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.ownLand")); } if (ownedByEuropeans) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.EuropeanLand")); } if (ownedByIndians) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.IndianLand")); } if (messages.size() > 0) { ModelMessage[] modelMessages = messages.toArray(new ModelMessage[0]); if (!freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes", "buildColony.no")) { return; } } } String name = freeColClient.getCanvas().showInputDialog("nameColony.text", freeColClient.getMyPlayer().getDefaultColonyName(), "nameColony.yes", "nameColony.no"); if (name == null) { // The user canceled the action. return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", "%name%", name); return; } Element buildColonyElement = Message.createNewRootElement("buildColony"); buildColonyElement.setAttribute("name", name); buildColonyElement.setAttribute("unit", unit.getId()); Element reply = client.ask(buildColonyElement); if (reply.getTagName().equals("buildColonyConfirmed")) { Element updateElement = getChildElement(reply, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().update(updateElement); } Element colonyElement = (Element) reply.getFirstChild(); Colony colony = (Colony) game.getFreeColGameObject(colonyElement.getAttribute("ID")); if (colony == null) { colony = new Colony(game, colonyElement); } else { colony.readFromXMLElement(colonyElement); } changeWorkType(unit, Goods.FOOD); unit.buildColony(colony); for(Unit unitInTile : tile.getUnitList()) { if (unitInTile.canCarryTreasure()) { checkCashInTreasureTrain(unitInTile); } } gui.setActiveUnit(null); gui.setSelectedTile(colony.getTile().getPosition()); } else { // Handle error message. } }
public void buildColony() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); GUI gui = freeColClient.getGUI(); Unit unit = freeColClient.getGUI().getActiveUnit(); if (unit == null || !unit.canBuildColony()) { return; } Tile tile = unit.getTile(); if (tile == null) { return; } if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) { boolean landLocked = true; boolean ownedByEuropeans = false; boolean ownedBySelf = false; boolean ownedByIndians = false; java.util.Map<GoodsType, Integer> goodsMap = new HashMap<GoodsType, Integer>(); for (GoodsType goodsType : FreeCol.getSpecification().getGoodsTypeList()) { if (goodsType.isFoodType()) { int potential = 0; if (tile.primaryGoods() == goodsType) { potential = tile.potential(goodsType); } goodsMap.put(goodsType, new Integer(potential)); } else if (goodsType.isBuildingMaterial()) { while (goodsType.isRefined()) { goodsType = goodsType.getRawMaterial(); } int potential = 0; if (tile.secondaryGoods() == goodsType) { potential = tile.potential(goodsType); } goodsMap.put(goodsType, new Integer(potential)); } } Map map = game.getMap(); Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition()); while (tileIterator.hasNext()) { Tile newTile = map.getTile(tileIterator.next()); if (newTile.isLand()) { for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { entry.setValue(entry.getValue().intValue() + newTile.potential(entry.getKey())); } Player tileOwner = newTile.getOwner(); if (tileOwner == unit.getOwner()) { if (newTile.getOwningSettlement() != null) { // we are using newTile ownedBySelf = true; } else { Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition()); while (ownTileIt.hasNext()) { Colony colony = map.getTile(ownTileIt.next()).getColony(); if (colony != null && colony.getOwner() == unit.getOwner()) { // newTile can be used from an own colony ownedBySelf = true; break; } } } } else if (tileOwner != null && tileOwner.isEuropean()) { ownedByEuropeans = true; } else if (tileOwner != null) { ownedByIndians = true; } } else { landLocked = false; } } int food = 0; for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { if (entry.getKey().isFoodType()) { food += entry.getValue().intValue(); } } ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); if (landLocked) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.fish"), "buildColony.landLocked")); } if (food < 8) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.food"), "buildColony.noFood")); } for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) { if (!entry.getKey().isFoodType() && entry.getValue().intValue() < 4) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, entry.getKey(), "buildColony.noBuildingMaterials", "%goods%", entry.getKey().getName())); } } if (ownedBySelf) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.ownLand")); } if (ownedByEuropeans) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.EuropeanLand")); } if (ownedByIndians) { messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.IndianLand")); } if (messages.size() > 0) { ModelMessage[] modelMessages = messages.toArray(new ModelMessage[0]); if (!freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes", "buildColony.no")) { return; } } } String name = freeColClient.getCanvas().showInputDialog("nameColony.text", freeColClient.getMyPlayer().getDefaultColonyName(), "nameColony.yes", "nameColony.no"); if (name == null) { // The user canceled the action. return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", "%name%", name); return; } Element buildColonyElement = Message.createNewRootElement("buildColony"); buildColonyElement.setAttribute("name", name); buildColonyElement.setAttribute("unit", unit.getId()); Element reply = client.ask(buildColonyElement); if (reply.getTagName().equals("buildColonyConfirmed")) { Element updateElement = getChildElement(reply, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().update(updateElement); } Element colonyElement = (Element) reply.getFirstChild(); Colony colony = (Colony) game.getFreeColGameObject(colonyElement.getAttribute("ID")); if (colony == null) { colony = new Colony(game, colonyElement); } else { colony.readFromXMLElement(colonyElement); } changeWorkType(unit, Goods.FOOD); unit.buildColony(colony); ArrayList<Unit> units = new ArrayList<Unit>(tile.getUnitList()); for(Unit unitInTile : units) { if (unitInTile.canCarryTreasure()) { checkCashInTreasureTrain(unitInTile); } } gui.setActiveUnit(null); gui.setSelectedTile(colony.getTile().getPosition()); } else { // Handle error message. } }
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_LEGION.java b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_LEGION.java index 11474d4f..3d892a5e 100644 --- a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_LEGION.java +++ b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_LEGION.java @@ -1,767 +1,768 @@ /* * This file is part of aion-unique <aion-unique.org>. * * aion-unique is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * aion-unique is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with aion-unique. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.network.aion.clientpackets; import java.util.Map.Entry; import org.apache.log4j.Logger; import com.aionemu.gameserver.configs.LegionConfig; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.gameobjects.player.RequestResponseHandler; import com.aionemu.gameserver.model.legion.Legion; import com.aionemu.gameserver.model.legion.LegionMember; import com.aionemu.gameserver.network.aion.AionClientPacket; import com.aionemu.gameserver.network.aion.AionServerPacket; import com.aionemu.gameserver.network.aion.serverpackets.SM_CHANGE_NICKNAME; import com.aionemu.gameserver.network.aion.serverpackets.SM_CHANGE_SELF_INTRODUCTION; import com.aionemu.gameserver.network.aion.serverpackets.SM_EDIT_LEGION; import com.aionemu.gameserver.network.aion.serverpackets.SM_LEAVE_LEGION; import com.aionemu.gameserver.network.aion.serverpackets.SM_LEGIONMEMBER_INFO; import com.aionemu.gameserver.network.aion.serverpackets.SM_LEGION_CREATED; import com.aionemu.gameserver.network.aion.serverpackets.SM_LEGION_INFO; import com.aionemu.gameserver.network.aion.serverpackets.SM_LEGION_TITLE; import com.aionemu.gameserver.network.aion.serverpackets.SM_QUESTION_WINDOW; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.network.aion.serverpackets.SM_UPDATE_LEGION_TITLE; import com.aionemu.gameserver.services.LegionService; import com.aionemu.gameserver.services.PlayerService; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.utils.idfactory.IDFactory; import com.aionemu.gameserver.utils.idfactory.IDFactoryAionObject; import com.aionemu.gameserver.world.World; import com.google.inject.Inject; /** * * @author Simple * */ @SuppressWarnings("unused") public class CM_LEGION extends AionClientPacket { private static final Logger log = Logger.getLogger(CM_LEGION.class); /** Legion based information **/ @Inject private LegionService legionService; @Inject private PlayerService playerService; @Inject private World world; @Inject @IDFactoryAionObject private IDFactory aionObjectsIDFactory; /** * exOpcode and the rest */ private int exOpcode; private int unk1; private int unk2; private int legionarPermission1; private int legionarPermission2; private int centurionPermission1; private int centurionPermission2; private int rank; private String legionName; private String charName; private String newNickname; private String announcement; private String newSelfIntro; /** * Legion Permission variables */ private static final int BRIGADE_GENERAL_RANK = 0x00; private static final int CENTURION_RANK = 0x01; private static final int LEGIONAIRY_RANK = 0x02; private static final int PERMISSION1_MIN = 0x60; private static final int PERMISSION2_MIN = 0x00; private static final int LEGIONAR_PERMISSION2_MAX = 0x08; private static final int CENTURION_PERMISSION1_MAX = 0x7C; private static final int CENTURION_PERMISSION2_MAX = 0x0E; /** * Constructs new instance of CM_LEGION packet * * @param opcode */ public CM_LEGION(int opcode) { super(opcode); } /** * {@inheritDoc} */ @Override protected void readImpl() { exOpcode = readC(); switch(exOpcode) { /** Create a legion **/ case 0x00: unk2 = readD(); // time? 00 78 19 00 40 legionName = readS(); break; /** Invite to legion **/ case 0x01: unk1 = readD(); // empty charName = readS(); break; /** Leave legion **/ case 0x02: unk1 = readD(); // empty unk2 = readH(); // empty break; /** Kick member from legion **/ case 0x04: unk1 = readD(); // empty charName = readS(); break; /** Appoint a new Brigade General **/ case 0x05: unk2 = readD(); charName = readS(); break; /** Appoint Centurion **/ case 0x06: rank = readD(); charName = readS(); break; /** Demote to Legionary **/ case 0x07: unk2 = readD(); // char id? 00 78 19 00 40 charName = readS(); break; /** Refresh legion info **/ case 0x08: break; /** Edit announcements **/ case 0x09: unk1 = readD(); // empty or char id? announcement = readS(); break; /** Change self introduction **/ case 0x0A: unk1 = readD(); // empty char id? newSelfIntro = readS(); break; /** Edit permissions **/ case 0x0D: centurionPermission1 = readC(); // 0x60 - 0x7C centurionPermission2 = readC(); // 0x00 - 0x0E legionarPermission1 = readC(); // can't be set is static 0x40 legionarPermission2 = readC(); // 0x00 - 0x08 break; /** Level legion up **/ case 0x0E: unk1 = readD(); // empty unk2 = readH(); // empty break; case 0x0F: charName = readS(); newNickname = readS(); break; default: log.info("Unknown Legion exOpcode? 0x" + Integer.toHexString(exOpcode).toUpperCase()); break; } } /** * {@inheritDoc} */ @Override protected void runImpl() { final Player activePlayer = getConnection().getActivePlayer(); if(activePlayer.isLegionMember()) { final Legion legion = activePlayer.getLegionMember().getLegion(); switch(exOpcode) { /** Invite to legion **/ case 0x01: if(activePlayer.getLifeStats().isAlreadyDead()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_INVITE_WHILE_DEAD()); } else { final Player targetPlayer = world.findPlayer(charName); if(charName.equalsIgnoreCase(activePlayer.getName())) { // Invalid chars } else if(targetPlayer == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_NO_USER_TO_INVITE()); } else if(targetPlayer.getObjectId() == activePlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CAN_NOT_INVITE_SELF()); } else if(targetPlayer.isLegionMember()) { if(targetPlayer.getLegionMember().getLegion() == legion) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_HE_IS_MY_GUILD_MEMBER(targetPlayer.getName())); } else { sendPacket(SM_SYSTEM_MESSAGE.LEGION_HE_IS_OTHER_GUILD_MEMBER(targetPlayer.getName())); } } else { invitePlayerToLegion(activePlayer, targetPlayer, legion); } } break; /** Leave legion **/ case 0x02: leaveLegion(activePlayer, legion); break; /** Kick member from legion **/ case 0x04: Player kickedPlayer = world.findPlayer(charName); if(kickedPlayer != null) { if(kickedPlayer.getObjectId() == activePlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_KICK_YOURSELF()); } else if(kickedPlayer.getLegionMember().getRank() == BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_KICK_BRIGADE_GENERAL()); } else { // TODO: Can not kick during a war!! kickMemberFromLegion(activePlayer.getName(), kickedPlayer, legion); } } else { // Player off line / does not exist? send message to player? } break; /** Appoint a new Brigade General **/ case 0x05: Player newBrigadeGeneral = world.findPlayer(charName); if(newBrigadeGeneral == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_NO_USER()); } else if(activePlayer.getLegionMember().getRank() != BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_DONT_HAVE_RIGHT()); } else if(activePlayer.getObjectId() == newBrigadeGeneral.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MASTER_ERROR_SELF()); } else { appointNewBrigadeGeneral(newBrigadeGeneral); } break; /** Appoint Centurion/Legionairy **/ case 0x06: Player targetPlayer = world.findPlayer(charName); if(targetPlayer == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_NO_USER()); } else if(activePlayer.getLegionMember().getRank() != BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_DONT_HAVE_RIGHT()); } else if(activePlayer.getObjectId() == targetPlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_ERROR_SELF()); } else { if(rank == LEGIONAIRY_RANK) { demoteToLegionary(targetPlayer); } else if(rank == CENTURION_RANK) { appointCenturion(targetPlayer); } } break; /** Refresh legion info **/ case 0x08: sendPacket(new SM_LEGION_INFO(legion)); break; /** Edit announcements **/ case 0x09: changeAnnouncement(legion); break; /** Change self introduction **/ case 0x0A: changeSelfIntro(activePlayer.getObjectId(), activePlayer.getLegionMember()); break; /** Edit permissions **/ case 0x0D: if(checkPermissions()) changePermissions(legion); break; /** Level legion up **/ case 0x0E: legionLevelUp(activePlayer.getInventory().getKinahItem().getItemCount(), legion); break; /** Set nickname **/ case 0x0F: Player selectedPlayer = world.findPlayer(charName); if(selectedPlayer == null || selectedPlayer.getLegionMember().getLegion() != legion) // Player offline or NOT in same legion as player return; changeNickname(selectedPlayer.getObjectId(), selectedPlayer.getLegionMember()); break; } } else { switch(exOpcode) { /** Create a legion **/ case 0x00: Legion legion = new Legion(aionObjectsIDFactory.nextId(), legionName); /* Some reasons why legions can' be created */ if(!legionService.isValidName(legion.getLegionName())) { log.debug("[CM_LEGION] Player " + activePlayer.getObjectId() + " tried to create legion with an invalid name."); aionObjectsIDFactory.releaseId(legion.getLegionId()); sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_INVALID_NAME()); return; } else if(!legionService.isFreeName(legion.getLegionName())) { log.debug("[CM_LEGION] Player " + activePlayer.getObjectId() + " tried to create legion with existing name."); aionObjectsIDFactory.releaseId(legion.getLegionId()); sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_NAME_EXISTS()); return; } // if(activePlayer.getDisbandLegionTime() < Config.LEGION_DISBAND_DIFFERENCE) // { // sendPacket(SM_SYSTEM_MESSAGE.LEGION_LEGION_CREATE_LAST_DAY_CHECK()); // } else if(activePlayer.isLegionMember()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_ALREADY_MEMBER()); } else if(activePlayer.getInventory().getKinahItem().getItemCount() < LegionConfig.LEGION_CREATE_REQUIRED_KINAH) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_NOT_ENOUGH_KINAH()); } else if(legionService.storeNewLegion(legion)) { log.debug("[CM_LEGION] Legion has been created!."); + activePlayer.getInventory().decreaseKinah(LegionConfig.LEGION_CREATE_REQUIRED_KINAH); /** Send the packets that contain legion info to legion leader **/ sendLegionCreationInfo(activePlayer, legion); } else { // Legion Creation Failed SYSTEM_MSG? // player.sendPacket(new SM_CREATE_CHARACTER(null, SM_CREATE_CHARACTER.RESPONSE_DB_ERROR)); } break; } } } /** * Method that will handle a invitation to a legion * * @param activePlayer * @param targetPlayer * @param legion */ private void invitePlayerToLegion(final Player activePlayer, final Player targetPlayer, final Legion legion) { RequestResponseHandler responseHandler = new RequestResponseHandler(activePlayer){ @Override public void acceptRequest(Creature requester, Player responder) { if(!targetPlayer.getCommonData().isOnline()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_INCORRECT_TARGET()); } else { int playerObjId = responder.getObjectId(); responder.setLegionMember(new LegionMember(playerObjId, legion)); if(legion.addLegionMember(playerObjId)) { legionService.storeNewLegionMember(playerObjId, responder.getLegionMember()); sendPacket(SM_SYSTEM_MESSAGE.NEW_MEMBER_JOINED(responder.getName())); // Tell all legion members a player joined the legion // Send the new legion member the required legion packets responder.getClientConnection().sendPacket(new SM_LEGION_TITLE(responder)); responder.getClientConnection().sendPacket(new SM_LEGION_INFO(legion)); refreshMembersInfoByPacket(legion, new SM_LEGIONMEMBER_INFO(responder)); for(Integer memberObjId : legion.getLegionMembers()) { Player legionMember = world.findPlayer(memberObjId); if(legionMember != null) { responder.getClientConnection().sendPacket(new SM_LEGIONMEMBER_INFO(legionMember)); } else { legionMember = playerService.getPlayer(memberObjId); responder.getClientConnection().sendPacket(new SM_LEGIONMEMBER_INFO(legionMember)); } } PacketSendUtility.broadcastPacket(responder, new SM_UPDATE_LEGION_TITLE(playerObjId, legion .getLegionId(), legion.getLegionName(), responder.getLegionMember().getRank()), true); /** (CURRENT ANNOUNCEMENT) Get 2 parameters from DB **/ Entry<Integer, String> currentAnnouncement = legion.getCurrentAnnouncement(); if(currentAnnouncement != null) { responder.getClientConnection().sendPacket( SM_SYSTEM_MESSAGE.LEGION_DISPLAY_ANNOUNCEMENT(currentAnnouncement.getValue(), currentAnnouncement.getKey(), 2)); } } else { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CAN_NOT_ADD_MEMBER_ANY_MORE()); responder.setLegionMember(null); } } } @Override public void denyRequest(Creature requester, Player responder) { sendPacket(SM_SYSTEM_MESSAGE.REJECTED_INVITE_REQUEST(responder.getName())); } }; boolean requested = targetPlayer.getResponseRequester().putRequest(SM_QUESTION_WINDOW.STR_LEGION_INVITE, responseHandler); // If the player is busy and could not be asked if(!requested) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_TARGET_BUSY()); } else { sendPacket(SM_SYSTEM_MESSAGE.SEND_INVITE_REQUEST(targetPlayer.getName())); // Send question packet to buddy targetPlayer.getClientConnection().sendPacket( new SM_QUESTION_WINDOW(SM_QUESTION_WINDOW.STR_LEGION_INVITE, activePlayer.getObjectId(), legion .getLegionName(), legion.getLegionLevel() + "", activePlayer.getName())); } } /** * This method will handle a player that leaves a legion * * @param activePlayer */ private void leaveLegion(Player activePlayer, Legion legion) { // TODO: Check if player is ONLY Brigade General in legion // Current state: Player can only leave when he/she is not brigade general if(activePlayer.getLegionMember().getRank() == BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_LEAVE_BEFORE_CHANGE_MASTER()); } else { PacketSendUtility.broadcastPacket(activePlayer, new SM_UPDATE_LEGION_TITLE(activePlayer.getObjectId(), 0, "", activePlayer.getLegionMember().getRank()), true); sendPacket(new SM_LEAVE_LEGION(1300241, 0, legion.getLegionName())); activePlayer.setLegionMember(null); legion.deleteLegionMember(activePlayer.getObjectId()); legionService.deleteLegionMember(activePlayer.getObjectId()); refreshMembersInfoByPacket(legion, new SM_LEAVE_LEGION(900699, activePlayer.getObjectId(), activePlayer.getName())); } } /** * This method will handle a player that leaves a legion * * @param activePlayer */ private void kickMemberFromLegion(String playerName, Player kickedPlayer, Legion legion) { PacketSendUtility.broadcastPacket(kickedPlayer, new SM_UPDATE_LEGION_TITLE(kickedPlayer.getObjectId(), 0, "", kickedPlayer.getLegionMember().getRank()), true); kickedPlayer.getClientConnection().sendPacket(new SM_LEAVE_LEGION(1300246, 0, legion.getLegionName())); kickedPlayer.setLegionMember(null); legion.deleteLegionMember(kickedPlayer.getObjectId()); legionService.deleteLegionMember(kickedPlayer.getObjectId()); refreshMembersInfoByPacket(legion, new SM_LEAVE_LEGION(1300247, kickedPlayer.getObjectId(), playerName, kickedPlayer.getName())); } /** * This method will handle a new appointed legion leader * * @param newBrigadeGeneral */ private void appointNewBrigadeGeneral(Player newBrigadeGeneral) { LegionMember legionMember = newBrigadeGeneral.getLegionMember(); if(legionMember.getRank() > BRIGADE_GENERAL_RANK) { newBrigadeGeneral.getLegionMember().setRank(BRIGADE_GENERAL_RANK); legionService.storeLegionMember(newBrigadeGeneral.getObjectId(), legionMember); // TODO: Need proper packet!!!! refreshMembersInfoByPacket(legionMember.getLegion(), new SM_LEGIONMEMBER_INFO(newBrigadeGeneral)); refreshMembersInfoByPacket(legionMember.getLegion(), SM_SYSTEM_MESSAGE .LEGION_CHANGE_MEMBER_RANK_DONE_1_GUILD_MASTER(newBrigadeGeneral.getName())); } } /** * This method will handle the process when a legionary is promoted to centurion * * @param newCenturion */ private void appointCenturion(Player newCenturion) { LegionMember legionMember = newCenturion.getLegionMember(); if(legionMember.getRank() > CENTURION_RANK) { legionMember.setRank(CENTURION_RANK); legionService.storeLegionMember(newCenturion.getObjectId(), legionMember); // TODO: Need proper packet!!!! refreshMembersInfoByPacket(legionMember.getLegion(), new SM_LEGIONMEMBER_INFO(newCenturion)); refreshMembersInfoByPacket(legionMember.getLegion(), SM_SYSTEM_MESSAGE .LEGION_CHANGE_MEMBER_RANK_DONE_2_GUILD_OFFICER(newCenturion.getName())); } } /** * This method will handle the process when a member is demoted to Legionary * * @param newCenturion */ private void demoteToLegionary(Player newLegionairy) { LegionMember legionMember = newLegionairy.getLegionMember(); if(legionMember.getRank() < LEGIONAIRY_RANK) { legionMember.setRank(LEGIONAIRY_RANK); legionService.storeLegionMember(newLegionairy.getObjectId(), legionMember); // TODO: Need proper packet!!!! refreshMembersInfoByPacket(legionMember.getLegion(), new SM_LEGIONMEMBER_INFO(newLegionairy)); refreshMembersInfoByPacket(legionMember.getLegion(), SM_SYSTEM_MESSAGE .LEGION_CHANGE_MEMBER_RANK_DONE_3_GUILD_MEMBER(newLegionairy.getName())); } } /** * This will add a new announcement to the DB and change the current announcement * * @param legion * @param unixTime * @param message */ private void changeAnnouncement(Legion legion) { if(legionService.isValidAnnouncement(announcement)) { int unixTime = (int) (System.currentTimeMillis() / 1000); legionService.storeNewAnnouncement(legion.getLegionId(), unixTime, announcement); legionService.renewAnnouncementList(legion); sendPacket(SM_SYSTEM_MESSAGE.LEGION_WRITE_NOTICE_DONE()); refreshMembersInfoByPacket(legion, new SM_EDIT_LEGION(0x05, unixTime, announcement)); } } /** * This method will handle the changement of a self intro * * @param playerObjId * @param legionMember */ private void changeSelfIntro(int playerObjId, LegionMember legionMember) { if(legionService.isValidSelfIntro(newSelfIntro)) { legionMember.setSelfIntro(newSelfIntro); legionService.storeLegionMember(playerObjId, legionMember); refreshMembersInfoByPacket(legionMember.getLegion(), new SM_CHANGE_SELF_INTRODUCTION(playerObjId, newSelfIntro)); } } /** * This method will handle the changement of permissions * * @param legion */ private void changePermissions(Legion legion) { legion.setLegionarPermissions(legionarPermission2, centurionPermission1, centurionPermission2); legionService.storeLegion(legion); refreshMembersInfoByPacket(legion, new SM_EDIT_LEGION(0x02, legion)); } /** * This method will handle the changement of a nickname * * @param playerObjId * @param legionMember */ private void changeNickname(int playerObjId, LegionMember legionMember) { if(playerService.isValidName(newNickname)) { legionMember.setNickname(newNickname); legionService.storeLegionMember(playerObjId, legionMember); refreshMembersInfoByPacket(legionMember.getLegion(), new SM_CHANGE_NICKNAME(playerObjId, newNickname)); } } /** * This method will handle the leveling up of a legion * * @param Legion */ private void legionLevelUp(int kinahAmount, Legion legion) { if(!legion.hasEnoughKinah(kinahAmount)) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_LEVEL_UP(legion.getLegionLevel())); } else if(!legion.hasRequiredMembers()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_LEVEL_UP(legion.getLegionLevel())); } // else if(!legion.hasEnoughAbyssPoints(1000000)) // { // sendPacket(SM_SYSTEM_MESSAGE.LEGION_LEVEL_UP(legion.getLegionLevel())); // } else { legion.setLegionLevel(legion.getLegionLevel() + 1); legionService.storeLegion(legion); refreshMembersInfoByPacket(legion, new SM_EDIT_LEGION(0x00, legion)); refreshMembersInfoByPacket(legion, SM_SYSTEM_MESSAGE.LEGION_LEVEL_UP(legion.getLegionLevel())); } } /** * This method will handle the creation of a legion * * @param player * @param legion */ private void sendLegionCreationInfo(Player activePlayer, Legion legion) { /** * Create a LegionMember and bind it to a Player */ LegionMember legionMember = new LegionMember(activePlayer.getObjectId(), legion, 0x00); // Leader Rank activePlayer.setLegionMember(legionMember); legion.addLegionMember(activePlayer.getObjectId()); legionService.storeNewLegionMember(activePlayer.getObjectId(), legionMember); /** * Send required packets */ sendPacket(new SM_LEGION_INFO(legion)); sendPacket(new SM_LEGION_TITLE(activePlayer)); sendPacket(new SM_LEGION_CREATED(legion.getLegionId())); sendPacket(new SM_EDIT_LEGION(0x08)); PacketSendUtility.broadcastPacket(activePlayer, new SM_UPDATE_LEGION_TITLE(activePlayer.getObjectId(), legion .getLegionId(), legion.getLegionName(), legionMember.getRank()), true); sendPacket(new SM_LEGIONMEMBER_INFO(activePlayer)); // 7A 55 39 00 00 34 00 00 00 03 02 00 sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATED(legion.getLegionName())); } /** * This method will send a packet to every legion member * * @param legion * @param packet */ private void refreshMembersInfoByPacket(Legion legion, AionServerPacket packet) { for(Player onlineLegionMember : legion.getOnlineLegionMembers(world)) { PacketSendUtility.sendPacket(onlineLegionMember, packet); } } /** * Check if all permissions are correct * * @return true or false */ private boolean checkPermissions() { /* * DEFAULT Centurion: 60 adds 0x04 (0x64) Invite to Legion => adds 0x08 (0x6c) Kick from Legion => adds 0x0F * (0x7C) ?!?!? DEFAULT: 00 Use Gate Guardian Stone => adds 0x08 (0x08) Use Artifact => adds 0x04 (0x0C) Edit * Announcement => adds 0x02 (0x0E) */ if(legionarPermission2 < PERMISSION2_MIN || legionarPermission2 > LEGIONAR_PERMISSION2_MAX) { return false; } if(centurionPermission1 < PERMISSION1_MIN || centurionPermission1 > CENTURION_PERMISSION1_MAX) { return false; } if(centurionPermission2 < PERMISSION2_MIN || centurionPermission2 > CENTURION_PERMISSION2_MAX) { return false; } return true; } }
true
true
protected void runImpl() { final Player activePlayer = getConnection().getActivePlayer(); if(activePlayer.isLegionMember()) { final Legion legion = activePlayer.getLegionMember().getLegion(); switch(exOpcode) { /** Invite to legion **/ case 0x01: if(activePlayer.getLifeStats().isAlreadyDead()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_INVITE_WHILE_DEAD()); } else { final Player targetPlayer = world.findPlayer(charName); if(charName.equalsIgnoreCase(activePlayer.getName())) { // Invalid chars } else if(targetPlayer == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_NO_USER_TO_INVITE()); } else if(targetPlayer.getObjectId() == activePlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CAN_NOT_INVITE_SELF()); } else if(targetPlayer.isLegionMember()) { if(targetPlayer.getLegionMember().getLegion() == legion) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_HE_IS_MY_GUILD_MEMBER(targetPlayer.getName())); } else { sendPacket(SM_SYSTEM_MESSAGE.LEGION_HE_IS_OTHER_GUILD_MEMBER(targetPlayer.getName())); } } else { invitePlayerToLegion(activePlayer, targetPlayer, legion); } } break; /** Leave legion **/ case 0x02: leaveLegion(activePlayer, legion); break; /** Kick member from legion **/ case 0x04: Player kickedPlayer = world.findPlayer(charName); if(kickedPlayer != null) { if(kickedPlayer.getObjectId() == activePlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_KICK_YOURSELF()); } else if(kickedPlayer.getLegionMember().getRank() == BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_KICK_BRIGADE_GENERAL()); } else { // TODO: Can not kick during a war!! kickMemberFromLegion(activePlayer.getName(), kickedPlayer, legion); } } else { // Player off line / does not exist? send message to player? } break; /** Appoint a new Brigade General **/ case 0x05: Player newBrigadeGeneral = world.findPlayer(charName); if(newBrigadeGeneral == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_NO_USER()); } else if(activePlayer.getLegionMember().getRank() != BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_DONT_HAVE_RIGHT()); } else if(activePlayer.getObjectId() == newBrigadeGeneral.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MASTER_ERROR_SELF()); } else { appointNewBrigadeGeneral(newBrigadeGeneral); } break; /** Appoint Centurion/Legionairy **/ case 0x06: Player targetPlayer = world.findPlayer(charName); if(targetPlayer == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_NO_USER()); } else if(activePlayer.getLegionMember().getRank() != BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_DONT_HAVE_RIGHT()); } else if(activePlayer.getObjectId() == targetPlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_ERROR_SELF()); } else { if(rank == LEGIONAIRY_RANK) { demoteToLegionary(targetPlayer); } else if(rank == CENTURION_RANK) { appointCenturion(targetPlayer); } } break; /** Refresh legion info **/ case 0x08: sendPacket(new SM_LEGION_INFO(legion)); break; /** Edit announcements **/ case 0x09: changeAnnouncement(legion); break; /** Change self introduction **/ case 0x0A: changeSelfIntro(activePlayer.getObjectId(), activePlayer.getLegionMember()); break; /** Edit permissions **/ case 0x0D: if(checkPermissions()) changePermissions(legion); break; /** Level legion up **/ case 0x0E: legionLevelUp(activePlayer.getInventory().getKinahItem().getItemCount(), legion); break; /** Set nickname **/ case 0x0F: Player selectedPlayer = world.findPlayer(charName); if(selectedPlayer == null || selectedPlayer.getLegionMember().getLegion() != legion) // Player offline or NOT in same legion as player return; changeNickname(selectedPlayer.getObjectId(), selectedPlayer.getLegionMember()); break; } } else { switch(exOpcode) { /** Create a legion **/ case 0x00: Legion legion = new Legion(aionObjectsIDFactory.nextId(), legionName); /* Some reasons why legions can' be created */ if(!legionService.isValidName(legion.getLegionName())) { log.debug("[CM_LEGION] Player " + activePlayer.getObjectId() + " tried to create legion with an invalid name."); aionObjectsIDFactory.releaseId(legion.getLegionId()); sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_INVALID_NAME()); return; } else if(!legionService.isFreeName(legion.getLegionName())) { log.debug("[CM_LEGION] Player " + activePlayer.getObjectId() + " tried to create legion with existing name."); aionObjectsIDFactory.releaseId(legion.getLegionId()); sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_NAME_EXISTS()); return; } // if(activePlayer.getDisbandLegionTime() < Config.LEGION_DISBAND_DIFFERENCE) // { // sendPacket(SM_SYSTEM_MESSAGE.LEGION_LEGION_CREATE_LAST_DAY_CHECK()); // } else if(activePlayer.isLegionMember()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_ALREADY_MEMBER()); } else if(activePlayer.getInventory().getKinahItem().getItemCount() < LegionConfig.LEGION_CREATE_REQUIRED_KINAH) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_NOT_ENOUGH_KINAH()); } else if(legionService.storeNewLegion(legion)) { log.debug("[CM_LEGION] Legion has been created!."); /** Send the packets that contain legion info to legion leader **/ sendLegionCreationInfo(activePlayer, legion); } else { // Legion Creation Failed SYSTEM_MSG? // player.sendPacket(new SM_CREATE_CHARACTER(null, SM_CREATE_CHARACTER.RESPONSE_DB_ERROR)); } break; } } }
protected void runImpl() { final Player activePlayer = getConnection().getActivePlayer(); if(activePlayer.isLegionMember()) { final Legion legion = activePlayer.getLegionMember().getLegion(); switch(exOpcode) { /** Invite to legion **/ case 0x01: if(activePlayer.getLifeStats().isAlreadyDead()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_INVITE_WHILE_DEAD()); } else { final Player targetPlayer = world.findPlayer(charName); if(charName.equalsIgnoreCase(activePlayer.getName())) { // Invalid chars } else if(targetPlayer == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_NO_USER_TO_INVITE()); } else if(targetPlayer.getObjectId() == activePlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CAN_NOT_INVITE_SELF()); } else if(targetPlayer.isLegionMember()) { if(targetPlayer.getLegionMember().getLegion() == legion) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_HE_IS_MY_GUILD_MEMBER(targetPlayer.getName())); } else { sendPacket(SM_SYSTEM_MESSAGE.LEGION_HE_IS_OTHER_GUILD_MEMBER(targetPlayer.getName())); } } else { invitePlayerToLegion(activePlayer, targetPlayer, legion); } } break; /** Leave legion **/ case 0x02: leaveLegion(activePlayer, legion); break; /** Kick member from legion **/ case 0x04: Player kickedPlayer = world.findPlayer(charName); if(kickedPlayer != null) { if(kickedPlayer.getObjectId() == activePlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_KICK_YOURSELF()); } else if(kickedPlayer.getLegionMember().getRank() == BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CANT_KICK_BRIGADE_GENERAL()); } else { // TODO: Can not kick during a war!! kickMemberFromLegion(activePlayer.getName(), kickedPlayer, legion); } } else { // Player off line / does not exist? send message to player? } break; /** Appoint a new Brigade General **/ case 0x05: Player newBrigadeGeneral = world.findPlayer(charName); if(newBrigadeGeneral == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_NO_USER()); } else if(activePlayer.getLegionMember().getRank() != BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_DONT_HAVE_RIGHT()); } else if(activePlayer.getObjectId() == newBrigadeGeneral.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MASTER_ERROR_SELF()); } else { appointNewBrigadeGeneral(newBrigadeGeneral); } break; /** Appoint Centurion/Legionairy **/ case 0x06: Player targetPlayer = world.findPlayer(charName); if(targetPlayer == null) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_NO_USER()); } else if(activePlayer.getLegionMember().getRank() != BRIGADE_GENERAL_RANK) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_DONT_HAVE_RIGHT()); } else if(activePlayer.getObjectId() == targetPlayer.getObjectId()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CHANGE_MEMBER_RANK_ERROR_SELF()); } else { if(rank == LEGIONAIRY_RANK) { demoteToLegionary(targetPlayer); } else if(rank == CENTURION_RANK) { appointCenturion(targetPlayer); } } break; /** Refresh legion info **/ case 0x08: sendPacket(new SM_LEGION_INFO(legion)); break; /** Edit announcements **/ case 0x09: changeAnnouncement(legion); break; /** Change self introduction **/ case 0x0A: changeSelfIntro(activePlayer.getObjectId(), activePlayer.getLegionMember()); break; /** Edit permissions **/ case 0x0D: if(checkPermissions()) changePermissions(legion); break; /** Level legion up **/ case 0x0E: legionLevelUp(activePlayer.getInventory().getKinahItem().getItemCount(), legion); break; /** Set nickname **/ case 0x0F: Player selectedPlayer = world.findPlayer(charName); if(selectedPlayer == null || selectedPlayer.getLegionMember().getLegion() != legion) // Player offline or NOT in same legion as player return; changeNickname(selectedPlayer.getObjectId(), selectedPlayer.getLegionMember()); break; } } else { switch(exOpcode) { /** Create a legion **/ case 0x00: Legion legion = new Legion(aionObjectsIDFactory.nextId(), legionName); /* Some reasons why legions can' be created */ if(!legionService.isValidName(legion.getLegionName())) { log.debug("[CM_LEGION] Player " + activePlayer.getObjectId() + " tried to create legion with an invalid name."); aionObjectsIDFactory.releaseId(legion.getLegionId()); sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_INVALID_NAME()); return; } else if(!legionService.isFreeName(legion.getLegionName())) { log.debug("[CM_LEGION] Player " + activePlayer.getObjectId() + " tried to create legion with existing name."); aionObjectsIDFactory.releaseId(legion.getLegionId()); sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_NAME_EXISTS()); return; } // if(activePlayer.getDisbandLegionTime() < Config.LEGION_DISBAND_DIFFERENCE) // { // sendPacket(SM_SYSTEM_MESSAGE.LEGION_LEGION_CREATE_LAST_DAY_CHECK()); // } else if(activePlayer.isLegionMember()) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_ALREADY_MEMBER()); } else if(activePlayer.getInventory().getKinahItem().getItemCount() < LegionConfig.LEGION_CREATE_REQUIRED_KINAH) { sendPacket(SM_SYSTEM_MESSAGE.LEGION_CREATE_NOT_ENOUGH_KINAH()); } else if(legionService.storeNewLegion(legion)) { log.debug("[CM_LEGION] Legion has been created!."); activePlayer.getInventory().decreaseKinah(LegionConfig.LEGION_CREATE_REQUIRED_KINAH); /** Send the packets that contain legion info to legion leader **/ sendLegionCreationInfo(activePlayer, legion); } else { // Legion Creation Failed SYSTEM_MSG? // player.sendPacket(new SM_CREATE_CHARACTER(null, SM_CREATE_CHARACTER.RESPONSE_DB_ERROR)); } break; } } }
diff --git a/dbflute-runtime/src/main/java/org/seasar/dbflute/cbean/sqlclause/SqlClauseMsAccess.java b/dbflute-runtime/src/main/java/org/seasar/dbflute/cbean/sqlclause/SqlClauseMsAccess.java index 6a49d9205..32136f0bf 100644 --- a/dbflute-runtime/src/main/java/org/seasar/dbflute/cbean/sqlclause/SqlClauseMsAccess.java +++ b/dbflute-runtime/src/main/java/org/seasar/dbflute/cbean/sqlclause/SqlClauseMsAccess.java @@ -1,165 +1,166 @@ /* * Copyright 2004-2011 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.dbflute.cbean.sqlclause; import java.util.Map; import org.seasar.dbflute.cbean.sqlclause.join.FixedConditionResolver; import org.seasar.dbflute.cbean.sqlclause.orderby.OrderByClause; import org.seasar.dbflute.dbmeta.name.ColumnRealName; import org.seasar.dbflute.dbway.DBWay; import org.seasar.dbflute.dbway.WayOfMSAccess; import org.seasar.dbflute.exception.IllegalConditionBeanOperationException; import org.seasar.dbflute.util.Srl; /** * SqlClause for MS Access. * @author jflute */ public class SqlClauseMsAccess extends AbstractSqlClause { // =================================================================================== // Definition // ========== /** Serial version UID. (Default) */ private static final long serialVersionUID = 1L; /** The instance of DBWay. */ protected static final DBWay _dbway = new WayOfMSAccess(); // =================================================================================== // Constructor // =========== /** * Constructor. * @param tableDbName The DB name of table. (NotNull) **/ public SqlClauseMsAccess(String tableDbName) { super(tableDbName); } // =================================================================================== // From Override // ============= @Override protected boolean isJoinInParentheses() { return true; // needs to join in parentheses at MS Access } // =================================================================================== // OuterJoin Override // ================== @Override public void registerOuterJoin(String foreignAliasName, String foreignTableDbName, String localAliasName, String localTableDbName, Map<ColumnRealName, ColumnRealName> joinOnMap, String fixedCondition, FixedConditionResolver fixedConditionResolver) { // MS-Access does not support additional conditions on OnClause // so switch it to in-line where clause - super.registerOuterJoin(foreignAliasName, foreignTableDbName, localAliasName, localTableDbName, joinOnMap, - null, null); - if (fixedCondition != null) { + super.registerOuterJoin(foreignAliasName, foreignTableDbName, localAliasName, localTableDbName // normal + , joinOnMap // normal until here + , null, null); // null set to OnClause + if (fixedCondition != null) { // uses it instead of null set if (fixedConditionResolver != null) { fixedCondition = fixedConditionResolver.resolveVariable(fixedCondition); } final String clause = Srl.replace(fixedCondition, foreignAliasName + ".", ""); registerOuterJoinInlineWhereClause(foreignAliasName, clause, false); } } // =================================================================================== // OrderBy Override // ================ @Override protected OrderByClause.OrderByNullsSetupper createOrderByNullsSetupper() { return createOrderByNullsSetupperByCaseWhen(); } /** * {@inheritDoc} */ protected void doFetchFirst() { } /** * {@inheritDoc} */ protected void doFetchPage() { } /** * {@inheritDoc} */ protected void doClearFetchPageClause() { } /** * {@inheritDoc} */ public boolean isFetchStartIndexSupported() { return false; } /** * {@inheritDoc} */ public boolean isFetchSizeSupported() { return false; } /** * {@inheritDoc} */ public void lockForUpdate() { String msg = "LockForUpdate-SQL is unavailable in the database. Sorry...: " + toString(); throw new IllegalConditionBeanOperationException(msg); } /** * {@inheritDoc} */ protected String createSelectHint() { return ""; } /** * {@inheritDoc} */ protected String createFromBaseTableHint() { return ""; } /** * {@inheritDoc} */ protected String createFromHint() { return ""; } /** * {@inheritDoc} */ protected String createSqlSuffix() { return ""; } // [DBFlute-0.9.8.4] // =================================================================================== // DBWay // ===== public DBWay dbway() { return _dbway; } }
true
true
public void registerOuterJoin(String foreignAliasName, String foreignTableDbName, String localAliasName, String localTableDbName, Map<ColumnRealName, ColumnRealName> joinOnMap, String fixedCondition, FixedConditionResolver fixedConditionResolver) { // MS-Access does not support additional conditions on OnClause // so switch it to in-line where clause super.registerOuterJoin(foreignAliasName, foreignTableDbName, localAliasName, localTableDbName, joinOnMap, null, null); if (fixedCondition != null) { if (fixedConditionResolver != null) { fixedCondition = fixedConditionResolver.resolveVariable(fixedCondition); } final String clause = Srl.replace(fixedCondition, foreignAliasName + ".", ""); registerOuterJoinInlineWhereClause(foreignAliasName, clause, false); } }
public void registerOuterJoin(String foreignAliasName, String foreignTableDbName, String localAliasName, String localTableDbName, Map<ColumnRealName, ColumnRealName> joinOnMap, String fixedCondition, FixedConditionResolver fixedConditionResolver) { // MS-Access does not support additional conditions on OnClause // so switch it to in-line where clause super.registerOuterJoin(foreignAliasName, foreignTableDbName, localAliasName, localTableDbName // normal , joinOnMap // normal until here , null, null); // null set to OnClause if (fixedCondition != null) { // uses it instead of null set if (fixedConditionResolver != null) { fixedCondition = fixedConditionResolver.resolveVariable(fixedCondition); } final String clause = Srl.replace(fixedCondition, foreignAliasName + ".", ""); registerOuterJoinInlineWhereClause(foreignAliasName, clause, false); } }
diff --git a/libraries/javalib/java/util/ArrayList.java b/libraries/javalib/java/util/ArrayList.java index 9147982d5..889069e18 100644 --- a/libraries/javalib/java/util/ArrayList.java +++ b/libraries/javalib/java/util/ArrayList.java @@ -1,250 +1,251 @@ /* * Java core library component. * * Copyright (c) 1999 * Archie L. Cobbs. All rights reserved. * Copyright (c) 1999 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. * * Author: Archie L. Cobbs <[email protected]> */ package java.util; import java.io.Serializable; import java.lang.reflect.Array; public class ArrayList extends AbstractList implements List, Cloneable, Serializable { private static final int DEFAULT_CAPACITY = 32; private Object[] a; private int off; private int len; public ArrayList() { this(DEFAULT_CAPACITY); } public ArrayList(Collection c) { final Iterator i = c.iterator(); a = new Object[(c.size() * 11) / 10]; off = 0; int count; for (count = 0; i.hasNext(); count++) { a[count] = i.next(); } len = count; } public ArrayList(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException("initialCapacity < 0"); } a = new Object[initialCapacity]; off = 0; len = 0; } // Used by Arrays.asList() ArrayList(Object[] a) { a = a; off = 0; len = a.length; } public void trimToSize() { if (off != 0 || len != a.length) { Object[] newa = new Object[len]; System.arraycopy(a, off, newa, 0, len); modCount++; off = 0; a = newa; } } public void ensureCapacity(int minCapacity) { // Check current capacity if (a.length - off >= minCapacity) { return; } // Round up desired capacity to nearest power of 2 (- 12) to // avoid n^2 behavior when adding one element at a time. The // -12 part should be optimized from empirical tests. int bit, newSize; for (bit = 0x10; bit != 0x80000000; bit <<= 1) { if (bit - 12 >= minCapacity) { break; } } if (bit == 0x80000000) { throw new IllegalArgumentException("too big"); } newSize = bit - 12; // Allocate new array Object[] newa = new Object[newSize]; System.arraycopy(a, off, newa, 0, len); modCount++; a = newa; + off = 0; } public int size() { return len; } public boolean isEmpty() { return len == 0; } public boolean contains(Object elem) { return indexOf(elem) != -1; } public int indexOf(Object elem) { for (int i = off; i < off + len; i++) { if (elem == null ? a[i] == null : elem.equals(a[i])) { return i - off; } } return -1; } public int lastIndexOf(Object elem) { for (int i = off + len - 1; i >= off; i--) { if (elem == null ? a[i] == null : elem.equals(a[i])) { return i - off; } } return -1; } public Object clone() { ArrayList minime = new ArrayList(len); System.arraycopy(a, off, minime.a, 0, len); minime.len = len; return minime; } public Object[] toArray() { Object[] newa = new Object[len]; System.arraycopy(a, off, newa, 0, len); return newa; } public Object[] toArray(Object[] ary) { if (ary.length < len) { ary = (Object[])Array.newInstance( ary.getClass().getComponentType(), len); } System.arraycopy(a, off, ary, 0, len); if (ary.length > len) { ary[len] = null; } return ary; } public Object get(int index) { if (index < 0 || index >= len) { throw new IndexOutOfBoundsException(); } return a[off + index]; } public Object set(int index, Object element) { if (index < 0 || index >= len) { throw new IndexOutOfBoundsException(); } Object old = a[off + index]; a[off + index] = element; return old; } public boolean add(Object element) { add(len, element); return true; } public void add(int index, Object element) { if (index < 0 || index > len) { throw new IndexOutOfBoundsException(); } final int initialModCount = modCount; if (off > 0 && index < len / 2) { System.arraycopy(a, off, a, off - 1, index); off--; } else { ensureCapacity(len + 1); System.arraycopy(a, off + index, a, off + index + 1, len - index); } modCount = initialModCount + 1; a[off + index] = element; len++; } public Object remove(int index) { Object old = a[off + index]; // exception here is OK removeRange(index, index + 1); return old; } public void clear() { modCount++; off = len = 0; } public boolean addAll(Collection c) { addAll(len, c); return true; } public boolean addAll(int index, Collection c) { if (index < 0 || index > len) { throw new IndexOutOfBoundsException(); } final Iterator i = c.iterator(); final int increase = c.size(); final int initialModCount = modCount; if (off >= increase && index < len / 2) { modCount++; System.arraycopy(a, off, a, off - increase, index); off -= increase; } else { ensureCapacity(len + increase); modCount = initialModCount + 1; System.arraycopy(a, off + index, a, off + index + increase, len - index); } for (int index2 = off + index; i.hasNext(); index2++) { a[index2] = i.next(); } len += increase; return true; } protected void removeRange(int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > len) { throw new IndexOutOfBoundsException(); } final int decrease = toIndex - fromIndex; if (decrease <= 0) { return; } modCount++; if (fromIndex == 0) { off += toIndex; } else { System.arraycopy(a, off + toIndex, a, off + fromIndex, len - toIndex); } len -= decrease; } }
true
true
public void ensureCapacity(int minCapacity) { // Check current capacity if (a.length - off >= minCapacity) { return; } // Round up desired capacity to nearest power of 2 (- 12) to // avoid n^2 behavior when adding one element at a time. The // -12 part should be optimized from empirical tests. int bit, newSize; for (bit = 0x10; bit != 0x80000000; bit <<= 1) { if (bit - 12 >= minCapacity) { break; } } if (bit == 0x80000000) { throw new IllegalArgumentException("too big"); } newSize = bit - 12; // Allocate new array Object[] newa = new Object[newSize]; System.arraycopy(a, off, newa, 0, len); modCount++; a = newa; }
public void ensureCapacity(int minCapacity) { // Check current capacity if (a.length - off >= minCapacity) { return; } // Round up desired capacity to nearest power of 2 (- 12) to // avoid n^2 behavior when adding one element at a time. The // -12 part should be optimized from empirical tests. int bit, newSize; for (bit = 0x10; bit != 0x80000000; bit <<= 1) { if (bit - 12 >= minCapacity) { break; } } if (bit == 0x80000000) { throw new IllegalArgumentException("too big"); } newSize = bit - 12; // Allocate new array Object[] newa = new Object[newSize]; System.arraycopy(a, off, newa, 0, len); modCount++; a = newa; off = 0; }
diff --git a/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java b/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java index 5fa91593..51b87809 100644 --- a/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java +++ b/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java @@ -1,179 +1,179 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.deltaspike.cdise.tck; import org.apache.deltaspike.cdise.api.CdiContainer; import org.apache.deltaspike.cdise.api.CdiContainerLoader; import org.apache.deltaspike.cdise.tck.beans.Car; import org.apache.deltaspike.cdise.tck.beans.CarRepair; import org.junit.Assert; import org.junit.Test; import javax.enterprise.context.ContextNotActiveException; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import java.util.Set; /** * TCK test for the {@link org.apache.deltaspike.cdise.api.CdiContainer} */ public class ContainerCtrlTckTest { @Test public void testContainerBoot() { CdiContainer cc = CdiContainerLoader.getCdiContainer(); Assert.assertNotNull(cc); cc.boot(); cc.getContextControl().startContexts(); BeanManager bm = cc.getBeanManager(); Assert.assertNotNull(bm); Set<Bean<?>> beans = bm.getBeans(CarRepair.class); Bean<?> bean = bm.resolve(beans); CarRepair carRepair = (CarRepair) bm.getReference(bean, CarRepair.class, bm.createCreationalContext(bean)); Assert.assertNotNull(carRepair); Assert.assertNotNull(carRepair.getCar()); Assert.assertNotNull(carRepair.getCar().getUser()); cc.shutdown(); } @Test public void testSimpleContainerBoot() { CdiContainer cc = CdiContainerLoader.getCdiContainer(); Assert.assertNotNull(cc); cc.boot(); cc.getContextControl().startContexts(); BeanManager bm = cc.getBeanManager(); Assert.assertNotNull(bm); Set<Bean<?>> beans = bm.getBeans(CarRepair.class); Bean<?> bean = bm.resolve(beans); CarRepair carRepair = (CarRepair) bm.getReference(bean, CarRepair.class, bm.createCreationalContext(bean)); Assert.assertNotNull(carRepair); Assert.assertNotNull(carRepair.getCar()); Assert.assertNotNull(carRepair.getCar().getUser()); cc.shutdown(); } /** * Stops and starts: application-, session- and request-scope. * <p/> * application-scoped instance has a ref to * request-scoped instance which has a ref to * session-scoped instance. * <p/> * If the deepest ref has the expected value, all levels in between were resetted correctly. */ @Test public void testRestartContexts() { CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer(); Assert.assertNotNull(cdiContainer); cdiContainer.boot(); cdiContainer.getContextControl().startContexts(); BeanManager beanManager = cdiContainer.getBeanManager(); Assert.assertNotNull(beanManager); Set<Bean<?>> beans = beanManager.getBeans(CarRepair.class); Bean<?> bean = beanManager.resolve(beans); CarRepair carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair); Car car = carRepair.getCar(); Assert.assertNotNull(car); Assert.assertNotNull(car.getUser()); carRepair.getCar().getUser().setName("tester"); Assert.assertEquals("tester", car.getUser().getName()); cdiContainer.getContextControl().stopContexts(); try { - Assert.assertNotNull(car.getUser()); + car.getUser(); // accessing the car should have triggered a ContextNotActiveException Assert.fail(); } catch (ContextNotActiveException e) { //do nothing - exception expected } cdiContainer.getContextControl().startContexts(); carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair.getCar()); Assert.assertNotNull(carRepair.getCar().getUser()); Assert.assertNull(carRepair.getCar().getUser().getName()); cdiContainer.shutdown(); } @Test public void testShutdownWithInactiveContexts() { CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer(); Assert.assertNotNull(cdiContainer); cdiContainer.boot(); cdiContainer.getContextControl().startContexts(); // now do some randmo stuff BeanManager beanManager = cdiContainer.getBeanManager(); Assert.assertNotNull(beanManager); Set<Bean<?>> beans = beanManager.getBeans(CarRepair.class); Bean<?> bean = beanManager.resolve(beans); CarRepair carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair); Car car = carRepair.getCar(); Assert.assertNotNull(car); cdiContainer.getContextControl().startContexts(); cdiContainer.shutdown(); } }
true
true
public void testRestartContexts() { CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer(); Assert.assertNotNull(cdiContainer); cdiContainer.boot(); cdiContainer.getContextControl().startContexts(); BeanManager beanManager = cdiContainer.getBeanManager(); Assert.assertNotNull(beanManager); Set<Bean<?>> beans = beanManager.getBeans(CarRepair.class); Bean<?> bean = beanManager.resolve(beans); CarRepair carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair); Car car = carRepair.getCar(); Assert.assertNotNull(car); Assert.assertNotNull(car.getUser()); carRepair.getCar().getUser().setName("tester"); Assert.assertEquals("tester", car.getUser().getName()); cdiContainer.getContextControl().stopContexts(); try { Assert.assertNotNull(car.getUser()); // accessing the car should have triggered a ContextNotActiveException Assert.fail(); } catch (ContextNotActiveException e) { //do nothing - exception expected } cdiContainer.getContextControl().startContexts(); carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair.getCar()); Assert.assertNotNull(carRepair.getCar().getUser()); Assert.assertNull(carRepair.getCar().getUser().getName()); cdiContainer.shutdown(); }
public void testRestartContexts() { CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer(); Assert.assertNotNull(cdiContainer); cdiContainer.boot(); cdiContainer.getContextControl().startContexts(); BeanManager beanManager = cdiContainer.getBeanManager(); Assert.assertNotNull(beanManager); Set<Bean<?>> beans = beanManager.getBeans(CarRepair.class); Bean<?> bean = beanManager.resolve(beans); CarRepair carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair); Car car = carRepair.getCar(); Assert.assertNotNull(car); Assert.assertNotNull(car.getUser()); carRepair.getCar().getUser().setName("tester"); Assert.assertEquals("tester", car.getUser().getName()); cdiContainer.getContextControl().stopContexts(); try { car.getUser(); // accessing the car should have triggered a ContextNotActiveException Assert.fail(); } catch (ContextNotActiveException e) { //do nothing - exception expected } cdiContainer.getContextControl().startContexts(); carRepair = (CarRepair) beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean)); Assert.assertNotNull(carRepair.getCar()); Assert.assertNotNull(carRepair.getCar().getUser()); Assert.assertNull(carRepair.getCar().getUser().getName()); cdiContainer.shutdown(); }
diff --git a/src/test/java/com/fasterxml/jackson/databind/interop/TestExternalizable.java b/src/test/java/com/fasterxml/jackson/databind/interop/TestExternalizable.java index a71422c6f..76ff088c3 100644 --- a/src/test/java/com/fasterxml/jackson/databind/interop/TestExternalizable.java +++ b/src/test/java/com/fasterxml/jackson/databind/interop/TestExternalizable.java @@ -1,242 +1,243 @@ package com.fasterxml.jackson.databind.interop; import java.io.*; import com.fasterxml.jackson.databind.*; /** * Simple test to ensure that we can make POJOs use Jackson * for JDK serialization, via {@link Externalizable} * * @since 2.1 */ public class TestExternalizable extends BaseMapTest { /* Not pretty, but needed to make ObjectMapper accessible from * static context (alternatively could use ThreadLocal). */ static class MapperHolder { private final ObjectMapper mapper = new ObjectMapper(); private final static MapperHolder instance = new MapperHolder(); public static ObjectMapper mapper() { return instance.mapper; } } /** * Helper class we need to adapt {@link ObjectOutput} as * {@link OutputStream} */ final static class ExternalizableInput extends InputStream { private final ObjectInput in; public ExternalizableInput(ObjectInput in) { this.in = in; } @Override public int available() throws IOException { return in.available(); } @Override public void close() throws IOException { in.close(); } @Override public boolean markSupported() { return false; } @Override public int read() throws IOException { return in.read(); } @Override public int read(byte[] buffer) throws IOException { return in.read(buffer); } @Override public int read(byte[] buffer, int offset, int len) throws IOException { return in.read(buffer, offset, len); } @Override public long skip(long n) throws IOException { return in.skip(n); } } /** * Helper class we need to adapt {@link ObjectOutput} as * {@link OutputStream} */ final static class ExternalizableOutput extends OutputStream { private final ObjectOutput out; public ExternalizableOutput(ObjectOutput out) { this.out = out; } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } @Override public void write(int ch) throws IOException { out.write(ch); } @Override public void write(byte[] data) throws IOException { out.write(data); } @Override public void write(byte[] data, int offset, int len) throws IOException { out.write(data, offset, len); } } // @com.fasterxml.jackson.annotation.JsonFormat(shape=com.fasterxml.jackson.annotation.JsonFormat.Shape.ARRAY) static class MyPojo implements Externalizable { public int id; public String name; public int[] values; public MyPojo() { } // for deserialization public MyPojo(int id, String name, int[] values) { this.id = id; this.name = name; this.values = values; } public void readExternal(ObjectInput in) throws IOException { // MapperHolder.mapper().readValue( MapperHolder.mapper().readerForUpdating(this).readValue(new ExternalizableInput(in)); } public void writeExternal(ObjectOutput oo) throws IOException { MapperHolder.mapper().writeValue(new ExternalizableOutput(oo), this); } @Override public boolean equals(Object o) { if (o == this) return true; if (o == null) return false; if (o.getClass() != getClass()) return false; MyPojo other = (MyPojo) o; if (other.id != id) return false; if (!other.name.equals(name)) return false; if (other.values.length != values.length) return false; for (int i = 0, end = values.length; i < end; ++i) { if (values[i] != other.values[i]) return false; } return true; } } /* /********************************************************** /* Actual tests /********************************************************** */ // Comparison, using JDK native static class MyPojoNative implements Serializable { private static final long serialVersionUID = 1L; public int id; public String name; public int[] values; public MyPojoNative(int id, String name, int[] values) { this.id = id; this.name = name; this.values = values; } } @SuppressWarnings("unused") public void testSerializeAsExternalizable() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(bytes); final MyPojo input = new MyPojo(13, "Foobar", new int[] { 1, 2, 3 } ); obs.writeObject(input); obs.close(); byte[] ser = bytes.toByteArray(); // Ok: just verify it contains stuff it should byte[] json = MapperHolder.mapper().writeValueAsBytes(input); int ix = indexOf(ser, json); if (ix < 0) { fail("Serialization ("+ser.length+") does NOT contain JSON (of "+json.length+")"); } // Sanity check: if (false) { bytes = new ByteArrayOutputStream(); obs = new ObjectOutputStream(bytes); MyPojoNative p = new MyPojoNative(13, "Foobar", new int[] { 1, 2, 3 } ); obs.writeObject(p); obs.close(); System.out.println("Native size: "+bytes.size()+", vs JSON: "+ser.length); } // then read back! ObjectInputStream ins = new ObjectInputStream(new ByteArrayInputStream(ser)); MyPojo output = (MyPojo) ins.readObject(); + ins.close(); assertNotNull(output); assertEquals(input, output); } /* /********************************************************** /* Helper methods /********************************************************** */ private int indexOf(byte[] full, byte[] fragment) { final byte first = fragment[0]; for (int i = 0, end = full.length-fragment.length; i < end; ++i) { if (full[i] != first) continue; if (matches(full, i, fragment)) { return i; } } return -1; } private boolean matches(byte[] full, int index, byte[] fragment) { for (int i = 1, end = fragment.length; i < end; ++i) { if (fragment[i] != full[index+i]) { return false; } } return true; } }
true
true
public void testSerializeAsExternalizable() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(bytes); final MyPojo input = new MyPojo(13, "Foobar", new int[] { 1, 2, 3 } ); obs.writeObject(input); obs.close(); byte[] ser = bytes.toByteArray(); // Ok: just verify it contains stuff it should byte[] json = MapperHolder.mapper().writeValueAsBytes(input); int ix = indexOf(ser, json); if (ix < 0) { fail("Serialization ("+ser.length+") does NOT contain JSON (of "+json.length+")"); } // Sanity check: if (false) { bytes = new ByteArrayOutputStream(); obs = new ObjectOutputStream(bytes); MyPojoNative p = new MyPojoNative(13, "Foobar", new int[] { 1, 2, 3 } ); obs.writeObject(p); obs.close(); System.out.println("Native size: "+bytes.size()+", vs JSON: "+ser.length); } // then read back! ObjectInputStream ins = new ObjectInputStream(new ByteArrayInputStream(ser)); MyPojo output = (MyPojo) ins.readObject(); assertNotNull(output); assertEquals(input, output); }
public void testSerializeAsExternalizable() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(bytes); final MyPojo input = new MyPojo(13, "Foobar", new int[] { 1, 2, 3 } ); obs.writeObject(input); obs.close(); byte[] ser = bytes.toByteArray(); // Ok: just verify it contains stuff it should byte[] json = MapperHolder.mapper().writeValueAsBytes(input); int ix = indexOf(ser, json); if (ix < 0) { fail("Serialization ("+ser.length+") does NOT contain JSON (of "+json.length+")"); } // Sanity check: if (false) { bytes = new ByteArrayOutputStream(); obs = new ObjectOutputStream(bytes); MyPojoNative p = new MyPojoNative(13, "Foobar", new int[] { 1, 2, 3 } ); obs.writeObject(p); obs.close(); System.out.println("Native size: "+bytes.size()+", vs JSON: "+ser.length); } // then read back! ObjectInputStream ins = new ObjectInputStream(new ByteArrayInputStream(ser)); MyPojo output = (MyPojo) ins.readObject(); ins.close(); assertNotNull(output); assertEquals(input, output); }
diff --git a/runtime/src/org/zaluum/launch/Run.java b/runtime/src/org/zaluum/launch/Run.java index 3315b12..ed2ab8f 100644 --- a/runtime/src/org/zaluum/launch/Run.java +++ b/runtime/src/org/zaluum/launch/Run.java @@ -1,55 +1,55 @@ package org.zaluum.launch; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.swing.JComponent; import javax.swing.JFrame; public class Run { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException { Class<?> c = Thread.currentThread().getContextClassLoader() .loadClass(args[0]); final Object instance = c.newInstance(); try { Field f = c.getField("_widget"); - final Method m = c.getMethod("apply"); + final Method m = c.getMethod("run"); JComponent comp = (JComponent) f.get(instance); JFrame frame = new JFrame(); frame.add(comp); frame.setSize(comp.getSize().width + 30, comp.getSize().height + 40); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent w) { System.exit(0); } }); new Thread(new Runnable() { public void run() { try { m.invoke(instance); } catch (InvocationTargetException e) { e.getCause().printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }).start(); frame.setVisible(true); } catch (NoSuchFieldError e) { System.err .println("FATAL : " + args[0] + " is not a widget Zaluum class"); return; } catch (NoSuchMethodError e) { System.err.println("FATAL : " + args[0] + " has not an apply() method"); } } }
true
true
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException { Class<?> c = Thread.currentThread().getContextClassLoader() .loadClass(args[0]); final Object instance = c.newInstance(); try { Field f = c.getField("_widget"); final Method m = c.getMethod("apply"); JComponent comp = (JComponent) f.get(instance); JFrame frame = new JFrame(); frame.add(comp); frame.setSize(comp.getSize().width + 30, comp.getSize().height + 40); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent w) { System.exit(0); } }); new Thread(new Runnable() { public void run() { try { m.invoke(instance); } catch (InvocationTargetException e) { e.getCause().printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }).start(); frame.setVisible(true); } catch (NoSuchFieldError e) { System.err .println("FATAL : " + args[0] + " is not a widget Zaluum class"); return; } catch (NoSuchMethodError e) { System.err.println("FATAL : " + args[0] + " has not an apply() method"); } }
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException { Class<?> c = Thread.currentThread().getContextClassLoader() .loadClass(args[0]); final Object instance = c.newInstance(); try { Field f = c.getField("_widget"); final Method m = c.getMethod("run"); JComponent comp = (JComponent) f.get(instance); JFrame frame = new JFrame(); frame.add(comp); frame.setSize(comp.getSize().width + 30, comp.getSize().height + 40); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent w) { System.exit(0); } }); new Thread(new Runnable() { public void run() { try { m.invoke(instance); } catch (InvocationTargetException e) { e.getCause().printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }).start(); frame.setVisible(true); } catch (NoSuchFieldError e) { System.err .println("FATAL : " + args[0] + " is not a widget Zaluum class"); return; } catch (NoSuchMethodError e) { System.err.println("FATAL : " + args[0] + " has not an apply() method"); } }
diff --git a/src/org/pixmob/hcl/HttpRequestBuilder.java b/src/org/pixmob/hcl/HttpRequestBuilder.java index 1507cc7..4470778 100644 --- a/src/org/pixmob/hcl/HttpRequestBuilder.java +++ b/src/org/pixmob/hcl/HttpRequestBuilder.java @@ -1,485 +1,487 @@ /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pixmob.hcl; import static org.pixmob.hcl.Constants.HTTP_GET; import static org.pixmob.hcl.Constants.HTTP_POST; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import android.content.Context; import android.os.Build; /** * This class is used to prepare and execute an Http request. * @author Pixmob */ public final class HttpRequestBuilder { private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private static final String CONTENT_CHARSET = "UTF-8"; private static final Map<String, List<String>> NO_HEADERS = new HashMap<String, List<String>>( 0); private static TrustManager[] trustManagers; private final byte[] buffer = new byte[1024]; private final HttpClient hc; private String uri; private String method; private Set<Integer> expectedStatusCodes = new HashSet<Integer>(2); private Map<String, String> cookies; private Map<String, List<String>> headers; private Map<String, String> parameters; private byte[] payload; private HttpResponseHandler handler; HttpRequestBuilder(final HttpClient hc, final String uri, final String method) { this.hc = hc; this.uri = uri; this.method = method; } public HttpRequestBuilder expectStatusCode(int... statusCodes) { if (statusCodes != null) { for (final int statusCode : statusCodes) { if (statusCode < 1) { throw new IllegalArgumentException("Invalid status code: " + statusCode); } expectedStatusCodes.add(statusCode); } } return this; } public HttpRequestBuilder setCookies(Map<String, String> cookies) { this.cookies = cookies; return this; } public HttpRequestBuilder setHeaders(Map<String, List<String>> headers) { this.headers = headers; return this; } public HttpRequestBuilder addHeader(String name, String value) { if (name == null) { throw new IllegalArgumentException("Header name cannot be null"); } if (value == null) { throw new IllegalArgumentException("Header value cannot be null"); } if (headers == null) { headers = new HashMap<String, List<String>>(2); } List<String> values = headers.get(name); if (values == null) { values = new ArrayList<String>(1); headers.put(name, values); } values.add(value); return this; } public HttpRequestBuilder setParameters(Map<String, String> parameters) { this.parameters = parameters; return this; } public HttpRequestBuilder setParameter(String name, String value) { if (name == null) { throw new IllegalArgumentException("Parameter name cannot be null"); } if (value == null) { throw new IllegalArgumentException("Parameter value cannot be null"); } if (parameters == null) { parameters = new HashMap<String, String>(4); } parameters.put(name, value); return this; } public HttpRequestBuilder setCookie(String name, String value) { if (name == null) { throw new IllegalArgumentException("Cookie name cannot be null"); } if (value == null) { throw new IllegalArgumentException("Cookie value cannot be null"); } if (cookies == null) { cookies = new HashMap<String, String>(2); } cookies.put(name, value); return this; } public HttpRequestBuilder setHandler(HttpResponseHandler handler) { this.handler = handler; return this; } public void execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try { if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (!HTTP_POST.equals(method)) { buf.append('?'); } for (final Map.Entry<String, String> e : parameters.entrySet()) { if (buf.length() != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)) .append(URLEncoder.encode(value, CONTENT_CHARSET)); } if (HTTP_POST.equals(method)) { try { payload = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); if (HTTP_GET.equals(method)) { conn.setDoInput(true); } if (HTTP_POST.equals(method)) { conn.setDoOutput(true); conn.setUseCaches(false); } if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers .entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (HTTP_POST.equals(method)) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); if (payload != null) { conn.setFixedLengthStreamingMode(payload.length); } } if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn .getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } payloadStream = new UncloseableInputStream(getInputStream(conn)); if (handler != null) { final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); try { handler.onResponse(resp); } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } + } else { + throw new HttpClientException("Response timeout from " + uri, e); } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) ; } catch (IOException ignore) { } payloadStream.forceClose(); } conn.disconnect(); } } } private static void prepareCookieHeader(Map<String, String> cookies, StringBuilder headerValue) { if (cookies != null) { for (final Map.Entry<String, String> e : cookies.entrySet()) { if (headerValue.length() != 0) { headerValue.append("; "); } headerValue.append(e.getKey()).append("=").append(e.getValue()); } } } /** * Open the {@link InputStream} of an Http response. This method supports * GZIP and DEFLATE responses. */ private static InputStream getInputStream(HttpURLConnection conn) throws IOException { final List<String> contentEncodingValues = conn.getHeaderFields().get( "Content-Encoding"); if (contentEncodingValues != null) { for (final String contentEncoding : contentEncodingValues) { if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { return new GZIPInputStream(conn.getInputStream()); } if (contentEncoding.contains("deflate")) { return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } } } } return conn.getInputStream(); } private static KeyStore loadCertificates(Context context) throws IOException { try { final KeyStore localTrustStore = KeyStore.getInstance("BKS"); final InputStream in = context.getResources().openRawResource( R.raw.hcl_keystore); try { localTrustStore.load(in, null); } finally { in.close(); } return localTrustStore; } catch (Exception e) { final IOException ioe = new IOException( "Failed to load SSL certificates"); ioe.initCause(e); throw ioe; } } /** * Setup SSL connection. */ private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException { final SSLContext sslContext; try { // SSL certificates are provided by the Guardian Project: // https://github.com/guardianproject/cacert if (trustManagers == null) { // Load SSL certificates: // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html // Earlier Android versions do not have updated root CA // certificates, resulting in connection errors. final KeyStore keyStore = loadCertificates(context); final CustomTrustManager customTrustManager = new CustomTrustManager( keyStore); trustManagers = new TrustManager[] { customTrustManager }; } // Init SSL connection with custom certificates. // The same SecureRandom instance is used for every connection to // speed up initialization. sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, SECURE_RANDOM); } catch (GeneralSecurityException e) { final IOException ioe = new IOException( "Failed to initialize SSL engine"); ioe.initCause(e); throw ioe; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Fix slow read: // http://code.google.com/p/android/issues/detail?id=13117 // Prior to ICS, the host name is still resolved even if we already // know its IP address, for each connection. final SSLSocketFactory delegate = sslContext.getSocketFactory(); final SSLSocketFactory socketFactory = new SSLSocketFactory() { @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { InetAddress addr = InetAddress.getByName(host); injectHostname(addr, host); return delegate.createSocket(addr, port); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return delegate.createSocket(host, port, localHost, localPort); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } private void injectHostname(InetAddress address, String host) { try { Field field = InetAddress.class .getDeclaredField("hostName"); field.setAccessible(true); field.set(address, host); } catch (Exception ignored) { } } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { injectHostname(s.getInetAddress(), host); return delegate.createSocket(s, host, port, autoClose); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } }; conn.setSSLSocketFactory(socketFactory); } else { conn.setSSLSocketFactory(sslContext.getSocketFactory()); } conn.setHostnameVerifier(new BrowserCompatHostnameVerifier()); } }
true
true
public void execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try { if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (!HTTP_POST.equals(method)) { buf.append('?'); } for (final Map.Entry<String, String> e : parameters.entrySet()) { if (buf.length() != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)) .append(URLEncoder.encode(value, CONTENT_CHARSET)); } if (HTTP_POST.equals(method)) { try { payload = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); if (HTTP_GET.equals(method)) { conn.setDoInput(true); } if (HTTP_POST.equals(method)) { conn.setDoOutput(true); conn.setUseCaches(false); } if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers .entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (HTTP_POST.equals(method)) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); if (payload != null) { conn.setFixedLengthStreamingMode(payload.length); } } if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn .getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } payloadStream = new UncloseableInputStream(getInputStream(conn)); if (handler != null) { final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); try { handler.onResponse(resp); } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) ; } catch (IOException ignore) { } payloadStream.forceClose(); } conn.disconnect(); } } }
public void execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try { if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (!HTTP_POST.equals(method)) { buf.append('?'); } for (final Map.Entry<String, String> e : parameters.entrySet()) { if (buf.length() != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)) .append(URLEncoder.encode(value, CONTENT_CHARSET)); } if (HTTP_POST.equals(method)) { try { payload = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); if (HTTP_GET.equals(method)) { conn.setDoInput(true); } if (HTTP_POST.equals(method)) { conn.setDoOutput(true); conn.setUseCaches(false); } if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers .entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (HTTP_POST.equals(method)) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); if (payload != null) { conn.setFixedLengthStreamingMode(payload.length); } } if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn .getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } payloadStream = new UncloseableInputStream(getInputStream(conn)); if (handler != null) { final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); try { handler.onResponse(resp); } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } } else { throw new HttpClientException("Response timeout from " + uri, e); } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) ; } catch (IOException ignore) { } payloadStream.forceClose(); } conn.disconnect(); } } }
diff --git a/src/main/java/com/minecraftdimensions/bungeesuiteteleports/listeners/TeleportsListener.java b/src/main/java/com/minecraftdimensions/bungeesuiteteleports/listeners/TeleportsListener.java index 58ca33b..3352be8 100644 --- a/src/main/java/com/minecraftdimensions/bungeesuiteteleports/listeners/TeleportsListener.java +++ b/src/main/java/com/minecraftdimensions/bungeesuiteteleports/listeners/TeleportsListener.java @@ -1,84 +1,93 @@ package com.minecraftdimensions.bungeesuiteteleports.listeners; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import com.minecraftdimensions.bungeesuiteteleports.managers.PermissionsManager; import com.minecraftdimensions.bungeesuiteteleports.managers.TeleportsManager; public class TeleportsListener implements Listener { @EventHandler public void playerConnect (PlayerJoinEvent e){ + if ( e.getPlayer().hasPermission( "bungeesuite.*" ) ) { + PermissionsManager.addAllPermissions( e.getPlayer() ); + } else if ( e.getPlayer().hasPermission( "bungeesuite.admin" ) ) { + PermissionsManager.addAdminPermissions( e.getPlayer() ); + } else if(e.getPlayer().hasPermission( "bungeesuite.vip" )){ + PermissionsManager.addVIPPermissions( e.getPlayer() ); + }else if ( e.getPlayer().hasPermission( "bungeesuite.user" ) ) { + PermissionsManager.addUserPermissions( e.getPlayer() ); + } if(TeleportsManager.pendingTeleports.containsKey(e.getPlayer().getName())){ Player t = TeleportsManager.pendingTeleports.get(e.getPlayer().getName()); TeleportsManager.pendingTeleports.remove(e.getPlayer().getName()); if(!t.isOnline()){ e.getPlayer().sendMessage("Player is no longer online"); return; } TeleportsManager.ignoreTeleport.add(e.getPlayer()); e.getPlayer().teleport(t); }else if (TeleportsManager.pendingTeleportLocations.containsKey(e.getPlayer().getName())){ Location l = TeleportsManager.pendingTeleportLocations.get(e.getPlayer().getName()); TeleportsManager.ignoreTeleport.add(e.getPlayer()); e.getPlayer().teleport(l); } } @EventHandler public void playerTeleport(PlayerTeleportEvent e){ if(e.isCancelled()){ return; } if(!e.getCause().equals(TeleportCause.PLUGIN)){ return; } if(TeleportsManager.ignoreTeleport.contains(e.getPlayer())){ TeleportsManager.ignoreTeleport.remove(e.getPlayer()); return; } TeleportsManager.sendTeleportBackLocation(e.getPlayer(), false); } @EventHandler public void playerLeave(PlayerQuitEvent e){ boolean empty = false; if(Bukkit.getOnlinePlayers().length==1){ empty = true; } TeleportsManager.sendTeleportBackLocation(e.getPlayer(), empty); } @EventHandler public void playerDeath(PlayerDeathEvent e){ TeleportsManager.sendDeathBackLocation(e.getEntity()); } @EventHandler(priority = EventPriority.NORMAL) public void setFormatChat(final PlayerLoginEvent e) { if(e.getPlayer().hasPermission("bungeesuite.*")){ PermissionsManager.addAllPermissions(e.getPlayer()); }else if(e.getPlayer().hasPermission("bungeesuite.admin")){ PermissionsManager.addAdminPermissions(e.getPlayer()); }else if(e.getPlayer().hasPermission("bungeesuite.vip")){ PermissionsManager.addVIPPermissions(e.getPlayer()); }else if(e.getPlayer().hasPermission("bungeesuite.user")){ PermissionsManager.addUserPermissions(e.getPlayer()); } } }
true
true
public void playerConnect (PlayerJoinEvent e){ if(TeleportsManager.pendingTeleports.containsKey(e.getPlayer().getName())){ Player t = TeleportsManager.pendingTeleports.get(e.getPlayer().getName()); TeleportsManager.pendingTeleports.remove(e.getPlayer().getName()); if(!t.isOnline()){ e.getPlayer().sendMessage("Player is no longer online"); return; } TeleportsManager.ignoreTeleport.add(e.getPlayer()); e.getPlayer().teleport(t); }else if (TeleportsManager.pendingTeleportLocations.containsKey(e.getPlayer().getName())){ Location l = TeleportsManager.pendingTeleportLocations.get(e.getPlayer().getName()); TeleportsManager.ignoreTeleport.add(e.getPlayer()); e.getPlayer().teleport(l); } }
public void playerConnect (PlayerJoinEvent e){ if ( e.getPlayer().hasPermission( "bungeesuite.*" ) ) { PermissionsManager.addAllPermissions( e.getPlayer() ); } else if ( e.getPlayer().hasPermission( "bungeesuite.admin" ) ) { PermissionsManager.addAdminPermissions( e.getPlayer() ); } else if(e.getPlayer().hasPermission( "bungeesuite.vip" )){ PermissionsManager.addVIPPermissions( e.getPlayer() ); }else if ( e.getPlayer().hasPermission( "bungeesuite.user" ) ) { PermissionsManager.addUserPermissions( e.getPlayer() ); } if(TeleportsManager.pendingTeleports.containsKey(e.getPlayer().getName())){ Player t = TeleportsManager.pendingTeleports.get(e.getPlayer().getName()); TeleportsManager.pendingTeleports.remove(e.getPlayer().getName()); if(!t.isOnline()){ e.getPlayer().sendMessage("Player is no longer online"); return; } TeleportsManager.ignoreTeleport.add(e.getPlayer()); e.getPlayer().teleport(t); }else if (TeleportsManager.pendingTeleportLocations.containsKey(e.getPlayer().getName())){ Location l = TeleportsManager.pendingTeleportLocations.get(e.getPlayer().getName()); TeleportsManager.ignoreTeleport.add(e.getPlayer()); e.getPlayer().teleport(l); } }
diff --git a/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/ProjectionFactory.java b/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/ProjectionFactory.java index cf1a8ca66..9805def64 100644 --- a/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/ProjectionFactory.java +++ b/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/ProjectionFactory.java @@ -1,44 +1,44 @@ /* * ProjectionFactory.java * * Created on 21 February 2002, 17:12 */ package org.geotools.proj4j; /** * * @author ian */ public class ProjectionFactory { /** Creates a new instance of ProjectionFactory */ public ProjectionFactory() { } /** Creates a new instance of Projection from an argument set*/ public static Projection createProjection(String[] args) throws ProjectionException{ ParamSet params = new ParamSet(); for(int i=0;i<args.length;i++){ params.addParam(args[i]); } if(params.contains("init")){ throw new ProjectionException("Init files not supported yet - please contribute code"); } if(!params.contains("proj")){ throw new ProjectionException("No proj parameter provided"); } String proj = params.getStringParam("proj"); proj=Character.toUpperCase(proj.charAt(0))+proj.substring(1); // convert to Java naming conventions Projection pin; try{ pin = (Projection)Class.forName("org.geotools.proj4j.projections."+proj).newInstance(); }catch(ClassNotFoundException e){ - throw new ProjectionException("Projection "+proj+" is not supported\n"+e); + throw new ProjectionException("Projection "+proj+" is not supported\n"); } catch(Exception ex){ throw new ProjectionException("Error creating instance of "+proj+"\n"+ex); } pin.setParams(params); return pin; } }
true
true
public static Projection createProjection(String[] args) throws ProjectionException{ ParamSet params = new ParamSet(); for(int i=0;i<args.length;i++){ params.addParam(args[i]); } if(params.contains("init")){ throw new ProjectionException("Init files not supported yet - please contribute code"); } if(!params.contains("proj")){ throw new ProjectionException("No proj parameter provided"); } String proj = params.getStringParam("proj"); proj=Character.toUpperCase(proj.charAt(0))+proj.substring(1); // convert to Java naming conventions Projection pin; try{ pin = (Projection)Class.forName("org.geotools.proj4j.projections."+proj).newInstance(); }catch(ClassNotFoundException e){ throw new ProjectionException("Projection "+proj+" is not supported\n"+e); } catch(Exception ex){ throw new ProjectionException("Error creating instance of "+proj+"\n"+ex); } pin.setParams(params); return pin; }
public static Projection createProjection(String[] args) throws ProjectionException{ ParamSet params = new ParamSet(); for(int i=0;i<args.length;i++){ params.addParam(args[i]); } if(params.contains("init")){ throw new ProjectionException("Init files not supported yet - please contribute code"); } if(!params.contains("proj")){ throw new ProjectionException("No proj parameter provided"); } String proj = params.getStringParam("proj"); proj=Character.toUpperCase(proj.charAt(0))+proj.substring(1); // convert to Java naming conventions Projection pin; try{ pin = (Projection)Class.forName("org.geotools.proj4j.projections."+proj).newInstance(); }catch(ClassNotFoundException e){ throw new ProjectionException("Projection "+proj+" is not supported\n"); } catch(Exception ex){ throw new ProjectionException("Error creating instance of "+proj+"\n"+ex); } pin.setParams(params); return pin; }
diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/channel/AbstractTxTimeoutMessageStoreTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/channel/AbstractTxTimeoutMessageStoreTests.java index 86227ad3ad..ae1d65188d 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/channel/AbstractTxTimeoutMessageStoreTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/channel/AbstractTxTimeoutMessageStoreTests.java @@ -1,92 +1,92 @@ /* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.springframework.integration.jdbc.store.channel; import javax.sql.DataSource; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.MessageChannel; import org.springframework.integration.jdbc.store.JdbcChannelMessageStore; import org.springframework.integration.support.MessageBuilder; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; /** * * @author Gunnar Hillert * */ abstract class AbstractTxTimeoutMessageStoreTests { private static final Log log = LogFactory.getLog(AbstractTxTimeoutMessageStoreTests.class); @Autowired protected DataSource dataSource; @Autowired protected MessageChannel inputChannel; @Autowired protected PlatformTransactionManager transactionManager; @Autowired protected TestService testService; @Autowired protected JdbcChannelMessageStore jdbcChannelMessageStore; public void test() throws InterruptedException { int maxMessages = 10; int maxWaitTime = 30000; final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value()); - transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); + transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); for (int i = 1; i <= maxMessages; ++i) { final String message = "TEST MESSAGE " + i; log.info("Sending message: " + message); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { inputChannel.send(MessageBuilder.withPayload(message).build()); } }); log.info(String.format("Done sending message %s of %s: %s", i, maxMessages, message)); } log.info("Done sending " + maxMessages + " messages."); Assert.assertTrue(String.format("Contdown latch did not count down from " + "%s to 0 in %sms.", maxMessages, maxWaitTime), testService.await(maxWaitTime)); Thread.sleep(2000); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(jdbcChannelMessageStore.getSizeOfIdCache())); Assert.assertEquals(Integer.valueOf(maxMessages), Integer.valueOf(testService.getSeenMessages().size())); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(testService.getDuplicateMessagesCount())); } }
true
true
public void test() throws InterruptedException { int maxMessages = 10; int maxWaitTime = 30000; final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value()); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); for (int i = 1; i <= maxMessages; ++i) { final String message = "TEST MESSAGE " + i; log.info("Sending message: " + message); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { inputChannel.send(MessageBuilder.withPayload(message).build()); } }); log.info(String.format("Done sending message %s of %s: %s", i, maxMessages, message)); } log.info("Done sending " + maxMessages + " messages."); Assert.assertTrue(String.format("Contdown latch did not count down from " + "%s to 0 in %sms.", maxMessages, maxWaitTime), testService.await(maxWaitTime)); Thread.sleep(2000); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(jdbcChannelMessageStore.getSizeOfIdCache())); Assert.assertEquals(Integer.valueOf(maxMessages), Integer.valueOf(testService.getSeenMessages().size())); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(testService.getDuplicateMessagesCount())); }
public void test() throws InterruptedException { int maxMessages = 10; int maxWaitTime = 30000; final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value()); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); for (int i = 1; i <= maxMessages; ++i) { final String message = "TEST MESSAGE " + i; log.info("Sending message: " + message); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { inputChannel.send(MessageBuilder.withPayload(message).build()); } }); log.info(String.format("Done sending message %s of %s: %s", i, maxMessages, message)); } log.info("Done sending " + maxMessages + " messages."); Assert.assertTrue(String.format("Contdown latch did not count down from " + "%s to 0 in %sms.", maxMessages, maxWaitTime), testService.await(maxWaitTime)); Thread.sleep(2000); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(jdbcChannelMessageStore.getSizeOfIdCache())); Assert.assertEquals(Integer.valueOf(maxMessages), Integer.valueOf(testService.getSeenMessages().size())); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(testService.getDuplicateMessagesCount())); }
diff --git a/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java b/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java index 0b25154..34c9382 100644 --- a/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java +++ b/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java @@ -1,328 +1,324 @@ /********************************************************************************** * $URL: https://source.sakaiproject.org/contrib/tfd/trunk/sdata/sdata-tool/impl/src/java/org/sakaiproject/sdata/tool/JCRDumper.java $ * $Id: JCRDumper.java 45207 2008-02-01 19:01:06Z [email protected] $ *********************************************************************************** * * Copyright (c) 2008 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.sdata.services.site; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.Role; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.sdata.tool.api.ServiceDefinition; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService.SelectionType; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.Tool; /** * TODO Javadoc * * @author */ public class SiteBean implements ServiceDefinition { private List<Site> mysites; private Session currentSession; private List<Map> MyMappedSites = new ArrayList<Map>(); private Map<String, Object> map2 = new HashMap<String, Object>();; private static final Log log = LogFactory.getLog(SiteBean.class); /** * TODO Javadoc * * @param sessionManager * @param siteService */ public SiteBean(SessionManager sessionManager, SiteService siteService, AuthzGroupService authzGroupService, String siteId) { boolean siteExists = true; String status = "900"; ArrayList<HashMap<String, Object>> arlpages = new ArrayList<HashMap<String, Object>>(); String curUser = sessionManager.getCurrentSessionUserId(); /* * Determine the sites the current user is a member of */ setCurrentSession(sessionManager.getCurrentSession()); setMysites((List<Site>) siteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null)); try { mysites.add(0, (siteService.getSite(siteService.getUserSiteId(currentSession .getUserId())))); } catch (IdUnusedException e) { e.printStackTrace(); } - for (Site site : mysites) - { - log.error(site.getTitle() + " - " + site.getId()); - } /* * See whether the user is allowed to see this page */ try { Site theSite = siteService.getSite(siteId); boolean member = false; map2.put("title", theSite.getTitle()); map2.put("id", siteId); if (!theSite.isPublished()) { status = "903"; } for (Site site : mysites) { if (site.getId().equals(siteId)) { member = true; } } if (member == false) { status = "902"; if (theSite.isAllowed(curUser, "read")) { status = "904"; member = true; } else if (theSite.isJoinable()) { status = "905"; } } int number = 0; if (member) { List<SitePage> pages = (List<SitePage>) theSite.getOrderedPages(); for (SitePage page : pages) { number++; HashMap<String, Object> mpages = new HashMap<String, Object>(); mpages.put("name", page.getTitle()); mpages.put("layout", page.getLayoutTitle()); mpages.put("number", number); mpages.put("popup", page.isPopUp()); ArrayList<HashMap<String, Object>> arltools = new ArrayList<HashMap<String, Object>>(); List<ToolConfiguration> lst = (List<ToolConfiguration>) page .getTools(); mpages.put("iconclass", "icon-" + lst.get(0).getToolId().replaceAll("[.]", "-")); for (ToolConfiguration conf : lst) { HashMap<String, Object> tool = new HashMap<String, Object>(); tool.put("url", conf.getId()); Tool t = conf.getTool(); if (t != null && t.getId() != null) { tool.put("title", conf.getTool().getTitle()); } else { tool.put("title", page.getTitle()); } arltools.add(tool); } mpages.put("tools", arltools); arlpages.add(mpages); } ArrayList<HashMap<String, String>> roles = new ArrayList<HashMap<String, String>>(); try { AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId); for (Object o : group.getRoles()) { Role r = (Role) o; HashMap<String, String> map = new HashMap<String, String>(); map.put("id", r.getId()); map.put("description", r.getDescription()); roles.add(map); } map2.put("roles", roles); } catch (Exception ex) { log.info("Roles undefined for " + siteId); } } } catch (IdUnusedException e) { status = "901"; e.printStackTrace(); } map2.put("status", status); map2.put("pages", arlpages); } protected class SDataSiteRole { private String id; private String description; public void setId(String id) { this.id = id; } public String getId() { return id; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } } /** * TODO Javadoc * * @param mysites */ public void setMysites(List<Site> mysites) { this.mysites = mysites; } /** * TODO Javadoc * * @return */ public List<Site> getMysites() { return mysites; } /** * TODO Javadoc * * @param currentSession */ public void setCurrentSession(Session currentSession) { this.currentSession = currentSession; } /** * TODO Javadoc * * @return */ public Session getCurrentSession() { return currentSession; } /* * (non-Javadoc) * * @see org.sakaiproject.sdata.tool.api.ServiceDefinition#getResponseMap() */ public Map<String, Object> getResponseMap() { return map2; } /** * TODO Javadoc * * @param myMappedSites */ public void setMyMappedSites(List<Map> myMappedSites) { MyMappedSites = myMappedSites; } /** * TODO Javadoc * * @return */ public List<Map> getMyMappedSites() { return MyMappedSites; } }
true
true
public SiteBean(SessionManager sessionManager, SiteService siteService, AuthzGroupService authzGroupService, String siteId) { boolean siteExists = true; String status = "900"; ArrayList<HashMap<String, Object>> arlpages = new ArrayList<HashMap<String, Object>>(); String curUser = sessionManager.getCurrentSessionUserId(); /* * Determine the sites the current user is a member of */ setCurrentSession(sessionManager.getCurrentSession()); setMysites((List<Site>) siteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null)); try { mysites.add(0, (siteService.getSite(siteService.getUserSiteId(currentSession .getUserId())))); } catch (IdUnusedException e) { e.printStackTrace(); } for (Site site : mysites) { log.error(site.getTitle() + " - " + site.getId()); } /* * See whether the user is allowed to see this page */ try { Site theSite = siteService.getSite(siteId); boolean member = false; map2.put("title", theSite.getTitle()); map2.put("id", siteId); if (!theSite.isPublished()) { status = "903"; } for (Site site : mysites) { if (site.getId().equals(siteId)) { member = true; } } if (member == false) { status = "902"; if (theSite.isAllowed(curUser, "read")) { status = "904"; member = true; } else if (theSite.isJoinable()) { status = "905"; } } int number = 0; if (member) { List<SitePage> pages = (List<SitePage>) theSite.getOrderedPages(); for (SitePage page : pages) { number++; HashMap<String, Object> mpages = new HashMap<String, Object>(); mpages.put("name", page.getTitle()); mpages.put("layout", page.getLayoutTitle()); mpages.put("number", number); mpages.put("popup", page.isPopUp()); ArrayList<HashMap<String, Object>> arltools = new ArrayList<HashMap<String, Object>>(); List<ToolConfiguration> lst = (List<ToolConfiguration>) page .getTools(); mpages.put("iconclass", "icon-" + lst.get(0).getToolId().replaceAll("[.]", "-")); for (ToolConfiguration conf : lst) { HashMap<String, Object> tool = new HashMap<String, Object>(); tool.put("url", conf.getId()); Tool t = conf.getTool(); if (t != null && t.getId() != null) { tool.put("title", conf.getTool().getTitle()); } else { tool.put("title", page.getTitle()); } arltools.add(tool); } mpages.put("tools", arltools); arlpages.add(mpages); } ArrayList<HashMap<String, String>> roles = new ArrayList<HashMap<String, String>>(); try { AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId); for (Object o : group.getRoles()) { Role r = (Role) o; HashMap<String, String> map = new HashMap<String, String>(); map.put("id", r.getId()); map.put("description", r.getDescription()); roles.add(map); } map2.put("roles", roles); } catch (Exception ex) { log.info("Roles undefined for " + siteId); } } } catch (IdUnusedException e) { status = "901"; e.printStackTrace(); } map2.put("status", status); map2.put("pages", arlpages); }
public SiteBean(SessionManager sessionManager, SiteService siteService, AuthzGroupService authzGroupService, String siteId) { boolean siteExists = true; String status = "900"; ArrayList<HashMap<String, Object>> arlpages = new ArrayList<HashMap<String, Object>>(); String curUser = sessionManager.getCurrentSessionUserId(); /* * Determine the sites the current user is a member of */ setCurrentSession(sessionManager.getCurrentSession()); setMysites((List<Site>) siteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null)); try { mysites.add(0, (siteService.getSite(siteService.getUserSiteId(currentSession .getUserId())))); } catch (IdUnusedException e) { e.printStackTrace(); } /* * See whether the user is allowed to see this page */ try { Site theSite = siteService.getSite(siteId); boolean member = false; map2.put("title", theSite.getTitle()); map2.put("id", siteId); if (!theSite.isPublished()) { status = "903"; } for (Site site : mysites) { if (site.getId().equals(siteId)) { member = true; } } if (member == false) { status = "902"; if (theSite.isAllowed(curUser, "read")) { status = "904"; member = true; } else if (theSite.isJoinable()) { status = "905"; } } int number = 0; if (member) { List<SitePage> pages = (List<SitePage>) theSite.getOrderedPages(); for (SitePage page : pages) { number++; HashMap<String, Object> mpages = new HashMap<String, Object>(); mpages.put("name", page.getTitle()); mpages.put("layout", page.getLayoutTitle()); mpages.put("number", number); mpages.put("popup", page.isPopUp()); ArrayList<HashMap<String, Object>> arltools = new ArrayList<HashMap<String, Object>>(); List<ToolConfiguration> lst = (List<ToolConfiguration>) page .getTools(); mpages.put("iconclass", "icon-" + lst.get(0).getToolId().replaceAll("[.]", "-")); for (ToolConfiguration conf : lst) { HashMap<String, Object> tool = new HashMap<String, Object>(); tool.put("url", conf.getId()); Tool t = conf.getTool(); if (t != null && t.getId() != null) { tool.put("title", conf.getTool().getTitle()); } else { tool.put("title", page.getTitle()); } arltools.add(tool); } mpages.put("tools", arltools); arlpages.add(mpages); } ArrayList<HashMap<String, String>> roles = new ArrayList<HashMap<String, String>>(); try { AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId); for (Object o : group.getRoles()) { Role r = (Role) o; HashMap<String, String> map = new HashMap<String, String>(); map.put("id", r.getId()); map.put("description", r.getDescription()); roles.add(map); } map2.put("roles", roles); } catch (Exception ex) { log.info("Roles undefined for " + siteId); } } } catch (IdUnusedException e) { status = "901"; e.printStackTrace(); } map2.put("status", status); map2.put("pages", arlpages); }
diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java index fca45c383..5b648d666 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java @@ -1,48 +1,48 @@ /** * * Copyright (C) 2011 Cloud Conscious, LLC. <[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 org.jclouds.gogrid.compute; import org.jclouds.compute.BaseComputeServiceLiveTest; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.sshj.config.SshjSshClientModule; import org.testng.annotations.Test; import com.google.inject.Module; /** * @author Oleksiy Yarmula */ //NOTE:without testName, this will not call @Before* and fail w/NPE during surefire @Test(groups = "live", singleThreaded = true, testName = "GoGridComputeServiceLiveTest") public class GoGridComputeServiceLiveTest extends BaseComputeServiceLiveTest { public GoGridComputeServiceLiveTest() { provider = "gogrid"; } @Override protected Module getSshModule() { return new SshjSshClientModule(); } protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) { // hostname is not completely predictable based on node metadata - assert execResponse.getOutput().trim().startsWith(node1.getName()); + assert execResponse.getOutput().trim().startsWith(node1.getName()) : execResponse + ": " + node1; } }
true
true
protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) { // hostname is not completely predictable based on node metadata assert execResponse.getOutput().trim().startsWith(node1.getName()); }
protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) { // hostname is not completely predictable based on node metadata assert execResponse.getOutput().trim().startsWith(node1.getName()) : execResponse + ": " + node1; }
diff --git a/src/org/encog/ml/genetic/population/BasicPopulation.java b/src/org/encog/ml/genetic/population/BasicPopulation.java index ab038ed04..c56857f09 100644 --- a/src/org/encog/ml/genetic/population/BasicPopulation.java +++ b/src/org/encog/ml/genetic/population/BasicPopulation.java @@ -1,479 +1,480 @@ /* * Encog(tm) Core v3.0 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2011 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.genetic.population; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.encog.ml.genetic.genome.Genome; import org.encog.ml.genetic.innovation.InnovationList; import org.encog.ml.genetic.species.Species; import org.encog.persist.BasicPersistedObject; import org.encog.persist.EncogCollection; import org.encog.persist.EncogPersistedObject; import org.encog.persist.Persistor; import org.encog.persist.map.PersistConst; import org.encog.persist.map.PersistedObject; import org.encog.persist.persistors.generic.GenericPersistor; import org.encog.util.identity.BasicGenerateID; import org.encog.util.identity.GenerateID; /** * Defines the basic functionality for a population of genomes. */ public class BasicPopulation extends BasicPersistedObject implements Population, EncogPersistedObject { /** * */ private static final long serialVersionUID = -4097921208348173582L; /** * Generate gene id's. */ private final GenerateID geneIDGenerate = new BasicGenerateID(); /** * Generate genome id's. */ private final GenerateID genomeIDGenerate = new BasicGenerateID(); /** * The population. */ private final List<Genome> genomes = new ArrayList<Genome>(); /** * Generate innovation id's. */ private final GenerateID innovationIDGenerate = new BasicGenerateID(); /** * A list of innovations, or null if this feature is not being used. */ private InnovationList innovations; /** * The old age penalty. */ private double oldAgePenalty = 0.3; /** * The old age threshold. */ private int oldAgeThreshold = 50; /** * How many genomes should be created. */ private int populationSize; /** * The species in this population. */ private final List<Species> species = new ArrayList<Species>(); /** * Generate species id's. */ private final GenerateID speciesIDGenerate = new BasicGenerateID(); /** * The survival rate. */ private double survivalRate = 0.2; /** * The young threshold. */ private int youngBonusAgeThreshold = 10; /** * The young score bonus. */ private double youngScoreBonus = 0.3; /** * The object name. */ private String name; /** * The object description. */ private String description; /** * The Encog collection this object belongs to, or null if none. */ private EncogCollection encogCollection; /** * Construct an empty population. */ public BasicPopulation() { this.populationSize = 0; } /** * Construct a population. * * @param populationSize * The population size. */ public BasicPopulation(final int populationSize) { this.populationSize = populationSize; } /** * Add a genome to the population. * * @param genome * The genome to add. */ public void add(final Genome genome) { this.genomes.add(genome); } /** * Add all of the specified members to this population. * * @param newPop * A list of new genomes to add. */ public void addAll(final List<? extends Genome> newPop) { this.genomes.addAll(newPop); } /** * @return Assign a gene id. */ public long assignGeneID() { return this.geneIDGenerate.generate(); } /** * @return Assign a genome id. */ public long assignGenomeID() { return this.genomeIDGenerate.generate(); } /** * @return Assign an innovation id. */ public long assignInnovationID() { return this.innovationIDGenerate.generate(); } /** * @return Assign a species id. */ public long assignSpeciesID() { return this.speciesIDGenerate.generate(); } /** * Clear all genomes from this population. */ public void clear() { this.genomes.clear(); } /** * @return A persistor for this object. */ public Persistor createPersistor() { return new GenericPersistor(BasicPopulation.class); } /** * Get a genome by index. Index 0 is the best genome. * * @param i * The genome to get. * @return The genome found at the specified index. */ public Genome get(final int i) { return this.genomes.get(i); } /** * @return The best genome in the population. */ public Genome getBest() { if (this.genomes.size() == 0) { return null; } else { return this.genomes.get(0); } } /** * @return This object's description. */ public String getDescription() { return this.description; } /** * @return The genomes in the population. */ public List<Genome> getGenomes() { return this.genomes; } /** * @return A list of innovations in this population. */ public InnovationList getInnovations() { return this.innovations; } /** * @return The name. */ public String getName() { return this.name; } /** * @return The old age penalty, or zero for none. */ public double getOldAgePenalty() { return this.oldAgePenalty; } /** * @return The old age threshold. */ public int getOldAgeThreshold() { return this.oldAgeThreshold; } /** * Get the population size. * * @return The population size. */ public int getPopulationSize() { return this.populationSize; } /** * @return The species in this population. */ public List<Species> getSpecies() { return this.species; } /** * @return The survival rate. */ public double getSurvivalRate() { return this.survivalRate; } /** * @return The age at which a genome is considered "young". */ public int getYoungBonusAgeThreshold() { return this.youngBonusAgeThreshold; } /** * @return The bonus applied to young genomes. */ public double getYoungScoreBonus() { return this.youngScoreBonus; } /** * Set the description. * @param theDescription The description. */ public void setDescription(final String theDescription) { this.description = theDescription; } /** * Set the innovation list. * * @param innovations * The innovations, or null to disable. */ public void setInnovations(final InnovationList innovations) { this.innovations = innovations; } /** * Set the name. * @param theName The new name. */ public void setName(final String theName) { this.name = theName; } /** * Set the old age penalty. * * @param oldAgePenalty * The percent the score is affected by. */ public void setOldAgePenalty(final double oldAgePenalty) { this.oldAgePenalty = oldAgePenalty; } /** * Set the threshold at which a genome is considered "old". * * @param oldAgeThreshold * The age. */ public void setOldAgeThreshold(final int oldAgeThreshold) { this.oldAgeThreshold = oldAgeThreshold; } /** * Set the population size. * * @param populationSize * The population size. */ public void setPopulationSize(final int populationSize) { this.populationSize = populationSize; } /** * Set the survival rate. * * @param survivalRate * The survival rate. */ public void setSurvivalRate(final double survivalRate) { this.survivalRate = survivalRate; } /** * Set the young bonus age threshold. * * @param youngBonusAgeThreshold * The age. */ public void setYoungBonusAgeThreshhold(final int youngBonusAgeThreshold) { this.youngBonusAgeThreshold = youngBonusAgeThreshold; } /** * Set the young genome bonus. * * @param youngScoreBonus * The score bonus. */ public void setYoungScoreBonus(final double youngScoreBonus) { this.youngScoreBonus = youngScoreBonus; } /** * @return The max size of the population. */ public int size() { return this.genomes.size(); } /** * Sort the population. */ public void sort() { Collections.sort(this.genomes); } /** * @return The collection this Encog object belongs to, null if none. */ public EncogCollection getCollection() { return this.encogCollection; } /** * Set the Encog collection that this object belongs to. */ public void setCollection(EncogCollection collection) { this.encogCollection = collection; } public boolean supportsMapPersistence() { return true; } public void persistToMap(PersistedObject obj) { obj.clear(PersistConst.TYPE_BASIC_POPULATION); obj.setStandardProperties(this); obj.setProperty( Population.PROPERTY_NEXT_GENE_ID, (int)this.geneIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_GENOME_ID, (int)this.genomeIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_INNOVATION_ID, (int)this.innovationIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_SPECIES_ID, (int)this.speciesIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_OLD_AGE_PENALTY ,this.oldAgePenalty, false); obj.setProperty( Population.PROPERTY_OLD_AGE_THRESHOLD ,this.oldAgeThreshold, false); obj.setProperty( Population.PROPERTY_POPULATION_SIZE ,this.populationSize, false); obj.setProperty( Population.PROPERTY_SURVIVAL_RATE ,this.survivalRate, false); obj.setProperty( Population.PROPERTY_YOUNG_AGE_BONUS ,this.youngScoreBonus, false); obj.setProperty( Population.PROPERTY_YOUNG_AGE_THRESHOLD ,this.youngBonusAgeThreshold, false); - obj.setPropertyGenericList( Population.PROPERTY_INNOVATIONS, this.innovations.getInnovations()); + if( this.innovations!=null ) + obj.setPropertyGenericList( Population.PROPERTY_INNOVATIONS, this.innovations.getInnovations()); obj.setPropertyGenericList( Population.PROPERTY_SPECIES, this.species); obj.setPropertyGenericList( Population.PROPERTY_GENOMES, this.genomes); } public void persistFromMap(PersistedObject obj) { obj.requireType(PersistConst.TYPE_BASIC_POPULATION); this.genomeIDGenerate.setCurrentID( obj.getPropertyInt( Population.PROPERTY_NEXT_GENOME_ID, true)); this.geneIDGenerate.setCurrentID( obj.getPropertyInt( Population.PROPERTY_NEXT_GENE_ID, true ) ); this.innovationIDGenerate.setCurrentID( obj.getPropertyInt( Population.PROPERTY_NEXT_INNOVATION_ID, true ) ); this.speciesIDGenerate.setCurrentID( obj.getPropertyInt( Population.PROPERTY_NEXT_SPECIES_ID, true ) ); this.oldAgePenalty = obj.getPropertyDouble(Population.PROPERTY_OLD_AGE_PENALTY, true); this.oldAgeThreshold = obj.getPropertyInt(Population.PROPERTY_OLD_AGE_THRESHOLD, true); this.populationSize = obj.getPropertyInt( Population.PROPERTY_POPULATION_SIZE, true); this.survivalRate = obj.getPropertyDouble( Population.PROPERTY_SURVIVAL_RATE, true); this.youngScoreBonus = obj.getPropertyDouble(Population.PROPERTY_YOUNG_AGE_BONUS, true); this.youngBonusAgeThreshold = obj.getPropertyInt(Population.PROPERTY_YOUNG_AGE_THRESHOLD, true); obj.getPropertyGenericList(Population.PROPERTY_GENOMES, this.genomes); } }
true
true
public void persistToMap(PersistedObject obj) { obj.clear(PersistConst.TYPE_BASIC_POPULATION); obj.setStandardProperties(this); obj.setProperty( Population.PROPERTY_NEXT_GENE_ID, (int)this.geneIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_GENOME_ID, (int)this.genomeIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_INNOVATION_ID, (int)this.innovationIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_SPECIES_ID, (int)this.speciesIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_OLD_AGE_PENALTY ,this.oldAgePenalty, false); obj.setProperty( Population.PROPERTY_OLD_AGE_THRESHOLD ,this.oldAgeThreshold, false); obj.setProperty( Population.PROPERTY_POPULATION_SIZE ,this.populationSize, false); obj.setProperty( Population.PROPERTY_SURVIVAL_RATE ,this.survivalRate, false); obj.setProperty( Population.PROPERTY_YOUNG_AGE_BONUS ,this.youngScoreBonus, false); obj.setProperty( Population.PROPERTY_YOUNG_AGE_THRESHOLD ,this.youngBonusAgeThreshold, false); obj.setPropertyGenericList( Population.PROPERTY_INNOVATIONS, this.innovations.getInnovations()); obj.setPropertyGenericList( Population.PROPERTY_SPECIES, this.species); obj.setPropertyGenericList( Population.PROPERTY_GENOMES, this.genomes); }
public void persistToMap(PersistedObject obj) { obj.clear(PersistConst.TYPE_BASIC_POPULATION); obj.setStandardProperties(this); obj.setProperty( Population.PROPERTY_NEXT_GENE_ID, (int)this.geneIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_GENOME_ID, (int)this.genomeIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_INNOVATION_ID, (int)this.innovationIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_NEXT_SPECIES_ID, (int)this.speciesIDGenerate.getCurrentID(), false ); obj.setProperty( Population.PROPERTY_OLD_AGE_PENALTY ,this.oldAgePenalty, false); obj.setProperty( Population.PROPERTY_OLD_AGE_THRESHOLD ,this.oldAgeThreshold, false); obj.setProperty( Population.PROPERTY_POPULATION_SIZE ,this.populationSize, false); obj.setProperty( Population.PROPERTY_SURVIVAL_RATE ,this.survivalRate, false); obj.setProperty( Population.PROPERTY_YOUNG_AGE_BONUS ,this.youngScoreBonus, false); obj.setProperty( Population.PROPERTY_YOUNG_AGE_THRESHOLD ,this.youngBonusAgeThreshold, false); if( this.innovations!=null ) obj.setPropertyGenericList( Population.PROPERTY_INNOVATIONS, this.innovations.getInnovations()); obj.setPropertyGenericList( Population.PROPERTY_SPECIES, this.species); obj.setPropertyGenericList( Population.PROPERTY_GENOMES, this.genomes); }
diff --git a/src/main/java/net/pms/util/StringUtil.java b/src/main/java/net/pms/util/StringUtil.java index 1927a05f8..b136fd15f 100644 --- a/src/main/java/net/pms/util/StringUtil.java +++ b/src/main/java/net/pms/util/StringUtil.java @@ -1,136 +1,137 @@ package net.pms.util; import static org.apache.commons.lang3.StringUtils.isBlank; public class StringUtil { private static final int[] MULTIPLIER = new int[] {1, 60, 3600, 24*3600}; public static final String ASS_TIME_FORMAT = "%01d:%02d:%02.2f"; public static final String SRT_TIME_FORMAT = "%02d:%02d:%02.3f"; public static final String SEC_TIME_FORMAT = "%02d:%02d:%02d"; /** * Appends "&lt;<u>tag</u> " to the StringBuilder. This is a typical HTML/DIDL/XML tag opening. * @param sb String to append the tag beginning to. * @param tag String that represents the tag */ public static void openTag(StringBuilder sb, String tag) { sb.append("&lt;"); sb.append(tag); } /** * Appends the closing symbol &gt; to the StringBuilder. This is a typical HTML/DIDL/XML tag closing. * @param sb String to append the ending character of a tag. */ public static void endTag(StringBuilder sb) { sb.append("&gt;"); } /** * Appends "&lt;/<u>tag</u>&gt;" to the StringBuilder. This is a typical closing HTML/DIDL/XML tag. * @param sb * @param tag */ public static void closeTag(StringBuilder sb, String tag) { sb.append("&lt;/"); sb.append(tag); sb.append("&gt;"); } public static void addAttribute(StringBuilder sb, String attribute, Object value) { sb.append(" "); sb.append(attribute); sb.append("=\""); sb.append(value); sb.append("\""); } public static void addXMLTagAndAttribute(StringBuilder sb, String tag, Object value) { sb.append("&lt;"); sb.append(tag); sb.append("&gt;"); sb.append(value); sb.append("&lt;/"); sb.append(tag); sb.append("&gt;"); } /** * Does basic transformations between characters and their HTML representation with ampersands. * @param s String to be encoded * @return Encoded String */ public static String encodeXML(String s) { s = s.replace("&", "&amp;"); s = s.replace("<", "&lt;"); s = s.replace(">", "&gt;"); s = s.replace("\"", "&quot;"); s = s.replace("'", "&apos;"); s = s.replace("&", "&amp;"); return s; } /** * Converts a URL string to a more canonical form * @param url String to be converted * @return Converted String. */ public static String convertURLToFileName(String url) { url = url.replace('/', '\u00b5'); url = url.replace('\\', '\u00b5'); url = url.replace(':', '\u00b5'); url = url.replace('?', '\u00b5'); url = url.replace('*', '\u00b5'); url = url.replace('|', '\u00b5'); url = url.replace('<', '\u00b5'); url = url.replace('>', '\u00b5'); return url; } /** * Parse as double, or if it's not just one number, handles {hour}:{minute}:{seconds} * * @param time * @return */ public static double convertStringToTime(String time) throws IllegalArgumentException { if (isBlank(time)) { throw new IllegalArgumentException("time String should not be blank."); } try { return Double.parseDouble(time); } catch (NumberFormatException e) { String[] arrs = time.split(":"); double value, sum = 0; for (int i = 0; i < arrs.length; i++) { - value = Double.parseDouble(arrs[arrs.length - i - 1]); + String tmp = arrs[arrs.length - i - 1]; + value = Double.parseDouble(tmp.replace(",", ".")); sum += value * MULTIPLIER[i]; } return sum; } } /** * Converts time to string. * * @param d time in double. * @param timeFormat Format string e.g. "%02d:%02d:%02d" or use predefined constants * ASS_TIME_FORMAT, SRT_TIME_FORMAT, SEC_TIME_FORMAT. * * @return Converted String. */ public static String convertTimeToString(double d, String timeFormat) { double s = d % 60; int h = (int) (d / 3600); int m = ((int) (d / 60)) % 60; if (timeFormat.equals(SRT_TIME_FORMAT)) { return String.format(timeFormat, h, m, s).replaceAll("\\.", ","); } return String.format(timeFormat, h, m, s); } }
true
true
public static double convertStringToTime(String time) throws IllegalArgumentException { if (isBlank(time)) { throw new IllegalArgumentException("time String should not be blank."); } try { return Double.parseDouble(time); } catch (NumberFormatException e) { String[] arrs = time.split(":"); double value, sum = 0; for (int i = 0; i < arrs.length; i++) { value = Double.parseDouble(arrs[arrs.length - i - 1]); sum += value * MULTIPLIER[i]; } return sum; } }
public static double convertStringToTime(String time) throws IllegalArgumentException { if (isBlank(time)) { throw new IllegalArgumentException("time String should not be blank."); } try { return Double.parseDouble(time); } catch (NumberFormatException e) { String[] arrs = time.split(":"); double value, sum = 0; for (int i = 0; i < arrs.length; i++) { String tmp = arrs[arrs.length - i - 1]; value = Double.parseDouble(tmp.replace(",", ".")); sum += value * MULTIPLIER[i]; } return sum; } }
diff --git a/src/net/jnotes/JNotes.java b/src/net/jnotes/JNotes.java index 7b684af..ee8af84 100644 --- a/src/net/jnotes/JNotes.java +++ b/src/net/jnotes/JNotes.java @@ -1,52 +1,52 @@ package net.jnotes; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.Scanner; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiUnavailableException; public class JNotes{ public static void main(String[] args) throws IOException { Tone t = new Tone(); LineNumberReader lnr = new LineNumberReader(new FileReader(new File("tune.txt"))); lnr.skip(Long.MAX_VALUE); System.out.println(lnr.getLineNumber()); TuneParser tp = new TuneParser(); Scanner sc = new Scanner(new File("tune.txt")); t.progChange(sc.nextInt()); - for(int i = 1; i < lnr.getLineNumber(); i++){ + for(int i = 1; i <= lnr.getLineNumber(); i++){ String note = sc.nextLine(); System.out.println(note.length()); for(int j = 4; j <= 24; j += 4){ if(note.length() == j){ int[] noteNo = new int[j / 4]; int[] delta = new int[j / 4]; for(int k = 0; k < noteNo.length; k++){ noteNo[k] = tp.decodeNote(note.substring(k * 4, k * 4 + 4)); delta[k] = tp.decodeDuration(note.substring(k * 4 + 2, k * 4 + 3)); t.noteOn(0, noteNo[k], 127); } t.noteOff(delta[0], noteNo[0]); for(int k = 1; k < noteNo.length; k++){ t.noteOff(0, noteNo[k]); } } } } t.writeToFile("tune.mid"); try { t.play("tune.mid"); } catch (MidiUnavailableException | InvalidMidiDataException e) { e.printStackTrace(); // TODO: Actually handle errors. } lnr.close(); sc.close(); } }
true
true
public static void main(String[] args) throws IOException { Tone t = new Tone(); LineNumberReader lnr = new LineNumberReader(new FileReader(new File("tune.txt"))); lnr.skip(Long.MAX_VALUE); System.out.println(lnr.getLineNumber()); TuneParser tp = new TuneParser(); Scanner sc = new Scanner(new File("tune.txt")); t.progChange(sc.nextInt()); for(int i = 1; i < lnr.getLineNumber(); i++){ String note = sc.nextLine(); System.out.println(note.length()); for(int j = 4; j <= 24; j += 4){ if(note.length() == j){ int[] noteNo = new int[j / 4]; int[] delta = new int[j / 4]; for(int k = 0; k < noteNo.length; k++){ noteNo[k] = tp.decodeNote(note.substring(k * 4, k * 4 + 4)); delta[k] = tp.decodeDuration(note.substring(k * 4 + 2, k * 4 + 3)); t.noteOn(0, noteNo[k], 127); } t.noteOff(delta[0], noteNo[0]); for(int k = 1; k < noteNo.length; k++){ t.noteOff(0, noteNo[k]); } } } } t.writeToFile("tune.mid"); try { t.play("tune.mid"); } catch (MidiUnavailableException | InvalidMidiDataException e) { e.printStackTrace(); // TODO: Actually handle errors. } lnr.close(); sc.close(); }
public static void main(String[] args) throws IOException { Tone t = new Tone(); LineNumberReader lnr = new LineNumberReader(new FileReader(new File("tune.txt"))); lnr.skip(Long.MAX_VALUE); System.out.println(lnr.getLineNumber()); TuneParser tp = new TuneParser(); Scanner sc = new Scanner(new File("tune.txt")); t.progChange(sc.nextInt()); for(int i = 1; i <= lnr.getLineNumber(); i++){ String note = sc.nextLine(); System.out.println(note.length()); for(int j = 4; j <= 24; j += 4){ if(note.length() == j){ int[] noteNo = new int[j / 4]; int[] delta = new int[j / 4]; for(int k = 0; k < noteNo.length; k++){ noteNo[k] = tp.decodeNote(note.substring(k * 4, k * 4 + 4)); delta[k] = tp.decodeDuration(note.substring(k * 4 + 2, k * 4 + 3)); t.noteOn(0, noteNo[k], 127); } t.noteOff(delta[0], noteNo[0]); for(int k = 1; k < noteNo.length; k++){ t.noteOff(0, noteNo[k]); } } } } t.writeToFile("tune.mid"); try { t.play("tune.mid"); } catch (MidiUnavailableException | InvalidMidiDataException e) { e.printStackTrace(); // TODO: Actually handle errors. } lnr.close(); sc.close(); }
diff --git a/src/com/android/mms/transaction/MessagingNotification.java b/src/com/android/mms/transaction/MessagingNotification.java index 64cddc29..369ffa15 100644 --- a/src/com/android/mms/transaction/MessagingNotification.java +++ b/src/com/android/mms/transaction/MessagingNotification.java @@ -1,1554 +1,1555 @@ /* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * QuickMessage Copyright (C) 2012 The CyanogenMod Project (DvTonder) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.transaction; import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND; import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SqliteWrapper; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.preference.PreferenceManager; import android.provider.Telephony.Mms; import android.provider.Telephony.Sms; import android.telephony.TelephonyManager; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.StyleSpan; import android.text.style.TextAppearanceSpan; import android.util.Log; import android.widget.Toast; import com.android.mms.LogTag; import com.android.mms.R; import com.android.mms.data.Contact; import com.android.mms.data.Conversation; import com.android.mms.data.WorkingMessage; import com.android.mms.model.SlideModel; import com.android.mms.model.SlideshowModel; import com.android.mms.quickmessage.QmMarkRead; import com.android.mms.quickmessage.QuickMessagePopup; import com.android.mms.ui.ComposeMessageActivity; import com.android.mms.ui.ConversationList; import com.android.mms.ui.MessageUtils; import com.android.mms.ui.MessagingPreferenceActivity; import com.android.mms.util.AddressUtils; import com.android.mms.util.DownloadManager; import com.android.mms.widget.MmsWidgetProvider; import com.google.android.mms.MmsException; import android.provider.Settings; import com.google.android.mms.pdu.EncodedStringValue; import com.google.android.mms.pdu.GenericPdu; import com.google.android.mms.pdu.MultimediaMessagePdu; import com.google.android.mms.pdu.PduHeaders; import com.google.android.mms.pdu.PduPersister; /** * This class is used to update the notification indicator. It will check whether * there are unread messages. If yes, it would show the notification indicator, * otherwise, hide the indicator. */ public class MessagingNotification { private static final String TAG = LogTag.APP; private static final boolean DEBUG = false; public static final int NOTIFICATION_ID = 123; public static final int MESSAGE_FAILED_NOTIFICATION_ID = 789; public static final int DOWNLOAD_FAILED_NOTIFICATION_ID = 531; /** * This is the volume at which to play the in-conversation notification sound, * expressed as a fraction of the system notification volume. */ private static final float IN_CONVERSATION_NOTIFICATION_VOLUME = 0.25f; // This must be consistent with the column constants below. private static final String[] MMS_STATUS_PROJECTION = new String[] { Mms.THREAD_ID, Mms.DATE, Mms._ID, Mms.SUBJECT, Mms.SUBJECT_CHARSET }; // This must be consistent with the column constants below. private static final String[] SMS_STATUS_PROJECTION = new String[] { Sms.THREAD_ID, Sms.DATE, Sms.ADDRESS, Sms.SUBJECT, Sms.BODY }; // These must be consistent with MMS_STATUS_PROJECTION and // SMS_STATUS_PROJECTION. private static final int COLUMN_THREAD_ID = 0; private static final int COLUMN_DATE = 1; private static final int COLUMN_MMS_ID = 2; private static final int COLUMN_SMS_ADDRESS = 2; private static final int COLUMN_SUBJECT = 3; private static final int COLUMN_SUBJECT_CS = 4; private static final int COLUMN_SMS_BODY = 4; private static final String[] SMS_THREAD_ID_PROJECTION = new String[] { Sms.THREAD_ID }; private static final String[] MMS_THREAD_ID_PROJECTION = new String[] { Mms.THREAD_ID }; private static final String NEW_INCOMING_SM_CONSTRAINT = "(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_INBOX + " AND " + Sms.SEEN + " = 0)"; private static final String NEW_DELIVERY_SM_CONSTRAINT = "(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_SENT + " AND " + Sms.STATUS + " = "+ Sms.STATUS_COMPLETE +")"; private static final String NEW_INCOMING_MM_CONSTRAINT = "(" + Mms.MESSAGE_BOX + "=" + Mms.MESSAGE_BOX_INBOX + " AND " + Mms.SEEN + "=0" + " AND (" + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_NOTIFICATION_IND + " OR " + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_RETRIEVE_CONF + "))"; private static final NotificationInfoComparator INFO_COMPARATOR = new NotificationInfoComparator(); private static final Uri UNDELIVERED_URI = Uri.parse("content://mms-sms/undelivered"); private final static String NOTIFICATION_DELETED_ACTION = "com.android.mms.NOTIFICATION_DELETED_ACTION"; public static class OnDeletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[MessagingNotification] clear notification: mark all msgs seen"); } Conversation.markAllConversationsAsSeen(context); } } public static final long THREAD_ALL = -1; public static final long THREAD_NONE = -2; /** * Keeps track of the thread ID of the conversation that's currently displayed to the user */ private static long sCurrentlyDisplayedThreadId; private static final Object sCurrentlyDisplayedThreadLock = new Object(); private static OnDeletedReceiver sNotificationDeletedReceiver = new OnDeletedReceiver(); private static Intent sNotificationOnDeleteIntent; private static Handler sHandler = new Handler(); private static PduPersister sPduPersister; private static final int MAX_BITMAP_DIMEN_DP = 360; private static float sScreenDensity; private static final int MAX_MESSAGES_TO_SHOW = 8; // the maximum number of new messages to // show in a single notification. private MessagingNotification() { } public static void init(Context context) { // set up the intent filter for notification deleted action IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(NOTIFICATION_DELETED_ACTION); // TODO: should we unregister when the app gets killed? context.registerReceiver(sNotificationDeletedReceiver, intentFilter); sPduPersister = PduPersister.getPduPersister(context); // initialize the notification deleted action sNotificationOnDeleteIntent = new Intent(NOTIFICATION_DELETED_ACTION); sScreenDensity = context.getResources().getDisplayMetrics().density; } /** * Specifies which message thread is currently being viewed by the user. New messages in that * thread will not generate a notification icon and will play the notification sound at a lower * volume. Make sure you set this to THREAD_NONE when the UI component that shows the thread is * no longer visible to the user (e.g. Activity.onPause(), etc.) * @param threadId The ID of the thread that the user is currently viewing. Pass THREAD_NONE * if the user is not viewing a thread, or THREAD_ALL if the user is viewing the conversation * list (note: that latter one has no effect as of this implementation) */ public static void setCurrentlyDisplayedThreadId(long threadId) { synchronized (sCurrentlyDisplayedThreadLock) { sCurrentlyDisplayedThreadId = threadId; if (DEBUG) { Log.d(TAG, "setCurrentlyDisplayedThreadId: " + sCurrentlyDisplayedThreadId); } } } /** * Checks to see if there are any "unseen" messages or delivery * reports. Shows the most recent notification if there is one. * Does its work and query in a worker thread. * * @param context the context to use */ public static void nonBlockingUpdateNewMessageIndicator(final Context context, final long newMsgThreadId, final boolean isStatusMessage) { if (DEBUG) { Log.d(TAG, "nonBlockingUpdateNewMessageIndicator: newMsgThreadId: " + newMsgThreadId + " sCurrentlyDisplayedThreadId: " + sCurrentlyDisplayedThreadId); } new Thread(new Runnable() { @Override public void run() { blockingUpdateNewMessageIndicator(context, newMsgThreadId, isStatusMessage); } }, "MessagingNotification.nonBlockingUpdateNewMessageIndicator").start(); } /** * Checks to see if there are any "unseen" messages or delivery * reports and builds a sorted (by delivery date) list of unread notifications. * * @param context the context to use * @param newMsgThreadId The thread ID of a new message that we're to notify about; if there's * no new message, use THREAD_NONE. If we should notify about multiple or unknown thread IDs, * use THREAD_ALL. * @param isStatusMessage */ public static void blockingUpdateNewMessageIndicator(Context context, long newMsgThreadId, boolean isStatusMessage) { if (DEBUG) { Contact.logWithTrace(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId: " + newMsgThreadId); } // notificationSet is kept sorted by the incoming message delivery time, with the // most recent message first. SortedSet<NotificationInfo> notificationSet = new TreeSet<NotificationInfo>(INFO_COMPARATOR); Set<Long> threads = new HashSet<Long>(4); addMmsNotificationInfos(context, threads, notificationSet); addSmsNotificationInfos(context, threads, notificationSet); if (notificationSet.isEmpty()) { if (DEBUG) { Log.d(TAG, "blockingUpdateNewMessageIndicator: notificationSet is empty, " + "canceling existing notifications"); } cancelNotification(context, NOTIFICATION_ID); } else { if (DEBUG || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "blockingUpdateNewMessageIndicator: count=" + notificationSet.size() + ", newMsgThreadId=" + newMsgThreadId); } synchronized (sCurrentlyDisplayedThreadLock) { if (newMsgThreadId > 0 && newMsgThreadId == sCurrentlyDisplayedThreadId && threads.contains(newMsgThreadId)) { if (DEBUG) { Log.d(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId == " + "sCurrentlyDisplayedThreadId so NOT showing notification," + " but playing soft sound. threadId: " + newMsgThreadId); } playInConversationNotificationSound(context); return; } } updateNotification(context, newMsgThreadId != THREAD_NONE, threads.size(), notificationSet); } // And deals with delivery reports (which use Toasts). It's safe to call in a worker // thread because the toast will eventually get posted to a handler. MmsSmsDeliveryInfo delivery = getSmsNewDeliveryInfo(context); if (delivery != null) { delivery.deliver(context, isStatusMessage); } notificationSet.clear(); threads.clear(); } /** * Play the in-conversation notification sound (it's the regular notification sound, but * played at half-volume */ private static void playInConversationNotificationSound(Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); if (TextUtils.isEmpty(ringtoneStr)) { // Nothing to play return; } Uri ringtoneUri = Uri.parse(ringtoneStr); final NotificationPlayer player = new NotificationPlayer(LogTag.APP); player.play(context, ringtoneUri, false, AudioManager.STREAM_NOTIFICATION, IN_CONVERSATION_NOTIFICATION_VOLUME); // Stop the sound after five seconds to handle continuous ringtones sHandler.postDelayed(new Runnable() { @Override public void run() { player.stop(); } }, 5000); } /** * Updates all pending notifications, clearing or updating them as * necessary. */ public static void blockingUpdateAllNotifications(final Context context, long threadId) { if (DEBUG) { Contact.logWithTrace(TAG, "blockingUpdateAllNotifications: newMsgThreadId: " + threadId); } nonBlockingUpdateNewMessageIndicator(context, threadId, false); nonBlockingUpdateSendFailedNotification(context); updateDownloadFailedNotification(context); MmsWidgetProvider.notifyDatasetChanged(context); } private static final class MmsSmsDeliveryInfo { public CharSequence mTicker; public long mTimeMillis; public MmsSmsDeliveryInfo(CharSequence ticker, long timeMillis) { mTicker = ticker; mTimeMillis = timeMillis; } public void deliver(Context context, boolean isStatusMessage) { updateDeliveryNotification( context, isStatusMessage, mTicker, mTimeMillis); } } public static final class NotificationInfo implements Parcelable { public final Intent mClickIntent; public final String mMessage; public final CharSequence mTicker; public final long mTimeMillis; public final String mTitle; public final Bitmap mAttachmentBitmap; public final Contact mSender; public final boolean mIsSms; public final int mAttachmentType; public final String mSubject; public final long mThreadId; /** * @param isSms true if sms, false if mms * @param clickIntent where to go when the user taps the notification * @param message for a single message, this is the message text * @param subject text of mms subject * @param ticker text displayed ticker-style across the notification, typically formatted * as sender: message * @param timeMillis date the message was received * @param title for a single message, this is the sender * @param attachmentBitmap a bitmap of an attachment, such as a picture or video * @param sender contact of the sender * @param attachmentType of the mms attachment * @param threadId thread this message belongs to */ public NotificationInfo(boolean isSms, Intent clickIntent, String message, String subject, CharSequence ticker, long timeMillis, String title, Bitmap attachmentBitmap, Contact sender, int attachmentType, long threadId) { mIsSms = isSms; mClickIntent = clickIntent; mMessage = message; mSubject = subject; mTicker = ticker; mTimeMillis = timeMillis; mTitle = title; mAttachmentBitmap = attachmentBitmap; mSender = sender; mAttachmentType = attachmentType; mThreadId = threadId; } public long getTime() { return mTimeMillis; } // This is the message string used in bigText and bigPicture notifications. public CharSequence formatBigMessage(Context context) { final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); // Change multiple newlines (with potential white space between), into a single new line final String message = !TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : ""; SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); if (!TextUtils.isEmpty(mSubject)) { spannableStringBuilder.append(mSubject); spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0); } if (mAttachmentType > WorkingMessage.TEXT) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append('\n'); } spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType)); } if (mMessage != null) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append('\n'); } spannableStringBuilder.append(mMessage); } return spannableStringBuilder; } // This is the message string used in each line of an inboxStyle notification. public CharSequence formatInboxMessage(Context context) { final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationSubjectText); // Change multiple newlines (with potential white space between), into a single new line final String message = !TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : ""; SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); final String sender = mSender.getName(); if (!TextUtils.isEmpty(sender)) { spannableStringBuilder.append(sender); spannableStringBuilder.setSpan(notificationSenderSpan, 0, sender.length(), 0); } String separator = context.getString(R.string.notification_separator); if (!mIsSms) { if (!TextUtils.isEmpty(mSubject)) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append(separator); } int start = spannableStringBuilder.length(); spannableStringBuilder.append(mSubject); spannableStringBuilder.setSpan(notificationSubjectSpan, start, start + mSubject.length(), 0); } if (mAttachmentType > WorkingMessage.TEXT) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append(separator); } spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType)); } } if (message.length() > 0) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append(separator); } int start = spannableStringBuilder.length(); spannableStringBuilder.append(message); spannableStringBuilder.setSpan(notificationSubjectSpan, start, start + message.length(), 0); } return spannableStringBuilder; } // This is the summary string used in bigPicture notifications. public CharSequence formatPictureMessage(Context context) { final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); // Change multiple newlines (with potential white space between), into a single new line final String message = !TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : ""; // Show the subject or the message (if no subject) SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); if (!TextUtils.isEmpty(mSubject)) { spannableStringBuilder.append(mSubject); spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0); } if (message.length() > 0 && spannableStringBuilder.length() == 0) { spannableStringBuilder.append(message); spannableStringBuilder.setSpan(notificationSubjectSpan, 0, message.length(), 0); } return spannableStringBuilder; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel arg0, int arg1) { arg0.writeByte((byte) (mIsSms ? 1 : 0)); arg0.writeParcelable(mClickIntent, 0); arg0.writeString(mMessage); arg0.writeString(mSubject); arg0.writeCharSequence(mTicker); arg0.writeLong(mTimeMillis); arg0.writeString(mTitle); arg0.writeParcelable(mAttachmentBitmap, 0); arg0.writeInt(mAttachmentType); arg0.writeLong(mThreadId); } public NotificationInfo(Parcel in) { mIsSms = in.readByte() == 1; mClickIntent = in.readParcelable(Intent.class.getClassLoader()); mMessage = in.readString(); mSubject = in.readString(); mTicker = in.readCharSequence(); mTimeMillis = in.readLong(); mTitle = in.readString(); mAttachmentBitmap = in.readParcelable(Bitmap.class.getClassLoader()); mSender = null; mAttachmentType = in.readInt(); mThreadId = in.readLong(); } public static final Parcelable.Creator<NotificationInfo> CREATOR = new Parcelable.Creator<NotificationInfo>() { public NotificationInfo createFromParcel(Parcel in) { return new NotificationInfo(in); } public NotificationInfo[] newArray(int size) { return new NotificationInfo[size]; } }; } // Return a formatted string with all the sender names separated by commas. private static CharSequence formatSenders(Context context, ArrayList<NotificationInfo> senders) { final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); String separator = context.getString(R.string.enumeration_comma); // ", " SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); int len = senders.size(); for (int i = 0; i < len; i++) { if (i > 0) { spannableStringBuilder.append(separator); } spannableStringBuilder.append(senders.get(i).mSender.getName()); } spannableStringBuilder.setSpan(notificationSenderSpan, 0, spannableStringBuilder.length(), 0); return spannableStringBuilder; } // Return a formatted string with the attachmentType spelled out as a string. For // no attachment (or just text), return null. private static CharSequence getAttachmentTypeString(Context context, int attachmentType) { final TextAppearanceSpan notificationAttachmentSpan = new TextAppearanceSpan( context, R.style.NotificationSecondaryText); int id = 0; switch (attachmentType) { case WorkingMessage.AUDIO: id = R.string.attachment_audio; break; case WorkingMessage.VIDEO: id = R.string.attachment_video; break; case WorkingMessage.SLIDESHOW: id = R.string.attachment_slideshow; break; case WorkingMessage.IMAGE: id = R.string.attachment_picture; break; } if (id > 0) { final SpannableString spannableString = new SpannableString(context.getString(id)); spannableString.setSpan(notificationAttachmentSpan, 0, spannableString.length(), 0); return spannableString; } return null; } /** * * Sorts by the time a notification was received in descending order -- newer first. * */ private static final class NotificationInfoComparator implements Comparator<NotificationInfo> { @Override public int compare( NotificationInfo info1, NotificationInfo info2) { return Long.signum(info2.getTime() - info1.getTime()); } } private static final void addMmsNotificationInfos( Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) { ContentResolver resolver = context.getContentResolver(); // This query looks like this when logged: // I/Database( 147): elapsedTime4Sql|/data/data/com.android.providers.telephony/databases/ // mmssms.db|0.362 ms|SELECT thread_id, date, _id, sub, sub_cs FROM pdu WHERE ((msg_box=1 // AND seen=0 AND (m_type=130 OR m_type=132))) ORDER BY date desc Cursor cursor = SqliteWrapper.query(context, resolver, Mms.CONTENT_URI, MMS_STATUS_PROJECTION, NEW_INCOMING_MM_CONSTRAINT, null, Mms.DATE + " desc"); if (cursor == null) { return; } try { while (cursor.moveToNext()) { long msgId = cursor.getLong(COLUMN_MMS_ID); Uri msgUri = Mms.CONTENT_URI.buildUpon().appendPath( Long.toString(msgId)).build(); String address = AddressUtils.getFrom(context, msgUri); Contact contact = Contact.get(address, false); if (contact.getSendToVoicemail()) { // don't notify, skip this one continue; } String subject = getMmsSubject( cursor.getString(COLUMN_SUBJECT), cursor.getInt(COLUMN_SUBJECT_CS)); subject = MessageUtils.cleanseMmsSubject(context, subject); long threadId = cursor.getLong(COLUMN_THREAD_ID); long timeMillis = cursor.getLong(COLUMN_DATE) * 1000; if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "addMmsNotificationInfos: count=" + cursor.getCount() + ", addr = " + address + ", thread_id=" + threadId); } // Extract the message and/or an attached picture from the first slide Bitmap attachedPicture = null; String messageBody = null; int attachmentType = WorkingMessage.TEXT; try { GenericPdu pdu = sPduPersister.load(msgUri); if (pdu != null && pdu instanceof MultimediaMessagePdu) { SlideshowModel slideshow = SlideshowModel.createFromPduBody(context, ((MultimediaMessagePdu)pdu).getBody()); attachmentType = getAttachmentType(slideshow); SlideModel firstSlide = slideshow.get(0); if (firstSlide != null) { if (firstSlide.hasImage()) { int maxDim = dp2Pixels(MAX_BITMAP_DIMEN_DP); attachedPicture = firstSlide.getImage().getBitmap(maxDim, maxDim); } if (firstSlide.hasText()) { messageBody = firstSlide.getText().getText(); } } } } catch (final MmsException e) { Log.e(TAG, "MmsException loading uri: " + msgUri, e); continue; // skip this bad boy -- don't generate an empty notification } NotificationInfo info = getNewMessageNotificationInfo(context, false /* isSms */, address, messageBody, subject, threadId, timeMillis, attachedPicture, contact, attachmentType); notificationSet.add(info); threads.add(threadId); } } finally { cursor.close(); } } // Look at the passed in slideshow and determine what type of attachment it is. private static int getAttachmentType(SlideshowModel slideshow) { int slideCount = slideshow.size(); if (slideCount == 0) { return WorkingMessage.TEXT; } else if (slideCount > 1) { return WorkingMessage.SLIDESHOW; } else { SlideModel slide = slideshow.get(0); if (slide.hasImage()) { return WorkingMessage.IMAGE; } else if (slide.hasVideo()) { return WorkingMessage.VIDEO; } else if (slide.hasAudio()) { return WorkingMessage.AUDIO; } } return WorkingMessage.TEXT; } private static final int dp2Pixels(int dip) { return (int) (dip * sScreenDensity + 0.5f); } private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) { ContentResolver resolver = context.getContentResolver(); Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI, SMS_STATUS_PROJECTION, NEW_DELIVERY_SM_CONSTRAINT, null, Sms.DATE); if (cursor == null) { return null; } try { if (!cursor.moveToLast()) { return null; } String address = cursor.getString(COLUMN_SMS_ADDRESS); long timeMillis = 3000; Contact contact = Contact.get(address, false); String name = contact.getNameAndNumber(); return new MmsSmsDeliveryInfo(context.getString(R.string.delivery_toast_body, name), timeMillis); } finally { cursor.close(); } } private static final void addSmsNotificationInfos( Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) { ContentResolver resolver = context.getContentResolver(); Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI, SMS_STATUS_PROJECTION, NEW_INCOMING_SM_CONSTRAINT, null, Sms.DATE + " desc"); if (cursor == null) { return; } try { while (cursor.moveToNext()) { String address = cursor.getString(COLUMN_SMS_ADDRESS); Contact contact = Contact.get(address, false); if (contact.getSendToVoicemail()) { // don't notify, skip this one continue; } String message = cursor.getString(COLUMN_SMS_BODY); long threadId = cursor.getLong(COLUMN_THREAD_ID); long timeMillis = cursor.getLong(COLUMN_DATE); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "addSmsNotificationInfos: count=" + cursor.getCount() + ", addr=" + address + ", thread_id=" + threadId); } NotificationInfo info = getNewMessageNotificationInfo(context, true /* isSms */, address, message, null /* subject */, threadId, timeMillis, null /* attachmentBitmap */, contact, WorkingMessage.TEXT); notificationSet.add(info); threads.add(threadId); threads.add(cursor.getLong(COLUMN_THREAD_ID)); } } finally { cursor.close(); } } private static final NotificationInfo getNewMessageNotificationInfo( Context context, boolean isSms, String address, String message, String subject, long threadId, long timeMillis, Bitmap attachmentBitmap, Contact contact, int attachmentType) { Intent clickIntent = ComposeMessageActivity.createIntent(context, threadId); clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); String senderInfo = buildTickerMessage( context, address, null, null).toString(); String senderInfoName = senderInfo.substring( 0, senderInfo.length() - 2); CharSequence ticker = buildTickerMessage( context, address, subject, message); return new NotificationInfo(isSms, clickIntent, message, subject, ticker, timeMillis, senderInfoName, attachmentBitmap, contact, attachmentType, threadId); } public static void cancelNotification(Context context, int notificationId) { NotificationManager nm = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); Log.d(TAG, "cancelNotification"); nm.cancel(notificationId); } private static void updateDeliveryNotification(final Context context, boolean isStatusMessage, final CharSequence message, final long timeMillis) { if (!isStatusMessage) { return; } if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { return; } sHandler.post(new Runnable() { @Override public void run() { Toast.makeText(context, message, (int)timeMillis).show(); } }); } /** * updateNotification is *the* main function for building the actual notification handed to * the NotificationManager * @param context * @param isNew if we've got a new message, show the ticker * @param uniqueThreadCount * @param notificationSet the set of notifications to display */ private static void updateNotification( Context context, boolean isNew, int uniqueThreadCount, SortedSet<NotificationInfo> notificationSet) { // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. final int messageCount = notificationSet.size(); NotificationInfo mostRecentNotification = notificationSet.first(); final Notification.Builder noti = new Notification.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false); if (isNew) { if (!privacyMode) { noti.setTicker(mostRecentNotification.mTicker); } else { noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode)); } } - TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; String privateModeContentText = null; Bitmap avatar = null; + PendingIntent pendingIntent = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); - taskStackBuilder.addNextIntent(mainActivityIntent); + pendingIntent = PendingIntent.getActivity(context, 0, + mainActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (!privacyMode) { title = context.getString(R.string.message_count_notification, messageCount); } else { title = context.getString(R.string.notification_multiple_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount); } } else { // same thread, single or multiple messages if (!privacyMode) { title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender .getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap( avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } } else { if (messageCount > 1) { title = context.getString(R.string.notification_multiple_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount); } else { title = context.getString(R.string.notification_single_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode); } } - taskStackBuilder.addParentStack(ComposeMessageActivity.class); - taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); + pendingIntent = PendingIntent.getActivity(context, 0, + mostRecentNotification.mClickIntent, + PendingIntent.FLAG_UPDATE_CURRENT); } // Always have to set the small icon or the notification is ignored if (Settings.System.getInt(context.getContentResolver(), Settings.System.KEY_SMS_BREATH, 0) == 1) { noti.setSmallIcon(R.drawable.stat_notify_sms_breath); } else { noti.setSmallIcon(R.drawable.stat_notify_sms); } NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) - .setContentIntent( - taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) + .setContentIntent(pendingIntent) .addKind(Notification.KIND_MESSAGE) .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. int defaults = 0; if (isNew) { boolean vibrate = false; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { // The most recent change to the vibrate preference is to store a boolean // value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that // first. vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { // This is to support the pre-JellyBean MR1.1 version of vibrate preferences // when vibrate was a tri-state setting. As soon as the user opens the Messaging // app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN // to the boolean value stored in NOTIFICATION_VIBRATE. String vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); vibrate = "always".equals(vibrateWhen); } if (vibrate) { String pattern = sp.getString( MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200"); if (!TextUtils.isEmpty(pattern)) { noti.setVibrate(parseVibratePattern(pattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } // Set light defaults defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); // See if QuickMessage pop-up support is enabled in preferences boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context); // Set up the QuickMessage intent Intent qmIntent = null; if (mostRecentNotification.mIsSms && !privacyMode) { // QuickMessage support is only for SMS when privacy mode is disabled qmIntent = new Intent(); qmIntent.setClass(context, QuickMessagePopup.class); qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName()); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber()); qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification); } // Start getting the notification ready final Notification notification; if (!privacyMode) { if (messageCount == 1 || uniqueThreadCount == 1) { // Add the Quick Reply action only if the pop-up won't be shown already if (!qmPopupEnabled && qmIntent != null) { // This is a QR, we should show the keyboard when the user taps to reply qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true); // Create the Quick reply pending intent and add it to the notification CharSequence qmText = context.getText(R.string.qm_quick_reply); PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent); } // Add the 'Mark as read' action CharSequence markReadText = context.getText(R.string.qm_mark_read); Intent mrIntent = new Intent(); mrIntent.setClass(context, QmMarkRead.class); mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId); PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent); // Add the Call action CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true)); PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new Notification.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)) .build(); } else { // Show a single notification -- big style with the text of the whole message notification = new Notification.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)) .build(); } if (DEBUG) { Log.d(TAG, "updateNotification: single message notification"); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new Notification.BigTextStyle(noti) .bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ") .build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages for single thread"); } } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = notificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); uniqueThreads.clear(); mostRecentNotifPerThread.clear(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } // Trigger the QuickMessage pop-up activity if enabled // But don't show the QuickMessage if the user is in a call or the phone is ringing if (qmPopupEnabled && qmIntent != null) { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE; if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) { // Show the popup context.startActivity(qmIntent); } } } else { // Show a standard notification in privacy mode noti.setContentText(privateModeContentText); notification = noti.build(); } // Post the notification nm.notify(NOTIFICATION_ID, notification); } protected static CharSequence buildTickerMessage( Context context, String address, String subject, String body) { String displayAddress = Contact.get(address, true).getName(); StringBuilder buf = new StringBuilder( displayAddress == null ? "" : displayAddress.replace('\n', ' ').replace('\r', ' ')); buf.append(':').append(' '); int offset = buf.length(); if (!TextUtils.isEmpty(subject)) { subject = subject.replace('\n', ' ').replace('\r', ' '); buf.append(subject); buf.append(' '); } if (!TextUtils.isEmpty(body)) { body = body.replace('\n', ' ').replace('\r', ' '); buf.append(body); } SpannableString spanText = new SpannableString(buf.toString()); spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return spanText; } private static String getMmsSubject(String sub, int charset) { return TextUtils.isEmpty(sub) ? "" : new EncodedStringValue(charset, PduPersister.getBytes(sub)).getString(); } public static void notifyDownloadFailed(Context context, long threadId) { notifyFailed(context, true, threadId, false); } public static void notifySendFailed(Context context) { notifyFailed(context, false, 0, false); } public static void notifySendFailed(Context context, boolean noisy) { notifyFailed(context, false, 0, noisy); } private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) { // TODO factor out common code for creating notifications boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context); if (!enabled) { return; } // Strategy: // a. If there is a single failure notification, tapping on the notification goes // to the compose view. // b. If there are two failure it stays in the thread view. Selecting one undelivered // thread will dismiss one undelivered notification but will still display the // notification.If you select the 2nd undelivered one it will dismiss the notification. long[] msgThreadId = {0, 1}; // Dummy initial values, just to initialize the memory int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId); if (totalFailedCount == 0 && !isDownload) { return; } // The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all // failures are from the same thread. // If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are // indeed in the same thread since there's only 1. boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload; Intent failedIntent; Notification notification = new Notification(); String title; String description; if (totalFailedCount > 1) { description = context.getString(R.string.notification_failed_multiple, Integer.toString(totalFailedCount)); title = context.getString(R.string.notification_failed_multiple_title); } else { title = isDownload ? context.getString(R.string.message_download_failed_title) : context.getString(R.string.message_send_failed_title); description = context.getString(R.string.message_failed_body); } TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); if (allFailedInSameThread) { failedIntent = new Intent(context, ComposeMessageActivity.class); if (isDownload) { // When isDownload is true, the valid threadId is passed into this function. failedIntent.putExtra("failed_download_flag", true); } else { threadId = msgThreadId[0]; failedIntent.putExtra("undelivered_flag", true); } failedIntent.putExtra("thread_id", threadId); taskStackBuilder.addParentStack(ComposeMessageActivity.class); } else { failedIntent = new Intent(context, ConversationList.class); } taskStackBuilder.addNextIntent(failedIntent); notification.icon = R.drawable.stat_notify_sms_failed; notification.tickerText = title; notification.setLatestEventInfo(context, title, description, taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)); if (noisy) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false /* don't vibrate by default */); if (vibrate) { notification.defaults |= Notification.DEFAULT_VIBRATE; } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr); } NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (isDownload) { notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification); } else { notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification); } } /** * Query the DB and return the number of undelivered messages (total for both SMS and MMS) * @param context The context * @param threadIdResult A container to put the result in, according to the following rules: * threadIdResult[0] contains the thread id of the first message. * threadIdResult[1] is nonzero if the thread ids of all the messages are the same. * You can pass in null for threadIdResult. * You can pass in a threadIdResult of size 1 to avoid the comparison of each thread id. */ private static int getUndeliveredMessageCount(Context context, long[] threadIdResult) { Cursor undeliveredCursor = SqliteWrapper.query(context, context.getContentResolver(), UNDELIVERED_URI, MMS_THREAD_ID_PROJECTION, "read=0", null, null); if (undeliveredCursor == null) { return 0; } int count = undeliveredCursor.getCount(); try { if (threadIdResult != null && undeliveredCursor.moveToFirst()) { threadIdResult[0] = undeliveredCursor.getLong(0); if (threadIdResult.length >= 2) { // Test to see if all the undelivered messages belong to the same thread. long firstId = threadIdResult[0]; while (undeliveredCursor.moveToNext()) { if (undeliveredCursor.getLong(0) != firstId) { firstId = 0; break; } } threadIdResult[1] = firstId; // non-zero if all ids are the same } } } finally { undeliveredCursor.close(); } return count; } public static void nonBlockingUpdateSendFailedNotification(final Context context) { new AsyncTask<Void, Void, Integer>() { protected Integer doInBackground(Void... none) { return getUndeliveredMessageCount(context, null); } protected void onPostExecute(Integer result) { if (result < 1) { cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID); } else { // rebuild and adjust the message count if necessary. notifySendFailed(context); } } }.execute(); } /** * If all the undelivered messages belong to "threadId", cancel the notification. */ public static void updateSendFailedNotificationForThread(Context context, long threadId) { long[] msgThreadId = {0, 0}; if (getUndeliveredMessageCount(context, msgThreadId) > 0 && msgThreadId[0] == threadId && msgThreadId[1] != 0) { cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID); } } private static int getDownloadFailedMessageCount(Context context) { // Look for any messages in the MMS Inbox that are of the type // NOTIFICATION_IND (i.e. not already downloaded) and in the // permanent failure state. If there are none, cancel any // failed download notification. Cursor c = SqliteWrapper.query(context, context.getContentResolver(), Mms.Inbox.CONTENT_URI, null, Mms.MESSAGE_TYPE + "=" + String.valueOf(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) + " AND " + Mms.STATUS + "=" + String.valueOf(DownloadManager.STATE_PERMANENT_FAILURE), null, null); if (c == null) { return 0; } int count = c.getCount(); c.close(); return count; } public static void updateDownloadFailedNotification(Context context) { if (getDownloadFailedMessageCount(context) < 1) { cancelNotification(context, DOWNLOAD_FAILED_NOTIFICATION_ID); } } public static boolean isFailedToDeliver(Intent intent) { return (intent != null) && intent.getBooleanExtra("undelivered_flag", false); } public static boolean isFailedToDownload(Intent intent) { return (intent != null) && intent.getBooleanExtra("failed_download_flag", false); } /** * Get the thread ID of the SMS message with the given URI * @param context The context * @param uri The URI of the SMS message * @return The thread ID, or THREAD_NONE if the URI contains no entries */ public static long getSmsThreadId(Context context, Uri uri) { Cursor cursor = SqliteWrapper.query( context, context.getContentResolver(), uri, SMS_THREAD_ID_PROJECTION, null, null, null); if (cursor == null) { if (DEBUG) { Log.d(TAG, "getSmsThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE"); } return THREAD_NONE; } try { if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(Sms.THREAD_ID); if (columnIndex < 0) { if (DEBUG) { Log.d(TAG, "getSmsThreadId uri: " + uri + " Couldn't read row 0, col -1! returning THREAD_NONE"); } return THREAD_NONE; } long threadId = cursor.getLong(columnIndex); if (DEBUG) { Log.d(TAG, "getSmsThreadId uri: " + uri + " returning threadId: " + threadId); } return threadId; } else { if (DEBUG) { Log.d(TAG, "getSmsThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE"); } return THREAD_NONE; } } finally { cursor.close(); } } /** * Get the thread ID of the MMS message with the given URI * @param context The context * @param uri The URI of the SMS message * @return The thread ID, or THREAD_NONE if the URI contains no entries */ public static long getThreadId(Context context, Uri uri) { Cursor cursor = SqliteWrapper.query( context, context.getContentResolver(), uri, MMS_THREAD_ID_PROJECTION, null, null, null); if (cursor == null) { if (DEBUG) { Log.d(TAG, "getThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE"); } return THREAD_NONE; } try { if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(Mms.THREAD_ID); if (columnIndex < 0) { if (DEBUG) { Log.d(TAG, "getThreadId uri: " + uri + " Couldn't read row 0, col -1! returning THREAD_NONE"); } return THREAD_NONE; } long threadId = cursor.getLong(columnIndex); if (DEBUG) { Log.d(TAG, "getThreadId uri: " + uri + " returning threadId: " + threadId); } return threadId; } else { if (DEBUG) { Log.d(TAG, "getThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE"); } return THREAD_NONE; } } finally { cursor.close(); } } // Parse the user provided custom vibrate pattern into a long[] private static long[] parseVibratePattern(String pattern) { String[] splitPattern = pattern.split(","); long[] result = new long[splitPattern.length]; for (int i = 0; i < splitPattern.length; i++) { try { result[i] = Long.parseLong(splitPattern[i]); } catch (NumberFormatException e) { return null; } } return result; } }
false
true
private static void updateNotification( Context context, boolean isNew, int uniqueThreadCount, SortedSet<NotificationInfo> notificationSet) { // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. final int messageCount = notificationSet.size(); NotificationInfo mostRecentNotification = notificationSet.first(); final Notification.Builder noti = new Notification.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false); if (isNew) { if (!privacyMode) { noti.setTicker(mostRecentNotification.mTicker); } else { noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode)); } } TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; String privateModeContentText = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); if (!privacyMode) { title = context.getString(R.string.message_count_notification, messageCount); } else { title = context.getString(R.string.notification_multiple_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount); } } else { // same thread, single or multiple messages if (!privacyMode) { title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender .getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap( avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } } else { if (messageCount > 1) { title = context.getString(R.string.notification_multiple_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount); } else { title = context.getString(R.string.notification_single_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode); } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // Always have to set the small icon or the notification is ignored if (Settings.System.getInt(context.getContentResolver(), Settings.System.KEY_SMS_BREATH, 0) == 1) { noti.setSmallIcon(R.drawable.stat_notify_sms_breath); } else { noti.setSmallIcon(R.drawable.stat_notify_sms); } NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent( taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) .addKind(Notification.KIND_MESSAGE) .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. int defaults = 0; if (isNew) { boolean vibrate = false; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { // The most recent change to the vibrate preference is to store a boolean // value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that // first. vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { // This is to support the pre-JellyBean MR1.1 version of vibrate preferences // when vibrate was a tri-state setting. As soon as the user opens the Messaging // app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN // to the boolean value stored in NOTIFICATION_VIBRATE. String vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); vibrate = "always".equals(vibrateWhen); } if (vibrate) { String pattern = sp.getString( MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200"); if (!TextUtils.isEmpty(pattern)) { noti.setVibrate(parseVibratePattern(pattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } // Set light defaults defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); // See if QuickMessage pop-up support is enabled in preferences boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context); // Set up the QuickMessage intent Intent qmIntent = null; if (mostRecentNotification.mIsSms && !privacyMode) { // QuickMessage support is only for SMS when privacy mode is disabled qmIntent = new Intent(); qmIntent.setClass(context, QuickMessagePopup.class); qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName()); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber()); qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification); } // Start getting the notification ready final Notification notification; if (!privacyMode) { if (messageCount == 1 || uniqueThreadCount == 1) { // Add the Quick Reply action only if the pop-up won't be shown already if (!qmPopupEnabled && qmIntent != null) { // This is a QR, we should show the keyboard when the user taps to reply qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true); // Create the Quick reply pending intent and add it to the notification CharSequence qmText = context.getText(R.string.qm_quick_reply); PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent); } // Add the 'Mark as read' action CharSequence markReadText = context.getText(R.string.qm_mark_read); Intent mrIntent = new Intent(); mrIntent.setClass(context, QmMarkRead.class); mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId); PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent); // Add the Call action CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true)); PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new Notification.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)) .build(); } else { // Show a single notification -- big style with the text of the whole message notification = new Notification.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)) .build(); } if (DEBUG) { Log.d(TAG, "updateNotification: single message notification"); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new Notification.BigTextStyle(noti) .bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ") .build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages for single thread"); } } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = notificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); uniqueThreads.clear(); mostRecentNotifPerThread.clear(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } // Trigger the QuickMessage pop-up activity if enabled // But don't show the QuickMessage if the user is in a call or the phone is ringing if (qmPopupEnabled && qmIntent != null) { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE; if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) { // Show the popup context.startActivity(qmIntent); } } } else { // Show a standard notification in privacy mode noti.setContentText(privateModeContentText); notification = noti.build(); } // Post the notification nm.notify(NOTIFICATION_ID, notification); }
private static void updateNotification( Context context, boolean isNew, int uniqueThreadCount, SortedSet<NotificationInfo> notificationSet) { // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. final int messageCount = notificationSet.size(); NotificationInfo mostRecentNotification = notificationSet.first(); final Notification.Builder noti = new Notification.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false); if (isNew) { if (!privacyMode) { noti.setTicker(mostRecentNotification.mTicker); } else { noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode)); } } // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; String privateModeContentText = null; Bitmap avatar = null; PendingIntent pendingIntent = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (!privacyMode) { title = context.getString(R.string.message_count_notification, messageCount); } else { title = context.getString(R.string.notification_multiple_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount); } } else { // same thread, single or multiple messages if (!privacyMode) { title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender .getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap( avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } } else { if (messageCount > 1) { title = context.getString(R.string.notification_multiple_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount); } else { title = context.getString(R.string.notification_single_title_privacy_mode); privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode); } } pendingIntent = PendingIntent.getActivity(context, 0, mostRecentNotification.mClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); } // Always have to set the small icon or the notification is ignored if (Settings.System.getInt(context.getContentResolver(), Settings.System.KEY_SMS_BREATH, 0) == 1) { noti.setSmallIcon(R.drawable.stat_notify_sms_breath); } else { noti.setSmallIcon(R.drawable.stat_notify_sms); } NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent(pendingIntent) .addKind(Notification.KIND_MESSAGE) .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. int defaults = 0; if (isNew) { boolean vibrate = false; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { // The most recent change to the vibrate preference is to store a boolean // value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that // first. vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { // This is to support the pre-JellyBean MR1.1 version of vibrate preferences // when vibrate was a tri-state setting. As soon as the user opens the Messaging // app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN // to the boolean value stored in NOTIFICATION_VIBRATE. String vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); vibrate = "always".equals(vibrateWhen); } if (vibrate) { String pattern = sp.getString( MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200"); if (!TextUtils.isEmpty(pattern)) { noti.setVibrate(parseVibratePattern(pattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } // Set light defaults defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); // See if QuickMessage pop-up support is enabled in preferences boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context); // Set up the QuickMessage intent Intent qmIntent = null; if (mostRecentNotification.mIsSms && !privacyMode) { // QuickMessage support is only for SMS when privacy mode is disabled qmIntent = new Intent(); qmIntent.setClass(context, QuickMessagePopup.class); qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName()); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber()); qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification); } // Start getting the notification ready final Notification notification; if (!privacyMode) { if (messageCount == 1 || uniqueThreadCount == 1) { // Add the Quick Reply action only if the pop-up won't be shown already if (!qmPopupEnabled && qmIntent != null) { // This is a QR, we should show the keyboard when the user taps to reply qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true); // Create the Quick reply pending intent and add it to the notification CharSequence qmText = context.getText(R.string.qm_quick_reply); PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent); } // Add the 'Mark as read' action CharSequence markReadText = context.getText(R.string.qm_mark_read); Intent mrIntent = new Intent(); mrIntent.setClass(context, QmMarkRead.class); mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId); PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent); // Add the Call action CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true)); PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new Notification.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)) .build(); } else { // Show a single notification -- big style with the text of the whole message notification = new Notification.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)) .build(); } if (DEBUG) { Log.d(TAG, "updateNotification: single message notification"); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new Notification.BigTextStyle(noti) .bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ") .build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages for single thread"); } } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = notificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); uniqueThreads.clear(); mostRecentNotifPerThread.clear(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } // Trigger the QuickMessage pop-up activity if enabled // But don't show the QuickMessage if the user is in a call or the phone is ringing if (qmPopupEnabled && qmIntent != null) { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE; if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) { // Show the popup context.startActivity(qmIntent); } } } else { // Show a standard notification in privacy mode noti.setContentText(privateModeContentText); notification = noti.build(); } // Post the notification nm.notify(NOTIFICATION_ID, notification); }
diff --git a/src/org/klnusbaum/udj/PlayerActivity.java b/src/org/klnusbaum/udj/PlayerActivity.java index 13843f5..e8ef3d7 100644 --- a/src/org/klnusbaum/udj/PlayerActivity.java +++ b/src/org/klnusbaum/udj/PlayerActivity.java @@ -1,216 +1,218 @@ /** * Copyright 2011 Kurtis L. Nusbaum * * This file is part of UDJ. * * UDJ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * UDJ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with UDJ. If not, see <http://www.gnu.org/licenses/>. */ package org.klnusbaum.udj; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentManager; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.accounts.AccountManager; import android.content.Intent; import android.content.IntentFilter; import android.view.MenuInflater; import android.util.Log; import android.content.BroadcastReceiver; import android.content.Context; import android.app.SearchManager; import org.klnusbaum.udj.Constants; import org.klnusbaum.udj.network.PlaylistSyncService; import com.viewpagerindicator.TitlePageIndicator; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; /** * The main activity display class. */ public class PlayerActivity extends PlayerInactivityListenerActivity { private static final String TAG = "PlayerActivity"; private PlayerPagerAdapter pagerAdapter; private ViewPager pager; private BroadcastReceiver playbackStateChangedListener = new BroadcastReceiver(){ public void onReceive(Context context, Intent intent){ Log.d(TAG, "Recieved playback changed broadcast"); invalidateOptionsMenu(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); getPlaylistFromServer(); pagerAdapter = new PlayerPagerAdapter(getSupportFragmentManager()); pager = (ViewPager)findViewById(R.id.player_pager); pager.setAdapter(pagerAdapter); TitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.titles); titleIndicator.setViewPager(pager); } @Override protected void onResume(){ super.onResume(); registerReceiver( playbackStateChangedListener, new IntentFilter(Constants.BROADCAST_PLAYBACK_CHANGED) ); } @Override protected void onPause(){ super.onPause(); unregisterReceiver(playbackStateChangedListener); } public void getPlaylistFromServer() { int playerState = Utils.getPlayerState(this, account); // TODO hanle if no player if (playerState == Constants.IN_PLAYER) { Intent getPlaylist = new Intent(Intent.ACTION_VIEW, UDJPlayerProvider.PLAYLIST_URI, this, PlaylistSyncService.class); getPlaylist.putExtra(Constants.ACCOUNT_EXTRA, account); startService(getPlaylist); } } public void onBackPressed(){ AccountManager am = AccountManager.get(this); Utils.leavePlayer(am, account); finish(); } public static class PlayerPagerAdapter extends FragmentPagerAdapter{ public PlayerPagerAdapter(FragmentManager fm){ super(fm); } @Override public int getCount(){ return 4; } public Fragment getItem(int position){ switch(position){ case 0: return new PlaylistFragment(); case 1: return new ArtistsDisplayFragment(); case 2: return new RecentlyPlayedFragment(); case 3: return new RandomSearchFragment(); default: return null; } } public String getPageTitle(int position){ switch(position){ case 0: return "Playlist"; case 1: return "Artists"; case 2: return "Recent"; case 3: return "Random"; default: return "Unknown"; } } } public boolean onCreateOptionsMenu(Menu menu){ AccountManager am = AccountManager.get(this); if(Utils.isCurrentPlayerOwner(am, account)){ int playbackState = Utils.getPlaybackState(am, account); if(playbackState == Constants.PLAYING_STATE){ menu.add("Pause") + .setIcon(R.drawable.ab_pause) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } else if(playbackState == Constants.PAUSED_STATE){ menu.add("Play") + .setIcon(R.drawable.ab_play) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } menu.add("Search") - .setIcon(R.drawable.ic_search) + .setIcon(R.drawable.ab_search_dark) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } public boolean onOptionsItemSelected(MenuItem item) { if(item.getTitle().equals("Search")){ startSearch(null, false, null, false); return true; } else if(item.getTitle().equals("Pause")){ setPlayback(Constants.PAUSED_STATE); } else if(item.getTitle().equals("Play")){ setPlayback(Constants.PLAYING_STATE); } return false; } private void setPlayback(int newPlaybackState){ changePlaybackMenuOption(newPlaybackState); Intent setPlaybackIntent = new Intent( Constants.ACTION_SET_PLAYBACK, Constants.PLAYER_URI, this, PlaylistSyncService.class); setPlaybackIntent.putExtra(Constants.ACCOUNT_EXTRA, account); setPlaybackIntent.putExtra(Constants.PLAYBACK_STATE_EXTRA, newPlaybackState); startService(setPlaybackIntent); } private void changePlaybackMenuOption(int newPlaybackState){ AccountManager am = AccountManager.get(this); am.setUserData(account, Constants.PLAYBACK_STATE_DATA, String.valueOf(newPlaybackState)); invalidateOptionsMenu(); } protected void onNewIntent(Intent intent){ if(Intent.ACTION_SEARCH.equals(intent.getAction())){ String searchQuery = intent.getStringExtra(SearchManager.QUERY); searchQuery = searchQuery.trim(); intent.putExtra(SearchManager.QUERY, searchQuery); intent.setClass(this, RegularSearchActivity.class); startActivityForResult(intent, 0); } else{ super.onNewIntent(intent); } } }
false
true
public boolean onCreateOptionsMenu(Menu menu){ AccountManager am = AccountManager.get(this); if(Utils.isCurrentPlayerOwner(am, account)){ int playbackState = Utils.getPlaybackState(am, account); if(playbackState == Constants.PLAYING_STATE){ menu.add("Pause") .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } else if(playbackState == Constants.PAUSED_STATE){ menu.add("Play") .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } menu.add("Search") .setIcon(R.drawable.ic_search) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; }
public boolean onCreateOptionsMenu(Menu menu){ AccountManager am = AccountManager.get(this); if(Utils.isCurrentPlayerOwner(am, account)){ int playbackState = Utils.getPlaybackState(am, account); if(playbackState == Constants.PLAYING_STATE){ menu.add("Pause") .setIcon(R.drawable.ab_pause) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } else if(playbackState == Constants.PAUSED_STATE){ menu.add("Play") .setIcon(R.drawable.ab_play) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } menu.add("Search") .setIcon(R.drawable.ab_search_dark) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; }
diff --git a/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java b/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java index f3a08b07..ee896fb7 100644 --- a/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java +++ b/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java @@ -1,721 +1,721 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * BaulastWindowSearch.java * * Created on 09.12.2010, 14:33:10 */ package de.cismet.cids.custom.wunda_blau.search; import Sirius.navigator.actiontag.ActionTagProtected; import Sirius.navigator.connection.SessionManager; import Sirius.navigator.exception.ConnectionException; import Sirius.navigator.search.CidsSearchExecutor; import Sirius.navigator.search.dynamic.SearchControlListener; import Sirius.navigator.search.dynamic.SearchControlPanel; import Sirius.server.middleware.types.MetaClass; import Sirius.server.middleware.types.MetaObject; import com.vividsolutions.jts.geom.Geometry; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JOptionPane; import de.cismet.cids.custom.objecteditors.wunda_blau.FlurstueckSelectionDialoge; import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport; import de.cismet.cids.custom.wunda_blau.search.server.BaulastSearchInfo; import de.cismet.cids.custom.wunda_blau.search.server.CidsBaulastSearchStatement; import de.cismet.cids.custom.wunda_blau.search.server.FlurstueckInfo; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.editors.DefaultBindableReferenceCombo; import de.cismet.cids.navigator.utils.CidsBeanDropListener; import de.cismet.cids.navigator.utils.CidsBeanDropTarget; import de.cismet.cids.navigator.utils.ClassCacheMultiple; import de.cismet.cids.server.search.MetaObjectNodeServerSearch; import de.cismet.cids.tools.search.clientstuff.CidsWindowSearch; import de.cismet.cismap.commons.CrsTransformer; import de.cismet.cismap.commons.XBoundingBox; import de.cismet.cismap.commons.features.Feature; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.cismap.commons.gui.piccolo.eventlistener.AbstractCreateSearchGeometryListener; import de.cismet.cismap.commons.interaction.CismapBroker; import de.cismet.cismap.navigatorplugin.CidsFeature; import de.cismet.tools.gui.StaticSwingTools; import java.awt.Dimension; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Box; /** * DOCUMENT ME! * * @author stefan * @version $Revision$, $Date$ */ @org.openide.util.lookup.ServiceProvider(service = CidsWindowSearch.class) public class BaulastWindowSearch extends javax.swing.JPanel implements CidsWindowSearch, CidsBeanDropListener, ActionTagProtected, SearchControlListener, PropertyChangeListener{ //~ Static fields/initializers --------------------------------------------- static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(BaulastWindowSearch.class); //~ Instance fields -------------------------------------------------------- private MetaClass mc = null; private ImageIcon icon = null; private FlurstueckSelectionDialoge fsSelectionDialoge = null; private DefaultListModel flurstuecksFilterModel = null; private SearchControlPanel pnlSearchCancel; private GeoSearchButton btnGeoSearch; private MappingComponent mappingComponent; private boolean geoSearchEnabled; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddFS; private javax.swing.JButton btnFromMapFS; private javax.swing.JButton btnRemoveFS; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox cbArt; private javax.swing.JCheckBox chkBeguenstigt; private javax.swing.JCheckBox chkBelastet; private javax.swing.JCheckBox chkGeloescht; private javax.swing.JCheckBox chkGueltig; private javax.swing.JCheckBox chkKartenausschnitt; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JList lstFlurstueck; private javax.swing.JPanel panCommand; private javax.swing.JPanel panSearch; private javax.swing.JPanel pnlAttributeFilter; private javax.swing.JPanel pnlFlurstuecksfilter; private javax.swing.JPanel pnlSearchFor; private javax.swing.JRadioButton rbBaulastBlaetter; private javax.swing.JRadioButton rbBaulasten; private javax.swing.JTextField txtBlattnummer; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form BaulastWindowSearch. */ public BaulastWindowSearch() { try { mc = ClassCacheMultiple.getMetaClass(CidsBeanSupport.DOMAIN_NAME, "ALB_BAULAST"); icon = new ImageIcon(mc.getIconData()); fsSelectionDialoge = new FlurstueckSelectionDialoge(false) { @Override public void okHook() { final List<CidsBean> result = getCurrentListToAdd(); if (result.size() > 0) { flurstuecksFilterModel.addElement(result.get(0)); } } }; initComponents(); final MetaClass artMC = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "ALB_BAULAST_ART"); final DefaultComboBoxModel cbArtModel; try { cbArtModel = DefaultBindableReferenceCombo.getModelByMetaClass(artMC, true); cbArt.setModel(cbArtModel); } catch (Exception ex) { log.error(ex, ex); } flurstuecksFilterModel = new DefaultListModel(); lstFlurstueck.setModel(flurstuecksFilterModel); StaticSwingTools.decorateWithFixedAutoCompleteDecorator(cbArt); new CidsBeanDropTarget(this); fsSelectionDialoge.pack(); // cmdAbort.setVisible(false); pnlSearchCancel = new SearchControlPanel(this); final Dimension max = pnlSearchCancel.getMaximumSize(); final Dimension min = pnlSearchCancel.getMinimumSize(); final Dimension pre = pnlSearchCancel.getPreferredSize(); pnlSearchCancel.setMaximumSize(new java.awt.Dimension( new Double(max.getWidth()).intValue(), new Double(max.getHeight() + 5).intValue())); pnlSearchCancel.setMinimumSize(new java.awt.Dimension( new Double(min.getWidth()).intValue(), new Double(min.getHeight() + 5).intValue())); pnlSearchCancel.setPreferredSize(new java.awt.Dimension( new Double(pre.getWidth() + 6).intValue(), new Double(pre.getHeight() + 5).intValue())); panCommand.add(pnlSearchCancel); panCommand.add(Box.createHorizontalStrut(5)); mappingComponent = CismapBroker.getInstance().getMappingComponent(); geoSearchEnabled = mappingComponent != null; if (geoSearchEnabled) { final BaulastCreateSearchGeometryListener baulastSearchGeometryListener = new BaulastCreateSearchGeometryListener(mappingComponent, new BaulastSearchTooltip(icon)); baulastSearchGeometryListener.addPropertyChangeListener(this); btnGeoSearch = new GeoSearchButton( BaulastCreateSearchGeometryListener.BAULAST_CREATE_SEARCH_GEOMETRY, mappingComponent, null, org.openide.util.NbBundle.getMessage( BaulastWindowSearch.class, "BaulastWindowSearch.btnGeoSearch.toolTipText")); btnGeoSearch.addActionListener(null); panCommand.add(btnGeoSearch); } } catch (Exception exception) { log.warn("Error in Constructor of BaulastWindowSearch", exception); } } //~ Methods ---------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); panSearch = new javax.swing.JPanel(); panCommand = new javax.swing.JPanel(); pnlAttributeFilter = new javax.swing.JPanel(); chkGeloescht = new javax.swing.JCheckBox(); chkGueltig = new javax.swing.JCheckBox(); cbArt = new javax.swing.JComboBox(); txtBlattnummer = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pnlFlurstuecksfilter = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); lstFlurstueck = new javax.swing.JList(); btnAddFS = new javax.swing.JButton(); btnRemoveFS = new javax.swing.JButton(); btnFromMapFS = new javax.swing.JButton(); chkBeguenstigt = new javax.swing.JCheckBox(); chkBelastet = new javax.swing.JCheckBox(); pnlSearchFor = new javax.swing.JPanel(); rbBaulastBlaetter = new javax.swing.JRadioButton(); rbBaulasten = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); chkKartenausschnitt = new javax.swing.JCheckBox(); setMaximumSize(new java.awt.Dimension(325, 460)); setMinimumSize(new java.awt.Dimension(325, 460)); setPreferredSize(new java.awt.Dimension(325, 460)); setLayout(new java.awt.BorderLayout()); panSearch.setMaximumSize(new java.awt.Dimension(400, 150)); panSearch.setMinimumSize(new java.awt.Dimension(400, 150)); panSearch.setPreferredSize(new java.awt.Dimension(400, 150)); panSearch.setLayout(new java.awt.GridBagLayout()); panCommand.setLayout(new javax.swing.BoxLayout(panCommand, javax.swing.BoxLayout.LINE_AXIS)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(panCommand, gridBagConstraints); pnlAttributeFilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Attributfilter")); pnlAttributeFilter.setLayout(new java.awt.GridBagLayout()); chkGeloescht.setSelected(true); chkGeloescht.setText("gelöscht / geschlossen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(chkGeloescht, gridBagConstraints); chkGueltig.setSelected(true); chkGueltig.setText("gültig"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(chkGueltig, gridBagConstraints); cbArt.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(cbArt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(txtBlattnummer, gridBagConstraints); jLabel1.setText("Blattnummer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(jLabel1, gridBagConstraints); jLabel2.setText("Art der Baulast:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlAttributeFilter, gridBagConstraints); pnlFlurstuecksfilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstücksfilter")); pnlFlurstuecksfilter.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setMaximumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 100)); jScrollPane1.setViewportView(lstFlurstueck); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(jScrollPane1, gridBagConstraints); btnAddFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-add.png"))); // NOI18N btnAddFS.setToolTipText("Flurstück hinzufügen"); btnAddFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnAddFS, gridBagConstraints); btnRemoveFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png"))); // NOI18N btnRemoveFS.setToolTipText("Ausgewählte Flurstücke entfernen"); btnRemoveFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnRemoveFS, gridBagConstraints); btnFromMapFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/bookmark-new.png"))); // NOI18N btnFromMapFS.setToolTipText("Selektierte Flurstücke aus Karte hinzufügen"); btnFromMapFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFromMapFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnFromMapFS, gridBagConstraints); chkBeguenstigt.setSelected(true); chkBeguenstigt.setText("begünstigt"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(chkBeguenstigt, gridBagConstraints); chkBelastet.setSelected(true); chkBelastet.setText("belastet"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(chkBelastet, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlFlurstuecksfilter, gridBagConstraints); pnlSearchFor.setBorder(javax.swing.BorderFactory.createTitledBorder("Suche nach")); pnlSearchFor.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(rbBaulastBlaetter); rbBaulastBlaetter.setSelected(true); rbBaulastBlaetter.setText("Baulastblätter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlSearchFor.add(rbBaulastBlaetter, gridBagConstraints); buttonGroup1.add(rbBaulasten); rbBaulasten.setText("Baulasten"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlSearchFor.add(rbBaulasten, gridBagConstraints); jPanel5.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; pnlSearchFor.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlSearchFor, gridBagConstraints); jPanel6.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panSearch.add(jPanel6, gridBagConstraints); - chkKartenausschnitt.setText("<html>Nur im aktuellen<br>Kartenausschnitt suchen</html>"); + chkKartenausschnitt.setText("<html>nur im aktuellen<br>Kartenausschnitt suchen</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; panSearch.add(chkKartenausschnitt, gridBagConstraints); add(panSearch, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddFSActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFSActionPerformed final List<CidsBean> result = new ArrayList<CidsBean>(1); fsSelectionDialoge.setCurrentListToAdd(result); StaticSwingTools.showDialog(StaticSwingTools.getParentFrame(this), fsSelectionDialoge, true); }//GEN-LAST:event_btnAddFSActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveFSActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveFSActionPerformed final Object[] selection = lstFlurstueck.getSelectedValues(); for (final Object o : selection) { flurstuecksFilterModel.removeElement(o); } }//GEN-LAST:event_btnRemoveFSActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnFromMapFSActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFromMapFSActionPerformed final Collection<Feature> selFeatures = CismapBroker.getInstance() .getMappingComponent() .getFeatureCollection() .getSelectedFeatures(); for (final Feature feature : selFeatures) { if (feature instanceof CidsFeature) { final CidsFeature cf = (CidsFeature)feature; final MetaObject mo = cf.getMetaObject(); final String tableName = mo.getMetaClass().getTableName(); if ("FLURSTUECK".equalsIgnoreCase(tableName) || "ALB_FLURSTUECK_KICKER".equalsIgnoreCase(tableName)) { // if ("FLURSTUECK".equalsIgnoreCase(tableName) || "ALB_FLURSTUECK_KICKER".equalsIgnoreCase(tableName) || "ALKIS_LANDPARCEL".equalsIgnoreCase(tableName)) { flurstuecksFilterModel.addElement(mo.getBean()); } } } }//GEN-LAST:event_btnFromMapFSActionPerformed /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public ImageIcon getIcon() { return icon; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public String getName() { return "Baulast Suche"; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public JComponent getSearchWindowComponent() { return this; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ private BaulastSearchInfo getBaulastInfoFromGUI() { final BaulastSearchInfo bsi = new BaulastSearchInfo(); bsi.setResult(rbBaulastBlaetter.isSelected() ? CidsBaulastSearchStatement.Result.BAULASTBLATT : CidsBaulastSearchStatement.Result.BAULAST); if (chkKartenausschnitt.isSelected()) { final XBoundingBox bb = (XBoundingBox)CismapBroker.getInstance().getMappingComponent() .getCurrentBoundingBox(); bsi.setGeometry(CrsTransformer.transformToDefaultCrs(bb.getGeometry())); } bsi.setBelastet(chkBelastet.isSelected()); bsi.setBeguenstigt(chkBeguenstigt.isSelected()); bsi.setUngueltig(chkGeloescht.isSelected()); bsi.setGueltig(chkGueltig.isSelected()); bsi.setBlattnummer(txtBlattnummer.getText()); final Object art = cbArt.getSelectedItem(); if (art != null) { bsi.setArt(art.toString()); } return bsi; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public MetaObjectNodeServerSearch getServerSearch() { return getServerSearch(null); } public MetaObjectNodeServerSearch getServerSearch(final Geometry geometry) { final BaulastSearchInfo bsi = getBaulastInfoFromGUI(); if(geometry != null) { bsi.setGeometry(CrsTransformer.transformToDefaultCrs(geometry)); } for (int i = 0; i < flurstuecksFilterModel.size(); ++i) { final CidsBean fsBean = (CidsBean)flurstuecksFilterModel.getElementAt(i); try { if ("ALB_FLURSTUECK_KICKER".equalsIgnoreCase(fsBean.getMetaObject().getMetaClass().getTableName())) { final FlurstueckInfo fi = new FlurstueckInfo((Integer)fsBean.getProperty("gemarkung"), (String)fsBean.getProperty("flur"), (String)fsBean.getProperty("zaehler"), (String)fsBean.getProperty("nenner")); bsi.getFlurstuecke().add(fi); } else if ("FLURSTUECK".equalsIgnoreCase(fsBean.getMetaObject().getMetaClass().getTableName())) { final CidsBean gemarkung = (CidsBean)fsBean.getProperty("gemarkungs_nr"); final FlurstueckInfo fi = new FlurstueckInfo((Integer)gemarkung.getProperty("gemarkungsnummer"), (String)fsBean.getProperty("flur"), String.valueOf(fsBean.getProperty("fstnr_z")), String.valueOf(fsBean.getProperty("fstnr_n"))); bsi.getFlurstuecke().add(fi); } // else if ("ALKIS_LANDPARCEL".equalsIgnoreCase(fsBean.getMetaObject().getMetaClass().getTableName())) { // //TODO: merke // FlurstueckInfo fi = new FlurstueckInfo(Integer.parseInt(String.valueOf(fsBean.getProperty("gemarkung"))), (String) fsBean.getProperty("flur"), String.valueOf(fsBean.getProperty("fstck_zaehler")), String.valueOf(fsBean.getProperty("fstck_nenner"))); // bsi.getFlurstuecke().add(fi); // } } catch (Exception ex) { log.error("Can not parse information from Flurstueck bean: " + fsBean, ex); } } MetaClass mc = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "ALB_BAULAST"); final int baulastClassID = mc.getID(); mc = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "ALB_BAULASTBLATT"); final int baulastblattClassID = mc.getID(); return new CidsBaulastSearchStatement(bsi, baulastClassID, baulastblattClassID); } /** * DOCUMENT ME! * * @param beans DOCUMENT ME! */ @Override public void beansDropped(final ArrayList<CidsBean> beans) { for (final CidsBean bean : beans) { if ("FLURSTUECK".equalsIgnoreCase(bean.getMetaObject().getMetaClass().getTableName())) { // if ("FLURSTUECK".equalsIgnoreCase(bean.getMetaObject().getMetaClass().getTableName()) || "ALKIS_LANDPARCEL".equalsIgnoreCase(bean.getMetaObject().getMetaClass().getTableName())) { flurstuecksFilterModel.addElement(bean); } lstFlurstueck.repaint(); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public boolean checkActionTag() { try { return SessionManager.getConnection() .getConfigAttr(SessionManager.getSession().getUser(), "navigator.baulasten.search@WUNDA_BLAU") != null; } catch (ConnectionException ex) { log.error("Can not validate ActionTag for Baulasten Suche!", ex); return false; } } @Override public MetaObjectNodeServerSearch assembleSearch() { MetaObjectNodeServerSearch result = null; final BaulastSearchInfo bsi = getBaulastInfoFromGUI(); final boolean keineBlattNummer = (bsi.getBlattnummer() == null) || (bsi.getBlattnummer().trim().length() == 0); final boolean keineArt = (bsi.getArt() == null) || (bsi.getArt().trim().length() == 0); final boolean keinFlurstueck = lstFlurstueck.getModel().getSize() == 0; final boolean keinKartenausschnitt = !chkKartenausschnitt.isSelected(); if (keineBlattNummer && keinKartenausschnitt && keineArt && keinFlurstueck) { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(this), "Ihre Suchanfrage ist nicht plausibel. Bitte präzisieren Sie die\n" + "Suchanfrage durch weitere Angaben im Attribut- und Flurstücksfilter.", "Plausibilitätskontrolle", JOptionPane.WARNING_MESSAGE); } else { result = getServerSearch(); } return result; } /** * DOCUMENT ME! */ @Override public void searchStarted() { } /** * DOCUMENT ME! * * @param results DOCUMENT ME! */ @Override public void searchDone(final int results) { if (results > 0) { txtBlattnummer.setText(""); cbArt.setSelectedItem(""); chkKartenausschnitt.setSelected(false); } } /** * DOCUMENT ME! */ @Override public void searchCanceled() { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public boolean suppressEmptyResultMessage() { return false; } @Override public void propertyChange(final PropertyChangeEvent evt) { if (AbstractCreateSearchGeometryListener.PROPERTY_FORGUI_LAST_FEATURE.equals(evt.getPropertyName()) || AbstractCreateSearchGeometryListener.PROPERTY_FORGUI_MODE.equals(evt.getPropertyName())) { btnGeoSearch.visualizeSearchMode((MauernCreateSearchGeometryListener)mappingComponent.getInputListener( MauernCreateSearchGeometryListener.MAUERN_CREATE_SEARCH_GEOMETRY)); } if (MeasurementPointCreateSearchGeometryListener.ACTION_SEARCH_STARTED.equals(evt.getPropertyName())) { if ((evt.getNewValue() != null) && (evt.getNewValue() instanceof Geometry)) { final MetaObjectNodeServerSearch search = getServerSearch((Geometry)evt.getNewValue()); CidsSearchExecutor.searchAndDisplayResultsWithDialog(search); } } } }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); panSearch = new javax.swing.JPanel(); panCommand = new javax.swing.JPanel(); pnlAttributeFilter = new javax.swing.JPanel(); chkGeloescht = new javax.swing.JCheckBox(); chkGueltig = new javax.swing.JCheckBox(); cbArt = new javax.swing.JComboBox(); txtBlattnummer = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pnlFlurstuecksfilter = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); lstFlurstueck = new javax.swing.JList(); btnAddFS = new javax.swing.JButton(); btnRemoveFS = new javax.swing.JButton(); btnFromMapFS = new javax.swing.JButton(); chkBeguenstigt = new javax.swing.JCheckBox(); chkBelastet = new javax.swing.JCheckBox(); pnlSearchFor = new javax.swing.JPanel(); rbBaulastBlaetter = new javax.swing.JRadioButton(); rbBaulasten = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); chkKartenausschnitt = new javax.swing.JCheckBox(); setMaximumSize(new java.awt.Dimension(325, 460)); setMinimumSize(new java.awt.Dimension(325, 460)); setPreferredSize(new java.awt.Dimension(325, 460)); setLayout(new java.awt.BorderLayout()); panSearch.setMaximumSize(new java.awt.Dimension(400, 150)); panSearch.setMinimumSize(new java.awt.Dimension(400, 150)); panSearch.setPreferredSize(new java.awt.Dimension(400, 150)); panSearch.setLayout(new java.awt.GridBagLayout()); panCommand.setLayout(new javax.swing.BoxLayout(panCommand, javax.swing.BoxLayout.LINE_AXIS)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(panCommand, gridBagConstraints); pnlAttributeFilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Attributfilter")); pnlAttributeFilter.setLayout(new java.awt.GridBagLayout()); chkGeloescht.setSelected(true); chkGeloescht.setText("gelöscht / geschlossen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(chkGeloescht, gridBagConstraints); chkGueltig.setSelected(true); chkGueltig.setText("gültig"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(chkGueltig, gridBagConstraints); cbArt.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(cbArt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(txtBlattnummer, gridBagConstraints); jLabel1.setText("Blattnummer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(jLabel1, gridBagConstraints); jLabel2.setText("Art der Baulast:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlAttributeFilter, gridBagConstraints); pnlFlurstuecksfilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstücksfilter")); pnlFlurstuecksfilter.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setMaximumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 100)); jScrollPane1.setViewportView(lstFlurstueck); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(jScrollPane1, gridBagConstraints); btnAddFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-add.png"))); // NOI18N btnAddFS.setToolTipText("Flurstück hinzufügen"); btnAddFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnAddFS, gridBagConstraints); btnRemoveFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png"))); // NOI18N btnRemoveFS.setToolTipText("Ausgewählte Flurstücke entfernen"); btnRemoveFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnRemoveFS, gridBagConstraints); btnFromMapFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/bookmark-new.png"))); // NOI18N btnFromMapFS.setToolTipText("Selektierte Flurstücke aus Karte hinzufügen"); btnFromMapFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFromMapFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnFromMapFS, gridBagConstraints); chkBeguenstigt.setSelected(true); chkBeguenstigt.setText("begünstigt"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(chkBeguenstigt, gridBagConstraints); chkBelastet.setSelected(true); chkBelastet.setText("belastet"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(chkBelastet, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlFlurstuecksfilter, gridBagConstraints); pnlSearchFor.setBorder(javax.swing.BorderFactory.createTitledBorder("Suche nach")); pnlSearchFor.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(rbBaulastBlaetter); rbBaulastBlaetter.setSelected(true); rbBaulastBlaetter.setText("Baulastblätter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlSearchFor.add(rbBaulastBlaetter, gridBagConstraints); buttonGroup1.add(rbBaulasten); rbBaulasten.setText("Baulasten"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlSearchFor.add(rbBaulasten, gridBagConstraints); jPanel5.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; pnlSearchFor.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlSearchFor, gridBagConstraints); jPanel6.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panSearch.add(jPanel6, gridBagConstraints); chkKartenausschnitt.setText("<html>Nur im aktuellen<br>Kartenausschnitt suchen</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; panSearch.add(chkKartenausschnitt, gridBagConstraints); add(panSearch, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); panSearch = new javax.swing.JPanel(); panCommand = new javax.swing.JPanel(); pnlAttributeFilter = new javax.swing.JPanel(); chkGeloescht = new javax.swing.JCheckBox(); chkGueltig = new javax.swing.JCheckBox(); cbArt = new javax.swing.JComboBox(); txtBlattnummer = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pnlFlurstuecksfilter = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); lstFlurstueck = new javax.swing.JList(); btnAddFS = new javax.swing.JButton(); btnRemoveFS = new javax.swing.JButton(); btnFromMapFS = new javax.swing.JButton(); chkBeguenstigt = new javax.swing.JCheckBox(); chkBelastet = new javax.swing.JCheckBox(); pnlSearchFor = new javax.swing.JPanel(); rbBaulastBlaetter = new javax.swing.JRadioButton(); rbBaulasten = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); chkKartenausschnitt = new javax.swing.JCheckBox(); setMaximumSize(new java.awt.Dimension(325, 460)); setMinimumSize(new java.awt.Dimension(325, 460)); setPreferredSize(new java.awt.Dimension(325, 460)); setLayout(new java.awt.BorderLayout()); panSearch.setMaximumSize(new java.awt.Dimension(400, 150)); panSearch.setMinimumSize(new java.awt.Dimension(400, 150)); panSearch.setPreferredSize(new java.awt.Dimension(400, 150)); panSearch.setLayout(new java.awt.GridBagLayout()); panCommand.setLayout(new javax.swing.BoxLayout(panCommand, javax.swing.BoxLayout.LINE_AXIS)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(panCommand, gridBagConstraints); pnlAttributeFilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Attributfilter")); pnlAttributeFilter.setLayout(new java.awt.GridBagLayout()); chkGeloescht.setSelected(true); chkGeloescht.setText("gelöscht / geschlossen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(chkGeloescht, gridBagConstraints); chkGueltig.setSelected(true); chkGueltig.setText("gültig"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(chkGueltig, gridBagConstraints); cbArt.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(cbArt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(txtBlattnummer, gridBagConstraints); jLabel1.setText("Blattnummer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(jLabel1, gridBagConstraints); jLabel2.setText("Art der Baulast:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAttributeFilter.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlAttributeFilter, gridBagConstraints); pnlFlurstuecksfilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstücksfilter")); pnlFlurstuecksfilter.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setMaximumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 100)); jScrollPane1.setViewportView(lstFlurstueck); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(jScrollPane1, gridBagConstraints); btnAddFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-add.png"))); // NOI18N btnAddFS.setToolTipText("Flurstück hinzufügen"); btnAddFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnAddFS, gridBagConstraints); btnRemoveFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png"))); // NOI18N btnRemoveFS.setToolTipText("Ausgewählte Flurstücke entfernen"); btnRemoveFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnRemoveFS, gridBagConstraints); btnFromMapFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/bookmark-new.png"))); // NOI18N btnFromMapFS.setToolTipText("Selektierte Flurstücke aus Karte hinzufügen"); btnFromMapFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFromMapFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(btnFromMapFS, gridBagConstraints); chkBeguenstigt.setSelected(true); chkBeguenstigt.setText("begünstigt"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(chkBeguenstigt, gridBagConstraints); chkBelastet.setSelected(true); chkBelastet.setText("belastet"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlFlurstuecksfilter.add(chkBelastet, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlFlurstuecksfilter, gridBagConstraints); pnlSearchFor.setBorder(javax.swing.BorderFactory.createTitledBorder("Suche nach")); pnlSearchFor.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(rbBaulastBlaetter); rbBaulastBlaetter.setSelected(true); rbBaulastBlaetter.setText("Baulastblätter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlSearchFor.add(rbBaulastBlaetter, gridBagConstraints); buttonGroup1.add(rbBaulasten); rbBaulasten.setText("Baulasten"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlSearchFor.add(rbBaulasten, gridBagConstraints); jPanel5.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; pnlSearchFor.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(pnlSearchFor, gridBagConstraints); jPanel6.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panSearch.add(jPanel6, gridBagConstraints); chkKartenausschnitt.setText("<html>nur im aktuellen<br>Kartenausschnitt suchen</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; panSearch.add(chkKartenausschnitt, gridBagConstraints); add(panSearch, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents