int number = -1;
//todo: refactor this horse shit.
for (String res: results) {
if(number == -1){
if(res.toLowerCase().contains("ten") || res.contains("10") || res.contains("10") || res.contains("十") || res.contains("십")){
number = 10;
}
else if(res.toLowerCase().contains("nine") || res.contains("9") || res.contains("9") || res.contains("九") || res.contains("구")){
number = 9;
}
else if(res.toLowerCase().contains("eight") || res.contains("8") || res.contains("8") || res.contains("八") || res.contains("팔")){
number = 8;
}
else if(res.toLowerCase().contains("seven") || res.contains("7") || res.contains("7") || res.contains("七") || res.contains("칠")){
number = 7;
}
else if(res.toLowerCase().contains("six") || res.contains("6") || res.contains("6") || res.contains("六") || res.contains("육")){
number = 6;
}
else if(res.toLowerCase().contains("five") || res.contains("5") || res.contains("5") || res.contains("五") || res.contains("오")){
number = 5;
}
else if(res.toLowerCase().contains("four") || res.contains("4") || res.contains("4") || res.contains("四") || res.contains("사")){
number = 4;
}
else if(res.toLowerCase().contains("three") || res.contains("3") || res.contains("3") || res.contains("三") || res.contains("삼")){
number = 3;
}
else if(res.toLowerCase().contains("two") || res.contains("2") || res.contains("2") || res.contains("二") || res.contains("이")){
number = 2;
}
else if(res.toLowerCase().contains("one") || res.contains("1") || res.contains("1") || res.contains("一") || res.contains("일")){
number = 1;
}
}
}
refactor this horse shit.
private static int alphabetToNumber(String letter) {
String s = letter.toLowerCase();
if (s.equals("a")) {
return 1;
} else if (s.equals("b")) {
return 2;
} else if (s.equals("c")) {
return 3;
} else if (s.equals("d")) {
return 4;
} else if (s.equals("e")) {
return 5;
} else if (s.equals("f")) {
return 6;
} else if (s.equals("g")) {
return 7;
} else if (s.equals("h")) {
return 8;
} else if (s.equals("i")) {
return 9;
} else if (s.equals("j")) {
return 10;
} else if (s.equals("k")) {
return 11;
} else if (s.equals("l")) {
return 12;
} else if (s.equals("m")) {
return 13;
} else if (s.equals("n")) {
return 14;
} else if (s.equals("o")) {
return 15;
} else if (s.equals("p")) {
return 16;
} else if (s.equals("q")) {
return 17;
} else if (s.equals("r")) {
return 18;
} else if (s.equals("s")) {
return 19;
} else if (s.equals("t")) {
return 20;
} else if (s.equals("u")) {
return 21;
} else if (s.equals("v")) {
return 22;
} else if (s.equals("w")) {
return 23;
} else if (s.equals("x")) {
return 24;
} else if (s.equals("y")) {
return 25;
} else if (s.equals("z")) {
return 26;
} else {
return 0;
}
}
private boolean isToRemove(byte b) {
byte[] toRemoveB = { -106 };
for(byte c : toRemoveB) {
if(b == c) {
return true;
}
}
return false;
}
it goes without saying...
Boolean b = new Boolean(true);
if (b == true){
...
}
think outside the autoboxing
boolean darkModeSelected = (!darkModeSelected ? true : false);
public static int[] sleepSort(int... args) {
final int[] sorted = new int[args.length];
final AtomicInteger index = new AtomicInteger(0);
List<Thread> threads = new ArrayList<Thread>(0);
for (int i = 0; i < args.length; i++) {
final int x = i;
Thread sorter = new Thread(() -> {
try {
Thread.sleep(args[x]);
} catch (InterruptedException ex) {
// shrug
}
sorted[index.getAndIncrement()] = args[x];
});
sorter.setDaemon(true);
sorter.start();
threads.add(sorter);
}
try {
for (Thread t : threads) { t.join(); }
} catch (InterruptedException e) {
e.printStackTrace();
}
return sorted;
}
Takes an unsorted array of integers, sorts by sleeping for the int value of each item in the array and then writing that into the resulting sorted array. Big-O analysis is... difficult.
public static int[] xxx(String filename) throws IOException{
int[] f = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine()) != null){
line = line.toUpperCase();
for(char ch:line.toCharArray()){
if(Character.isLetter(ch)){
f[ch - 'A']++;
}
}
}
in.close();
return f;
}
public static int maximum(int f, int g)
{
try
{
int[] far = new int[f];
far[g] = 1;
return f;
}
catch(NegativeArraySizeException e)
{
f = -f;
g = -g;
return (-maximum(f, g) == -f)? -g : -f;
}
catch(IndexOutOfBoundsException e)
{
return (maximum(g, 0) == 0)? f : g;
}
}
public enum DataSize {
BYTE,
DOUBLE_BYTE,
INT,
LONG;
public boolean isEqualTo(Object value) {
if(value instanceof Byte && this.equals(BYTE)) {
return true;
} else if ((value instanceof Character || value instanceof Short) && this.equals(DOUBLE_BYTE)) {
return true;
} else if ((value instanceof Integer) && this.equals(INT)) {
return true;
} else if ((value instanceof Long) && this.equals(LONG)) {
return true;
}
return false;
}
}
if (baza[mCurrentIndex] == Boolean.TRUE) {
if (mCurrentIndex != baza.length-1) {
up();
nextQuestion();
}
if (mCurrentIndex == baza.length) {
WypiszWynik();
}
}
so you have an array of booleans and you're comparing it to Boolean.TRUE why
@EventHandler
public void onCpUse(PlayerMoveEvent e) {
Player player = e.getPlayer();
if(Main.main.state != Gamestate.JUMP) return;
if(!Main.main.alive.contains(player)) return;
Location loc = e.getPlayer().getLocation();
loc.setY(loc.getY() -1);
Block standingOnBlock = loc.getBlock();
int currentCP = Main.main.checkpointTracker.get(player);
int nextCP = currentCP+1;
if(standingOnBlock.getType() == Material.EMERALD_BLOCK) {
Main.main.lm.setLocation(Main.main.map + "x" + nextCP + "x" + player.getName(), player.getLocation());
standingOnBlock.setType(Material.BEDROCK);
giveCPEquip(player, nextCP);
Main.main.checkpointTracker.put(player, nextCP);
Main.main.scoreboard.setIngameScoreboard(player);
player.sendMessage(Main.main.pr + "�aDu hast den " + nextCP + ". Checkpoint erreicht!");
if(Main.main.particleTracker.containsKey(player)) {
player.spawnParticle(Main.main.particleTracker.get(player), player.getLocation(), 10);
}
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 10, 1);
}
}
public void giveCPEquip(Player p, int cp) {
Inventory i = p.getInventory();
ItemStack cp1Helmet = Main.main.utils.create(Material.LEATHER_HELMET, 1);
ItemStack cp1Chest = Main.main.utils.create(Material.LEATHER_CHESTPLATE, 1);
ItemStack cp1Leggings = Main.main.utils.create(Material.LEATHER_LEGGINGS, 1);
ItemStack cp1Boots = Main.main.utils.create(Material.LEATHER_BOOTS, 1);
ItemStack cp2Sword = Main.main.utils.createSharp1Item(Material.STONE_SWORD, 1);
ItemStack cp3Apples = Main.main.utils.create(Material.GOLDEN_APPLE, 3);
ItemStack cp4Chest = Main.main.utils.create(Material.CHAINMAIL_CHESTPLATE, 1);
ItemStack cp4Leggings = Main.main.utils.create(Material.CHAINMAIL_LEGGINGS, 1);
ItemStack cp5Helmet = Main.main.utils.create(Material.IRON_HELMET, 1);
ItemStack cp5Boots = Main.main.utils.create(Material.IRON_BOOTS, 1);
//6 Add extra Herzen
ItemStack cp7Sword = Main.main.utils.create(Material.DIAMOND_SWORD, 1);
ItemStack cp8Sword = Main.main.utils.create(Material.SHIELD, 1);
ItemStack cp1Helmet1 = Main.main.utils.create(Material.DIAMOND_HELMET, 1);
ItemStack cp1Chest1 = Main.main.utils.create(Material.DIAMOND_CHESTPLATE, 1);
ItemStack cp1Leggings1 = Main.main.utils.create(Material.DIAMOND_LEGGINGS, 1);
ItemStack cp1Boots1 = Main.main.utils.create(Material.DIAMOND_BOOTS, 1);
ItemStack cp2Sword1 = Main.main.utils.createSharp1Item(Material.DIAMOND_SWORD, 1);
ItemStack cp3Apples1 = Main.main.utils.create(Material.SHIELD, 1);
ItemStack cp4Leggings1 = Main.main.utils.create(Material.NETHERITE_LEGGINGS, 1);
ItemStack cp5Helmet1 = Main.main.utils.create(Material.NETHERITE_HELMET, 1);
ItemStack cp5Boots1 = Main.main.utils.create(Material.NETHERITE_BOOTS, 1);
//6 Add extra Herzen
ItemStack cp7Sword1 = Main.main.utils.create(Material.NETHERITE_CHESTPLATE, 1);
ItemStack cp8Sword1 = Main.main.utils.createSharp1Item(Material.NETHERITE_SWORD, 1);
ItemStack cp1Helmet2 = Main.main.utils.create(Material.GOLDEN_HELMET, 1);
ItemStack cp1Chest2 = Main.main.utils.create(Material.GOLDEN_CHESTPLATE, 1);
ItemStack cp1Leggings2 = Main.main.utils.create(Material.GOLDEN_LEGGINGS, 1);
ItemStack cp1Boots2 = Main.main.utils.create(Material.GOLDEN_BOOTS, 1);
ItemStack cp2Sword2 = Main.main.utils.createSharp1Item(Material.STONE_SWORD, 1);
ItemStack cp3Apples2 = Main.main.utils.create(Material.GOLDEN_APPLE, 3);
ItemStack cp3Apple2 = Main.main.utils.create(Material.SHIELD, 1);
ItemStack cp4Leggings2 = Main.main.utils.create(Material.IRON_LEGGINGS, 1);
ItemStack cp5Helmet2 = Main.main.utils.create(Material.IRON_HELMET, 1);
ItemStack cp5Boots2 = Main.main.utils.create(Material.IRON_BOOTS, 1);
//6 Add extra Herzen
ItemStack cp7Sword2 = Main.main.utils.create(Material.IRON_CHESTPLATE, 1);
ItemStack cp8Sword2 = Main.main.utils.createSharp1Item(Material.IRON_SWORD, 1);
if(!Main.main.random) {
if(Main.main.rn ==0) {
if(cp == 1) {
i.addItem(cp1Helmet);
i.addItem(cp1Chest);
i.addItem(cp1Leggings);
i.addItem(cp1Boots);
}else if(cp == 2) {
i.addItem(cp2Sword);
}else if(cp == 3) {
i.addItem(cp3Apples);
}else if(cp == 4) {
i.addItem(cp4Chest);
i.addItem(cp4Leggings);
}else if(cp == 5) {
i.addItem(cp5Helmet);
i.addItem(cp5Boots);
}else if(cp == 6) {
p.setMaxHealth(24);
p.sendMessage(Main.main.pr + "�aDu hast zwei Extraherzen erhalten!");
}else if(cp == 7) {
i.addItem(cp7Sword);
}else if(cp == 8) {
i.addItem(cp8Sword);
if(Main.main.fallTracker.get(p) == 0) {
p.sendMessage(Main.main.pr + "Du hast das Ziel ohne JumpFail erreicht!");
p.getInventory().addItem(Main.main.utils.create(Material.DIAMOND_HELMET, 1));
}
Bukkit.broadcastMessage(Main.main.pr + "�5" + p.getName() + " �a hat das Ziel erreicht!");
Main.main.cd.cancelIngameTask();
Main.main.cd.startDeathmatchCD();
}
}else if(Main.main.rn == 1) {
if(cp == 1) {
i.addItem(cp1Helmet1);
i.addItem(cp1Chest1);
i.addItem(cp1Leggings1);
i.addItem(cp1Boots1);
}else if(cp == 2) {
i.addItem(cp2Sword1);
}else if(cp == 3) {
i.addItem(cp3Apples1);
}else if(cp == 4) {
i.addItem(cp4Leggings1);
}else if(cp == 5) {
i.addItem(cp5Helmet1);
i.addItem(cp5Boots1);
}else if(cp == 6) {
p.setMaxHealth(24);
p.sendMessage(Main.main.pr + "�aDu hast zwei Extraherzen erhalten!");
}else if(cp == 7) {
i.addItem(cp7Sword1);
}else if(cp == 8) {
i.addItem(cp8Sword1);
if(Main.main.fallTracker.get(p) == 0) {
p.sendMessage(Main.main.pr + "Du hast das Ziel ohne JumpFail erreicht!");
p.getInventory().addItem(Main.main.utils.create(Material.GOLDEN_APPLE, 10));
}
Bukkit.broadcastMessage(Main.main.pr + "�5" + p.getName() + " �a hat das Ziel erreicht!");
Main.main.cd.cancelIngameTask();
Main.main.cd.startDeathmatchCD();
}
}else if(Main.main.rn == 2) {
if(cp == 1) {
i.addItem(cp1Helmet2);
i.addItem(cp1Chest2);
i.addItem(cp1Leggings2);
i.addItem(cp1Boots2);
}else if(cp == 2) {
i.addItem(cp2Sword2);
}else if(cp == 3) {
i.addItem(cp3Apples2);
i.addItem(cp3Apple2);
}else if(cp == 4) {
i.addItem(cp4Leggings2);
}else if(cp == 5) {
i.addItem(cp5Helmet2);
i.addItem(cp5Boots2);
}else if(cp == 6) {
p.setMaxHealth(24);
p.sendMessage(Main.main.pr + "�aDu hast zwei Extraherzen erhalten!");
}else if(cp == 7) {
i.addItem(cp7Sword2);
}else if(cp == 8) {
i.addItem(cp8Sword2);
if(Main.main.fallTracker.get(p) == 0) {
p.sendMessage(Main.main.pr + "Du hast das Ziel ohne JumpFail erreicht!");
p.getInventory().addItem(Main.main.utils.create(Material.GOLDEN_APPLE, 10));
}
Bukkit.broadcastMessage(Main.main.pr + "�5" + p.getName() + " �a hat das Ziel erreicht!");
Main.main.cd.cancelIngameTask();
Main.main.cd.startDeathmatchCD();
}
}
}else {
Random random = new Random();
List<Material> materials = Arrays.asList(Material.values());
int size = materials.size()-1;
Material ran = materials.get(random.nextInt(size));
p.getInventory().addItem(new ItemStack(ran, 1));
if(cp == 8) {
if(Main.main.fallTracker.get(p) == 0) {
p.sendMessage(Main.main.pr + "Du hast das Ziel ohne JumpFail erreicht!");
p.getInventory().addItem(Main.main.utils.create(Material.DIAMOND_HELMET, 1));
}
Bukkit.broadcastMessage(Main.main.pr + "�5" + p.getName() + " �a hat das Ziel erreicht!");
Main.main.cd.cancelIngameTask();
Main.main.cd.startDeathmatchCD();
}
}
}
This beautiful code snippet was found in one of the repositories of people who sell their products on Fiverr. As you may have noticed only the functionally of code is beautiful but also the formatting style.
@SuppressWarnings("unchecked")
private void addEndpointsTags(JsonArray tagsArray) throws IOException {
if (registeredHandlers == null || registeredHandlers.isEmpty()) {
return;
}
TreeSet<String> handlerNamesSorted = new TreeSet<>(registeredHandlers.keySet());
handlerNamesSorted.forEach(key -> {
StringBuilder sb = new StringBuilder();
sb.append("{\"name\":\"");
sb.append(key);
sb.append("\",\"request\":{\"name\":\"");
try {
ServiceMethodHandler handler = registeredHandlers.get(key);
Class<? extends Message> requestClass = (Class<? extends Message>)
findSubClassParameterType(handler, 0);
Class<? extends Message> responseClass = (Class<? extends Message>)
findSubClassParameterType(handler, 1);
sb.append(requestClass.getSimpleName());
sb.append("\",\"type\":\"");
sb.append(requestClass.getSimpleName());
sb.append("\",\"values\":[");
sb.append(getProtobufClassFieldDescriptions(requestClass, new HashSet<>()));
sb.append("]},\"response\":{\"name\":\"");
sb.append(responseClass.getSimpleName());
sb.append("\",\"type\":\"");
sb.append(responseClass.getSimpleName());
sb.append("\",\"values\":[");
sb.append(getProtobufClassFieldDescriptions(responseClass, new HashSet<>()));
sb.append("]},\"metadata\":{\"stream\":\"false\"}}");
} catch (Exception e) {
logger.error("Error inspecting handlers", e);
return;
}
String tag = sb.toString();
tagsArray.add(new JsonPrimitive("e-" + binaryEncode(tag)));
});
}
outerloop:
try {
if (selectedFile == null) {
break outerloop;
} else {
if (selectedFile != null) {
readTo = new PrintStream(selectedFile);
readTo.println(userCodeInput.getText());
readTo = readTheOptionsIntegers(readTo);
}
} catch(IOException e) {
System.out.println(e);
}
public class SentCon3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double input;
char choice;
System.out.println("**** Menu-Driven Temperature Converter*****");
System.out.println("only lowwer case is vaild");
System.out.print("Enter the value to beconverted==> ");
input = scan.nextDouble();
System.out.println("What is your choice?");
System.out.println("a)Fahrenheit to Celsius");
System.out.println("b)Celsius to Fahrenheit");
System.out.println("c)Kelvin to Celsius");
System.out.println("d)Celsius to Kelvin");
System.out.println("e)Kelvin to Fahrenheit");
System.out.println("f)Fahrenheit to Kelvin.");
System.out.print("Please enter your choice ==>");
choice = scan.next().charAt(0);
while (choice == 'a') {
System.out.println((input / 5) * 9 + 32);
break;
}
while (choice == 'b') {
System.out.println((input - 32) * 5 / 9);
break;
}
while (choice == 'c') {
System.out.println(input - 273.15);
break;
}
while (choice == 'd') {
System.out.println(input + 273.15);
break;
}
while (choice == 'e') {
System.out.println((input - 273.5) * 9 / 5 + 32);
break;
}
while (choice == 'f') {
System.out.println((input + 459.67) * 5 / 9);
break;
}
}
}
use while as if!!!!
/**
* fk--folder key,dk--doc key -->value is key string
* dt--doc type,ft--folder type -->both have 19 key options:
* bom tr amend history help info loeid cust cust0-cust9 custhist
* folder type only seen as "history" in toc,why ??do we use other ones? -- it only has one child
* doc type only seen two "tr" and "history" in toc??-- it only has one child
* node with "folder type="history"" is the only child of it parent either "<doc type="tr" key="xxx" trnum="xxx"....." or "<doc type="tr" trnum="xxx""
* <folder type="history" could has more then one doc children .e.g. title="History of AMM31-32-00-720-807" in 700/amm
*
*
*
* folder element has the follwing to identify itself:
* 1, key
* 2, type="history", in this case, folder is the only child of doc element with type ="tr"?????
*
* doc element has the following to identify itself
* 1, key
* 2, type="tr" trnum="xxxxx"
* 3, type="history", in this case, doc isthe only child of a folder element???
*
*
*
* the return json format likes following:
* [
* { "data" : "A node", "children" , "state" : "open" },
* { "data" : "Only child", "state" : "closed" },
* "Ajax node"
* ]
*/
public class XMLToJson
{
private static final Map<String, String> pathMap;
static
{
Map<String, String> aMap = new HashMap<String, String>();
aMap.put("fk", "folder[@key");
aMap.put("ft", "folder[@type");
aMap.put("fth", "folder[@type='history'");
aMap.put("dk", "doc[@key");
aMap.put("dt", "doc[@type");
aMap.put("dth", "doc[@type='history'");
aMap.put("dtrn", "doc[@trnum");
pathMap = Collections.unmodifiableMap(aMap);
}
Util util = new Util();
/*
* @param url the path to TOC.xml
* @param xPathString the short format searched node path
* @throws DocumentException
*
* sample xPathString : "fk:AMM24_fk:AMM24-FM_dk"
*/
@SuppressWarnings({ "unchecked" })
public String getJson(URL url, String xPathString) throws Exception
{
Document TOCDoc = util.getDocument(url);
String jsonString = "[";
Element node = null;
if (xPathString.equals("/"))
{
node = TOCDoc.getRootElement();
}
else
{
String realXPathString = pathMapping(xPathString);
System.out.println(realXPathString);
node = (Element) TOCDoc.selectSingleNode(realXPathString);
}
//List<Element> li = node.elements();
for (Iterator<Element> i = node.elementIterator(); i.hasNext();)
{
Element elem = (Element) i.next();
String eleName = elem.getName();
Boolean hasChildren = false;
if ((elem.elements().size() > 0))
{
hasChildren = true;
//current element has children itself, state shoud be "closed"
}
List<Attribute> list = elem.attributes();
String titleAttrContent = elem.attributeValue("title");
//Boolean isFileAttr = false;
String fileAttrContent = elem.attributeValue("file");
//if (fileAttrContent.isEmpty() )
if (eleName == "doc")
{
//doc element always has "file" attribute
for (Attribute attribute : list)
{
jsonString = jsonString.concat("{");
String attrName = attribute.getName();
//System.out.println("doc arribute Name : " + attrName);
//each one has to have "data" line, "attr" line "state" line and "children" line
jsonString = jsonString.concat("'data':'").concat(titleAttrContent).concat("',");
if (attrName.equals("key"))
{
String keyContent = elem.attributeValue("key");
jsonString = jsonString.concat("'attr':{'id':'").concat(xPathString).concat("_dk:").concat(keyContent).concat("','file':'").concat(fileAttrContent).concat("'}");
break;
}
else if (attrName.equals("trnum"))
{
String trnumContent = elem.attributeValue("trnum");
jsonString = jsonString.concat("'attr':{'id':'").concat(xPathString).concat("_dtrn:").concat(trnumContent).concat("','file':'").concat(fileAttrContent).concat("'}");
break;
}
/* else if (attrName.equals("type"))//type attribute for doc element won't determite what exactly the element is
{
String typeContent = elem.attributeValue("type");
//doc element has type "history"
if (typeContent == "history"){
jsonString = jsonString.concat("'attr':{'id':'").concat(xPathString).concat("_dth,");
}else if (typeContent == "?????"){
//any values for type attribute need to concern????
}
}
else if (attrName.equals("file"))
{
}*/
}
if (hasChildren)
{
//state set up as "closed" and no need to set up "children" field
jsonString = jsonString.concat(",'state':'closed'");
}
else
{
//no need to put anything
//jsonString = jsonString.concat("'state':'???'");
}
jsonString = jsonString.concat("},");
}
else if (eleName == "folder")
{
jsonString = jsonString.concat("{");
for (Attribute attribute : list)
{
String attrName = attribute.getName();
jsonString = jsonString.concat("'data':'").concat(titleAttrContent).concat("',");
if (attrName.equals("key"))
{
String keyContent = elem.attributeValue("key");
jsonString = jsonString.concat("'attr':{'id':'").concat(xPathString).concat("_fk:").concat(keyContent).concat("'}");
if (fileAttrContent != null)
{
jsonString = jsonString.concat("','file':'").concat(fileAttrContent).concat("'}");
}
break;
}
else if (attrName.equals("type"))
{
String typeContent = elem.attributeValue("type");
//doc element has type "history"
if (typeContent == "history")
{
jsonString = jsonString.concat("'attr':{'id':'").concat(xPathString).concat("_fth,");
}
else if (typeContent == "?????")
{
//any values need to concern????
}
break;
}
}
jsonString = jsonString.concat("},");
}
continue;
}
//return list;
jsonString = jsonString.substring(0, jsonString.length() - 1);
jsonString = jsonString.concat("]");
return jsonString;
}
/*
* read xpathstring from post request and generate the real xpath for toc
*/
public String getXPathString()
{
//readPostRequest()
return null;
}
/*
* post string looks like : "fk:LOETR_dtrn:TR12-118_fth_dth"
* it represents the inner doc elemnet:
* <folder key="LOETR" type="loetr" title="List of Effective TRs" file="loetr.html">
* <doc type="tr" trnum="TR12-118" trdate="May 07/2012" title="[TR12-118] TASK AMM12-31-00-660-806 - Inspection and Removal of De-Hydrated Anti-Icing Fluid inside the Flight Control Surfaces" file="TR12-118.pdf" refloc="AMM12-31-00-660-806">
* <folder type="history" title="History of AMM12-31-00-660-806">
* <doc title="TASK 12-31-00-660-806 - Inspection and Removal of De-Hydrated Anti-Icing Fluid inside the Flight Control Surfaces" file="AMM12-31-00-660-806.pdf" type="history" refloc="AMM12-31-00-660-806"/>
* </folder>
* the xpath string should be:
* folder[@key="LOETR"]/doc[@trnum="TR12-118"]/folder[@type="history"]/doc[@type="history"]
*
*
* the String : "fk:AMM24_fk:AMM24-FM_dk:CTOC-24"
* it represents the inner doc with attribute file="CTOC-24.pdf"
* the string : "fk:AMM24_fk:AMM24-00-00_fk:AMM24-00-00-02_dk:AMM24-00-00-700-801" represents
* <folder key="AMM24" title="CH 24 - Electrical Power">
* <folder key="AMM24-FM" title="Front Matter">
* <doc key="CTOC-24" title="Table of Contents" file="CTOC-24.pdf"/>
* </folder>
* <folder key="AMM24-00-00" title="24-00-00 - General">
* <folder key="AMM24-00-00-02" title="General - Maintenance Practices">
* <doc key="AMM24-00-00-700-801" title="TASK 24-00-00-700-801 - AC Power, DC Power and Battery Maintenance Practice Recommendations" file="AMM24-00-00-700-801.pdf"/>
*
* it can be even optimized as :
* "fk:AMM24_fk:00-00_fk:02_dk:AMM24-00-00-700-801"
* if the inner key fully include the previous key, omit it, otherwise use full string
* the xpath string should be:
* folder[@key="AMM24"]/folder[@key="AMM24-00-00"]/folder[@key="AMM24-00-00-02"]/doc[@key="AMM24-00-00-700-801"]
*
* if shortXPath is ?? which means the query based on the root of the document
*
*
*/
public String pathMapping(String shortXPath) throws Exception
{
String tagetString = null;
if (shortXPath.equals(""))
{
tagetString = "//toc";
}
else
{
tagetString = "//";
}
int newStart = 0;
String segString = "";
String valueString = "";
//dth???
//need mapping all senarios
//already??
while (shortXPath.indexOf("_", newStart) > -1)
{
int keyValueSepPos = 0;
String keyString = "";//not necessary key, might be type attribute
segString = shortXPath.substring(newStart, shortXPath.indexOf("_", newStart));
newStart = shortXPath.indexOf("_", newStart) + 1;//new start search point
//System.out.println(newStart);
if (segString.indexOf(":") > 0)
{
keyValueSepPos = segString.indexOf(":");
keyString = segString.substring(0, keyValueSepPos);
valueString = segString.substring(keyValueSepPos + 1);
if (pathMap.get(keyString).length() > 0)
{
tagetString = tagetString.concat(pathMap.get(keyString));
}
else
{
throw new Exception("no mapping found");
}
tagetString = tagetString.concat("='").concat(valueString).concat("']/");
}
}
//this is for scenerio either no "_" or sub string after "_"
segString = shortXPath.substring(newStart);
System.out.println(segString);
if (segString.indexOf(":") > 0)
{
int lastKeyValueSepPos = segString.indexOf(":");
String lastKeyString = segString.substring(0, lastKeyValueSepPos);
String lastValueString = segString.substring(lastKeyValueSepPos + 1);
if (pathMap.get(lastKeyString).length() > 0)
{
tagetString = tagetString.concat(pathMap.get(lastKeyString));
}
else
{
throw new Exception("no mapping found");
}
tagetString = tagetString.concat("='").concat(lastValueString).concat("']");
}
return tagetString;
}
public static void main(String[] args) throws Exception
{
XMLToJson x2j = new XMLToJson();
String test = "fk:AMM24_fk:AMM24-FM";
test = "";
System.out.println(x2j.getJson(new URL("http://localhost:8080/WebNavSpring/q400/amm/toc.xml"), test));
//System.out.println(x2j.pathMapping(test));
}
}
easy clean code to convert XML to JSON .