List of usage examples for org.json.simple JSONValue toJSONString
public static String toJSONString(Object value)
From source file:amulet.resourceprofiler.ResourceProfiler.java
/** * Create a "cost profiler" object from a JSON formatted file which contains * a mapping of RESOURCE<-->ENERGY_COST which can be used by the ResourceProfiler * to compute "cost scores" that can be used to give application developers * feedback about their application's runtime/energy consumption behavior. * /*from w w w .j a va 2 s . co m*/ * @param filename Name of the JSON file with energy cost information. * * @warning There are typing issues with the parameterization of JSONObjects * in the `org.json.simple.*` package which require us to 'SupressWarnings' manually. * In the future we can implement a wrapper class or find a new JSON library to * solve this issue. * * TODO: each state here should have a JSON object written for stateEntryCost & stateExitCost. * --> this may mean we need to modify how we account for resources when "walking" the code. (state context variable for "entry" vs. "exit") */ @SuppressWarnings("unchecked") public String calculateCost(String filename) { /* * 0. Load the lookup table */ BufferedReader br = null; String line = ""; String dataFile = "AppBuildTool/src/amulet/resourceprofiler/clear_fill_pixel_lookup.csv"; double[][] fill_rect_lookup = new double[128][128]; double[][] clear_rect_lookup = new double[128][128]; int line_counter = 0; try { br = new BufferedReader(new FileReader(dataFile)); while ((line = br.readLine()) != null) { // use comma as separator String[] table_entry = line.split(","); if (line_counter++ % 2 == 1) { // Odd is Clear clear_rect_lookup[Integer.parseInt(table_entry[2].trim())][Integer .parseInt(table_entry[3].trim())] = Double.parseDouble(table_entry[0].trim()); } else { // Even is Fill fill_rect_lookup[Integer.parseInt(table_entry[2].trim())][Integer .parseInt(table_entry[3].trim())] = Double.parseDouble(table_entry[0].trim()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } /* * 1. Load energy data from the input JSON file. */ m_jsonResourceReader.read(filename); /* * 2. Update the resource records for the QM Apps known to the ResourceProfiler. * --> Use the JSON model file supplied by the device manufacturer. */ // Get primary data objects from the JSON resource reader. LinkedHashMap<String, EnergyParam> api_energy_lookup = m_jsonResourceReader.getEnergyParams(); DeviceInfo deviceInfo = m_jsonResourceReader.getDeviceInfo(); SteadyStateInfo steadyStateInfo = m_jsonResourceReader.getSteadyStateInfo(); // Update 1:: Resolve variables used in iterative blocks (e.g., for-loops). for (QMApp qmapp : m_qmapps) { for (Resource resource : qmapp.resources) { String strStopVal = resource.extras.get(Resource.EXTRA_LOOP_END_VALUE); if (strStopVal == null) continue; // If the current "stop value" is an integer, it will be parsed successfully // and no update is necessary; if, however, a NumberFormatException is raised, // attempt to look up the string (a variable name) in the simple intVariableResolver. try { Integer.parseInt(strStopVal); } catch (NumberFormatException nfe) { String resolvedValue = getResolverIntVar(strStopVal); if (resolvedValue != null) { // Resolved integer value found -- update the extra's value. resource.extras.put(Resource.EXTRA_LOOP_END_VALUE, resolvedValue); } } } } // Update 2:: Update "cost" values for each operation defined in each QM application. for (QMApp qmapp : m_qmapps) { for (String currentOp : qmapp.operationCostMap.keySet()) { /* * NOTE--this only computes an ENERGY cost and EXECUTION TIME of calling some operation--no memory costs are calculated. * This seems permissible since the memory is only used when the function is called and is "released" as * soon as the function returns; also, we have no intension of attributing "memory" costs to a state/transition * when it calls some Amulet API call or a non-Amulet API call. */ // Compute the cost of all resources used in the current operation. double updatedOpCost = 0.0; double updatedOpTime = 0.0; for (Resource opResource : getResourcesByContext(qmapp.resources, QmStateMachineContext.OPERATION)) { if (opResource.getStringExtra(Resource.EXTRA_QM_OPERATION_NAME).equals(currentOp)) { updatedOpCost += getCostHelper(opResource, qmapp, deviceInfo, steadyStateInfo, api_energy_lookup, fill_rect_lookup, clear_rect_lookup); updatedOpTime += getTimeHelper(opResource, qmapp, deviceInfo, steadyStateInfo, api_energy_lookup, fill_rect_lookup, clear_rect_lookup); } } // Update the record in the operation map. qmapp.operationCostMap.put(currentOp, updatedOpCost); qmapp.operationTimeMap.put(currentOp, updatedOpTime); } } // Update 3:: Update "cost" values for each resource record with real power/time measurements from JSON file. for (QMApp qmapp : m_qmapps) { for (Resource resource : qmapp.resources) { // if(resource.name.contains("Amulet")) { // System.out.println("2 (before)************************" + resource); // } resource.cost = getCostHelper(resource, qmapp, deviceInfo, steadyStateInfo, api_energy_lookup, fill_rect_lookup, clear_rect_lookup); resource.time = getTimeHelper(resource, qmapp, deviceInfo, steadyStateInfo, api_energy_lookup, fill_rect_lookup, clear_rect_lookup); // if(resource.name.contains("Amulet")) { // System.out.println("2 (after)************************" + resource); // } } } /* * 3. Compute sums, and provide feedback in the form of a JSON file for later use by any program. * --> Currently the output file is used by our web application. */ JSONArray appJSONlist = new JSONArray(); for (QMApp qmapp : m_qmapps) { /* * Record costs for energy, memory, and global memory resources across various application "contexts". */ LinkedHashMap<String, Double> stateEnergySums = new LinkedHashMap<String, Double>(); LinkedHashMap<String, Double> transitionEnergySums = new LinkedHashMap<String, Double>(); //LinkedHashMap<String, Double> guardEnergySums = new LinkedHashMap<String, Double>(); LinkedHashMap<String, Double> stateExecutionTimeSums = new LinkedHashMap<String, Double>(); LinkedHashMap<String, Double> transitionExecutionTimeSums = new LinkedHashMap<String, Double>(); //LinkedHashMap<String, Double> guardExecutionTimeSums = new LinkedHashMap<String, Double>(); LinkedHashMap<String, Double> sensorSubscriptions = new LinkedHashMap<String, Double>(); LinkedHashMap<String, Integer> timerSubscriptions = new LinkedHashMap<String, Integer>(); LinkedHashMap<String, Double> stateLocalMemorySums = new LinkedHashMap<String, Double>(); LinkedHashMap<String, Double> transitionLocalMemorySums = new LinkedHashMap<String, Double>(); //LinkedHashMap<String, Double> guardLocalMemorySums = new LinkedHashMap<String, Double>(); //LinkedHashMap<String, Double> globalMemorySums = new LinkedHashMap<String, Double>(); // Iterate over each resource, summing costs along the way. for (Resource resource : qmapp.resources) { // A temp holder for the current map to add resource to. LinkedHashMap<String, Double> currentCostSumMap = null; LinkedHashMap<String, Double> currentTimeSumMap = null; // High-level resource information. String name = null; Double cost = null; Double time = null; // Use information about the *CONTEXT* of the resource to determine where cost // is incurred in the application/model. if (resource.isQmStateResource()) { // State. currentCostSumMap = stateEnergySums; currentTimeSumMap = stateExecutionTimeSums; // Use state name as "key". name = resource.getStringExtra(Resource.EXTRA_QM_STATE_NAME); cost = resource.cost; time = resource.time; } else if (resource.isQmActionResource()) { // Transition. currentCostSumMap = transitionEnergySums; currentTimeSumMap = transitionExecutionTimeSums; // Use SRC->TRAN->DEST as "key". String currentState = resource.getStringExtra(Resource.EXTRA_QM_ACTION_CURRENT_STATE_NAME); String trigger = resource.getStringExtra(Resource.EXTRA_QM_ACTION_TRIGGER_NAME); String targetState = resource.getStringExtra(Resource.EXTRA_QM_ACTION_TARGET_STATE_NAME); name = currentState + "->" + trigger + "->" + targetState; cost = resource.cost; time = resource.time; } else if (resource.isQmGuardResource()) { // Guard. IGNORE FOR NOW -- NO APPLICATIONS USE THESE (ANYMORE). } else if (resource.isQmOperationResource()) { // Operation. IGNORE FOR NOW -- THE COST OF OPERATIONS ARE COMPUTED BEFOREHAND AND ARE ADDED TO THE CALLING STATE/TRANSITION AS ANY OTHER FUNCTION CALL. } // Use information about the *TYPE* of resource (in combination with information from above) // to compute energy/memory costs for relevant areas of the application. switch (resource.type) { case MEMORY: if (resource.isQmStateResource()) { // Local State Memory. currentCostSumMap = stateLocalMemorySums; } else if (resource.isQmActionResource()) { // Local Transition Memory. currentCostSumMap = transitionLocalMemorySums; } break; case GLOBAL_MEMORY: //currentSumMap = globalMemorySums; break; case SENSOR_SUBSCRIPTION: name = resource.name; currentCostSumMap = sensorSubscriptions; currentTimeSumMap = null; break; case TIMER_SUBSCRIPTION: // timerSubscriptions.put("AmuletTimer", resource.getIntExtra(Resource.EXTRA_TIMER_DELAY_IN_SECONDS)); timerSubscriptions.put("Timer", resource.getIntExtra(Resource.EXTRA_TIMER_DELAY_IN_SECONDS)); case AMULET_API_FUNCTION_CALL: break; case NON_AMULET_API_FUNCTION_CALL: break; case COMPUTATION: break; case UNKNOWN: break; default: // Do nothing (at least for now). break; } // If an appropriate "cost sum" map has been set, add to it. if (currentCostSumMap != null && name != null & cost != null) { sumMapHelper(currentCostSumMap, name, cost); } // If an appropriate "time sum" map has been set, add to it. if (currentTimeSumMap != null && name != null & time != null) { sumMapHelper(currentTimeSumMap, name, time); } } // Slightly easier to read DEBUG output... // System.out.println("=======> DEBUG stateEnergySums::" + stateEnergySums); // System.out.println("=======> DEBUG transitionEnergySums::" + transitionEnergySums); // System.out.println("=======> DEBUG localMemorySums::" + localMemorySums); // System.out.println("=======> DEBUG globalMemorySums::" + globalMemorySums); /* * 4. Make JSON object(s) and return string representation that will be written out. */ JSONObject appCostJSONObject = new JSONObject(); JSONObject stateEnergyCostJSON = new JSONObject(stateEnergySums); JSONObject transitionEnergyCostJSON = new JSONObject(transitionEnergySums); //JSONObject guardEnergyCostJSON = new JSONObject(guardEnergySums); JSONObject stateExecutionTimesJSON = new JSONObject(stateExecutionTimeSums); JSONObject transitionExecutionTimesJSON = new JSONObject(transitionExecutionTimeSums); //JSONObject guardExecutionTimesJSON = new JSONObject(guardExecutionTimeSums); JSONObject sensorSubscriptionsJSON = new JSONObject(sensorSubscriptions); JSONObject timerSubscriptionsJSON = new JSONObject(timerSubscriptions); JSONObject stateLocalMemoryCostJSON = new JSONObject(stateLocalMemorySums); JSONObject transitionLocalMemoryCostJSON = new JSONObject(transitionLocalMemorySums); //JSONObject guardLocalMemoryCostJSON = new JSONObject(guardLocalMemorySums); // int globalMemoryCost = getGlobalMemoryCosts().get(qmapp.filename); int globalMemoryCost = getMemoryCosts(ResourceType.GLOBAL_MEMORY).get(qmapp.filename); // Write data to JSON "App Costs" object. appCostJSONObject.put("filename", qmapp.filename); appCostJSONObject.put("device_info", deviceInfo.jsonDeviceInfo); // hack: add to each app appCostJSONObject.put("steady_state_info", steadyStateInfo.jsonSteadyStateInfo); // hack: add to each app appCostJSONObject.put("state_energy_costs", stateEnergyCostJSON); appCostJSONObject.put("transition_energy_costs", transitionEnergyCostJSON); //appCostJSONObject.put("guard_energy_costs", guardEnergyCostJSON); appCostJSONObject.put("state_execution_times", stateExecutionTimesJSON); appCostJSONObject.put("transition_execution_times", transitionExecutionTimesJSON); //appCostJSONObject.put("guard_execution_times", guardExecutionTimesJSON); appCostJSONObject.put("app_sensor_subscriptions", sensorSubscriptionsJSON); appCostJSONObject.put("app_timer_subscriptions", timerSubscriptionsJSON); appCostJSONObject.put("state_sram_costs", stateLocalMemoryCostJSON); appCostJSONObject.put("transition_sram_costs", transitionLocalMemoryCostJSON); //appCostJSONObject.put("guard_sram_costs", guardLocalMemoryCostJSON); appCostJSONObject.put("app_fram_costs", globalMemoryCost); appJSONlist.add(appCostJSONObject); } JSONObject costsJSONObject = new JSONObject(); costsJSONObject.put("applications", appJSONlist); costsJSONObject.put("device_info", deviceInfo.jsonDeviceInfo); costsJSONObject.put("steady_state_info", steadyStateInfo.jsonSteadyStateInfo); costsJSONObject.put("api_calls", m_jsonResourceReader.getApiInfo()); return JSONValue.toJSONString(costsJSONObject); }
From source file:com.wasteofplastic.askyblock.schematics.Schematic.java
/** * This method pastes a schematic and returns a location where a cow (or other entity) * could be placed. Actually, the location should be that of a grass block. * @param world/*from w ww . j a v a 2 s. c o m*/ * @param loc * @param player * @return Location of highest grass block */ @SuppressWarnings("deprecation") public void pasteSchematic(final Location loc, final Player player) { // If this is not a file schematic, paste the default island if (this.file == null) { if (Settings.GAMETYPE == GameType.ACIDISLAND) { generateIslandBlocks(loc, player); } else { loc.getBlock().setType(Material.BEDROCK); ASkyBlock.getPlugin().getLogger().severe("Missing schematic - using bedrock block only"); } return; } World world = loc.getWorld(); Map<BlockVector, Map<String, Tag>> tileEntitiesMap = this.getTileEntitiesMap(); //Bukkit.getLogger().info("World is " + world.getName() + "and schematic size is " + width + " x " + height + " x " + length); // Bukkit.getLogger().info("DEBUG Location to place island is:" + // loc.toString()); // Center on the last bedrock location //Bukkit.getLogger().info("DEBUG bedrock is:" + bedrock.toString()); // Bukkit.getLogger().info("DEBUG loc is before subtract:" + // loc.toString()); Location blockLoc = new Location(world, loc.getX(), loc.getY(), loc.getZ()); blockLoc.subtract(bedrock); //Bukkit.getLogger().info("DEBUG loc is after subtract:" + // loc.toString()); //Bukkit.getLogger().info("DEBUG blockloc is:" + blockLoc.toString()); // Bukkit.getLogger().info("DEBUG there are " + tileEntitiesMap.size() + // " tile entities in the schematic"); // Bukkit.getLogger().info("Placing blocks..."); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { for (int z = 0; z < length; ++z) { int index = y * width * length + z * width + x; Block block = new Location(world, x, y, z).add(blockLoc).getBlock(); block.setBiome(biome); try { // Do not post torches because they fall off every so often // May have to include banners too //if (blocks[index] != Material.TORCH.getId()) { Material blockMat = Material.getMaterial(blocks[index]); if (blockMat != null && !attachable.contains(blockMat)) { //block.setTypeIdAndData(blocks[index], data[index], this.usePhysics); nms.setBlockSuperFast(block, blocks[index], data[index], this.usePhysics); } else if (blocks[index] == 179) { // Red sandstone - use red sand instead //block.setTypeIdAndData(12, (byte)1, this.usePhysics); nms.setBlockSuperFast(block, 12, (byte) 1, this.usePhysics); } } catch (Exception e) { e.printStackTrace(); plugin.getLogger().info("Could not set (" + x + "," + y + "," + z + ") block ID:" + blocks[index] + " block data = " + data[index]); } } } } // Second pass - just paste attachables and deal with chests etc. for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { for (int z = 0; z < length; ++z) { int index = y * width * length + z * width + x; Block block = new Location(world, x, y, z).add(blockLoc).getBlock(); try { Material blockMat = Material.getMaterial(blocks[index]); if (blockMat != null && attachable.contains(blockMat)) { nms.setBlockSuperFast(block, blocks[index], data[index], this.usePhysics); } //block.setTypeIdAndData(blocks[index], data[index], this.usePhysics); } catch (Exception e) { plugin.getLogger().info("Could not set (" + x + "," + y + "," + z + ") block ID:" + blocks[index] + " block data = " + data[index]); } // Tile Entities if (tileEntitiesMap.containsKey(new BlockVector(x, y, z))) { String ver = Bukkit.getServer().getBukkitVersion(); int major = Integer.valueOf(ver.substring(0, 1)); int minor = Integer.valueOf(ver.substring(ver.indexOf(".") + 1, ver.indexOf(".") + 2)); if (major >= 1 && minor >= 8) { if (block.getType() == Material.STANDING_BANNER || block.getType() == Material.WALL_BANNER) { BannerBlock.set(block, tileEntitiesMap.get(new BlockVector(x, y, z))); } } // Monster spawner blocks if (block.getType() == Material.MOB_SPAWNER) { Map<String, Tag> tileData = tileEntitiesMap.get(new BlockVector(x, y, z)); CreatureSpawner cs = (CreatureSpawner) block.getState(); String creatureType = ((StringTag) tileData.get("EntityId")).getValue().toUpperCase(); EntityType et = null; if (WEtoME.containsKey(creatureType)) { et = WEtoME.get(creatureType); } else { et = EntityType.valueOf(creatureType); } cs.setSpawnedType(et); //Bukkit.getLogger().info("DEBUG: " + tileData); /* for (String key : tileData.keySet()) { Bukkit.getLogger().info("DEBUG: key = " + key + " : " + tileData.get(key)); StringTag st = (StringTag) tileData.get(key); Bukkit.getLogger().info("DEBUG: key = " + key + " : " + st.getName() + " " + st.getValue()); } */ } // Signs if ((block.getType() == Material.SIGN_POST) || (block.getType() == Material.WALL_SIGN)) { Sign sign = (Sign) block.getState(); Map<String, Tag> tileData = tileEntitiesMap.get(new BlockVector(x, y, z)); List<String> text = new ArrayList<String>(); text.add(((StringTag) tileData.get("Text1")).getValue()); text.add(((StringTag) tileData.get("Text2")).getValue()); text.add(((StringTag) tileData.get("Text3")).getValue()); text.add(((StringTag) tileData.get("Text4")).getValue()); // TODO Parse sign text formatting, colors and ULR's using JSON - this does not work right now JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; /* for (int line = 0; line < 4; line++) { if (!text.get(line).equals("\"\"")) { try{ Bukkit.getLogger().info("Text: '" + text.get(line) + "'"); Map json = (Map)parser.parse(text.get(line), containerFactory); Iterator iter = json.entrySet().iterator(); System.out.println("==iterate result=="); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); if (entry.getValue().toString().equals("extra")) { List content = (List)parser.parse(entry) } System.out.println(entry.getKey() + "=>" + entry.getValue()); } System.out.println("==toJSONString()=="); System.out.println(JSONValue.toJSONString(json)); } catch(ParseException pe){ System.out.println(pe); } } */ // This just removes all the JSON formatting and provides the raw text for (int line = 0; line < 4; line++) { if (!text.get(line).equals("\"\"") && !text.get(line).isEmpty()) { //String lineText = text.get(line).replace("{\"extra\":[\"", "").replace("\"],\"text\":\"\"}", ""); //Bukkit.getLogger().info("DEBUG: sign text = '" + text.get(line) + "'"); String lineText = ""; if (text.get(line).startsWith("{")) { // JSON string try { Map json = (Map) parser.parse(text.get(line), containerFactory); List list = (List) json.get("extra"); //System.out.println("DEBUG1:" + JSONValue.toJSONString(list)); Iterator iter = list.iterator(); while (iter.hasNext()) { Object next = iter.next(); String format = JSONValue.toJSONString(next); //System.out.println("DEBUG2:" + format); // This doesn't see right, but appears to be the easiest way to identify this string as JSON... if (format.startsWith("{")) { // JSON string Map jsonFormat = (Map) parser.parse(format, containerFactory); Iterator formatIter = jsonFormat.entrySet().iterator(); while (formatIter.hasNext()) { Map.Entry entry = (Map.Entry) formatIter.next(); //System.out.println("DEBUG3:" + entry.getKey() + "=>" + entry.getValue()); String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (key.equalsIgnoreCase("color")) { try { lineText += ChatColor.valueOf(value.toUpperCase()); } catch (Exception noColor) { Bukkit.getLogger().warning("Unknown color " + value + " in sign when pasting schematic, skipping..."); } } else if (key.equalsIgnoreCase("text")) { lineText += value; } else { // Formatting - usually the value is always true, but check just in case if (key.equalsIgnoreCase("obfuscated") && value.equalsIgnoreCase("true")) { lineText += ChatColor.MAGIC; } else if (key.equalsIgnoreCase("underlined") && value.equalsIgnoreCase("true")) { lineText += ChatColor.UNDERLINE; } else { // The rest of the formats try { lineText += ChatColor .valueOf(key.toUpperCase()); } catch (Exception noFormat) { // Ignore Bukkit.getLogger().warning("Unknown format " + value + " in sign when pasting schematic, skipping..."); } } } } } else { // This is unformatted text. It is included in "". A reset is required to clear // any previous formatting if (format.length() > 1) { lineText += ChatColor.RESET + format.substring( format.indexOf('"') + 1, format.lastIndexOf('"')); } } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // This is unformatted text (not JSON). It is included in "". if (text.get(line).length() > 1) { try { lineText = text.get(line).substring(text.get(line).indexOf('"') + 1, text.get(line).lastIndexOf('"')); } catch (Exception e) { //There may not be those "'s, so just use the raw line lineText = text.get(line); } } else { // just in case it isn't - show the raw line lineText = text.get(line); } } //Bukkit.getLogger().info("Line " + line + " is " + lineText); // Set the line sign.setLine(line, lineText); } } sign.update(); } if (block.getType().equals(Material.CHEST)) { // Check if there is another chest around (double chest) Chest chestBlock = (Chest) block.getState(); DoubleChest doubleChest = null; InventoryHolder iH = chestBlock.getInventory().getHolder(); if (iH instanceof DoubleChest) { //Bukkit.getLogger().info("DEBUG: double chest"); doubleChest = (DoubleChest) iH; } //Bukkit.getLogger().info("Chest tile entity found at " + x + " " + y + " " + z); Map<String, Tag> tileData = tileEntitiesMap.get(new BlockVector(x, y, z)); try { ListTag chestItems = (ListTag) tileData.get("Items"); if (chestItems != null) { //int number = 0; for (Tag item : chestItems.getValue()) { // Format for chest items is: // id = short value of item id // Damage = short value of item damage // Count = the number of items // Slot = the slot in the chest // inventory if (item instanceof CompoundTag) { try { // Id is a number short itemType = (Short) ((CompoundTag) item).getValue().get("id") .getValue(); short itemDamage = (Short) ((CompoundTag) item).getValue() .get("Damage").getValue(); byte itemAmount = (Byte) ((CompoundTag) item).getValue() .get("Count").getValue(); byte itemSlot = (Byte) ((CompoundTag) item).getValue().get("Slot") .getValue(); ItemStack chestItem = new ItemStack(itemType, itemAmount, itemDamage); chestBlock.getInventory().setItem(itemSlot, chestItem); } catch (ClassCastException ex) { // Id is a material String itemType = (String) ((CompoundTag) item).getValue().get("id") .getValue(); try { // Get the material if (itemType.startsWith("minecraft:")) { String material = itemType.substring(10).toUpperCase(); // Special case for non-standard material names Material itemMaterial; //Bukkit.getLogger().info("DEBUG: " + material); if (WEtoM.containsKey(material)) { //Bukkit.getLogger().info("DEBUG: Found in hashmap"); itemMaterial = WEtoM.get(material); } else { //Bukkit.getLogger().info("DEBUG: Not in hashmap"); itemMaterial = Material.valueOf(material); } short itemDamage = (Short) ((CompoundTag) item).getValue() .get("Damage").getValue(); byte itemAmount = (Byte) ((CompoundTag) item).getValue() .get("Count").getValue(); byte itemSlot = (Byte) ((CompoundTag) item).getValue() .get("Slot").getValue(); ItemStack chestItem = new ItemStack(itemMaterial, itemAmount, itemDamage); if (doubleChest != null) { // This does not respect the original order so gaps won't be there. doubleChest.getInventory().addItem(chestItem); } else { chestBlock.getInventory().setItem(itemSlot, chestItem); } //number++; } } catch (Exception exx) { // Bukkit.getLogger().info(item.toString()); // Bukkit.getLogger().info(((CompoundTag)item).getValue().get("id").getName()); Bukkit.getLogger() .severe("Could not parse item [" + itemType.substring(10).toUpperCase() + "] in schematic - skipping!"); // Bukkit.getLogger().severe(item.toString()); //exx.printStackTrace(); } } // Bukkit.getLogger().info("Set chest inventory slot " // + itemSlot + " to " + // chestItem.toString()); } } //Bukkit.getLogger().info("Added " + number + " items to chest"); } } catch (Exception e) { Bukkit.getLogger().severe("Could not parse schematic file item, skipping!"); // e.printStackTrace(); } } } } } } // PASTE ENTS //Bukkit.getLogger().info("Block loc = " + blockLoc); if (pasteEntities) { for (EntityObject ent : entitiesList) { Location entitySpot = ent.getLocation().toLocation(blockLoc.getWorld()).add(blockLoc.toVector()); entitySpot.setPitch(ent.getPitch()); entitySpot.setYaw(ent.getYaw()); //Bukkit.getLogger().info("Spawning " + ent.getType().toString() + " at " + entitySpot); Entity spawned = blockLoc.getWorld().spawnEntity(entitySpot, ent.getType()); spawned.setVelocity(ent.getMotion()); if (ent.getType() == EntityType.SHEEP) { Sheep sheep = (Sheep) spawned; if (ent.isSheared()) { sheep.setSheared(true); } DyeColor[] set = DyeColor.values(); sheep.setColor(set[ent.getColor()]); sheep.setAge(ent.getAge()); } else if (ent.getType() == EntityType.HORSE) { Horse horse = (Horse) spawned; Horse.Color[] set = Horse.Color.values(); horse.setColor(set[ent.getColor()]); horse.setAge(ent.getAge()); horse.setCarryingChest(ent.isCarryingChest()); } else if (ent.getType() == EntityType.VILLAGER) { Villager villager = (Villager) spawned; villager.setAge(ent.getAge()); Profession[] proffs = Profession.values(); villager.setProfession(proffs[ent.getProfession()]); } else if (ent.getType() == EntityType.RABBIT) { Rabbit rabbit = (Rabbit) spawned; Rabbit.Type[] set = Rabbit.Type.values(); rabbit.setRabbitType(set[ent.getRabbitType()]); rabbit.setAge(ent.getAge()); } else if (ent.getType() == EntityType.OCELOT) { Ocelot cat = (Ocelot) spawned; if (ent.isOwned()) { cat.setTamed(true); cat.setOwner(player); } Ocelot.Type[] set = Ocelot.Type.values(); cat.setCatType(set[ent.getCatType()]); cat.setAge(ent.getAge()); cat.setSitting(ent.isSitting()); } else if (ent.getType() == EntityType.WOLF) { Wolf wolf = (Wolf) spawned; if (ent.isOwned()) { wolf.setTamed(true); wolf.setOwner(player); } wolf.setAge(ent.getAge()); wolf.setSitting(ent.isSitting()); DyeColor[] color = DyeColor.values(); wolf.setCollarColor(color[ent.getCollarColor()]); } } } // TODO do this on load because it can be pre-processed // Go through all the grass blocks and try to find a safe one final Location grass; if (topGrass != null) { Location gr = topGrass.clone().toLocation(loc.getWorld()).subtract(bedrock); gr.add(loc.toVector()); gr.add(new Vector(0.5D, 1.1D, 0.5D)); // Center of block and a bit up so the animal drops a bit grass = gr; } else { grass = null; } //Bukkit.getLogger().info("DEBUG cow location " + grass); Block blockToChange = null; // world.spawnEntity(grass, EntityType.COW); // Place a helpful sign in front of player if (welcomeSign != null) { // Bukkit.getLogger().info("DEBUG welcome sign schematic relative is:" // + welcomeSign.toString()); Vector ws = welcomeSign.clone().subtract(bedrock); // Bukkit.getLogger().info("DEBUG welcome sign relative to bedrock is:" // + welcomeSign.toString()); ws.add(loc.toVector()); // Bukkit.getLogger().info("DEBUG welcome sign actual position is:" // + welcomeSign.toString()); blockToChange = ws.toLocation(world).getBlock(); blockToChange.setType(Material.SIGN_POST); Sign sign = (Sign) blockToChange.getState(); sign.setLine(0, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine1.replace("[player]", player.getName())); sign.setLine(1, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine2.replace("[player]", player.getName())); sign.setLine(2, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine3.replace("[player]", player.getName())); sign.setLine(3, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine4.replace("[player]", player.getName())); // BlockFace direction = ((org.bukkit.material.Sign) // sign.getData()).getFacing(); ((org.bukkit.material.Sign) sign.getData()).setFacingDirection(BlockFace.NORTH); sign.update(); } if (chest != null) { Vector ch = chest.clone().subtract(bedrock); ch.add(loc.toVector()); // Place the chest - no need to use the safe spawn function because we // know what this island looks like blockToChange = ch.toLocation(world).getBlock(); // Bukkit.getLogger().info("Chest block = " + blockToChange); // blockToChange.setType(Material.CHEST); // Bukkit.getLogger().info("Chest item settings = " + // Settings.chestItems[0]); // Bukkit.getLogger().info("Chest item settings length = " + // Settings.chestItems.length); if (useDefaultChest) { // Fill the chest if (blockToChange.getType() == Material.CHEST) { final Chest islandChest = (Chest) blockToChange.getState(); DoubleChest doubleChest = null; InventoryHolder iH = islandChest.getInventory().getHolder(); if (iH instanceof DoubleChest) { //Bukkit.getLogger().info("DEBUG: double chest"); doubleChest = (DoubleChest) iH; } if (doubleChest != null) { Inventory inventory = doubleChest.getInventory(); inventory.clear(); inventory.setContents(defaultChestItems); } else { Inventory inventory = islandChest.getInventory(); inventory.clear(); inventory.setContents(defaultChestItems); } } } } if (!islandCompanion.isEmpty() && grass != null) { Bukkit.getServer().getScheduler().runTaskLater(ASkyBlock.getPlugin(), new Runnable() { @Override public void run() { spawnCompanion(player, grass); } }, 40L); } }
From source file:it.infn.ct.aleph_portlet.java
/** * This method is used to make ajax calls from the portlet' js page * * @param request Render request object instance * @param response Render response object instance * //w w w. j av a2 s. c om * @throws PortletException * @throws IOException */ @Override public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { _log.info("Calling serverResource()"); // Get portlet common information getPortletInfo(null, request, null); // Retrieve portletPreferences (not used yet) // PortletPreferences portletPreferences = (PortletPreferences) request.getPreferences(); Map obj = new LinkedHashMap(); // Used to prepare JSON output String commandParameters = ""; // Used to log commands input parameter String commandValue = (String) request.getParameter("command"); // Received command if (commandValue == null) commandValue = "none"; // Set unhandled command if no command received // Switch among possible commands received from the js switch (serveCommands.valueOf(commandValue)) { case test: // Retrieve command parameters String testParamValue1 = request.getParameter("testParam1"); String testParamValue2 = request.getParameter("testParam2"); // Prepare log parameter output obj.put("testParamValue1", testParamValue1); obj.put("testParamValue2", testParamValue2); commandParameters = "testParamValue1: '" + testParamValue1 + "'" + LS + "testParamValue2: '" + testParamValue2 + "'"; // Do something with parameters // ... // Prepare JSON ouptut obj.put("commandRes", "OK"); obj.put("testParamValue1", testParamValue1); obj.put("testParamValue2", testParamValue2); break; case setprefs: String jsonPrefs = (String) request.getParameter("prefs"); _log.info(LS + "Set preferences" + LS + "---------------" + LS + "prefs: '" + jsonPrefs + "'" + LS); String params[] = jsonPrefs.split(";"); for (int i = 0; i < params.length; i++) { String param[] = params[i].split("="); prefs.setPrefValue(param[0], param[1]); //_log.info( "Param#"+i+" name: '"+param[0]+"' - Param#"+i+" value: '"+param[1]+"'"+LS); } prefs.setPortletPrefs(); //_log.info(prefs.dump()); // Update changes on Guacamole XML info if (iSrv.isCloudMgrEnabled()) { guacamole_dir = prefs.getPrefValue("guacamole_dir"); guacamole_noauthxml = prefs.getPrefValue("guacamole_noauthxml"); iSrv.initNoAuthConfigXML(guacamole_dir + java.io.File.separator + guacamole_noauthxml); } obj.put("commandRes", "OK"); break; case getprefs: _log.info(LS + "Get preferences" + LS + "---------------" + LS); obj.put("commandRes", "OK"); String prefNames[] = prefs.getPrefNames(); for (int i = 0; i < prefNames.length; i++) { obj.put(prefs.getPrefName(i), prefs.getPrefValue(prefs.getPrefName(i))); } break; case resetprefs: _log.info(LS + "Reset preferences" + LS + "-----------------" + LS); obj.put("commandRes", "OK"); initialized = true; // Will force to reset prefs init(); break; case submit: // Retrieve command parameters String alephfile = request.getParameter("aleph_file"); String alephAlg = request.getParameter("aleph_alg"); _log.info("Submit:" + LS + "=======" + LS + "Aleph file: '" + alephfile + "'" + LS + "Aleph algorithm: '" + alephAlg + "'"); // Services may be installed only having iSrv class enabled if (alephAlg == null && !iSrv.isEnabled()) { obj.put("commandRes", "KO"); obj.put("commandInfo", "Service: '" + iSrv.getServiceName() + "' cannot be instantiated because iservice class is not available. Please contact the administrator."); } // In case of new service check for its maximum allowed allocations number else if (alephAlg == null && iSrv.getNumAllocations() == iSrv.getMaxAllowedAllocations()) { obj.put("commandRes", "KO"); obj.put("commandInfo", "Reached maximum allowed allocations for service: '" + iSrv.getServiceName() + "'"); } // Otherwise submit the job else { occiSubmit(userName, firstName, lastName, portalName, alephfile, alephAlg); obj.put("commandRes", "OK"); } break; case allocinfo: if (iSrv.isEnabled()) { LinkedList allocList = new LinkedList(); for (int i = 0; i < iSrv.getNumAllocations(); i++) { // Get values from iservices iservices.AllocInfo alliV[] = iSrv.allocInfo; // Put values into JSON elemen Map allocEntry = new LinkedHashMap(); allocEntry.put("allocTs", "" + alliV[i].getAllocTs()); allocEntry.put("allocExpTs", "" + alliV[i].getAllocExpTs()); allocEntry.put("allocState", alliV[i].getAllocState()); allocEntry.put("allocId", alliV[i].getAllocId()); allocEntry.put("srvUUID", alliV[i].getSrvUUID()); // accInfo LinkedList accessList = new LinkedList(); if (iSrv.allocInfo[i].accInfo != null && iSrv.allocInfo[i].accInfo.length > 0) { for (int j = 0; j < iSrv.allocInfo[i].accInfo.length; j++) { // Get values iservices.AccessInfo[] acciV = iSrv.allocInfo[i].getAccInfo(); // Put values Map accessEntry = new LinkedHashMap(); accessEntry.put("ip", acciV[j].getIP()); accessEntry.put("workgroup", acciV[j].getWorkGroup()); accessEntry.put("username", acciV[j].getUserName()); accessEntry.put("password", acciV[j].getPassword()); accessEntry.put("port", acciV[j].getPort()); accessEntry.put("proto", acciV[j].getProto()); accessList.add(accessEntry); } } allocEntry.put("accInfo", accessList); allocList.add(allocEntry); } obj.put("commandRes", "OK"); obj.put("allocInfo", allocList); } else { _log.info("Ignoring allocinfo command since iservices class is not enabled"); obj.put("commandRes", "KO"); } break; case notify: // Something has to be notified to the portlet String sender = request.getParameter("sender"); String keyname = request.getParameter("keyname"); String keyvalue = request.getParameter("keyvalue"); if (keyname.equalsIgnoreCase("ipaddr")) { _log.info("Retrieving notification from '" + sender + "': " + keyname + "='" + keyvalue + "'"); } else _log.info( "Ignored notification message: '" + keyname + "='" + keyvalue + "' from: '" + sender + "'"); break; // default condition does not work since null commands are generating an // exception on request.getParameter('command') call // the warning below could be replaced by a dedicated catch condition default: _log.warn("Unhandled command: '" + commandValue + "'"); return; } // swicth // Set the content type response.setContentType("application/json"); // Prepare JSON Object obj.put("commandValue", commandValue); response.getPortletOutputStream().write(JSONValue.toJSONString(obj).getBytes()); // Show taken parameters _log.info(LS + "Command: '" + commandValue + "'" + LS + "------------------------------" + LS + "Parameters: " + LS + "------------------------------" + LS + commandParameters + LS + "------------------------------" + LS + "JSON output: " + LS + "------------------------------" + LS + JSONValue.toJSONString(obj)); }
From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java
@SuppressWarnings("unchecked") private void postFinishRegistration(final String username, final String password, final String invitorCode, final String invitorSecret) throws ClientProtocolException, IOException { T.REGISTRATION();//ww w . j ava2s . c o m final String mobileInfo = getMobileInfo(); HttpClient httpClient = HTTPUtil.getHttpClient(); final HttpPost httpPost = new HttpPost(CloudConstants.REGISTRATION_FINISH_URL); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("mobileInfo", mobileInfo)); formParams.add(new BasicNameValuePair("account", username)); formParams.add(new BasicNameValuePair("password", password)); formParams.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID)); org.json.simple.JSONArray accounts = new org.json.simple.JSONArray(); if (mAccounts != null) { for (Account acc : mAccounts) { Map<String, String> jacc = new LinkedHashMap<String, String>(); jacc.put("type", acc.type); jacc.put("name", acc.name); accounts.add(jacc); } } formParams.add(new BasicNameValuePair("accounts", accounts.toString())); formParams.add(new BasicNameValuePair("invitor_code", invitorCode)); formParams.add(new BasicNameValuePair("invitor_secret", invitorSecret)); org.json.simple.JSONArray beacons = new org.json.simple.JSONArray(); for (BeaconDiscoveredRequestTO bdr : mWiz.getDetectedBeacons()) { beacons.add(bdr.toJSONMap()); } formParams.add(new BasicNameValuePair("beacons", beacons.toString())); httpPost.setEntity(new UrlEncodedFormEntity(formParams, HTTP.UTF_8)); L.d("before http final post"); HttpResponse response = httpClient.execute(httpPost); L.d("after http final post"); final int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpStatus.SC_OK) { throw new IOException("HTTP request resulted in status code " + responseCode); } L.d("finish_registration call sent"); HttpEntity httpEntity = response.getEntity(); if (httpEntity == null) { throw new IOException("Response of '/unauthenticated/mobi/registration/finish' was null"); } final Map<String, Object> responseMap = (Map<String, Object>) JSONValue .parse(new InputStreamReader(httpEntity.getContent())); if (responseMap == null) { throw new IOException("HTTP request responseMap was null"); } JSONArray beaconRegions = (JSONArray) responseMap.get("discovered_beacons"); if (beaconRegions != null && beaconRegions.size() > 0) { mDiscoveredBeacons = JSONValue.toJSONString(beaconRegions); } else { mDiscoveredBeacons = null; } }
From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java
@Override public void writePickle(DataOutput out) throws IOException { T.dontCare();// w ww . j av a 2 s.c o m out.writeInt(mQueue.size()); for (BrandedItem item : mQueue) { out.writeUTF(JSONValue.toJSONString(item.toJSONMap())); } out.writeInt(mDownloadMgrQueue.size()); for (BrandedItem item : mDownloadMgrQueue.values()) { out.writeUTF(JSONValue.toJSONString(item.toJSONMap())); } }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
protected void output(Map info, Map<String, String[]> params, String pathInfo, HttpServletResponse res) { int statusCode = 200; try {/* w ww . j a v a 2s.co m*/ Integer statusInteger = (Integer) info.get("statusCode"); if (statusInteger != null) { statusCode = statusInteger.intValue(); } } catch (Exception ex) { log.error("Error processing status code", ex); } // auto-populate basic request info info.put("request", pathInfo); if (statusCode < 400) { info.put("status", "OK"); } else { info.put("status", "ERROR"); } // convert errors to 200/OK + error message for Flash, etc. String flash = getParamString(params, "flash", ""); if (flash != null && flash.equals("true")) { info.put("flash", "true"); info.put("statusCode", String.valueOf(statusCode)); statusCode = SC_OK; } String content = null; String contentType = null; String format = getParamString(params, "format", formatDefault); // if format is not specified/configured, or is invalid, send a warning // but don't clobber existing request status/message if (format == null) { // handle missing formatDefault info.put("warning", "No format specified and no default format configured"); format = "xml"; } else if (!format.equals("json") && !format.equals("html") && !format.equals("properties") && !format.equals("xml")) { // handle invalid format info.put("warning", "Invalid format: '" + format + "'"); format = "xml"; } if (format.equals("json")) { // convert exceptions to strings b/c toJSONString can't handle them Exception e = (Exception) info.get("exception"); if (e != null) { info.put("exception", e.getMessage()); } content = JSONValue.toJSONString(info); contentType = "application/json"; } else if (format.equals("html")) { content = toHTML(info); contentType = "text/html"; } else if (format.equals("properties")) { content = toProperties(info); contentType = "text/plain"; } else if (format.equals("xml")) { content = toXMLString(info); contentType = "application/xml; charset=utf-8"; } output(statusCode, content, contentType, res); }
From source file:com.mobicage.rogerthat.NewsActivity.java
private void processFriendInfoReceived(Intent intent) { if (expectedEmailHash != null && expectedEmailHash.equals(intent.getStringExtra(ProcessScanActivity.EMAILHASH))) { mProgressDialog.dismiss();/*from ww w . j a v a 2s . c om*/ if (intent.getBooleanExtra(ProcessScanActivity.SUCCESS, true)) { Intent launchIntent = new Intent(NewsActivity.this, ServiceDetailActivity.class); if (existence == Friend.DELETED || existence == Friend.DELETION_PENDING) { launchIntent.putExtra(ServiceDetailActivity.EXISTENCE, Friend.NOT_FOUND); } else { launchIntent.putExtra(ServiceDetailActivity.EXISTENCE, existence); } GetUserInfoResponseTO item = new GetUserInfoResponseTO(); item.avatar = intent.getStringExtra(ProcessScanActivity.AVATAR); item.avatar_id = -1; item.description = intent.getStringExtra(ProcessScanActivity.DESCRIPTION); item.descriptionBranding = intent.getStringExtra(ProcessScanActivity.DESCRIPTION_BRANDING); item.email = intent.getStringExtra(ProcessScanActivity.EMAIL); item.name = intent.getStringExtra(ProcessScanActivity.NAME); item.qualifiedIdentifier = intent.getStringExtra(ProcessScanActivity.QUALIFIED_IDENTIFIER); item.type = intent.getLongExtra(ProcessScanActivity.TYPE, FriendsPlugin.FRIEND_TYPE_SERVICE); launchIntent.putExtra(ServiceDetailActivity.GET_USER_INFO_RESULT, JSONValue.toJSONString(item.toJSONMap())); startActivity(launchIntent); } else { UIUtils.showErrorDialog(this, intent); } } }
From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface", "NewApi" }) @Override//from w ww . j a v a 2s .com public void onCreate(Bundle savedInstanceState) { if (CloudConstants.isContentBrandingApp()) { super.setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen); } super.onCreate(savedInstanceState); setContentView(R.layout.action_screen); mBranding = (WebView) findViewById(R.id.branding); WebSettings brandingSettings = mBranding.getSettings(); brandingSettings.setJavaScriptEnabled(true); brandingSettings.setCacheMode(WebSettings.LOAD_DEFAULT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { brandingSettings.setAllowFileAccessFromFileURLs(true); } mBrandingHttp = (WebView) findViewById(R.id.branding_http); mBrandingHttp.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); WebSettings brandingSettingsHttp = mBrandingHttp.getSettings(); brandingSettingsHttp.setJavaScriptEnabled(true); brandingSettingsHttp.setCacheMode(WebSettings.LOAD_DEFAULT); if (CloudConstants.isContentBrandingApp()) { mSoundThread = new HandlerThread("rogerthat_actionscreenactivity_sound"); mSoundThread.start(); Looper looper = mSoundThread.getLooper(); mSoundHandler = new Handler(looper); int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (cameraPermission == PackageManager.PERMISSION_GRANTED) { mQRCodeScanner = QRCodeScanner.getInstance(this); final LinearLayout previewHolder = (LinearLayout) findViewById(R.id.preview_view); previewHolder.addView(mQRCodeScanner.view); } mBranding.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initFullScreenForContentBranding(); } }); mBrandingHttp.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initFullScreenForContentBranding(); } }); } final View brandingHeader = findViewById(R.id.branding_header_container); final ImageView brandingHeaderClose = (ImageView) findViewById(R.id.branding_header_close); final TextView brandingHeaderText = (TextView) findViewById(R.id.branding_header_text); brandingHeaderClose .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text))); brandingHeaderClose.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.onResume(); } brandingHeader.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl("about:blank"); } }); final View brandingFooter = findViewById(R.id.branding_footer_container); if (CloudConstants.isContentBrandingApp()) { brandingHeaderClose.setVisibility(View.GONE); final ImageView brandingFooterClose = (ImageView) findViewById(R.id.branding_footer_close); final TextView brandingFooterText = (TextView) findViewById(R.id.branding_footer_text); brandingFooterText.setText(getString(R.string.back)); brandingFooterClose .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text))); brandingFooter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.onResume(); } brandingHeader.setVisibility(View.GONE); brandingFooter.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl("about:blank"); } }); } final RelativeLayout openPreview = (RelativeLayout) findViewById(R.id.preview_holder); openPreview.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.previewHolderClicked(); } } }); mBranding.addJavascriptInterface(new JSInterface(this), "__rogerthat__"); mBranding.setWebChromeClient(new WebChromeClient() { @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (sourceID != null) { try { sourceID = new File(sourceID).getName(); } catch (Exception e) { L.d("Could not get fileName of sourceID: " + sourceID, e); } } if (mIsHtmlContent) { L.i("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message); } else { L.d("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message); } } }); mBranding.setWebViewClient(new WebViewClient() { private boolean isExternalUrl(String url) { for (String regularExpression : mBrandingResult.externalUrlPatterns) { if (url.matches(regularExpression)) { return true; } } return false; } @SuppressLint("DefaultLocale") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { L.i("Branding is loading url: " + url); Uri uri = Uri.parse(url); String lowerCaseUrl = url.toLowerCase(); if (lowerCaseUrl.startsWith("tel:") || lowerCaseUrl.startsWith("mailto:") || isExternalUrl(url)) { Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } else if (lowerCaseUrl.startsWith(POKE)) { String tag = url.substring(POKE.length()); poke(tag); return true; } else if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) { if (mQRCodeScanner != null) { mQRCodeScanner.onPause(); } brandingHeaderText.setText(getString(R.string.loading)); brandingHeader.setVisibility(View.VISIBLE); if (CloudConstants.isContentBrandingApp()) { brandingFooter.setVisibility(View.VISIBLE); } mBranding.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl(url); return true; } else { brandingHeader.setVisibility(View.GONE); brandingFooter.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); } return false; } @Override public void onPageFinished(WebView view, String url) { L.i("onPageFinished " + url); if (!mInfoSet && mService != null && mIsHtmlContent) { Map<String, Object> info = mFriendsPlugin.getRogerthatUserAndServiceInfo(mServiceEmail, mServiceFriend); executeJS(true, "if (typeof rogerthat !== 'undefined') rogerthat._setInfo(%s)", JSONValue.toJSONString(info)); mInfoSet = true; } } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { L.i("Checking access to: '" + url + "'"); final URL parsedUrl; try { parsedUrl = new URL(url); } catch (MalformedURLException e) { L.d("Webview tried to load malformed URL"); return new WebResourceResponse("text/plain", "UTF-8", null); } if (!parsedUrl.getProtocol().equals("file")) { return null; } File urlPath = new File(parsedUrl.getPath()); if (urlPath.getAbsolutePath().startsWith(mBrandingResult.dir.getAbsolutePath())) { return null; } L.d("404: Webview tries to load outside its sandbox."); return new WebResourceResponse("text/plain", "UTF-8", null); } }); mBrandingHttp.setWebViewClient(new WebViewClient() { @SuppressLint("DefaultLocale") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { L.i("BrandingHttp is loading url: " + url); return false; } @Override public void onPageFinished(WebView view, String url) { brandingHeaderText.setText(view.getTitle()); L.i("onPageFinished " + url); } }); Intent intent = getIntent(); mBrandingKey = intent.getStringExtra(BRANDING_KEY); mServiceEmail = intent.getStringExtra(SERVICE_EMAIL); mItemTagHash = intent.getStringExtra(ITEM_TAG_HASH); mItemLabel = intent.getStringExtra(ITEM_LABEL); mItemCoords = intent.getLongArrayExtra(ITEM_COORDS); mRunInBackground = intent.getBooleanExtra(RUN_IN_BACKGROUND, true); }
From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java
private void deliverApiResult(ServiceApiCallbackResult r) { // Using JSONValue.toJSONString on these string for null value support and quote encoding executeJS(false, "if (typeof rogerthat !== 'undefined') rogerthat.api._setResult(%s, %s, %s, %s)", JSONValue.toJSONString(r.method), JSONValue.toJSONString(r.result), JSONValue.toJSONString(r.error), JSONValue.toJSONString(r.tag)); }
From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java
private void deliverFacebookResult(String requestId, Map<String, Object> result, Map<String, Object> error) { executeJS(false, "if (typeof rogerthat !== 'undefined') rogerthat.facebook._setResult('%s', %s, %s)", requestId, JSONValue.toJSONString(result), JSONValue.toJSONString(error)); }