repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
huandu/spritemapper
src/dk/cego/spritemapper/OptimalAlgorithmLayouter.java
// Path: src/dk/cego/spritemapper/guillotine/OptimalGuillotineLayouter.java // public class OptimalGuillotineLayouter extends OptimalLayouter { // public OptimalGuillotineLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // FreeSpaceSplitStrategy splitStrategies[] = new FreeSpaceSplitStrategy[] { // new LongestAxisSplitStrategy(), // new ShortestAxisSplitStrategy(), // new LongestLeftoverAxisSplitStrategy(), // new ShortestLeftoverAxisSplitStrategy(), // new MaximumAreaDifferenceSplitStrategy(), // new MinimumAreaDifferenceSplitStrategy() // }; // // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // for (FreeSpaceSplitStrategy splitStrategy : splitStrategies) { // add(new GuillotineLayouter().setFreeSpaceChooser(chooser).setFreeSpaceSplitStrategy(splitStrategy)); // } // } // } // } // // Path: src/dk/cego/spritemapper/shelf/ShelfLayouter.java // public class ShelfLayouter extends SpriteLayouter { // private final static int MAX_HEIGHT = 1024 * 1024 * 1024; // // public int layout(int maxWidth, int maxHeight, List<Sprite> sprites) { // if (sprites.isEmpty()) { // return 0; // } // // if (maxHeight == 0) { // maxHeight = MAX_HEIGHT; // } // // int x = 0, y = 0, nextY = 0; // int spacing = getSpacing(); // // int mapNumber = 0; // // for (Sprite s : sprites) { // if (x + s.w > maxWidth) { // // try to rotate sprite. // if (x + s.h <= maxWidth) { // s.rotate(); // } else { // x = 0; // y = nextY; // // if (s.w > maxWidth && s.h <= maxWidth) { // s.rotate(); // } // } // } // // s.x = x; // s.y = y; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = Math.max(nextY, s.bottom() + spacing); // // if (nextY > maxHeight) { // if ((s.w > maxWidth && s.w > maxHeight) || (s.h > maxWidth && s.h > maxHeight)) { // throw new RuntimeException("No free space can be found."); // } // // mapNumber++; // s.x = 0; // s.y = 0; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = s.bottom(); // } // } // // mapNumber++; // return mapNumber; // } // // public String toString() { // return "Shelf()"; // } // } // // Path: src/dk/cego/spritemapper/maxrects/OptimalMaxRectsLayouter.java // public class OptimalMaxRectsLayouter extends OptimalLayouter { // public OptimalMaxRectsLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // add(new MaxRectsLayouter().setFreeSpaceChooser(chooser)); // } // } // }
import dk.cego.spritemapper.guillotine.OptimalGuillotineLayouter; import dk.cego.spritemapper.shelf.ShelfLayouter; import dk.cego.spritemapper.maxrects.OptimalMaxRectsLayouter; import java.util.Map; import java.util.TreeMap;
/** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper; /** * This layouter knows all the different algorithms and chooses * the best one for the specific set of sprites. */ public class OptimalAlgorithmLayouter extends OptimalLayouter { private Map<String, SpriteLayouter> layouterNames; public OptimalAlgorithmLayouter() { layouterNames = new TreeMap<String, SpriteLayouter>();
// Path: src/dk/cego/spritemapper/guillotine/OptimalGuillotineLayouter.java // public class OptimalGuillotineLayouter extends OptimalLayouter { // public OptimalGuillotineLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // FreeSpaceSplitStrategy splitStrategies[] = new FreeSpaceSplitStrategy[] { // new LongestAxisSplitStrategy(), // new ShortestAxisSplitStrategy(), // new LongestLeftoverAxisSplitStrategy(), // new ShortestLeftoverAxisSplitStrategy(), // new MaximumAreaDifferenceSplitStrategy(), // new MinimumAreaDifferenceSplitStrategy() // }; // // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // for (FreeSpaceSplitStrategy splitStrategy : splitStrategies) { // add(new GuillotineLayouter().setFreeSpaceChooser(chooser).setFreeSpaceSplitStrategy(splitStrategy)); // } // } // } // } // // Path: src/dk/cego/spritemapper/shelf/ShelfLayouter.java // public class ShelfLayouter extends SpriteLayouter { // private final static int MAX_HEIGHT = 1024 * 1024 * 1024; // // public int layout(int maxWidth, int maxHeight, List<Sprite> sprites) { // if (sprites.isEmpty()) { // return 0; // } // // if (maxHeight == 0) { // maxHeight = MAX_HEIGHT; // } // // int x = 0, y = 0, nextY = 0; // int spacing = getSpacing(); // // int mapNumber = 0; // // for (Sprite s : sprites) { // if (x + s.w > maxWidth) { // // try to rotate sprite. // if (x + s.h <= maxWidth) { // s.rotate(); // } else { // x = 0; // y = nextY; // // if (s.w > maxWidth && s.h <= maxWidth) { // s.rotate(); // } // } // } // // s.x = x; // s.y = y; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = Math.max(nextY, s.bottom() + spacing); // // if (nextY > maxHeight) { // if ((s.w > maxWidth && s.w > maxHeight) || (s.h > maxWidth && s.h > maxHeight)) { // throw new RuntimeException("No free space can be found."); // } // // mapNumber++; // s.x = 0; // s.y = 0; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = s.bottom(); // } // } // // mapNumber++; // return mapNumber; // } // // public String toString() { // return "Shelf()"; // } // } // // Path: src/dk/cego/spritemapper/maxrects/OptimalMaxRectsLayouter.java // public class OptimalMaxRectsLayouter extends OptimalLayouter { // public OptimalMaxRectsLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // add(new MaxRectsLayouter().setFreeSpaceChooser(chooser)); // } // } // } // Path: src/dk/cego/spritemapper/OptimalAlgorithmLayouter.java import dk.cego.spritemapper.guillotine.OptimalGuillotineLayouter; import dk.cego.spritemapper.shelf.ShelfLayouter; import dk.cego.spritemapper.maxrects.OptimalMaxRectsLayouter; import java.util.Map; import java.util.TreeMap; /** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper; /** * This layouter knows all the different algorithms and chooses * the best one for the specific set of sprites. */ public class OptimalAlgorithmLayouter extends OptimalLayouter { private Map<String, SpriteLayouter> layouterNames; public OptimalAlgorithmLayouter() { layouterNames = new TreeMap<String, SpriteLayouter>();
layouterNames.put("guillotine", new OptimalGuillotineLayouter());
huandu/spritemapper
src/dk/cego/spritemapper/OptimalAlgorithmLayouter.java
// Path: src/dk/cego/spritemapper/guillotine/OptimalGuillotineLayouter.java // public class OptimalGuillotineLayouter extends OptimalLayouter { // public OptimalGuillotineLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // FreeSpaceSplitStrategy splitStrategies[] = new FreeSpaceSplitStrategy[] { // new LongestAxisSplitStrategy(), // new ShortestAxisSplitStrategy(), // new LongestLeftoverAxisSplitStrategy(), // new ShortestLeftoverAxisSplitStrategy(), // new MaximumAreaDifferenceSplitStrategy(), // new MinimumAreaDifferenceSplitStrategy() // }; // // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // for (FreeSpaceSplitStrategy splitStrategy : splitStrategies) { // add(new GuillotineLayouter().setFreeSpaceChooser(chooser).setFreeSpaceSplitStrategy(splitStrategy)); // } // } // } // } // // Path: src/dk/cego/spritemapper/shelf/ShelfLayouter.java // public class ShelfLayouter extends SpriteLayouter { // private final static int MAX_HEIGHT = 1024 * 1024 * 1024; // // public int layout(int maxWidth, int maxHeight, List<Sprite> sprites) { // if (sprites.isEmpty()) { // return 0; // } // // if (maxHeight == 0) { // maxHeight = MAX_HEIGHT; // } // // int x = 0, y = 0, nextY = 0; // int spacing = getSpacing(); // // int mapNumber = 0; // // for (Sprite s : sprites) { // if (x + s.w > maxWidth) { // // try to rotate sprite. // if (x + s.h <= maxWidth) { // s.rotate(); // } else { // x = 0; // y = nextY; // // if (s.w > maxWidth && s.h <= maxWidth) { // s.rotate(); // } // } // } // // s.x = x; // s.y = y; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = Math.max(nextY, s.bottom() + spacing); // // if (nextY > maxHeight) { // if ((s.w > maxWidth && s.w > maxHeight) || (s.h > maxWidth && s.h > maxHeight)) { // throw new RuntimeException("No free space can be found."); // } // // mapNumber++; // s.x = 0; // s.y = 0; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = s.bottom(); // } // } // // mapNumber++; // return mapNumber; // } // // public String toString() { // return "Shelf()"; // } // } // // Path: src/dk/cego/spritemapper/maxrects/OptimalMaxRectsLayouter.java // public class OptimalMaxRectsLayouter extends OptimalLayouter { // public OptimalMaxRectsLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // add(new MaxRectsLayouter().setFreeSpaceChooser(chooser)); // } // } // }
import dk.cego.spritemapper.guillotine.OptimalGuillotineLayouter; import dk.cego.spritemapper.shelf.ShelfLayouter; import dk.cego.spritemapper.maxrects.OptimalMaxRectsLayouter; import java.util.Map; import java.util.TreeMap;
/** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper; /** * This layouter knows all the different algorithms and chooses * the best one for the specific set of sprites. */ public class OptimalAlgorithmLayouter extends OptimalLayouter { private Map<String, SpriteLayouter> layouterNames; public OptimalAlgorithmLayouter() { layouterNames = new TreeMap<String, SpriteLayouter>(); layouterNames.put("guillotine", new OptimalGuillotineLayouter());
// Path: src/dk/cego/spritemapper/guillotine/OptimalGuillotineLayouter.java // public class OptimalGuillotineLayouter extends OptimalLayouter { // public OptimalGuillotineLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // FreeSpaceSplitStrategy splitStrategies[] = new FreeSpaceSplitStrategy[] { // new LongestAxisSplitStrategy(), // new ShortestAxisSplitStrategy(), // new LongestLeftoverAxisSplitStrategy(), // new ShortestLeftoverAxisSplitStrategy(), // new MaximumAreaDifferenceSplitStrategy(), // new MinimumAreaDifferenceSplitStrategy() // }; // // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // for (FreeSpaceSplitStrategy splitStrategy : splitStrategies) { // add(new GuillotineLayouter().setFreeSpaceChooser(chooser).setFreeSpaceSplitStrategy(splitStrategy)); // } // } // } // } // // Path: src/dk/cego/spritemapper/shelf/ShelfLayouter.java // public class ShelfLayouter extends SpriteLayouter { // private final static int MAX_HEIGHT = 1024 * 1024 * 1024; // // public int layout(int maxWidth, int maxHeight, List<Sprite> sprites) { // if (sprites.isEmpty()) { // return 0; // } // // if (maxHeight == 0) { // maxHeight = MAX_HEIGHT; // } // // int x = 0, y = 0, nextY = 0; // int spacing = getSpacing(); // // int mapNumber = 0; // // for (Sprite s : sprites) { // if (x + s.w > maxWidth) { // // try to rotate sprite. // if (x + s.h <= maxWidth) { // s.rotate(); // } else { // x = 0; // y = nextY; // // if (s.w > maxWidth && s.h <= maxWidth) { // s.rotate(); // } // } // } // // s.x = x; // s.y = y; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = Math.max(nextY, s.bottom() + spacing); // // if (nextY > maxHeight) { // if ((s.w > maxWidth && s.w > maxHeight) || (s.h > maxWidth && s.h > maxHeight)) { // throw new RuntimeException("No free space can be found."); // } // // mapNumber++; // s.x = 0; // s.y = 0; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = s.bottom(); // } // } // // mapNumber++; // return mapNumber; // } // // public String toString() { // return "Shelf()"; // } // } // // Path: src/dk/cego/spritemapper/maxrects/OptimalMaxRectsLayouter.java // public class OptimalMaxRectsLayouter extends OptimalLayouter { // public OptimalMaxRectsLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // add(new MaxRectsLayouter().setFreeSpaceChooser(chooser)); // } // } // } // Path: src/dk/cego/spritemapper/OptimalAlgorithmLayouter.java import dk.cego.spritemapper.guillotine.OptimalGuillotineLayouter; import dk.cego.spritemapper.shelf.ShelfLayouter; import dk.cego.spritemapper.maxrects.OptimalMaxRectsLayouter; import java.util.Map; import java.util.TreeMap; /** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper; /** * This layouter knows all the different algorithms and chooses * the best one for the specific set of sprites. */ public class OptimalAlgorithmLayouter extends OptimalLayouter { private Map<String, SpriteLayouter> layouterNames; public OptimalAlgorithmLayouter() { layouterNames = new TreeMap<String, SpriteLayouter>(); layouterNames.put("guillotine", new OptimalGuillotineLayouter());
layouterNames.put("shelf", new ShelfLayouter());
huandu/spritemapper
src/dk/cego/spritemapper/OptimalAlgorithmLayouter.java
// Path: src/dk/cego/spritemapper/guillotine/OptimalGuillotineLayouter.java // public class OptimalGuillotineLayouter extends OptimalLayouter { // public OptimalGuillotineLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // FreeSpaceSplitStrategy splitStrategies[] = new FreeSpaceSplitStrategy[] { // new LongestAxisSplitStrategy(), // new ShortestAxisSplitStrategy(), // new LongestLeftoverAxisSplitStrategy(), // new ShortestLeftoverAxisSplitStrategy(), // new MaximumAreaDifferenceSplitStrategy(), // new MinimumAreaDifferenceSplitStrategy() // }; // // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // for (FreeSpaceSplitStrategy splitStrategy : splitStrategies) { // add(new GuillotineLayouter().setFreeSpaceChooser(chooser).setFreeSpaceSplitStrategy(splitStrategy)); // } // } // } // } // // Path: src/dk/cego/spritemapper/shelf/ShelfLayouter.java // public class ShelfLayouter extends SpriteLayouter { // private final static int MAX_HEIGHT = 1024 * 1024 * 1024; // // public int layout(int maxWidth, int maxHeight, List<Sprite> sprites) { // if (sprites.isEmpty()) { // return 0; // } // // if (maxHeight == 0) { // maxHeight = MAX_HEIGHT; // } // // int x = 0, y = 0, nextY = 0; // int spacing = getSpacing(); // // int mapNumber = 0; // // for (Sprite s : sprites) { // if (x + s.w > maxWidth) { // // try to rotate sprite. // if (x + s.h <= maxWidth) { // s.rotate(); // } else { // x = 0; // y = nextY; // // if (s.w > maxWidth && s.h <= maxWidth) { // s.rotate(); // } // } // } // // s.x = x; // s.y = y; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = Math.max(nextY, s.bottom() + spacing); // // if (nextY > maxHeight) { // if ((s.w > maxWidth && s.w > maxHeight) || (s.h > maxWidth && s.h > maxHeight)) { // throw new RuntimeException("No free space can be found."); // } // // mapNumber++; // s.x = 0; // s.y = 0; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = s.bottom(); // } // } // // mapNumber++; // return mapNumber; // } // // public String toString() { // return "Shelf()"; // } // } // // Path: src/dk/cego/spritemapper/maxrects/OptimalMaxRectsLayouter.java // public class OptimalMaxRectsLayouter extends OptimalLayouter { // public OptimalMaxRectsLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // add(new MaxRectsLayouter().setFreeSpaceChooser(chooser)); // } // } // }
import dk.cego.spritemapper.guillotine.OptimalGuillotineLayouter; import dk.cego.spritemapper.shelf.ShelfLayouter; import dk.cego.spritemapper.maxrects.OptimalMaxRectsLayouter; import java.util.Map; import java.util.TreeMap;
/** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper; /** * This layouter knows all the different algorithms and chooses * the best one for the specific set of sprites. */ public class OptimalAlgorithmLayouter extends OptimalLayouter { private Map<String, SpriteLayouter> layouterNames; public OptimalAlgorithmLayouter() { layouterNames = new TreeMap<String, SpriteLayouter>(); layouterNames.put("guillotine", new OptimalGuillotineLayouter()); layouterNames.put("shelf", new ShelfLayouter());
// Path: src/dk/cego/spritemapper/guillotine/OptimalGuillotineLayouter.java // public class OptimalGuillotineLayouter extends OptimalLayouter { // public OptimalGuillotineLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // FreeSpaceSplitStrategy splitStrategies[] = new FreeSpaceSplitStrategy[] { // new LongestAxisSplitStrategy(), // new ShortestAxisSplitStrategy(), // new LongestLeftoverAxisSplitStrategy(), // new ShortestLeftoverAxisSplitStrategy(), // new MaximumAreaDifferenceSplitStrategy(), // new MinimumAreaDifferenceSplitStrategy() // }; // // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // for (FreeSpaceSplitStrategy splitStrategy : splitStrategies) { // add(new GuillotineLayouter().setFreeSpaceChooser(chooser).setFreeSpaceSplitStrategy(splitStrategy)); // } // } // } // } // // Path: src/dk/cego/spritemapper/shelf/ShelfLayouter.java // public class ShelfLayouter extends SpriteLayouter { // private final static int MAX_HEIGHT = 1024 * 1024 * 1024; // // public int layout(int maxWidth, int maxHeight, List<Sprite> sprites) { // if (sprites.isEmpty()) { // return 0; // } // // if (maxHeight == 0) { // maxHeight = MAX_HEIGHT; // } // // int x = 0, y = 0, nextY = 0; // int spacing = getSpacing(); // // int mapNumber = 0; // // for (Sprite s : sprites) { // if (x + s.w > maxWidth) { // // try to rotate sprite. // if (x + s.h <= maxWidth) { // s.rotate(); // } else { // x = 0; // y = nextY; // // if (s.w > maxWidth && s.h <= maxWidth) { // s.rotate(); // } // } // } // // s.x = x; // s.y = y; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = Math.max(nextY, s.bottom() + spacing); // // if (nextY > maxHeight) { // if ((s.w > maxWidth && s.w > maxHeight) || (s.h > maxWidth && s.h > maxHeight)) { // throw new RuntimeException("No free space can be found."); // } // // mapNumber++; // s.x = 0; // s.y = 0; // s.mapNumber = mapNumber; // // x = s.right() + spacing; // nextY = s.bottom(); // } // } // // mapNumber++; // return mapNumber; // } // // public String toString() { // return "Shelf()"; // } // } // // Path: src/dk/cego/spritemapper/maxrects/OptimalMaxRectsLayouter.java // public class OptimalMaxRectsLayouter extends OptimalLayouter { // public OptimalMaxRectsLayouter() { // FreeSpaceChooser freeSpaceChoosers[] = new FreeSpaceChooser[] { // new BestFitChooser(), // new BestShortSideChooser(), // new BestLongSideChooser(), // new TopLeftChooser() // }; // for (FreeSpaceChooser chooser : freeSpaceChoosers) { // add(new MaxRectsLayouter().setFreeSpaceChooser(chooser)); // } // } // } // Path: src/dk/cego/spritemapper/OptimalAlgorithmLayouter.java import dk.cego.spritemapper.guillotine.OptimalGuillotineLayouter; import dk.cego.spritemapper.shelf.ShelfLayouter; import dk.cego.spritemapper.maxrects.OptimalMaxRectsLayouter; import java.util.Map; import java.util.TreeMap; /** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper; /** * This layouter knows all the different algorithms and chooses * the best one for the specific set of sprites. */ public class OptimalAlgorithmLayouter extends OptimalLayouter { private Map<String, SpriteLayouter> layouterNames; public OptimalAlgorithmLayouter() { layouterNames = new TreeMap<String, SpriteLayouter>(); layouterNames.put("guillotine", new OptimalGuillotineLayouter()); layouterNames.put("shelf", new ShelfLayouter());
layouterNames.put("maxrects", new OptimalMaxRectsLayouter());
huandu/spritemapper
src/dk/cego/spritemapper/guillotine/MinimumAreaDifferenceSplitStrategy.java
// Path: src/dk/cego/spritemapper/Rectangle.java // public class Rectangle { // public int x, y, w, h; // // public Rectangle(int x, int y, int w, int h) { // this.x = x; // this.y = y; // this.w = w; // this.h = h; // } // // public int left() { // return x; // } // // public int right() { // return x + w; // } // // public int top() { // return y; // } // // public int bottom() { // return y + h; // } // // public int area() { // return w * h; // } // // /** // * Return true if this fits inside 'other'. // */ // public boolean fits(Rectangle other) { // return w <= other.w && h <= other.h; // } // // public boolean collides(Rectangle other) { // return right() > other.left() && left() < other.right() && // bottom() > other.top() && top() < other.bottom(); // } // // public boolean contains(Rectangle other) { // return left() <= other.left() && right() >= other.right() && // top() <= other.top() && bottom() >= other.bottom(); // } // // public boolean inside(Rectangle other) { // return left() >= other.left() && right() <= other.right() && // top() >= other.top() && bottom() <= other.bottom(); // } // // public String toString() { // return "Rectangle(" + x + "," + y + ", " + w + "," + h + ")"; // } // } // // Path: src/dk/cego/spritemapper/Sprite.java // public class Sprite extends Rectangle { // public String name; // public int mapNumber = 0; // public BufferedImage image; // public boolean rotated; // public Rectangle colorRect; // public Dimension originalDimension; // // public Sprite(String name, BufferedImage image) { // this(name, image, 0, 0, image.getWidth(), image.getHeight(), false); // } // // public Sprite(String name, BufferedImage image, int x, int y, int w, int h, boolean rotated) { // this(name, image, x, y, w, h, 0, 0, w, h, w, h, rotated); // } // // public Sprite(String name, BufferedImage image, int x, int y, int w, int h, int colorX, int colorY, int colorW, int colorH, int originalW, int originalH, boolean rotated) { // super(x, y, w, h); // this.name = name; // this.image = image; // this.rotated = rotated; // this.colorRect = new Rectangle(colorX, colorY, colorW, colorH); // this.originalDimension = new Dimension(originalW, originalH); // } // // public Sprite rotate() { // int tmp = w; // w = h; // h = tmp; // // rotated = !rotated; // return this; // } // // public final static Sprite copy(Sprite toCopy) { // return new Sprite(toCopy.name, toCopy.image, // toCopy.x, toCopy.y, toCopy.w, toCopy.h, // toCopy.colorRect.x, toCopy.colorRect.y, toCopy.colorRect.w, toCopy.colorRect.h, // toCopy.originalDimension.width, toCopy.originalDimension.height, // toCopy.rotated); // } // // public final static List<Sprite> copy(List<Sprite> toCopy) { // LinkedList<Sprite> c = new LinkedList<Sprite>(); // for (Sprite s : toCopy) { // c.add(copy(s)); // } // return c; // } // // /** // * Calculate dimension of sprites. // * @param sprites // * @param maxMapNumber // * @return Dimension[] which contains maxMapNumber dimensions. // */ // public final static Dimension[] dimensions(List<Sprite> sprites, int maxMapNumber) { // Dimension[] dimensions = new Dimension[maxMapNumber]; // Dimension d = null; // // for (int i = 0; i < maxMapNumber; i++) { // dimensions[i] = new Dimension(); // } // // for (Sprite s : sprites) { // d = dimensions[s.mapNumber]; // d.width = Math.max(d.width, s.right()); // d.height = Math.max(d.height, s.bottom()); // } // // return dimensions; // } // // public final static int collectiveArea(List<Sprite> sprites) { // int area = 0; // for (Sprite s : sprites) { // area += s.area(); // } // return area; // } // // public String toString() { // return "Sprite(" + name + "," + (rotated ? "rotated" : "not rotated") + "," + x + "," + y + "," + w + "," + h + ")"; // } // }
import dk.cego.spritemapper.Rectangle; import dk.cego.spritemapper.Sprite;
/** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper.guillotine; public class MinimumAreaDifferenceSplitStrategy implements FreeSpaceSplitStrategy { private Rectangle areas[]; public MinimumAreaDifferenceSplitStrategy() { areas = new Rectangle[2]; }
// Path: src/dk/cego/spritemapper/Rectangle.java // public class Rectangle { // public int x, y, w, h; // // public Rectangle(int x, int y, int w, int h) { // this.x = x; // this.y = y; // this.w = w; // this.h = h; // } // // public int left() { // return x; // } // // public int right() { // return x + w; // } // // public int top() { // return y; // } // // public int bottom() { // return y + h; // } // // public int area() { // return w * h; // } // // /** // * Return true if this fits inside 'other'. // */ // public boolean fits(Rectangle other) { // return w <= other.w && h <= other.h; // } // // public boolean collides(Rectangle other) { // return right() > other.left() && left() < other.right() && // bottom() > other.top() && top() < other.bottom(); // } // // public boolean contains(Rectangle other) { // return left() <= other.left() && right() >= other.right() && // top() <= other.top() && bottom() >= other.bottom(); // } // // public boolean inside(Rectangle other) { // return left() >= other.left() && right() <= other.right() && // top() >= other.top() && bottom() <= other.bottom(); // } // // public String toString() { // return "Rectangle(" + x + "," + y + ", " + w + "," + h + ")"; // } // } // // Path: src/dk/cego/spritemapper/Sprite.java // public class Sprite extends Rectangle { // public String name; // public int mapNumber = 0; // public BufferedImage image; // public boolean rotated; // public Rectangle colorRect; // public Dimension originalDimension; // // public Sprite(String name, BufferedImage image) { // this(name, image, 0, 0, image.getWidth(), image.getHeight(), false); // } // // public Sprite(String name, BufferedImage image, int x, int y, int w, int h, boolean rotated) { // this(name, image, x, y, w, h, 0, 0, w, h, w, h, rotated); // } // // public Sprite(String name, BufferedImage image, int x, int y, int w, int h, int colorX, int colorY, int colorW, int colorH, int originalW, int originalH, boolean rotated) { // super(x, y, w, h); // this.name = name; // this.image = image; // this.rotated = rotated; // this.colorRect = new Rectangle(colorX, colorY, colorW, colorH); // this.originalDimension = new Dimension(originalW, originalH); // } // // public Sprite rotate() { // int tmp = w; // w = h; // h = tmp; // // rotated = !rotated; // return this; // } // // public final static Sprite copy(Sprite toCopy) { // return new Sprite(toCopy.name, toCopy.image, // toCopy.x, toCopy.y, toCopy.w, toCopy.h, // toCopy.colorRect.x, toCopy.colorRect.y, toCopy.colorRect.w, toCopy.colorRect.h, // toCopy.originalDimension.width, toCopy.originalDimension.height, // toCopy.rotated); // } // // public final static List<Sprite> copy(List<Sprite> toCopy) { // LinkedList<Sprite> c = new LinkedList<Sprite>(); // for (Sprite s : toCopy) { // c.add(copy(s)); // } // return c; // } // // /** // * Calculate dimension of sprites. // * @param sprites // * @param maxMapNumber // * @return Dimension[] which contains maxMapNumber dimensions. // */ // public final static Dimension[] dimensions(List<Sprite> sprites, int maxMapNumber) { // Dimension[] dimensions = new Dimension[maxMapNumber]; // Dimension d = null; // // for (int i = 0; i < maxMapNumber; i++) { // dimensions[i] = new Dimension(); // } // // for (Sprite s : sprites) { // d = dimensions[s.mapNumber]; // d.width = Math.max(d.width, s.right()); // d.height = Math.max(d.height, s.bottom()); // } // // return dimensions; // } // // public final static int collectiveArea(List<Sprite> sprites) { // int area = 0; // for (Sprite s : sprites) { // area += s.area(); // } // return area; // } // // public String toString() { // return "Sprite(" + name + "," + (rotated ? "rotated" : "not rotated") + "," + x + "," + y + "," + w + "," + h + ")"; // } // } // Path: src/dk/cego/spritemapper/guillotine/MinimumAreaDifferenceSplitStrategy.java import dk.cego.spritemapper.Rectangle; import dk.cego.spritemapper.Sprite; /** * Copyright (C) 2011 CEGO ApS * Written by Robert Larsen <robert@komogvind.dk> for CEGO ApS * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package dk.cego.spritemapper.guillotine; public class MinimumAreaDifferenceSplitStrategy implements FreeSpaceSplitStrategy { private Rectangle areas[]; public MinimumAreaDifferenceSplitStrategy() { areas = new Rectangle[2]; }
public FreeSpaceSplitStrategy.Split chooseSplit(Rectangle r, Sprite s, int spacing) {
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/RoutingService.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // }
import org.optaplanner.core.api.solver.Solver; import org.optaplanner.core.api.solver.SolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import xyz.thepathfinder.routing.domain.RoutingSolution;
package xyz.thepathfinder.routing.service; @Path("/") public class RoutingService { Logger logger = LoggerFactory.getLogger(RoutingService.class); public static final String SOLVER_CONFIG = "xyz/thepathfinder/routing/solverconfig.xml"; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ProblemSolution solveProblem(ProblemDescription problemDescription) { logger.info("Received request to route: " + problemDescription); SolverFactory solverFactory = SolverFactory.createFromXmlResource(SOLVER_CONFIG); Solver solver = solverFactory.buildSolver();
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/RoutingService.java import org.optaplanner.core.api.solver.Solver; import org.optaplanner.core.api.solver.SolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import xyz.thepathfinder.routing.domain.RoutingSolution; package xyz.thepathfinder.routing.service; @Path("/") public class RoutingService { Logger logger = LoggerFactory.getLogger(RoutingService.class); public static final String SOLVER_CONFIG = "xyz/thepathfinder/routing/solverconfig.xml"; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ProblemSolution solveProblem(ProblemDescription problemDescription) { logger.info("Received request to route: " + problemDescription); SolverFactory solverFactory = SolverFactory.createFromXmlResource(SOLVER_CONFIG); Solver solver = solverFactory.buildSolver();
RoutingSolution routingSolution = problemDescription.createEmptyRoutingSolution();
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/RoutingScoreCalculator.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // }
import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; import java.util.HashMap; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.RoutingSolution; import static java.util.stream.Collectors.summingLong;
package xyz.thepathfinder.routing.score; public class RoutingScoreCalculator implements EasyScoreCalculator<RoutingSolution> { @Override public Score calculateScore(RoutingSolution solution) { long hardScore = 0; long softScore = 0; hardScore -= pickupOutOfOrderViolations(solution); hardScore -= capacitiesViolated(solution); softScore -= getTotalDistance(solution); System.out.println("Score: " + hardScore + ", " + softScore); return HardSoftLongScore.valueOf(hardScore, softScore); } static long pickupOutOfOrderViolations(RoutingSolution solution) { return solution.getTransportList().stream().collect(summingLong(t -> {
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/RoutingScoreCalculator.java import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; import java.util.HashMap; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.RoutingSolution; import static java.util.stream.Collectors.summingLong; package xyz.thepathfinder.routing.score; public class RoutingScoreCalculator implements EasyScoreCalculator<RoutingSolution> { @Override public Score calculateScore(RoutingSolution solution) { long hardScore = 0; long softScore = 0; hardScore -= pickupOutOfOrderViolations(solution); hardScore -= capacitiesViolated(solution); softScore -= getTotalDistance(solution); System.out.println("Score: " + hardScore + ", " + softScore); return HardSoftLongScore.valueOf(hardScore, softScore); } static long pickupOutOfOrderViolations(RoutingSolution solution) { return solution.getTransportList().stream().collect(summingLong(t -> {
List<CommodityAction> route = t.getRoute();
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/RoutingScoreCalculator.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // }
import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; import java.util.HashMap; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.RoutingSolution; import static java.util.stream.Collectors.summingLong;
package xyz.thepathfinder.routing.score; public class RoutingScoreCalculator implements EasyScoreCalculator<RoutingSolution> { @Override public Score calculateScore(RoutingSolution solution) { long hardScore = 0; long softScore = 0; hardScore -= pickupOutOfOrderViolations(solution); hardScore -= capacitiesViolated(solution); softScore -= getTotalDistance(solution); System.out.println("Score: " + hardScore + ", " + softScore); return HardSoftLongScore.valueOf(hardScore, softScore); } static long pickupOutOfOrderViolations(RoutingSolution solution) { return solution.getTransportList().stream().collect(summingLong(t -> { List<CommodityAction> route = t.getRoute(); long violations = 0; for (int i = 0; i < route.size(); i++) {
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/RoutingScoreCalculator.java import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; import java.util.HashMap; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.RoutingSolution; import static java.util.stream.Collectors.summingLong; package xyz.thepathfinder.routing.score; public class RoutingScoreCalculator implements EasyScoreCalculator<RoutingSolution> { @Override public Score calculateScore(RoutingSolution solution) { long hardScore = 0; long softScore = 0; hardScore -= pickupOutOfOrderViolations(solution); hardScore -= capacitiesViolated(solution); softScore -= getTotalDistance(solution); System.out.println("Score: " + hardScore + ", " + softScore); return HardSoftLongScore.valueOf(hardScore, softScore); } static long pickupOutOfOrderViolations(RoutingSolution solution) { return solution.getTransportList().stream().collect(summingLong(t -> { List<CommodityAction> route = t.getRoute(); long violations = 0; for (int i = 0; i < route.size(); i++) {
if (route.get(i) instanceof CommodityDropoff) {
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/ProblemDescription.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityPickup.java // public class CommodityPickup implements CommodityStart, CommodityAction { // final String name; // // public CommodityPickup(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/RouteAction.java // public interface RouteAction { // // String getName(); // } // // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.CommodityPickup; import xyz.thepathfinder.routing.domain.RouteAction; import xyz.thepathfinder.routing.domain.RoutingSolution; import xyz.thepathfinder.routing.domain.Transport; import static java.util.function.Function.identity;
} public List<Integer> getTransports() { return transports; } public Map<Integer, Integer> getCommodities() { return commodities; } public Integer[][] getDurations() { return durations; } public Integer[][] getDistances() { return distances; } public Map<String, Map<Integer, Integer>> getCapacities() { return capacities; } public Map<String, Map<Integer, Integer>> getParameters() { return parameters; } public String getObjective() { return objective; }
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityPickup.java // public class CommodityPickup implements CommodityStart, CommodityAction { // final String name; // // public CommodityPickup(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/RouteAction.java // public interface RouteAction { // // String getName(); // } // // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/ProblemDescription.java import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.CommodityPickup; import xyz.thepathfinder.routing.domain.RouteAction; import xyz.thepathfinder.routing.domain.RoutingSolution; import xyz.thepathfinder.routing.domain.Transport; import static java.util.function.Function.identity; } public List<Integer> getTransports() { return transports; } public Map<Integer, Integer> getCommodities() { return commodities; } public Integer[][] getDurations() { return durations; } public Integer[][] getDistances() { return distances; } public Map<String, Map<Integer, Integer>> getCapacities() { return capacities; } public Map<String, Map<Integer, Integer>> getParameters() { return parameters; } public String getObjective() { return objective; }
public RoutingSolution createEmptyRoutingSolution() {
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // }
import java.util.List; import xyz.thepathfinder.routing.domain.RoutingSolution; import xyz.thepathfinder.routing.domain.Transport; import static java.util.stream.Collectors.toList;
package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { }
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java import java.util.List; import xyz.thepathfinder.routing.domain.RoutingSolution; import xyz.thepathfinder.routing.domain.Transport; import static java.util.stream.Collectors.toList; package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { }
public static ProblemSolution create(RoutingSolution solution) {
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // }
import java.util.List; import xyz.thepathfinder.routing.domain.RoutingSolution; import xyz.thepathfinder.routing.domain.Transport; import static java.util.stream.Collectors.toList;
package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { } public static ProblemSolution create(RoutingSolution solution) { return new ProblemSolution(solution.getTransportList().stream()
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/RoutingSolution.java // @PlanningSolution // public class RoutingSolution implements Solution<HardSoftLongScore> { // // HardSoftLongScore score; // List<Transport> transportList; // List<CommodityAction> commodityActionList; // // @Override // public HardSoftLongScore getScore() { // return score; // } // // @Override // public void setScore(HardSoftLongScore score) { // this.score = score; // } // // @Override // public Collection<? extends RouteAction> getProblemFacts() { // List<RouteAction> routeActions = new ArrayList<>(); // routeActions.addAll(transportList); // routeActions.addAll(commodityActionList); // return routeActions; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "transportRange") // public List<Transport> getTransportList() { // return transportList; // } // // public void setTransportList(List<Transport> transports) { // transportList = transports; // } // // @PlanningEntityCollectionProperty // @ValueRangeProvider(id = "commodityActionRange") // public List<CommodityAction> getCommodityActionList() { // return commodityActionList; // } // // public void setCommodityActionList(List<CommodityAction> commodityActions) { // commodityActionList = commodityActions; // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java import java.util.List; import xyz.thepathfinder.routing.domain.RoutingSolution; import xyz.thepathfinder.routing.domain.Transport; import static java.util.stream.Collectors.toList; package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { } public static ProblemSolution create(RoutingSolution solution) { return new ProblemSolution(solution.getTransportList().stream()
.map(Transport::getPathfinderRoute).collect(toList()));
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/NaiveDifficultyComparator.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityPickup.java // public class CommodityPickup implements CommodityStart, CommodityAction { // final String name; // // public CommodityPickup(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/RouteAction.java // public interface RouteAction { // // String getName(); // }
import java.util.Comparator; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.CommodityPickup; import xyz.thepathfinder.routing.domain.RouteAction;
package xyz.thepathfinder.routing.score; public class NaiveDifficultyComparator implements Comparator<CommodityAction> { @Override public int compare(CommodityAction o1, CommodityAction o2) {
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityPickup.java // public class CommodityPickup implements CommodityStart, CommodityAction { // final String name; // // public CommodityPickup(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/RouteAction.java // public interface RouteAction { // // String getName(); // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/NaiveDifficultyComparator.java import java.util.Comparator; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.CommodityPickup; import xyz.thepathfinder.routing.domain.RouteAction; package xyz.thepathfinder.routing.score; public class NaiveDifficultyComparator implements Comparator<CommodityAction> { @Override public int compare(CommodityAction o1, CommodityAction o2) {
if (o1 instanceof CommodityDropoff && o2 instanceof CommodityPickup) {
CSSE497/pathfinder-routing
heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/NaiveDifficultyComparator.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityPickup.java // public class CommodityPickup implements CommodityStart, CommodityAction { // final String name; // // public CommodityPickup(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/RouteAction.java // public interface RouteAction { // // String getName(); // }
import java.util.Comparator; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.CommodityPickup; import xyz.thepathfinder.routing.domain.RouteAction;
package xyz.thepathfinder.routing.score; public class NaiveDifficultyComparator implements Comparator<CommodityAction> { @Override public int compare(CommodityAction o1, CommodityAction o2) {
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityDropoff.java // public class CommodityDropoff implements CommodityAction { // final CommodityStart start; // final String name; // // public CommodityDropoff(String name, CommodityStart start) { // this.start = start; // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/CommodityPickup.java // public class CommodityPickup implements CommodityStart, CommodityAction { // final String name; // // public CommodityPickup(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/RouteAction.java // public interface RouteAction { // // String getName(); // } // Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/score/NaiveDifficultyComparator.java import java.util.Comparator; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.CommodityDropoff; import xyz.thepathfinder.routing.domain.CommodityPickup; import xyz.thepathfinder.routing.domain.RouteAction; package xyz.thepathfinder.routing.score; public class NaiveDifficultyComparator implements Comparator<CommodityAction> { @Override public int compare(CommodityAction o1, CommodityAction o2) {
if (o1 instanceof CommodityDropoff && o2 instanceof CommodityPickup) {
CSSE497/pathfinder-routing
simulatedannealing/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.Transport;
package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { }
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java import java.util.ArrayList; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.Transport; package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { }
public static ProblemSolution create(Map<Transport, List<CommodityAction>> routes) {
CSSE497/pathfinder-routing
simulatedannealing/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.Transport;
package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { }
// Path: heuristicsearch/src/main/java/xyz/thepathfinder/routing/domain/CommodityAction.java // @PlanningEntity(difficultyComparatorClass = NaiveDifficultyComparator.class) // public abstract class CommodityAction implements RouteAction { // Transport transport; // CommodityAction nextCommodityAction; // RouteAction previousRouteAction; // Map<RouteAction, Long> distances = new HashMap<>(); // Map<String, Integer> capacities; // int id; // // @Override // @AnchorShadowVariable(sourceVariableName = "previousRouteAction") // public Transport getTransport() { // return transport; // } // // public void setTransport(Transport transport) { // this.transport = transport; // } // // @Override // public CommodityAction getNextCommodityAction() { // return nextCommodityAction; // } // // @Override // public void setNextCommodityAction(CommodityAction commodityAction) { // nextCommodityAction = commodityAction; // } // // @PlanningVariable(valueRangeProviderRefs = {"transportRange", "commodityActionRange"}, // graphType = PlanningVariableGraphType.CHAINED) // public RouteAction getPreviousRouteAction() { // return previousRouteAction; // } // // public void setPreviousRouteAction(RouteAction routeAction) { // previousRouteAction = routeAction; // } // // @Override // public long distanceTo(RouteAction routeAction) { // return distances.getOrDefault(routeAction, Long.MAX_VALUE); // } // // @Override // public void setDistance(RouteAction routeAction, long distance) { // distances.put(routeAction, distance); // } // // @Override // public int id() { // return id; // } // // @Override // public int getCapacity(String key) { // return capacities.getOrDefault(key, 0); // } // } // // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/domain/Transport.java // public class Transport implements CommodityStart { // final String name; // // public Transport(String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: simulatedannealing/src/main/java/xyz/thepathfinder/routing/service/ProblemSolution.java import java.util.ArrayList; import java.util.List; import java.util.Map; import xyz.thepathfinder.routing.domain.CommodityAction; import xyz.thepathfinder.routing.domain.Transport; package xyz.thepathfinder.routing.service; public class ProblemSolution { private List<List<Integer>> routes; public ProblemSolution() { }
public static ProblemSolution create(Map<Transport, List<CommodityAction>> routes) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshConnectionFactory.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritDefaultValues.java // public final class GerritDefaultValues { // // /** // * Default private constructor to hinder instantiation. // */ // private GerritDefaultValues() { // // } // /** // * The default gerrit name. // */ // public static final String DEFAULT_GERRIT_NAME = ""; // /** // * The default gerrit hostname. // */ // public static final String DEFAULT_GERRIT_HOSTNAME = ""; // /** // * The default gerrit front end url. // */ // public static final String DEFAULT_GERRIT_FRONT_END_URL = ""; // /** // * The default ssh port for the gerrit server. // */ // public static final int DEFAULT_GERRIT_SSH_PORT = 29418; // /** // * The default scheme for the gerrit server. // */ // public static final String DEFAULT_GERRIT_SCHEME = "ssh"; // /** // * The default gerrit proxy. // */ // public static final String DEFAULT_GERRIT_PROXY = ""; // /** // * The default gerrit ssh connection timeout. // */ // public static final int DEFAULT_GERRIT_SSH_CONNECTION_TIMEOUT = 0; // // /** // * The default key-file to use when authenticating to the gerrit server. // */ // public static final File DEFAULT_GERRIT_AUTH_KEY_FILE = new File(new File(System.getProperty("user.home"), ".ssh"), // "id_rsa"); // /** // * The default password for the private key-file. // */ // public static final String DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD = null; // /** // * The default username to use when authenticating to the gerrit server. // */ // public static final String DEFAULT_GERRIT_USERNAME = ""; // /** // * The default nr of event worker threads. // */ // public static final int DEFAULT_NR_OF_RECEIVING_WORKER_THREADS = 3; // /** // * The default keep alive time for receiving threads in seconds. // */ // public static final int DEFAULT_RECEIVE_THREAD_KEEP_ALIVE_TIME = 1200; // /** // * The minimum keep alive time for receiving threads in seconds. // */ // public static final int MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME = 10; // /** // * The default nr of worker threads that sends approvals/review commands. // */ // public static final int DEFAULT_NR_OF_SENDING_WORKER_THREADS = 1; // /** // * The default build schedule delay. // */ // public static final int DEFAULT_BUILD_SCHEDULE_DELAY = 3; // /** // * The default refresh interval for the Dynamic Trigger Configuration. // */ // public static final int DEFAULT_DYNAMIC_CONFIG_REFRESH_INTERVAL = 30; // // /** // * The minimum refresh interval for dynamic configuration. // */ // public static final int MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL = 5; // }
import com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues; import java.io.IOException;
/* * The MIT License * * Copyright 2011 Sony Ericsson Mobile Communications. All rights reserved. * Copyright 2014 Sony Mobile Communications AB. All rights reserved.s * * 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 com.sonymobile.tools.gerrit.gerritevents.ssh; /** * Factory class for {@link SshConnection}s. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public abstract class SshConnectionFactory { /** * Private constructor to hinder instantiation. */ private SshConnectionFactory() { throw new UnsupportedOperationException("Cannot instantiate util classes."); } /** * Creates a {@link SshConnection}. * * @param host the host name * @param port the port * @param authentication the credentials * @return a new connection. * * @throws IOException if so. * @see SshConnection * @see SshConnectionImpl */ public static SshConnection getConnection(String host, int port, Authentication authentication) throws IOException {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritDefaultValues.java // public final class GerritDefaultValues { // // /** // * Default private constructor to hinder instantiation. // */ // private GerritDefaultValues() { // // } // /** // * The default gerrit name. // */ // public static final String DEFAULT_GERRIT_NAME = ""; // /** // * The default gerrit hostname. // */ // public static final String DEFAULT_GERRIT_HOSTNAME = ""; // /** // * The default gerrit front end url. // */ // public static final String DEFAULT_GERRIT_FRONT_END_URL = ""; // /** // * The default ssh port for the gerrit server. // */ // public static final int DEFAULT_GERRIT_SSH_PORT = 29418; // /** // * The default scheme for the gerrit server. // */ // public static final String DEFAULT_GERRIT_SCHEME = "ssh"; // /** // * The default gerrit proxy. // */ // public static final String DEFAULT_GERRIT_PROXY = ""; // /** // * The default gerrit ssh connection timeout. // */ // public static final int DEFAULT_GERRIT_SSH_CONNECTION_TIMEOUT = 0; // // /** // * The default key-file to use when authenticating to the gerrit server. // */ // public static final File DEFAULT_GERRIT_AUTH_KEY_FILE = new File(new File(System.getProperty("user.home"), ".ssh"), // "id_rsa"); // /** // * The default password for the private key-file. // */ // public static final String DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD = null; // /** // * The default username to use when authenticating to the gerrit server. // */ // public static final String DEFAULT_GERRIT_USERNAME = ""; // /** // * The default nr of event worker threads. // */ // public static final int DEFAULT_NR_OF_RECEIVING_WORKER_THREADS = 3; // /** // * The default keep alive time for receiving threads in seconds. // */ // public static final int DEFAULT_RECEIVE_THREAD_KEEP_ALIVE_TIME = 1200; // /** // * The minimum keep alive time for receiving threads in seconds. // */ // public static final int MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME = 10; // /** // * The default nr of worker threads that sends approvals/review commands. // */ // public static final int DEFAULT_NR_OF_SENDING_WORKER_THREADS = 1; // /** // * The default build schedule delay. // */ // public static final int DEFAULT_BUILD_SCHEDULE_DELAY = 3; // /** // * The default refresh interval for the Dynamic Trigger Configuration. // */ // public static final int DEFAULT_DYNAMIC_CONFIG_REFRESH_INTERVAL = 30; // // /** // * The minimum refresh interval for dynamic configuration. // */ // public static final int MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL = 5; // } // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshConnectionFactory.java import com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues; import java.io.IOException; /* * The MIT License * * Copyright 2011 Sony Ericsson Mobile Communications. All rights reserved. * Copyright 2014 Sony Mobile Communications AB. All rights reserved.s * * 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 com.sonymobile.tools.gerrit.gerritevents.ssh; /** * Factory class for {@link SshConnection}s. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public abstract class SshConnectionFactory { /** * Private constructor to hinder instantiation. */ private SshConnectionFactory() { throw new UnsupportedOperationException("Cannot instantiate util classes."); } /** * Creates a {@link SshConnection}. * * @param host the host name * @param port the port * @param authentication the credentials * @return a new connection. * * @throws IOException if so. * @see SshConnection * @see SshConnectionImpl */ public static SshConnection getConnection(String host, int port, Authentication authentication) throws IOException {
return getConnection(host, port, GerritDefaultValues.DEFAULT_GERRIT_PROXY, authentication);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritQueryHandlerWithPersistedConnection.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/Authentication.java // public class Authentication { // private File privateKeyFile; // private byte[] privateKeyPhrase; // private String username; // private String privateKeyFilePassword; // // /** // * Constructor. // * @param privateKeyFile the key. // * @param username the username. // * @param privateKeyFilePassword password for the key file, or null if there is none. // * @param privateKeyPhrase phrase of privatekey. // */ // public Authentication(File privateKeyFile, // String username, // String privateKeyFilePassword, // byte[] privateKeyPhrase) { // this.privateKeyFile = privateKeyFile; // this.username = username; // this.privateKeyFilePassword = privateKeyFilePassword; // this.privateKeyPhrase = privateKeyPhrase; // } // // /** // * Constructor. // * @param privateKeyFile the key. // * @param username the username. // * @param privateKeyFilePassword password for the key file, or null if there is none. // */ // public Authentication(File privateKeyFile, String username, String privateKeyFilePassword) { // this(privateKeyFile, username, privateKeyFilePassword, null); // } // // /** // * Constructor. // * With null as privateKeyFilePassword. // * @param privateKeyFile the key. // * @param username the username. // */ // public Authentication(File privateKeyFile, String username) { // this(privateKeyFile, username, null, null); // } // // /** // * The file path to the private key. // * @return the path. // */ // public File getPrivateKeyFile() { // return privateKeyFile; // } // // /** // * The password for the private key file. // * @return the password. // */ // public String getPrivateKeyFilePassword() { // return privateKeyFilePassword; // } // // /** // * The username to authenticate as. // * @return the username. // */ // public String getUsername() { // return username; // } // // /** // * The phrase of private key. // * @return the phrase. // */ // public byte[] getPrivateKeyPhrase() { // return privateKeyPhrase; // } // }
import com.sonymobile.tools.gerrit.gerritevents.ssh.Authentication; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshConnection; import java.io.IOException;
package com.sonymobile.tools.gerrit.gerritevents; /** * {@link GerritQueryHandler} with a persisted SSH connection. * Saves the performance overhead of creating a new connection for each query. */ public class GerritQueryHandlerWithPersistedConnection extends GerritQueryHandler { private SshConnection activeConnection = null; /** * Creates a {@link GerritQueryHandler} with persisted SSH connection. * * @param gerritHostName the hostName * @param gerritSshPort the ssh port that the gerrit server listens to. * @param gerritProxy the ssh Proxy url * @param authentication the authentication credentials. * @param connectionTimeout the connection timeout. */ public GerritQueryHandlerWithPersistedConnection(String gerritHostName, int gerritSshPort,
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/Authentication.java // public class Authentication { // private File privateKeyFile; // private byte[] privateKeyPhrase; // private String username; // private String privateKeyFilePassword; // // /** // * Constructor. // * @param privateKeyFile the key. // * @param username the username. // * @param privateKeyFilePassword password for the key file, or null if there is none. // * @param privateKeyPhrase phrase of privatekey. // */ // public Authentication(File privateKeyFile, // String username, // String privateKeyFilePassword, // byte[] privateKeyPhrase) { // this.privateKeyFile = privateKeyFile; // this.username = username; // this.privateKeyFilePassword = privateKeyFilePassword; // this.privateKeyPhrase = privateKeyPhrase; // } // // /** // * Constructor. // * @param privateKeyFile the key. // * @param username the username. // * @param privateKeyFilePassword password for the key file, or null if there is none. // */ // public Authentication(File privateKeyFile, String username, String privateKeyFilePassword) { // this(privateKeyFile, username, privateKeyFilePassword, null); // } // // /** // * Constructor. // * With null as privateKeyFilePassword. // * @param privateKeyFile the key. // * @param username the username. // */ // public Authentication(File privateKeyFile, String username) { // this(privateKeyFile, username, null, null); // } // // /** // * The file path to the private key. // * @return the path. // */ // public File getPrivateKeyFile() { // return privateKeyFile; // } // // /** // * The password for the private key file. // * @return the password. // */ // public String getPrivateKeyFilePassword() { // return privateKeyFilePassword; // } // // /** // * The username to authenticate as. // * @return the username. // */ // public String getUsername() { // return username; // } // // /** // * The phrase of private key. // * @return the phrase. // */ // public byte[] getPrivateKeyPhrase() { // return privateKeyPhrase; // } // } // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritQueryHandlerWithPersistedConnection.java import com.sonymobile.tools.gerrit.gerritevents.ssh.Authentication; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshConnection; import java.io.IOException; package com.sonymobile.tools.gerrit.gerritevents; /** * {@link GerritQueryHandler} with a persisted SSH connection. * Saves the performance overhead of creating a new connection for each query. */ public class GerritQueryHandlerWithPersistedConnection extends GerritQueryHandler { private SshConnection activeConnection = null; /** * Creates a {@link GerritQueryHandler} with persisted SSH connection. * * @param gerritHostName the hostName * @param gerritSshPort the ssh port that the gerrit server listens to. * @param gerritProxy the ssh Proxy url * @param authentication the authentication credentials. * @param connectionTimeout the connection timeout. */ public GerritQueryHandlerWithPersistedConnection(String gerritHostName, int gerritSshPort,
String gerritProxy, Authentication authentication,
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE;
/* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE; /* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
if (json.containsKey(TYPE) && json.containsKey(VALUE)) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE;
/* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE; /* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
if (json.containsKey(TYPE) && json.containsKey(VALUE)) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE;
/* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { if (json.containsKey(TYPE) && json.containsKey(VALUE)) { type = getString(json, TYPE); value = getString(json, VALUE); }
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE; /* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { if (json.containsKey(TYPE) && json.containsKey(VALUE)) { type = getString(json, TYPE); value = getString(json, VALUE); }
if (json.containsKey(BY)) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE;
/* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { if (json.containsKey(TYPE) && json.containsKey(VALUE)) { type = getString(json, TYPE); value = getString(json, VALUE); } if (json.containsKey(BY)) { by = new Account(json.getJSONObject(BY)); }
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE; /* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { if (json.containsKey(TYPE) && json.containsKey(VALUE)) { type = getString(json, TYPE); value = getString(json, VALUE); } if (json.containsKey(BY)) { by = new Account(json.getJSONObject(BY)); }
if (json.containsKey(UPDATED)) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE;
/* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { if (json.containsKey(TYPE) && json.containsKey(VALUE)) { type = getString(json, TYPE); value = getString(json, VALUE); } if (json.containsKey(BY)) { by = new Account(json.getJSONObject(BY)); } if (json.containsKey(UPDATED)) { updated = getBoolean(json, UPDATED); }
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String BY = "by"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String TYPE = "type"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String VALUE = "value"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String UPDATED = "updated"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLD_VALUE = "oldValue"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Approval.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.VALUE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPDATED; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLD_VALUE; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.BY; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.TYPE; /* * The MIT License * * Copyright 2012 Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Approval DTO. * * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class Approval implements GerritJsonDTO { /** * The approval category. */ private String type; /** * The approval value */ private String value; /** * Approval value update indicator */ private Boolean updated; /** * The old (or previous) approval value */ private String oldValue; /** * The user who has approved the patch */ private Account by; /* username has been replaced by Approval.by Account. * This allows old builds to deserialize without warnings. * Below readResolve() method will handle the migration. * I can't flag it transient as it will skip the deserialization * part, preventing any migration. */ @SuppressWarnings("unused") private String username; /** * Default constructor. */ public Approval() { } /** * Constructor that fills with data directly. * * @param json the JSON object with corresponding data. */ public Approval(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { if (json.containsKey(TYPE) && json.containsKey(VALUE)) { type = getString(json, TYPE); value = getString(json, VALUE); } if (json.containsKey(BY)) { by = new Account(json.getJSONObject(BY)); } if (json.containsKey(UPDATED)) { updated = getBoolean(json, UPDATED); }
if (json.containsKey(OLD_VALUE)) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV;
/* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; /* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
project = getString(json, PROJECT);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV;
/* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { project = getString(json, PROJECT);
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; /* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { project = getString(json, PROJECT);
refName = getString(json, REFNAME);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV;
/* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { project = getString(json, PROJECT); refName = getString(json, REFNAME);
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; /* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { project = getString(json, PROJECT); refName = getString(json, REFNAME);
oldRev = getString(json, OLDREV);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV;
/* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { project = getString(json, PROJECT); refName = getString(json, REFNAME); oldRev = getString(json, OLDREV);
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdate.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; /* * The MIT License * * Copyright 2012 Hewlett-Packard Development Company, L.P. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Reference Updated DTO. * @author James E. Blair &lt;jeblair@hp.com&gt; */ public class RefUpdate implements GerritJsonDTO { private static final String REFS_HEADS = "refs/heads/"; /** * Project path in Gerrit. */ private String project; /** * Ref name within project. */ private String refName; /** * Old revision at ref. */ private String oldRev; /** * New revision at ref. */ private String newRev; /** * Default constructor. */ public RefUpdate() { } /** * Constructor that fills with data directly. * @param json the JSON Object with corresponding data. * @see #fromJson(net.sf.json.JSONObject) */ public RefUpdate(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { project = getString(json, PROJECT); refName = getString(json, REFNAME); oldRev = getString(json, OLDREV);
newRev = getString(json, NEWREV);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Comment.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String MESSAGE = "message"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVIEWER = "reviewer";
import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.MESSAGE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVIEWER;
/* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** */ public class Comment implements GerritJsonDTO { private Account reviewer; private String message; /** * Default Constructor. */ public Comment() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Comment(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String MESSAGE = "message"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVIEWER = "reviewer"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Comment.java import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.MESSAGE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVIEWER; /* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** */ public class Comment implements GerritJsonDTO { private Account reviewer; private String message; /** * Default Constructor. */ public Comment() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Comment(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) {
message = getString(json, MESSAGE);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Comment.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String MESSAGE = "message"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVIEWER = "reviewer";
import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.MESSAGE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVIEWER;
/* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** */ public class Comment implements GerritJsonDTO { private Account reviewer; private String message; /** * Default Constructor. */ public Comment() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Comment(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { message = getString(json, MESSAGE);
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String MESSAGE = "message"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVIEWER = "reviewer"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Comment.java import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.MESSAGE; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVIEWER; /* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** */ public class Comment implements GerritJsonDTO { private Account reviewer; private String message; /** * Default Constructor. */ public Comment() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Comment(JSONObject json) { this.fromJson(json); } @Override public void fromJson(JSONObject json) { message = getString(json, MESSAGE);
if (json.containsKey(REVIEWER)) {
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshConnectionImpl.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritDefaultValues.java // public final class GerritDefaultValues { // // /** // * Default private constructor to hinder instantiation. // */ // private GerritDefaultValues() { // // } // /** // * The default gerrit name. // */ // public static final String DEFAULT_GERRIT_NAME = ""; // /** // * The default gerrit hostname. // */ // public static final String DEFAULT_GERRIT_HOSTNAME = ""; // /** // * The default gerrit front end url. // */ // public static final String DEFAULT_GERRIT_FRONT_END_URL = ""; // /** // * The default ssh port for the gerrit server. // */ // public static final int DEFAULT_GERRIT_SSH_PORT = 29418; // /** // * The default scheme for the gerrit server. // */ // public static final String DEFAULT_GERRIT_SCHEME = "ssh"; // /** // * The default gerrit proxy. // */ // public static final String DEFAULT_GERRIT_PROXY = ""; // /** // * The default gerrit ssh connection timeout. // */ // public static final int DEFAULT_GERRIT_SSH_CONNECTION_TIMEOUT = 0; // // /** // * The default key-file to use when authenticating to the gerrit server. // */ // public static final File DEFAULT_GERRIT_AUTH_KEY_FILE = new File(new File(System.getProperty("user.home"), ".ssh"), // "id_rsa"); // /** // * The default password for the private key-file. // */ // public static final String DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD = null; // /** // * The default username to use when authenticating to the gerrit server. // */ // public static final String DEFAULT_GERRIT_USERNAME = ""; // /** // * The default nr of event worker threads. // */ // public static final int DEFAULT_NR_OF_RECEIVING_WORKER_THREADS = 3; // /** // * The default keep alive time for receiving threads in seconds. // */ // public static final int DEFAULT_RECEIVE_THREAD_KEEP_ALIVE_TIME = 1200; // /** // * The minimum keep alive time for receiving threads in seconds. // */ // public static final int MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME = 10; // /** // * The default nr of worker threads that sends approvals/review commands. // */ // public static final int DEFAULT_NR_OF_SENDING_WORKER_THREADS = 1; // /** // * The default build schedule delay. // */ // public static final int DEFAULT_BUILD_SCHEDULE_DELAY = 3; // /** // * The default refresh interval for the Dynamic Trigger Configuration. // */ // public static final int DEFAULT_DYNAMIC_CONFIG_REFRESH_INTERVAL = 30; // // /** // * The minimum refresh interval for dynamic configuration. // */ // public static final int MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL = 5; // }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.HostKey; import com.jcraft.jsch.HostKeyRepository; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.ProxyHTTP; import com.jcraft.jsch.ProxySOCKS5; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; import com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues;
/* * The MIT License * * Copyright 2011 Sony Ericsson Mobile Communications. All rights reserved. * Copyright 2014 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.ssh; /** * A simple ssh client connection with private key. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class SshConnectionImpl implements SshConnection { private static final Logger logger = LoggerFactory.getLogger(SshConnectionImpl.class); /** * Keep-alive interval [msec] */ private static final int ALIVE_INTERVAL = 30 * 1000; /** * Time to wait for the channel to close [msec] */ private static final int CLOSURE_WAIT_TIMEOUT = 200; /** * Time to check for channel to close [msec] */ private static final int CLOSURE_WAIT_INTERVAL = 50; /** * SSH Command to open an "exec channel". */ protected static final String CMD_EXEC = "exec"; /** * The str length of "://" used for proxy parsing. */ protected static final int PROTO_HOST_DELIM_LENGTH = 3; private JSch client; private Session connectSession; private String host; private int port; private String proxy; private Authentication authentication; private AuthenticationUpdater updater; private int connectionTimeout; //CS IGNORE RedundantThrows FOR NEXT 30 LINES. REASON: Informative /** * Creates and opens a SshConnection. * * @param host the host to connect to. * @param port the port. * @param authentication the authentication-info */ protected SshConnectionImpl(String host, int port, Authentication authentication) {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritDefaultValues.java // public final class GerritDefaultValues { // // /** // * Default private constructor to hinder instantiation. // */ // private GerritDefaultValues() { // // } // /** // * The default gerrit name. // */ // public static final String DEFAULT_GERRIT_NAME = ""; // /** // * The default gerrit hostname. // */ // public static final String DEFAULT_GERRIT_HOSTNAME = ""; // /** // * The default gerrit front end url. // */ // public static final String DEFAULT_GERRIT_FRONT_END_URL = ""; // /** // * The default ssh port for the gerrit server. // */ // public static final int DEFAULT_GERRIT_SSH_PORT = 29418; // /** // * The default scheme for the gerrit server. // */ // public static final String DEFAULT_GERRIT_SCHEME = "ssh"; // /** // * The default gerrit proxy. // */ // public static final String DEFAULT_GERRIT_PROXY = ""; // /** // * The default gerrit ssh connection timeout. // */ // public static final int DEFAULT_GERRIT_SSH_CONNECTION_TIMEOUT = 0; // // /** // * The default key-file to use when authenticating to the gerrit server. // */ // public static final File DEFAULT_GERRIT_AUTH_KEY_FILE = new File(new File(System.getProperty("user.home"), ".ssh"), // "id_rsa"); // /** // * The default password for the private key-file. // */ // public static final String DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD = null; // /** // * The default username to use when authenticating to the gerrit server. // */ // public static final String DEFAULT_GERRIT_USERNAME = ""; // /** // * The default nr of event worker threads. // */ // public static final int DEFAULT_NR_OF_RECEIVING_WORKER_THREADS = 3; // /** // * The default keep alive time for receiving threads in seconds. // */ // public static final int DEFAULT_RECEIVE_THREAD_KEEP_ALIVE_TIME = 1200; // /** // * The minimum keep alive time for receiving threads in seconds. // */ // public static final int MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME = 10; // /** // * The default nr of worker threads that sends approvals/review commands. // */ // public static final int DEFAULT_NR_OF_SENDING_WORKER_THREADS = 1; // /** // * The default build schedule delay. // */ // public static final int DEFAULT_BUILD_SCHEDULE_DELAY = 3; // /** // * The default refresh interval for the Dynamic Trigger Configuration. // */ // public static final int DEFAULT_DYNAMIC_CONFIG_REFRESH_INTERVAL = 30; // // /** // * The minimum refresh interval for dynamic configuration. // */ // public static final int MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL = 5; // } // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshConnectionImpl.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.HostKey; import com.jcraft.jsch.HostKeyRepository; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.ProxyHTTP; import com.jcraft.jsch.ProxySOCKS5; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; import com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues; /* * The MIT License * * Copyright 2011 Sony Ericsson Mobile Communications. All rights reserved. * Copyright 2014 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.ssh; /** * A simple ssh client connection with private key. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class SshConnectionImpl implements SshConnection { private static final Logger logger = LoggerFactory.getLogger(SshConnectionImpl.class); /** * Keep-alive interval [msec] */ private static final int ALIVE_INTERVAL = 30 * 1000; /** * Time to wait for the channel to close [msec] */ private static final int CLOSURE_WAIT_TIMEOUT = 200; /** * Time to check for channel to close [msec] */ private static final int CLOSURE_WAIT_INTERVAL = 50; /** * SSH Command to open an "exec channel". */ protected static final String CMD_EXEC = "exec"; /** * The str length of "://" used for proxy parsing. */ protected static final int PROTO_HOST_DELIM_LENGTH = 3; private JSch client; private Session connectSession; private String host; private int port; private String proxy; private Authentication authentication; private AuthenticationUpdater updater; private int connectionTimeout; //CS IGNORE RedundantThrows FOR NEXT 30 LINES. REASON: Informative /** * Creates and opens a SshConnection. * * @param host the host to connect to. * @param port the port. * @param authentication the authentication-info */ protected SshConnectionImpl(String host, int port, Authentication authentication) {
this(host, port, GerritDefaultValues.DEFAULT_GERRIT_PROXY, authentication, null,
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/workers/rest/AbstractRestCommandJob2.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ChangeId.java // public class ChangeId { // private static final Logger logger = LoggerFactory.getLogger(ChangeId.class); // // private final String projectName; // private final String branchName; // private final String id; // // /** // * Constructor. // * // * @param projectName project name // * @param branchName branch name // * @param id id // */ // public ChangeId(String projectName, String branchName, String id) { // this.projectName = projectName; // this.branchName = branchName; // this.id = id; // } // // /** // * Constructor getting values from a change object. // * // * @param change the change // * @see #ChangeId(String, String, String) // */ // public ChangeId(Change change) { // this(change.getProject(), change.getBranch(), change.getId()); // } // // /** // * As the part of the URL. // * // * @return the url part. // */ // public String asUrlPart() { // try { // return encode(projectName) + "~" + encode(branchName) + "~" + id; // } catch (UnsupportedEncodingException e) { // String parameter = projectName + "~" + branchName + "~" + id; // logger.error("Failed to encode ChangeId {}, falling back to unencoded {}", this, parameter); // return parameter; // } // } // // /** // * Encode given String for usage in URL. UTF-8 is used as per recommendation // * at http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // * @param s String to be encoded // * @return Encoded string // * @throws UnsupportedEncodingException if UTF-8 is unsupported, handled in caller for better log message // */ // private String encode(final String s) throws UnsupportedEncodingException { // return URLEncoder.encode(s, CharEncoding.UTF_8); // } // // @Override // public String toString() { // return "ChangeId{" // + "projectName='" + projectName + '\'' // + ", branchName='" + branchName + '\'' // + ", id='" + id + '\'' // + '}'; // } // } // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/rest/RestConnectionConfig.java // public interface RestConnectionConfig { // // /** // * Base URL for Gerrit HTTP. // * // * @return the gerrit front end URL. Always ends with '/' // */ // String getGerritFrontEndUrl(); // // /** // * The credentials to use when connecting with the REST API. // * For example a {@link org.apache.http.auth.UsernamePasswordCredentials}. // * // * @return the credentials to use. // */ // Credentials getHttpCredentials(); // // /** // * The http or socks5 proxy url. // * // * @return the proxy url. // */ // String getGerritProxy(); // }
import com.google.gson.Gson; import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ChangeId; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ReviewInput; import com.sonymobile.tools.gerrit.gerritevents.rest.RestConnectionConfig; import org.apache.http.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Callable;
HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (UnsupportedEncodingException e) { logger.error("Failed to create JSON for posting to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to create JSON for posting to Gerrit: " + e.toString()); } return null; } entity.setContentType("application/json"); httpPost.setEntity(entity); return httpPost; } /** * What it says resolve Endpoint URL. * * @return the url. */ private String resolveEndpointURL() { String gerritFrontEndUrl = frontEndUrl; if (!gerritFrontEndUrl.endsWith("/")) { gerritFrontEndUrl = gerritFrontEndUrl + "/"; }
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ChangeId.java // public class ChangeId { // private static final Logger logger = LoggerFactory.getLogger(ChangeId.class); // // private final String projectName; // private final String branchName; // private final String id; // // /** // * Constructor. // * // * @param projectName project name // * @param branchName branch name // * @param id id // */ // public ChangeId(String projectName, String branchName, String id) { // this.projectName = projectName; // this.branchName = branchName; // this.id = id; // } // // /** // * Constructor getting values from a change object. // * // * @param change the change // * @see #ChangeId(String, String, String) // */ // public ChangeId(Change change) { // this(change.getProject(), change.getBranch(), change.getId()); // } // // /** // * As the part of the URL. // * // * @return the url part. // */ // public String asUrlPart() { // try { // return encode(projectName) + "~" + encode(branchName) + "~" + id; // } catch (UnsupportedEncodingException e) { // String parameter = projectName + "~" + branchName + "~" + id; // logger.error("Failed to encode ChangeId {}, falling back to unencoded {}", this, parameter); // return parameter; // } // } // // /** // * Encode given String for usage in URL. UTF-8 is used as per recommendation // * at http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // * @param s String to be encoded // * @return Encoded string // * @throws UnsupportedEncodingException if UTF-8 is unsupported, handled in caller for better log message // */ // private String encode(final String s) throws UnsupportedEncodingException { // return URLEncoder.encode(s, CharEncoding.UTF_8); // } // // @Override // public String toString() { // return "ChangeId{" // + "projectName='" + projectName + '\'' // + ", branchName='" + branchName + '\'' // + ", id='" + id + '\'' // + '}'; // } // } // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/rest/RestConnectionConfig.java // public interface RestConnectionConfig { // // /** // * Base URL for Gerrit HTTP. // * // * @return the gerrit front end URL. Always ends with '/' // */ // String getGerritFrontEndUrl(); // // /** // * The credentials to use when connecting with the REST API. // * For example a {@link org.apache.http.auth.UsernamePasswordCredentials}. // * // * @return the credentials to use. // */ // Credentials getHttpCredentials(); // // /** // * The http or socks5 proxy url. // * // * @return the proxy url. // */ // String getGerritProxy(); // } // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/workers/rest/AbstractRestCommandJob2.java import com.google.gson.Gson; import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ChangeId; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ReviewInput; import com.sonymobile.tools.gerrit.gerritevents.rest.RestConnectionConfig; import org.apache.http.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Callable; HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (UnsupportedEncodingException e) { logger.error("Failed to create JSON for posting to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to create JSON for posting to Gerrit: " + e.toString()); } return null; } entity.setContentType("application/json"); httpPost.setEntity(entity); return httpPost; } /** * What it says resolve Endpoint URL. * * @return the url. */ private String resolveEndpointURL() { String gerritFrontEndUrl = frontEndUrl; if (!gerritFrontEndUrl.endsWith("/")) { gerritFrontEndUrl = gerritFrontEndUrl + "/"; }
ChangeId changeId = new ChangeId(event.getChange().getProject(), event.getChange().getBranch(),
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Account.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String EMAIL = "email"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NAME = "name"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String USERNAME = "username";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.USERNAME; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NAME;
/* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Account DTO. * An account that is related to an event or attribute. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class Account implements GerritJsonDTO { /** * Account user's full name. */ private String name; /** * Account user's preferred email. */ private String email; /** * Account username. */ private String username; /** * Default constructor. */ public Account() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Account(JSONObject json) { this.fromJson(json); } /** * For easier testing. * @param name the name. * @param email the email. */ public Account(String name, String email) { this.name = name; this.email = email; } @Override public void fromJson(JSONObject json) {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String EMAIL = "email"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NAME = "name"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String USERNAME = "username"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Account.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.USERNAME; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NAME; /* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Account DTO. * An account that is related to an event or attribute. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class Account implements GerritJsonDTO { /** * Account user's full name. */ private String name; /** * Account user's preferred email. */ private String email; /** * Account username. */ private String username; /** * Default constructor. */ public Account() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Account(JSONObject json) { this.fromJson(json); } /** * For easier testing. * @param name the name. * @param email the email. */ public Account(String name, String email) { this.name = name; this.email = email; } @Override public void fromJson(JSONObject json) {
name = getString(json, NAME);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Account.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String EMAIL = "email"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NAME = "name"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String USERNAME = "username";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.USERNAME; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NAME;
/* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Account DTO. * An account that is related to an event or attribute. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class Account implements GerritJsonDTO { /** * Account user's full name. */ private String name; /** * Account user's preferred email. */ private String email; /** * Account username. */ private String username; /** * Default constructor. */ public Account() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Account(JSONObject json) { this.fromJson(json); } /** * For easier testing. * @param name the name. * @param email the email. */ public Account(String name, String email) { this.name = name; this.email = email; } @Override public void fromJson(JSONObject json) { name = getString(json, NAME);
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String EMAIL = "email"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NAME = "name"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String USERNAME = "username"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Account.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.USERNAME; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NAME; /* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Account DTO. * An account that is related to an event or attribute. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class Account implements GerritJsonDTO { /** * Account user's full name. */ private String name; /** * Account user's preferred email. */ private String email; /** * Account username. */ private String username; /** * Default constructor. */ public Account() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Account(JSONObject json) { this.fromJson(json); } /** * For easier testing. * @param name the name. * @param email the email. */ public Account(String name, String email) { this.name = name; this.email = email; } @Override public void fromJson(JSONObject json) { name = getString(json, NAME);
email = getString(json, EMAIL);
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Account.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String EMAIL = "email"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NAME = "name"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String USERNAME = "username";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.USERNAME; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NAME;
/* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Account DTO. * An account that is related to an event or attribute. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class Account implements GerritJsonDTO { /** * Account user's full name. */ private String name; /** * Account user's preferred email. */ private String email; /** * Account username. */ private String username; /** * Default constructor. */ public Account() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Account(JSONObject json) { this.fromJson(json); } /** * For easier testing. * @param name the name. * @param email the email. */ public Account(String name, String email) { this.name = name; this.email = email; } @Override public void fromJson(JSONObject json) { name = getString(json, NAME); email = getString(json, EMAIL);
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String EMAIL = "email"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NAME = "name"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String USERNAME = "username"; // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/Account.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.USERNAME; import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO; import net.sf.json.JSONObject; import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NAME; /* * The MIT License * * Copyright 2010 Sony Ericsson Mobile Communications. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Represents a Gerrit JSON Account DTO. * An account that is related to an event or attribute. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class Account implements GerritJsonDTO { /** * Account user's full name. */ private String name; /** * Account user's preferred email. */ private String email; /** * Account username. */ private String username; /** * Default constructor. */ public Account() { } /** * Constructor that fills with data directly. * * @param json the JSON Object with data. * @see #fromJson(net.sf.json.JSONObject) */ public Account(JSONObject json) { this.fromJson(json); } /** * For easier testing. * @param name the name. * @param email the email. */ public Account(String name, String email) { this.name = name; this.email = email; } @Override public void fromJson(JSONObject json) { name = getString(json, NAME); email = getString(json, EMAIL);
username = getString(json, USERNAME);
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit;
/* * The MIT License * * Copyright 2010 Sony Mobile Communications Inc. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet}. * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class PatchSetTest { /** * Tests {@link PatchSet#fromJson(net.sf.json.JSONObject)}. * @throws Exception if so. */ @Test public void testFromJson() throws Exception { JSONObject json = new JSONObject();
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit; /* * The MIT License * * Copyright 2010 Sony Mobile Communications Inc. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet}. * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class PatchSetTest { /** * Tests {@link PatchSet#fromJson(net.sf.json.JSONObject)}. * @throws Exception if so. */ @Test public void testFromJson() throws Exception { JSONObject json = new JSONObject();
json.put(NUMBER, "2");
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit;
/* * The MIT License * * Copyright 2010 Sony Mobile Communications Inc. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet}. * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class PatchSetTest { /** * Tests {@link PatchSet#fromJson(net.sf.json.JSONObject)}. * @throws Exception if so. */ @Test public void testFromJson() throws Exception { JSONObject json = new JSONObject(); json.put(NUMBER, "2");
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit; /* * The MIT License * * Copyright 2010 Sony Mobile Communications Inc. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet}. * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class PatchSetTest { /** * Tests {@link PatchSet#fromJson(net.sf.json.JSONObject)}. * @throws Exception if so. */ @Test public void testFromJson() throws Exception { JSONObject json = new JSONObject(); json.put(NUMBER, "2");
json.put(REVISION, "ad123456789");
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit;
/* * The MIT License * * Copyright 2010 Sony Mobile Communications Inc. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet}. * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class PatchSetTest { /** * Tests {@link PatchSet#fromJson(net.sf.json.JSONObject)}. * @throws Exception if so. */ @Test public void testFromJson() throws Exception { JSONObject json = new JSONObject(); json.put(NUMBER, "2"); json.put(REVISION, "ad123456789");
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit; /* * The MIT License * * Copyright 2010 Sony Mobile Communications Inc. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet}. * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ public class PatchSetTest { /** * Tests {@link PatchSet#fromJson(net.sf.json.JSONObject)}. * @throws Exception if so. */ @Test public void testFromJson() throws Exception { JSONObject json = new JSONObject(); json.put(NUMBER, "2"); json.put(REVISION, "ad123456789");
json.put(REF, "refs/changes/00/100/2");
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit;
* @throws Exception if so. */ @Test public void testInitFromJson() throws Exception { JSONObject json = new JSONObject(); json.put(NUMBER, "2"); json.put(REVISION, "ad123456789"); json.put(REF, "refs/changes/00/100/2"); json.put("isDraft", true); PatchSet patchSet = new PatchSet(json); assertEquals("2", patchSet.getNumber()); assertEquals("ad123456789", patchSet.getRevision()); assertEquals("refs/changes/00/100/2", patchSet.getRef()); assertEquals(true, patchSet.isDraft()); } /** * Test {@link PatchSet#PatchSet(net.sf.json.JSONObject)}. * With createdOn. * @throws Exception if so. */ @Test // CS IGNORE MagicNumber FOR NEXT 3 LINES. REASON: TestData public void testCreatedOnFromJson() throws Exception { long createdOn = 100000000L; //In gerrit, time is written in seconds, not milliseconds. long milliseconds = TimeUnit.SECONDS.toMillis(createdOn); Date createdOnAsDate = new Date(milliseconds); JSONObject json = new JSONObject();
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NUMBER = "number"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REF = "ref"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REVISION = "revision"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String CREATED_ON = "createdOn"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/PatchSetTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sf.json.JSONObject; import org.junit.Test; import java.util.Date; import java.util.concurrent.TimeUnit; * @throws Exception if so. */ @Test public void testInitFromJson() throws Exception { JSONObject json = new JSONObject(); json.put(NUMBER, "2"); json.put(REVISION, "ad123456789"); json.put(REF, "refs/changes/00/100/2"); json.put("isDraft", true); PatchSet patchSet = new PatchSet(json); assertEquals("2", patchSet.getNumber()); assertEquals("ad123456789", patchSet.getRevision()); assertEquals("refs/changes/00/100/2", patchSet.getRef()); assertEquals(true, patchSet.isDraft()); } /** * Test {@link PatchSet#PatchSet(net.sf.json.JSONObject)}. * With createdOn. * @throws Exception if so. */ @Test // CS IGNORE MagicNumber FOR NEXT 3 LINES. REASON: TestData public void testCreatedOnFromJson() throws Exception { long createdOn = 100000000L; //In gerrit, time is written in seconds, not milliseconds. long milliseconds = TimeUnit.SECONDS.toMillis(createdOn); Date createdOnAsDate = new Date(milliseconds); JSONObject json = new JSONObject();
json.put(CREATED_ON, createdOn);
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/SshUtilTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshUtil.java // public final class SshUtil { // // /** // * Default hidden constructor. // */ // private SshUtil() { // } // // /** // * Does a series of checks in the file to see if it is a valid private key file. // * @param keyFile the file // * @return true if valid. // */ // public static boolean isPrivateKeyFileValid(File keyFile) { // return parsePrivateKeyFile(keyFile) != null; // } // // /** // * Parses the keyFile hiding any Exceptions that might occur. // * @param keyFile the file. // * @return the "parsed" file. // */ // private static KeyPair parsePrivateKeyFile(File keyFile) { // if (keyFile == null) { // return null; // } // // try { // JSch jsch = new JSch(); // KeyPair key = KeyPair.load(jsch, keyFile.getAbsolutePath()); // return key; // } catch (JSchException ex) { // return null; // } // } // // /** // * Checks to see if the passPhrase is valid for the private key file. // * @param keyFilePath the private key file. // * @param passPhrase the password for the file. // * @return true if it is valid. // */ // public static boolean checkPassPhrase(File keyFilePath, String passPhrase) { // KeyPair key = parsePrivateKeyFile(keyFilePath); // boolean isValidPhrase = passPhrase != null && !passPhrase.trim().isEmpty(); // if (key == null) { // return false; // } else if (key.isEncrypted() != isValidPhrase) { // return false; // } else if (key.isEncrypted()) { // return key.decrypt(passPhrase); // } // return true; // } // }
import java.io.File; import java.net.URL; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshUtil;
package com.sonymobile.tools.gerrit.gerritevents; /** * Test that SSH keys are correctly handled for keys with and without passphrases * Created by svanoort on 9/11/15. */ public class SshUtilTest { static final String PASSPHRASE = "letmein"; /** * Test basic key file loading. * @throws Exception If test fails. */ @Test public void testBasicKeyFileLoading() throws Exception {
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshUtil.java // public final class SshUtil { // // /** // * Default hidden constructor. // */ // private SshUtil() { // } // // /** // * Does a series of checks in the file to see if it is a valid private key file. // * @param keyFile the file // * @return true if valid. // */ // public static boolean isPrivateKeyFileValid(File keyFile) { // return parsePrivateKeyFile(keyFile) != null; // } // // /** // * Parses the keyFile hiding any Exceptions that might occur. // * @param keyFile the file. // * @return the "parsed" file. // */ // private static KeyPair parsePrivateKeyFile(File keyFile) { // if (keyFile == null) { // return null; // } // // try { // JSch jsch = new JSch(); // KeyPair key = KeyPair.load(jsch, keyFile.getAbsolutePath()); // return key; // } catch (JSchException ex) { // return null; // } // } // // /** // * Checks to see if the passPhrase is valid for the private key file. // * @param keyFilePath the private key file. // * @param passPhrase the password for the file. // * @return true if it is valid. // */ // public static boolean checkPassPhrase(File keyFilePath, String passPhrase) { // KeyPair key = parsePrivateKeyFile(keyFilePath); // boolean isValidPhrase = passPhrase != null && !passPhrase.trim().isEmpty(); // if (key == null) { // return false; // } else if (key.isEncrypted() != isValidPhrase) { // return false; // } else if (key.isEncrypted()) { // return key.decrypt(passPhrase); // } // return true; // } // } // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/SshUtilTest.java import java.io.File; import java.net.URL; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshUtil; package com.sonymobile.tools.gerrit.gerritevents; /** * Test that SSH keys are correctly handled for keys with and without passphrases * Created by svanoort on 9/11/15. */ public class SshUtilTest { static final String PASSPHRASE = "letmein"; /** * Test basic key file loading. * @throws Exception If test fails. */ @Test public void testBasicKeyFileLoading() throws Exception {
boolean tested = SshUtil.isPrivateKeyFileValid(null);
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/DeserializeProviderTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/events/PatchsetCreated.java // public class PatchsetCreated extends ChangeBasedEvent implements RepositoryModifiedEvent { // // /* Uploader has been replaced by GerritTriggeredEvent.account. // * This allows old builds to deserialize without warnings. */ // @SuppressWarnings("unused") // private transient Account uploader; // // @Override // public GerritEventType getEventType() { // return GerritEventType.PATCHSET_CREATED; // } // // @Override // public boolean isScorable() { // return true; // } // // @Override // public void fromJson(JSONObject json) { // super.fromJson(json); // if (json.containsKey(UPLOADER)) { // this.account = new Account(json.getJSONObject(UPLOADER)); // } // } // // @Override // public String toString() { // return "PatchsetCreated: " + change + " " + patchSet; // } // // @Override // public String getModifiedProject() { // if (change != null) { // return change.getProject(); // } // return null; // } // // @Override // public String getModifiedRef() { // if (patchSet != null) { // return patchSet.getRef(); // } // return null; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.sonymobile.tools.gerrit.gerritevents.dto.events.PatchsetCreated; import com.thoughtworks.xstream.XStream; import org.junit.Test; import org.powermock.reflect.Whitebox; import java.io.IOException;
/* * The MIT License * * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Serialization handling test for {@link Provider}. */ public class DeserializeProviderTest { /** * Tests that reading an XStream file with the proto attribute converts to the scheme attribute. * Jenkins behaves a bit differently than XStream does out of the box, so it isn't a fully comparable test. * * @throws IOException if so. */ @Test public void testProtoToScheme() throws IOException { //Provider = "Default", "review", "29418", "ssh", "http://review:8080/", "2.6" XStream x = new XStream(); x.aliasPackage("com.sonyericsson.hudson.plugins.gerrit.gerritevents", "com.sonymobile.tools.gerrit.gerritevents"); x.allowTypesByWildcard(new String[]{"com.sonymobile.tools.gerrit.gerritevents.dto.**"});
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/events/PatchsetCreated.java // public class PatchsetCreated extends ChangeBasedEvent implements RepositoryModifiedEvent { // // /* Uploader has been replaced by GerritTriggeredEvent.account. // * This allows old builds to deserialize without warnings. */ // @SuppressWarnings("unused") // private transient Account uploader; // // @Override // public GerritEventType getEventType() { // return GerritEventType.PATCHSET_CREATED; // } // // @Override // public boolean isScorable() { // return true; // } // // @Override // public void fromJson(JSONObject json) { // super.fromJson(json); // if (json.containsKey(UPLOADER)) { // this.account = new Account(json.getJSONObject(UPLOADER)); // } // } // // @Override // public String toString() { // return "PatchsetCreated: " + change + " " + patchSet; // } // // @Override // public String getModifiedProject() { // if (change != null) { // return change.getProject(); // } // return null; // } // // @Override // public String getModifiedRef() { // if (patchSet != null) { // return patchSet.getRef(); // } // return null; // } // } // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/DeserializeProviderTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.sonymobile.tools.gerrit.gerritevents.dto.events.PatchsetCreated; import com.thoughtworks.xstream.XStream; import org.junit.Test; import org.powermock.reflect.Whitebox; import java.io.IOException; /* * The MIT License * * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Serialization handling test for {@link Provider}. */ public class DeserializeProviderTest { /** * Tests that reading an XStream file with the proto attribute converts to the scheme attribute. * Jenkins behaves a bit differently than XStream does out of the box, so it isn't a fully comparable test. * * @throws IOException if so. */ @Test public void testProtoToScheme() throws IOException { //Provider = "Default", "review", "29418", "ssh", "http://review:8080/", "2.6" XStream x = new XStream(); x.aliasPackage("com.sonyericsson.hudson.plugins.gerrit.gerritevents", "com.sonymobile.tools.gerrit.gerritevents"); x.allowTypesByWildcard(new String[]{"com.sonymobile.tools.gerrit.gerritevents.dto.**"});
PatchsetCreated event = (PatchsetCreated)x.fromXML(getClass()
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/workers/rest/AbstractRestCommandJob.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ChangeId.java // public class ChangeId { // private static final Logger logger = LoggerFactory.getLogger(ChangeId.class); // // private final String projectName; // private final String branchName; // private final String id; // // /** // * Constructor. // * // * @param projectName project name // * @param branchName branch name // * @param id id // */ // public ChangeId(String projectName, String branchName, String id) { // this.projectName = projectName; // this.branchName = branchName; // this.id = id; // } // // /** // * Constructor getting values from a change object. // * // * @param change the change // * @see #ChangeId(String, String, String) // */ // public ChangeId(Change change) { // this(change.getProject(), change.getBranch(), change.getId()); // } // // /** // * As the part of the URL. // * // * @return the url part. // */ // public String asUrlPart() { // try { // return encode(projectName) + "~" + encode(branchName) + "~" + id; // } catch (UnsupportedEncodingException e) { // String parameter = projectName + "~" + branchName + "~" + id; // logger.error("Failed to encode ChangeId {}, falling back to unencoded {}", this, parameter); // return parameter; // } // } // // /** // * Encode given String for usage in URL. UTF-8 is used as per recommendation // * at http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // * @param s String to be encoded // * @return Encoded string // * @throws UnsupportedEncodingException if UTF-8 is unsupported, handled in caller for better log message // */ // private String encode(final String s) throws UnsupportedEncodingException { // return URLEncoder.encode(s, CharEncoding.UTF_8); // } // // @Override // public String toString() { // return "ChangeId{" // + "projectName='" + projectName + '\'' // + ", branchName='" + branchName + '\'' // + ", id='" + id + '\'' // + '}'; // } // } // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/rest/RestConnectionConfig.java // public interface RestConnectionConfig { // // /** // * Base URL for Gerrit HTTP. // * // * @return the gerrit front end URL. Always ends with '/' // */ // String getGerritFrontEndUrl(); // // /** // * The credentials to use when connecting with the REST API. // * For example a {@link org.apache.http.auth.UsernamePasswordCredentials}. // * // * @return the credentials to use. // */ // Credentials getHttpCredentials(); // // /** // * The http or socks5 proxy url. // * // * @return the proxy url. // */ // String getGerritProxy(); // }
import com.google.gson.Gson; import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ChangeId; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ReviewInput; import com.sonymobile.tools.gerrit.gerritevents.rest.RestConnectionConfig; import org.apache.http.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL;
/* * The MIT License * * Copyright 2013 Jyrki Puttonen. All rights reserved. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.workers.rest; /** * An abstract Job implementation * to be scheduled on {@link com.sonymobile.tools.gerrit.gerritevents.GerritSendCommandQueue}. * */ public abstract class AbstractRestCommandJob implements Runnable { private static final Logger logger = LoggerFactory.getLogger(AbstractRestCommandJob.class); /** * The GSON API. */ private static final Gson GSON = new Gson(); /** * The config. */
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ChangeId.java // public class ChangeId { // private static final Logger logger = LoggerFactory.getLogger(ChangeId.class); // // private final String projectName; // private final String branchName; // private final String id; // // /** // * Constructor. // * // * @param projectName project name // * @param branchName branch name // * @param id id // */ // public ChangeId(String projectName, String branchName, String id) { // this.projectName = projectName; // this.branchName = branchName; // this.id = id; // } // // /** // * Constructor getting values from a change object. // * // * @param change the change // * @see #ChangeId(String, String, String) // */ // public ChangeId(Change change) { // this(change.getProject(), change.getBranch(), change.getId()); // } // // /** // * As the part of the URL. // * // * @return the url part. // */ // public String asUrlPart() { // try { // return encode(projectName) + "~" + encode(branchName) + "~" + id; // } catch (UnsupportedEncodingException e) { // String parameter = projectName + "~" + branchName + "~" + id; // logger.error("Failed to encode ChangeId {}, falling back to unencoded {}", this, parameter); // return parameter; // } // } // // /** // * Encode given String for usage in URL. UTF-8 is used as per recommendation // * at http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // * @param s String to be encoded // * @return Encoded string // * @throws UnsupportedEncodingException if UTF-8 is unsupported, handled in caller for better log message // */ // private String encode(final String s) throws UnsupportedEncodingException { // return URLEncoder.encode(s, CharEncoding.UTF_8); // } // // @Override // public String toString() { // return "ChangeId{" // + "projectName='" + projectName + '\'' // + ", branchName='" + branchName + '\'' // + ", id='" + id + '\'' // + '}'; // } // } // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/rest/RestConnectionConfig.java // public interface RestConnectionConfig { // // /** // * Base URL for Gerrit HTTP. // * // * @return the gerrit front end URL. Always ends with '/' // */ // String getGerritFrontEndUrl(); // // /** // * The credentials to use when connecting with the REST API. // * For example a {@link org.apache.http.auth.UsernamePasswordCredentials}. // * // * @return the credentials to use. // */ // Credentials getHttpCredentials(); // // /** // * The http or socks5 proxy url. // * // * @return the proxy url. // */ // String getGerritProxy(); // } // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/workers/rest/AbstractRestCommandJob.java import com.google.gson.Gson; import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ChangeId; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ReviewInput; import com.sonymobile.tools.gerrit.gerritevents.rest.RestConnectionConfig; import org.apache.http.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; /* * The MIT License * * Copyright 2013 Jyrki Puttonen. All rights reserved. * Copyright 2013 Sony Mobile Communications AB. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.workers.rest; /** * An abstract Job implementation * to be scheduled on {@link com.sonymobile.tools.gerrit.gerritevents.GerritSendCommandQueue}. * */ public abstract class AbstractRestCommandJob implements Runnable { private static final Logger logger = LoggerFactory.getLogger(AbstractRestCommandJob.class); /** * The GSON API. */ private static final Gson GSON = new Gson(); /** * The config. */
private final RestConnectionConfig config;
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/workers/rest/AbstractRestCommandJob.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ChangeId.java // public class ChangeId { // private static final Logger logger = LoggerFactory.getLogger(ChangeId.class); // // private final String projectName; // private final String branchName; // private final String id; // // /** // * Constructor. // * // * @param projectName project name // * @param branchName branch name // * @param id id // */ // public ChangeId(String projectName, String branchName, String id) { // this.projectName = projectName; // this.branchName = branchName; // this.id = id; // } // // /** // * Constructor getting values from a change object. // * // * @param change the change // * @see #ChangeId(String, String, String) // */ // public ChangeId(Change change) { // this(change.getProject(), change.getBranch(), change.getId()); // } // // /** // * As the part of the URL. // * // * @return the url part. // */ // public String asUrlPart() { // try { // return encode(projectName) + "~" + encode(branchName) + "~" + id; // } catch (UnsupportedEncodingException e) { // String parameter = projectName + "~" + branchName + "~" + id; // logger.error("Failed to encode ChangeId {}, falling back to unencoded {}", this, parameter); // return parameter; // } // } // // /** // * Encode given String for usage in URL. UTF-8 is used as per recommendation // * at http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // * @param s String to be encoded // * @return Encoded string // * @throws UnsupportedEncodingException if UTF-8 is unsupported, handled in caller for better log message // */ // private String encode(final String s) throws UnsupportedEncodingException { // return URLEncoder.encode(s, CharEncoding.UTF_8); // } // // @Override // public String toString() { // return "ChangeId{" // + "projectName='" + projectName + '\'' // + ", branchName='" + branchName + '\'' // + ", id='" + id + '\'' // + '}'; // } // } // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/rest/RestConnectionConfig.java // public interface RestConnectionConfig { // // /** // * Base URL for Gerrit HTTP. // * // * @return the gerrit front end URL. Always ends with '/' // */ // String getGerritFrontEndUrl(); // // /** // * The credentials to use when connecting with the REST API. // * For example a {@link org.apache.http.auth.UsernamePasswordCredentials}. // * // * @return the credentials to use. // */ // Credentials getHttpCredentials(); // // /** // * The http or socks5 proxy url. // * // * @return the proxy url. // */ // String getGerritProxy(); // }
import com.google.gson.Gson; import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ChangeId; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ReviewInput; import com.sonymobile.tools.gerrit.gerritevents.rest.RestConnectionConfig; import org.apache.http.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL;
HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (UnsupportedEncodingException e) { logger.error("Failed to create JSON for posting to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to create JSON for posting to Gerrit: " + e.toString()); } return null; } entity.setContentType("application/json"); httpPost.setEntity(entity); return httpPost; } /** * What it says resolve Endpoint URL. * * @return the url. */ private String resolveEndpointURL() { String gerritFrontEndUrl = config.getGerritFrontEndUrl(); if (!gerritFrontEndUrl.endsWith("/")) { gerritFrontEndUrl = gerritFrontEndUrl + "/"; }
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ChangeId.java // public class ChangeId { // private static final Logger logger = LoggerFactory.getLogger(ChangeId.class); // // private final String projectName; // private final String branchName; // private final String id; // // /** // * Constructor. // * // * @param projectName project name // * @param branchName branch name // * @param id id // */ // public ChangeId(String projectName, String branchName, String id) { // this.projectName = projectName; // this.branchName = branchName; // this.id = id; // } // // /** // * Constructor getting values from a change object. // * // * @param change the change // * @see #ChangeId(String, String, String) // */ // public ChangeId(Change change) { // this(change.getProject(), change.getBranch(), change.getId()); // } // // /** // * As the part of the URL. // * // * @return the url part. // */ // public String asUrlPart() { // try { // return encode(projectName) + "~" + encode(branchName) + "~" + id; // } catch (UnsupportedEncodingException e) { // String parameter = projectName + "~" + branchName + "~" + id; // logger.error("Failed to encode ChangeId {}, falling back to unencoded {}", this, parameter); // return parameter; // } // } // // /** // * Encode given String for usage in URL. UTF-8 is used as per recommendation // * at http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // * @param s String to be encoded // * @return Encoded string // * @throws UnsupportedEncodingException if UTF-8 is unsupported, handled in caller for better log message // */ // private String encode(final String s) throws UnsupportedEncodingException { // return URLEncoder.encode(s, CharEncoding.UTF_8); // } // // @Override // public String toString() { // return "ChangeId{" // + "projectName='" + projectName + '\'' // + ", branchName='" + branchName + '\'' // + ", id='" + id + '\'' // + '}'; // } // } // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/rest/RestConnectionConfig.java // public interface RestConnectionConfig { // // /** // * Base URL for Gerrit HTTP. // * // * @return the gerrit front end URL. Always ends with '/' // */ // String getGerritFrontEndUrl(); // // /** // * The credentials to use when connecting with the REST API. // * For example a {@link org.apache.http.auth.UsernamePasswordCredentials}. // * // * @return the credentials to use. // */ // Credentials getHttpCredentials(); // // /** // * The http or socks5 proxy url. // * // * @return the proxy url. // */ // String getGerritProxy(); // } // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/workers/rest/AbstractRestCommandJob.java import com.google.gson.Gson; import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ChangeId; import com.sonymobile.tools.gerrit.gerritevents.dto.rest.ReviewInput; import com.sonymobile.tools.gerrit.gerritevents.rest.RestConnectionConfig; import org.apache.http.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (UnsupportedEncodingException e) { logger.error("Failed to create JSON for posting to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to create JSON for posting to Gerrit: " + e.toString()); } return null; } entity.setContentType("application/json"); httpPost.setEntity(entity); return httpPost; } /** * What it says resolve Endpoint URL. * * @return the url. */ private String resolveEndpointURL() { String gerritFrontEndUrl = config.getGerritFrontEndUrl(); if (!gerritFrontEndUrl.endsWith("/")) { gerritFrontEndUrl = gerritFrontEndUrl + "/"; }
ChangeId changeId = new ChangeId(event.getChange().getProject(), event.getChange().getBranch(),
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME;
/* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject();
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; /* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject();
json.put(PROJECT, "abc");
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME;
/* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject(); json.put(PROJECT, "abc");
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; /* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject(); json.put(PROJECT, "abc");
json.put(OLDREV, "ad123456789");
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME;
/* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject(); json.put(PROJECT, "abc"); json.put(OLDREV, "ad123456789");
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; /* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject(); json.put(PROJECT, "abc"); json.put(OLDREV, "ad123456789");
json.put(NEWREV, "cd123456789");
sonyxperiadev/gerrit-events
src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project";
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME;
/* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject(); json.put(PROJECT, "abc"); json.put(OLDREV, "ad123456789"); json.put(NEWREV, "cd123456789");
// Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String OLDREV = "oldRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String NEWREV = "newRev"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String REFNAME = "refName"; // // Path: src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/GerritEventKeys.java // public static final String PROJECT = "project"; // Path: src/test/java/com/sonymobile/tools/gerrit/gerritevents/dto/attr/RefUpdatedTest.java import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PROJECT; import static org.junit.Assert.assertEquals; import net.sf.json.JSONObject; import org.junit.Test; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.OLDREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NEWREV; import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REFNAME; /* * The MIT License * * Copyright 2015 Ericsson. All rights reserved. * * 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 com.sonymobile.tools.gerrit.gerritevents.dto.attr; /** * Tests {@link com.sonymobile.tools.gerrit.gerritevents.dto.attr.RefUpdate}. */ public class RefUpdatedTest { /** * Test to verify that getRefName returns branch name when * event contains long name. * @throws Exception if so. */ @Test public void testLongRefName() throws Exception { JSONObject json = new JSONObject(); json.put(PROJECT, "abc"); json.put(OLDREV, "ad123456789"); json.put(NEWREV, "cd123456789");
json.put(REFNAME, "refs/heads/master");
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/commands/owner/SetnameCmd.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // }
import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; import net.dv8tion.jda.api.exceptions.RateLimitedException;
/* * Copyright 2018 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SetnameCmd extends OwnerCommand {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/commands/owner/SetnameCmd.java import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; import net.dv8tion.jda.api.exceptions.RateLimitedException; /* * Copyright 2018 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SetnameCmd extends OwnerCommand {
public SetnameCmd(Bot bot)
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/commands/owner/SetstatusCmd.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // }
import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; import net.dv8tion.jda.api.OnlineStatus;
/* * Copyright 2017 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SetstatusCmd extends OwnerCommand {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/commands/owner/SetstatusCmd.java import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; import net.dv8tion.jda.api.OnlineStatus; /* * Copyright 2017 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SetstatusCmd extends OwnerCommand {
public SetstatusCmd(Bot bot)
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/commands/owner/ShutdownCmd.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // }
import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand;
/* * Copyright 2017 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class ShutdownCmd extends OwnerCommand {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/commands/owner/ShutdownCmd.java import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; /* * Copyright 2017 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class ShutdownCmd extends OwnerCommand {
private final Bot bot;
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/commands/owner/SetgameCmd.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // }
import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; import net.dv8tion.jda.api.entities.Activity;
/* * Copyright 2017 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SetgameCmd extends OwnerCommand {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/commands/owner/SetgameCmd.java import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; import net.dv8tion.jda.api.entities.Activity; /* * Copyright 2017 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SetgameCmd extends OwnerCommand {
public SetgameCmd(Bot bot)
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/gui/GUI.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // }
import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import com.jagrosh.jmusicbot.Bot;
/* * Copyright 2016 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.gui; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class GUI extends JFrame { private final ConsolePanel console;
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/gui/GUI.java import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import com.jagrosh.jmusicbot.Bot; /* * Copyright 2016 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.gui; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class GUI extends JFrame { private final ConsolePanel console;
private final Bot bot;
jagrosh/MusicBot
src/test/java/com/jagrosh/jmusicbot/FairQueueTest.java
// Path: src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java // public class FairQueue<T extends Queueable> { // private final List<T> list = new ArrayList<>(); // private final Set<Long> set = new HashSet<>(); // // public int add(T item) // { // int lastIndex; // for(lastIndex=list.size()-1; lastIndex>-1; lastIndex--) // if(list.get(lastIndex).getIdentifier()==item.getIdentifier()) // break; // lastIndex++; // set.clear(); // for(; lastIndex<list.size(); lastIndex++) // { // if(set.contains(list.get(lastIndex).getIdentifier())) // break; // set.add(list.get(lastIndex).getIdentifier()); // } // list.add(lastIndex, item); // return lastIndex; // } // // public void addAt(int index, T item) // { // if(index >= list.size()) // list.add(item); // else // list.add(index, item); // } // // public int size() // { // return list.size(); // } // // public T pull() // { // return list.remove(0); // } // // public boolean isEmpty() // { // return list.isEmpty(); // } // // public List<T> getList() // { // return list; // } // // public T get(int index) // { // return list.get(index); // } // // public T remove(int index) // { // return list.remove(index); // } // // public int removeAll(long identifier) // { // int count = 0; // for(int i=list.size()-1; i>=0; i--) // { // if(list.get(i).getIdentifier()==identifier) // { // list.remove(i); // count++; // } // } // return count; // } // // public void clear() // { // list.clear(); // } // // public int shuffle(long identifier) // { // List<Integer> iset = new ArrayList<>(); // for(int i=0; i<list.size(); i++) // { // if(list.get(i).getIdentifier()==identifier) // iset.add(i); // } // for(int j=0; j<iset.size(); j++) // { // int first = iset.get(j); // int second = iset.get((int)(Math.random()*iset.size())); // T temp = list.get(first); // list.set(first, list.get(second)); // list.set(second, temp); // } // return iset.size(); // } // // public void skip(int number) // { // for(int i=0; i<number; i++) // list.remove(0); // } // // /** // * Move an item to a different position in the list // * @param from The position of the item // * @param to The new position of the item // * @return the moved item // */ // public T moveItem(int from, int to) // { // T item = list.remove(from); // list.add(to, item); // return item; // } // }
import com.jagrosh.jmusicbot.queue.FairQueue; import com.jagrosh.jmusicbot.queue.Queueable; import org.junit.Test; import static org.junit.Assert.*;
/* * Copyright 2018 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot; /** * * @author John Grosh (john.a.grosh@gmail.com) */ public class FairQueueTest { @Test public void differentIdentifierSize() {
// Path: src/main/java/com/jagrosh/jmusicbot/queue/FairQueue.java // public class FairQueue<T extends Queueable> { // private final List<T> list = new ArrayList<>(); // private final Set<Long> set = new HashSet<>(); // // public int add(T item) // { // int lastIndex; // for(lastIndex=list.size()-1; lastIndex>-1; lastIndex--) // if(list.get(lastIndex).getIdentifier()==item.getIdentifier()) // break; // lastIndex++; // set.clear(); // for(; lastIndex<list.size(); lastIndex++) // { // if(set.contains(list.get(lastIndex).getIdentifier())) // break; // set.add(list.get(lastIndex).getIdentifier()); // } // list.add(lastIndex, item); // return lastIndex; // } // // public void addAt(int index, T item) // { // if(index >= list.size()) // list.add(item); // else // list.add(index, item); // } // // public int size() // { // return list.size(); // } // // public T pull() // { // return list.remove(0); // } // // public boolean isEmpty() // { // return list.isEmpty(); // } // // public List<T> getList() // { // return list; // } // // public T get(int index) // { // return list.get(index); // } // // public T remove(int index) // { // return list.remove(index); // } // // public int removeAll(long identifier) // { // int count = 0; // for(int i=list.size()-1; i>=0; i--) // { // if(list.get(i).getIdentifier()==identifier) // { // list.remove(i); // count++; // } // } // return count; // } // // public void clear() // { // list.clear(); // } // // public int shuffle(long identifier) // { // List<Integer> iset = new ArrayList<>(); // for(int i=0; i<list.size(); i++) // { // if(list.get(i).getIdentifier()==identifier) // iset.add(i); // } // for(int j=0; j<iset.size(); j++) // { // int first = iset.get(j); // int second = iset.get((int)(Math.random()*iset.size())); // T temp = list.get(first); // list.set(first, list.get(second)); // list.set(second, temp); // } // return iset.size(); // } // // public void skip(int number) // { // for(int i=0; i<number; i++) // list.remove(0); // } // // /** // * Move an item to a different position in the list // * @param from The position of the item // * @param to The new position of the item // * @return the moved item // */ // public T moveItem(int from, int to) // { // T item = list.remove(from); // list.add(to, item); // return item; // } // } // Path: src/test/java/com/jagrosh/jmusicbot/FairQueueTest.java import com.jagrosh.jmusicbot.queue.FairQueue; import com.jagrosh.jmusicbot.queue.Queueable; import org.junit.Test; import static org.junit.Assert.*; /* * Copyright 2018 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot; /** * * @author John Grosh (john.a.grosh@gmail.com) */ public class FairQueueTest { @Test public void differentIdentifierSize() {
FairQueue<Q> queue = new FairQueue<>();
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // }
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand;
/* * Copyright 2016 John Grosh (jagrosh). * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh (jagrosh) */ public class EvalCmd extends OwnerCommand {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // // Path: src/main/java/com/jagrosh/jmusicbot/commands/OwnerCommand.java // public abstract class OwnerCommand extends Command // { // public OwnerCommand() // { // this.category = new Category("Owner"); // this.ownerCommand = true; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/commands/owner/EvalCmd.java import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.commands.OwnerCommand; /* * Copyright 2016 John Grosh (jagrosh). * * 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.jagrosh.jmusicbot.commands.owner; /** * * @author John Grosh (jagrosh) */ public class EvalCmd extends OwnerCommand {
private final Bot bot;
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/audio/AloneInVoiceHandler.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // }
import com.jagrosh.jmusicbot.Bot; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent; import java.time.Instant; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit;
/* * Copyright 2021 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.audio; /** * * @author Michaili K (mysteriouscursor+git@protonmail.com) */ public class AloneInVoiceHandler {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/audio/AloneInVoiceHandler.java import com.jagrosh.jmusicbot.Bot; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent; import java.time.Instant; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /* * Copyright 2021 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.audio; /** * * @author Michaili K (mysteriouscursor+git@protonmail.com) */ public class AloneInVoiceHandler {
private final Bot bot;
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/commands/music/SCSearchCmd.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // }
import com.jagrosh.jmusicbot.Bot;
/* * Copyright 2016 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.music; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SCSearchCmd extends SearchCmd {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/commands/music/SCSearchCmd.java import com.jagrosh.jmusicbot.Bot; /* * Copyright 2016 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.commands.music; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SCSearchCmd extends SearchCmd {
public SCSearchCmd(Bot bot)
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // }
import com.jagrosh.jmusicbot.Bot; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager; import com.typesafe.config.Config; import net.dv8tion.jda.api.entities.Guild;
/* * Copyright 2018 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.audio; /** * * @author John Grosh (john.a.grosh@gmail.com) */ public class PlayerManager extends DefaultAudioPlayerManager {
// Path: src/main/java/com/jagrosh/jmusicbot/Bot.java // public class Bot // { // private final EventWaiter waiter; // private final ScheduledExecutorService threadpool; // private final BotConfig config; // private final SettingsManager settings; // private final PlayerManager players; // private final PlaylistLoader playlists; // private final NowplayingHandler nowplaying; // private final AloneInVoiceHandler aloneInVoiceHandler; // // private boolean shuttingDown = false; // private JDA jda; // private GUI gui; // // public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings) // { // this.waiter = waiter; // this.config = config; // this.settings = settings; // this.playlists = new PlaylistLoader(config); // this.threadpool = Executors.newSingleThreadScheduledExecutor(); // this.players = new PlayerManager(this); // this.players.init(); // this.nowplaying = new NowplayingHandler(this); // this.nowplaying.init(); // this.aloneInVoiceHandler = new AloneInVoiceHandler(this); // this.aloneInVoiceHandler.init(); // } // // public BotConfig getConfig() // { // return config; // } // // public SettingsManager getSettingsManager() // { // return settings; // } // // public EventWaiter getWaiter() // { // return waiter; // } // // public ScheduledExecutorService getThreadpool() // { // return threadpool; // } // // public PlayerManager getPlayerManager() // { // return players; // } // // public PlaylistLoader getPlaylistLoader() // { // return playlists; // } // // public NowplayingHandler getNowplayingHandler() // { // return nowplaying; // } // // public AloneInVoiceHandler getAloneInVoiceHandler() // { // return aloneInVoiceHandler; // } // // public JDA getJDA() // { // return jda; // } // // public void closeAudioConnection(long guildId) // { // Guild guild = jda.getGuildById(guildId); // if(guild!=null) // threadpool.submit(() -> guild.getAudioManager().closeAudioConnection()); // } // // public void resetGame() // { // Activity game = config.getGame()==null || config.getGame().getName().equalsIgnoreCase("none") ? null : config.getGame(); // if(!Objects.equals(jda.getPresence().getActivity(), game)) // jda.getPresence().setActivity(game); // } // // public void shutdown() // { // if(shuttingDown) // return; // shuttingDown = true; // threadpool.shutdownNow(); // if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) // { // jda.getGuilds().stream().forEach(g -> // { // g.getAudioManager().closeAudioConnection(); // AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); // if(ah!=null) // { // ah.stopAndClear(); // ah.getPlayer().destroy(); // nowplaying.updateTopic(g.getIdLong(), ah, true); // } // }); // jda.shutdown(); // } // if(gui!=null) // gui.dispose(); // System.exit(0); // } // // public void setJDA(JDA jda) // { // this.jda = jda; // } // // public void setGUI(GUI gui) // { // this.gui = gui; // } // } // Path: src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java import com.jagrosh.jmusicbot.Bot; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager; import com.typesafe.config.Config; import net.dv8tion.jda.api.entities.Guild; /* * Copyright 2018 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.audio; /** * * @author John Grosh (john.a.grosh@gmail.com) */ public class PlayerManager extends DefaultAudioPlayerManager {
private final Bot bot;
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java
// Path: src/main/java/com/jagrosh/jmusicbot/utils/FormatUtil.java // public class FormatUtil { // // public static String formatTime(long duration) // { // if(duration == Long.MAX_VALUE) // return "LIVE"; // long seconds = Math.round(duration/1000.0); // long hours = seconds/(60*60); // seconds %= 60*60; // long minutes = seconds/60; // seconds %= 60; // return (hours>0 ? hours+":" : "") + (minutes<10 ? "0"+minutes : minutes) + ":" + (seconds<10 ? "0"+seconds : seconds); // } // // public static String progressBar(double percent) // { // String str = ""; // for(int i=0; i<12; i++) // if(i == (int)(percent*12)) // str+="\uD83D\uDD18"; // 🔘 // else // str+="▬"; // return str; // } // // public static String volumeIcon(int volume) // { // if(volume == 0) // return "\uD83D\uDD07"; // 🔇 // if(volume < 30) // return "\uD83D\uDD08"; // 🔈 // if(volume < 70) // return "\uD83D\uDD09"; // 🔉 // return "\uD83D\uDD0A"; // 🔊 // } // // public static String listOfTChannels(List<TextChannel> list, String query) // { // String out = " Multiple text channels found matching \""+query+"\":"; // for(int i=0; i<6 && i<list.size(); i++) // out+="\n - "+list.get(i).getName()+" (<#"+list.get(i).getId()+">)"; // if(list.size()>6) // out+="\n**And "+(list.size()-6)+" more...**"; // return out; // } // // public static String listOfVChannels(List<VoiceChannel> list, String query) // { // String out = " Multiple voice channels found matching \""+query+"\":"; // for(int i=0; i<6 && i<list.size(); i++) // out+="\n - "+list.get(i).getAsMention()+" (ID:"+list.get(i).getId()+")"; // if(list.size()>6) // out+="\n**And "+(list.size()-6)+" more...**"; // return out; // } // // public static String listOfRoles(List<Role> list, String query) // { // String out = " Multiple text channels found matching \""+query+"\":"; // for(int i=0; i<6 && i<list.size(); i++) // out+="\n - "+list.get(i).getName()+" (ID:"+list.get(i).getId()+")"; // if(list.size()>6) // out+="\n**And "+(list.size()-6)+" more...**"; // return out; // } // // public static String filter(String input) // { // return input.replace("\u202E","") // .replace("@everyone", "@\u0435veryone") // cyrillic letter e // .replace("@here", "@h\u0435re") // cyrillic letter e // .trim(); // } // }
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.jagrosh.jmusicbot.queue.Queueable; import com.jagrosh.jmusicbot.utils.FormatUtil; import net.dv8tion.jda.api.entities.User;
/* * Copyright 2021 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.audio; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class QueuedTrack implements Queueable { private final AudioTrack track; public QueuedTrack(AudioTrack track, User owner) { this(track, new RequestMetadata(owner)); } public QueuedTrack(AudioTrack track, RequestMetadata rm) { this.track = track; this.track.setUserData(rm); } @Override public long getIdentifier() { return track.getUserData(RequestMetadata.class).getOwner(); } public AudioTrack getTrack() { return track; } @Override public String toString() {
// Path: src/main/java/com/jagrosh/jmusicbot/utils/FormatUtil.java // public class FormatUtil { // // public static String formatTime(long duration) // { // if(duration == Long.MAX_VALUE) // return "LIVE"; // long seconds = Math.round(duration/1000.0); // long hours = seconds/(60*60); // seconds %= 60*60; // long minutes = seconds/60; // seconds %= 60; // return (hours>0 ? hours+":" : "") + (minutes<10 ? "0"+minutes : minutes) + ":" + (seconds<10 ? "0"+seconds : seconds); // } // // public static String progressBar(double percent) // { // String str = ""; // for(int i=0; i<12; i++) // if(i == (int)(percent*12)) // str+="\uD83D\uDD18"; // 🔘 // else // str+="▬"; // return str; // } // // public static String volumeIcon(int volume) // { // if(volume == 0) // return "\uD83D\uDD07"; // 🔇 // if(volume < 30) // return "\uD83D\uDD08"; // 🔈 // if(volume < 70) // return "\uD83D\uDD09"; // 🔉 // return "\uD83D\uDD0A"; // 🔊 // } // // public static String listOfTChannels(List<TextChannel> list, String query) // { // String out = " Multiple text channels found matching \""+query+"\":"; // for(int i=0; i<6 && i<list.size(); i++) // out+="\n - "+list.get(i).getName()+" (<#"+list.get(i).getId()+">)"; // if(list.size()>6) // out+="\n**And "+(list.size()-6)+" more...**"; // return out; // } // // public static String listOfVChannels(List<VoiceChannel> list, String query) // { // String out = " Multiple voice channels found matching \""+query+"\":"; // for(int i=0; i<6 && i<list.size(); i++) // out+="\n - "+list.get(i).getAsMention()+" (ID:"+list.get(i).getId()+")"; // if(list.size()>6) // out+="\n**And "+(list.size()-6)+" more...**"; // return out; // } // // public static String listOfRoles(List<Role> list, String query) // { // String out = " Multiple text channels found matching \""+query+"\":"; // for(int i=0; i<6 && i<list.size(); i++) // out+="\n - "+list.get(i).getName()+" (ID:"+list.get(i).getId()+")"; // if(list.size()>6) // out+="\n**And "+(list.size()-6)+" more...**"; // return out; // } // // public static String filter(String input) // { // return input.replace("\u202E","") // .replace("@everyone", "@\u0435veryone") // cyrillic letter e // .replace("@here", "@h\u0435re") // cyrillic letter e // .trim(); // } // } // Path: src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.jagrosh.jmusicbot.queue.Queueable; import com.jagrosh.jmusicbot.utils.FormatUtil; import net.dv8tion.jda.api.entities.User; /* * Copyright 2021 John Grosh <john.a.grosh@gmail.com>. * * 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.jagrosh.jmusicbot.audio; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class QueuedTrack implements Queueable { private final AudioTrack track; public QueuedTrack(AudioTrack track, User owner) { this(track, new RequestMetadata(owner)); } public QueuedTrack(AudioTrack track, RequestMetadata rm) { this.track = track; this.track.setUserData(rm); } @Override public long getIdentifier() { return track.getUserData(RequestMetadata.class).getOwner(); } public AudioTrack getTrack() { return track; } @Override public String toString() {
return "`[" + FormatUtil.formatTime(track.getDuration()) + "]` [**" + track.getInfo().title + "**]("+track.getInfo().uri+") - <@" + track.getUserData(RequestMetadata.class).getOwner() + ">";
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/IntDictionaryEncoder.java
// Path: hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/SizeOf.java // public final class SizeOf // { // public static final byte SIZE_OF_BYTE = 1; // public static final byte SIZE_OF_SHORT = 2; // public static final byte SIZE_OF_INT = 4; // public static final byte SIZE_OF_LONG = 8; // public static final byte SIZE_OF_FLOAT = 4; // public static final byte SIZE_OF_DOUBLE = 8; // // private static final Unsafe UNSAFE; // static { // try { // // fetch theUnsafe object // Field field = Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // UNSAFE = (Unsafe) field.get(null); // if (UNSAFE == null) { // throw new RuntimeException("Unsafe access not available"); // } // } // catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static final int ARRAY_BOOLEAN_BASE_OFFSET = UNSAFE.arrayBaseOffset(boolean[].class); // public static final int ARRAY_BOOLEAN_INDEX_SCALE = UNSAFE.arrayIndexScale(boolean[].class); // public static final int ARRAY_BYTE_BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class); // public static final int ARRAY_BYTE_INDEX_SCALE = UNSAFE.arrayIndexScale(byte[].class); // public static final int ARRAY_SHORT_BASE_OFFSET = UNSAFE.arrayBaseOffset(short[].class); // public static final int ARRAY_SHORT_INDEX_SCALE = UNSAFE.arrayIndexScale(short[].class); // public static final int ARRAY_INT_BASE_OFFSET = UNSAFE.arrayBaseOffset(int[].class); // public static final int ARRAY_INT_INDEX_SCALE = UNSAFE.arrayIndexScale(int[].class); // public static final int ARRAY_LONG_BASE_OFFSET = UNSAFE.arrayBaseOffset(long[].class); // public static final int ARRAY_LONG_INDEX_SCALE = UNSAFE.arrayIndexScale(long[].class); // public static final int ARRAY_FLOAT_BASE_OFFSET = UNSAFE.arrayBaseOffset(float[].class); // public static final int ARRAY_FLOAT_INDEX_SCALE = UNSAFE.arrayIndexScale(float[].class); // public static final int ARRAY_DOUBLE_BASE_OFFSET = UNSAFE.arrayBaseOffset(double[].class); // public static final int ARRAY_DOUBLE_INDEX_SCALE = UNSAFE.arrayIndexScale(double[].class); // public static final int ARRAY_OBJECT_BASE_OFFSET = UNSAFE.arrayBaseOffset(Object[].class); // public static final int ARRAY_OBJECT_INDEX_SCALE = UNSAFE.arrayIndexScale(Object[].class); // // public static long sizeOf(boolean[] array) // { // if (array == null) { // return 0; // } // // return ARRAY_BOOLEAN_BASE_OFFSET + ((long) ARRAY_BOOLEAN_INDEX_SCALE * array.length); // } // // public static long sizeOf(byte[] array) // { // if (array == null) { // return 0; // } // return ARRAY_BYTE_BASE_OFFSET + ((long) ARRAY_BYTE_INDEX_SCALE * array.length); // } // // public static long sizeOf(short[] array) // { // if (array == null) { // return 0; // } // return ARRAY_SHORT_BASE_OFFSET + ((long) ARRAY_SHORT_INDEX_SCALE * array.length); // } // // public static long sizeOf(int[] array) // { // if (array == null) { // return 0; // } // return ARRAY_INT_BASE_OFFSET + ((long) ARRAY_INT_INDEX_SCALE * array.length); // } // // public static long sizeOf(long[] array) // { // if (array == null) { // return 0; // } // return ARRAY_LONG_BASE_OFFSET + ((long) ARRAY_LONG_INDEX_SCALE * array.length); // } // // public static long sizeOf(float[] array) // { // if (array == null) { // return 0; // } // return ARRAY_FLOAT_BASE_OFFSET + ((long) ARRAY_FLOAT_INDEX_SCALE * array.length); // } // // public static long sizeOf(double[] array) // { // if (array == null) { // return 0; // } // return ARRAY_DOUBLE_BASE_OFFSET + ((long) ARRAY_DOUBLE_INDEX_SCALE * array.length); // } // // public static long sizeOf(Object[] array) // { // if (array == null) { // return 0; // } // return ARRAY_OBJECT_BASE_OFFSET + ((long) ARRAY_OBJECT_INDEX_SCALE * array.length); // } // // private SizeOf() // { // } // }
import it.unimi.dsi.fastutil.ints.IntArrays; import it.unimi.dsi.fastutil.ints.IntComparator; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import org.apache.hadoop.hive.ql.io.slice.SizeOf; import java.io.IOException; import java.io.OutputStream;
return compareValue(keys.get(pos), keys.get(cmpPos)); } } public void visitDictionary(Visitor<Long> visitor, IntDictionaryEncoderVisitorContext context) throws IOException { int[] keysArray = null; if (sortKeys) { keysArray = new int[numElements]; for (int idx = 0; idx < numElements; idx++) { keysArray[idx] = idx; } IntArrays.quickSort(keysArray, new LongPositionComparator()); } for (int pos = 0; pos < numElements; pos++) { context.setOriginalPosition(keysArray == null? pos : keysArray[pos]); visitor.visit(context); } } public void visit(Visitor<Long> visitor) throws IOException { visitDictionary(visitor, new IntDictionaryEncoderVisitorContext()); } @Override public void clear() { keys.clear(); counts.clear(); dictionary.cleanup(); dictionary = new Long2IntOpenHashMapWithByteSize(); // Decrement the dictionary memory by the total size of all the elements
// Path: hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/SizeOf.java // public final class SizeOf // { // public static final byte SIZE_OF_BYTE = 1; // public static final byte SIZE_OF_SHORT = 2; // public static final byte SIZE_OF_INT = 4; // public static final byte SIZE_OF_LONG = 8; // public static final byte SIZE_OF_FLOAT = 4; // public static final byte SIZE_OF_DOUBLE = 8; // // private static final Unsafe UNSAFE; // static { // try { // // fetch theUnsafe object // Field field = Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // UNSAFE = (Unsafe) field.get(null); // if (UNSAFE == null) { // throw new RuntimeException("Unsafe access not available"); // } // } // catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static final int ARRAY_BOOLEAN_BASE_OFFSET = UNSAFE.arrayBaseOffset(boolean[].class); // public static final int ARRAY_BOOLEAN_INDEX_SCALE = UNSAFE.arrayIndexScale(boolean[].class); // public static final int ARRAY_BYTE_BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class); // public static final int ARRAY_BYTE_INDEX_SCALE = UNSAFE.arrayIndexScale(byte[].class); // public static final int ARRAY_SHORT_BASE_OFFSET = UNSAFE.arrayBaseOffset(short[].class); // public static final int ARRAY_SHORT_INDEX_SCALE = UNSAFE.arrayIndexScale(short[].class); // public static final int ARRAY_INT_BASE_OFFSET = UNSAFE.arrayBaseOffset(int[].class); // public static final int ARRAY_INT_INDEX_SCALE = UNSAFE.arrayIndexScale(int[].class); // public static final int ARRAY_LONG_BASE_OFFSET = UNSAFE.arrayBaseOffset(long[].class); // public static final int ARRAY_LONG_INDEX_SCALE = UNSAFE.arrayIndexScale(long[].class); // public static final int ARRAY_FLOAT_BASE_OFFSET = UNSAFE.arrayBaseOffset(float[].class); // public static final int ARRAY_FLOAT_INDEX_SCALE = UNSAFE.arrayIndexScale(float[].class); // public static final int ARRAY_DOUBLE_BASE_OFFSET = UNSAFE.arrayBaseOffset(double[].class); // public static final int ARRAY_DOUBLE_INDEX_SCALE = UNSAFE.arrayIndexScale(double[].class); // public static final int ARRAY_OBJECT_BASE_OFFSET = UNSAFE.arrayBaseOffset(Object[].class); // public static final int ARRAY_OBJECT_INDEX_SCALE = UNSAFE.arrayIndexScale(Object[].class); // // public static long sizeOf(boolean[] array) // { // if (array == null) { // return 0; // } // // return ARRAY_BOOLEAN_BASE_OFFSET + ((long) ARRAY_BOOLEAN_INDEX_SCALE * array.length); // } // // public static long sizeOf(byte[] array) // { // if (array == null) { // return 0; // } // return ARRAY_BYTE_BASE_OFFSET + ((long) ARRAY_BYTE_INDEX_SCALE * array.length); // } // // public static long sizeOf(short[] array) // { // if (array == null) { // return 0; // } // return ARRAY_SHORT_BASE_OFFSET + ((long) ARRAY_SHORT_INDEX_SCALE * array.length); // } // // public static long sizeOf(int[] array) // { // if (array == null) { // return 0; // } // return ARRAY_INT_BASE_OFFSET + ((long) ARRAY_INT_INDEX_SCALE * array.length); // } // // public static long sizeOf(long[] array) // { // if (array == null) { // return 0; // } // return ARRAY_LONG_BASE_OFFSET + ((long) ARRAY_LONG_INDEX_SCALE * array.length); // } // // public static long sizeOf(float[] array) // { // if (array == null) { // return 0; // } // return ARRAY_FLOAT_BASE_OFFSET + ((long) ARRAY_FLOAT_INDEX_SCALE * array.length); // } // // public static long sizeOf(double[] array) // { // if (array == null) { // return 0; // } // return ARRAY_DOUBLE_BASE_OFFSET + ((long) ARRAY_DOUBLE_INDEX_SCALE * array.length); // } // // public static long sizeOf(Object[] array) // { // if (array == null) { // return 0; // } // return ARRAY_OBJECT_BASE_OFFSET + ((long) ARRAY_OBJECT_INDEX_SCALE * array.length); // } // // private SizeOf() // { // } // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/IntDictionaryEncoder.java import it.unimi.dsi.fastutil.ints.IntArrays; import it.unimi.dsi.fastutil.ints.IntComparator; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import org.apache.hadoop.hive.ql.io.slice.SizeOf; import java.io.IOException; import java.io.OutputStream; return compareValue(keys.get(pos), keys.get(cmpPos)); } } public void visitDictionary(Visitor<Long> visitor, IntDictionaryEncoderVisitorContext context) throws IOException { int[] keysArray = null; if (sortKeys) { keysArray = new int[numElements]; for (int idx = 0; idx < numElements; idx++) { keysArray[idx] = idx; } IntArrays.quickSort(keysArray, new LongPositionComparator()); } for (int pos = 0; pos < numElements; pos++) { context.setOriginalPosition(keysArray == null? pos : keysArray[pos]); visitor.visit(context); } } public void visit(Visitor<Long> visitor) throws IOException { visitDictionary(visitor, new IntDictionaryEncoderVisitorContext()); } @Override public void clear() { keys.clear(); counts.clear(); dictionary.cleanup(); dictionary = new Long2IntOpenHashMapWithByteSize(); // Decrement the dictionary memory by the total size of all the elements
memoryEstimate.decrementDictionaryMemory(SizeOf.SIZE_OF_LONG * numElements);
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestInStream.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.compression.ZlibCodec; import junit.framework.Assert; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.PositionedReadable;
ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); InStream in = InStream.create("test", inBuf, null, 100); assertEquals("uncompressed stream test base: 0 offset: 0 limit: 1024", in.toString()); for(int i=0; i < 1024; ++i) { int x = in.read(); assertEquals(i & 0xff, x); } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=1023; i >= 0; --i) { in.seek(i); assertEquals(i & 0xff, in.read()); } } /** * There was a bug where if seek was called on a compressed stream that was initialized from a * byte buffer, then all inputs were read, then available was called, the stream would attempt * to read additional data, fail, and then report a corrupt header. This test verifies that * that series of events no longer fails. * * @throws Exception */ @Test public void testCompressedSeekReadAllAvailable() throws Exception { // Prepare an output stream ReaderWriterProfiler.setProfilerOptions(null); OutputCollector collect = new OutputCollector();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestInStream.java import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.compression.ZlibCodec; import junit.framework.Assert; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.PositionedReadable; ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); InStream in = InStream.create("test", inBuf, null, 100); assertEquals("uncompressed stream test base: 0 offset: 0 limit: 1024", in.toString()); for(int i=0; i < 1024; ++i) { int x = in.read(); assertEquals(i & 0xff, x); } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=1023; i >= 0; --i) { in.seek(i); assertEquals(i & 0xff, in.read()); } } /** * There was a bug where if seek was called on a compressed stream that was initialized from a * byte buffer, then all inputs were read, then available was called, the stream would attempt * to read additional data, fail, and then report a corrupt header. This test verifies that * that series of events no longer fails. * * @throws Exception */ @Test public void testCompressedSeekReadAllAvailable() throws Exception { // Prepare an output stream ReaderWriterProfiler.setProfilerOptions(null); OutputCollector collect = new OutputCollector();
CompressionCodec codec = new ZlibCodec();
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestInStream.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.compression.ZlibCodec; import junit.framework.Assert; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.PositionedReadable;
ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); InStream in = InStream.create("test", inBuf, null, 100); assertEquals("uncompressed stream test base: 0 offset: 0 limit: 1024", in.toString()); for(int i=0; i < 1024; ++i) { int x = in.read(); assertEquals(i & 0xff, x); } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=1023; i >= 0; --i) { in.seek(i); assertEquals(i & 0xff, in.read()); } } /** * There was a bug where if seek was called on a compressed stream that was initialized from a * byte buffer, then all inputs were read, then available was called, the stream would attempt * to read additional data, fail, and then report a corrupt header. This test verifies that * that series of events no longer fails. * * @throws Exception */ @Test public void testCompressedSeekReadAllAvailable() throws Exception { // Prepare an output stream ReaderWriterProfiler.setProfilerOptions(null); OutputCollector collect = new OutputCollector();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestInStream.java import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.compression.ZlibCodec; import junit.framework.Assert; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.PositionedReadable; ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); InStream in = InStream.create("test", inBuf, null, 100); assertEquals("uncompressed stream test base: 0 offset: 0 limit: 1024", in.toString()); for(int i=0; i < 1024; ++i) { int x = in.read(); assertEquals(i & 0xff, x); } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=1023; i >= 0; --i) { in.seek(i); assertEquals(i & 0xff, in.read()); } } /** * There was a bug where if seek was called on a compressed stream that was initialized from a * byte buffer, then all inputs were read, then available was called, the stream would attempt * to read additional data, fail, and then report a corrupt header. This test verifies that * that series of events no longer fails. * * @throws Exception */ @Test public void testCompressedSeekReadAllAvailable() throws Exception { // Prepare an output stream ReaderWriterProfiler.setProfilerOptions(null); OutputCollector collect = new OutputCollector();
CompressionCodec codec = new ZlibCodec();
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestInStream.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.compression.ZlibCodec; import junit.framework.Assert; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.PositionedReadable;
@Override public void readFully(long arg0, byte[] arg1, int arg2, int arg3) throws IOException { } @Override public int read() throws IOException { return 1; } public List<ByteBuffer> readFullyScatterGather(long arg0, int arg1) throws IOException { return null; } } /** * Tests reading from a file so big that the offset to read from exceeds the size of an integer * @throws IOException */ @Test public void testBigFile() throws IOException { InputStream inputStream = new TestInputStream(); // Assert that seek is called with a value outside the range of ints TestFSDataInputStream stream = new TestFSDataInputStream(inputStream, (long) Integer.MAX_VALUE + 1); // Initialize an InStream with an offset outside the range of ints, the values of the stream // length and buffer size (32899 and 32896 respectively) are to accomodate the fact that // TestInputStream returns 1 for all calls to read() InStream in = InStream.create("testStram", stream, (long) Integer.MAX_VALUE + 1,
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestInStream.java import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.compression.ZlibCodec; import junit.framework.Assert; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.PositionedReadable; @Override public void readFully(long arg0, byte[] arg1, int arg2, int arg3) throws IOException { } @Override public int read() throws IOException { return 1; } public List<ByteBuffer> readFullyScatterGather(long arg0, int arg1) throws IOException { return null; } } /** * Tests reading from a file so big that the offset to read from exceeds the size of an integer * @throws IOException */ @Test public void testBigFile() throws IOException { InputStream inputStream = new TestInputStream(); // Assert that seek is called with a value outside the range of ints TestFSDataInputStream stream = new TestFSDataInputStream(inputStream, (long) Integer.MAX_VALUE + 1); // Initialize an InStream with an offset outside the range of ints, the values of the stream // length and buffer size (32899 and 32896 respectively) are to accomodate the fact that // TestInputStream returns 1 for all calls to read() InStream in = InStream.create("testStram", stream, (long) Integer.MAX_VALUE + 1,
32899, WriterImpl.createCodec(CompressionKind.ZLIB), 32896);
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthIntegerReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import java.util.Random; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
/** * 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.facebook.hive.orc; public class TestRunLengthIntegerReader { public void runSeekTest(CompressionCodec codec) throws Exception { TestInStream.OutputCollector collect = new TestInStream.OutputCollector(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthIntegerWriter out = new RunLengthIntegerWriter( new OutStream("test", 1000, codec, collect, new MemoryEstimate()), true, 4, true); RowIndex.Builder rowIndex = OrcProto.RowIndex.newBuilder(); RowIndexEntry.Builder rowIndexEntry = OrcProto.RowIndexEntry.newBuilder();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthIntegerReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import java.util.Random; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; /** * 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.facebook.hive.orc; public class TestRunLengthIntegerReader { public void runSeekTest(CompressionCodec codec) throws Exception { TestInStream.OutputCollector collect = new TestInStream.OutputCollector(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthIntegerWriter out = new RunLengthIntegerWriter( new OutStream("test", 1000, codec, collect, new MemoryEstimate()), true, 4, true); RowIndex.Builder rowIndex = OrcProto.RowIndex.newBuilder(); RowIndexEntry.Builder rowIndexEntry = OrcProto.RowIndexEntry.newBuilder();
WriterImpl.RowIndexPositionRecorder rowIndexPosition = new RowIndexPositionRecorder(rowIndexEntry);
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthIntegerReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import java.util.Random; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
int x = (int) in.next(); if (i < 1024) { assertEquals(i/4, x); } else if (i < 2048) { assertEquals(2*i, x); } else { assertEquals(junk[i-2048], x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=2047; i >= 0; --i) { in.seek(i); int x = (int) in.next(); if (i < 1024) { assertEquals(i/4, x); } else if (i < 2048) { assertEquals(2*i, x); } else { assertEquals(junk[i-2048], x); } } } @Test public void testUncompressedSeek() throws Exception { runSeekTest(null); } @Test public void testCompressedSeek() throws Exception {
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthIntegerReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import java.util.Random; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; int x = (int) in.next(); if (i < 1024) { assertEquals(i/4, x); } else if (i < 2048) { assertEquals(2*i, x); } else { assertEquals(junk[i-2048], x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=2047; i >= 0; --i) { in.seek(i); int x = (int) in.next(); if (i < 1024) { assertEquals(i/4, x); } else if (i < 2048) { assertEquals(2*i, x); } else { assertEquals(junk[i-2048], x); } } } @Test public void testUncompressedSeek() throws Exception { runSeekTest(null); } @Test public void testCompressedSeek() throws Exception {
runSeekTest(new ZlibCodec());
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/RecordReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyRow.java // public class OrcLazyRow extends OrcLazyStruct { // // private OrcLazyObject[] fields; // private final List<String> fieldNames; // // public OrcLazyRow(OrcLazyObject[] fields, List<String> fieldNames) { // super(null); // this.fields = fields; // this.fieldNames = fieldNames; // } // // @Override // public void next() { // super.next(); // for (OrcLazyObject field : fields) { // if (field != null) { // field.next(); // } // } // } // // @Override // public void startStripe(Map<StreamName, InStream> streams, List<OrcProto.ColumnEncoding> encodings, // RowIndex[] indexes, long rowBaseInStripe) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.startStripe(streams, encodings, indexes, rowBaseInStripe); // } // } // } // // @Override // public Object materialize(long row, Object previous) throws IOException { // OrcStruct previousRow; // if (previous != null) { // previousRow = (OrcStruct) previous; // previousRow.setFieldNames(fieldNames); // } else { // previousRow = new OrcStruct(fieldNames); // } // for (int i = 0; i < fields.length; i++) { // previousRow.setFieldValue(i, fields[i]); // } // return previousRow; // } // // @Override // public void seekToRow(long rowNumber) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.seekToRow(rowNumber); // } // } // } // // public int getNumFields() { // return fields.length; // } // // public OrcLazyObject getFieldValue(int index) { // if (index >= fields.length) { // return null; // } // // return fields[index]; // } // // public void reset(OrcLazyRow other) throws IOException { // this.fields = other.getRawFields(); // seekToRow(0); // } // // public OrcLazyObject[] getRawFields() { // return fields; // } // // @Override // public void close() throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.close(); // } // } // } // }
import com.facebook.hive.orc.lazy.OrcLazyRow; import java.io.IOException;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * A row-by-row iterator for ORC files. */ public interface RecordReader { /** * Does the reader have more rows available. * @return true if there are more rows * @throws java.io.IOException */ boolean hasNext() throws IOException; /** * Read the next row. * @param previous a row object that can be reused by the reader * @return the row that was read * @throws java.io.IOException */ Object next(Object previous) throws IOException; /** * Get the row number of the row that will be returned by the following * call to next(). * @return the row number from 0 to the number of rows in the file * @throws java.io.IOException */ long getRowNumber() throws IOException; /** * Get the progress of the reader through the rows. * @return a fraction between 0.0 and 1.0 of rows read * @throws java.io.IOException */ float getProgress() throws IOException; /** * Release the resources associated with the given reader. * @throws java.io.IOException */ void close() throws IOException; /** * Seek to a particular row number. * The row number here refers to row number in that particular file. * We might be reading only a part of the file but the rowCount will still be the count with respect to the * complete file. */ void seekToRow(long rowCount) throws IOException; /** * Get the underlying reader. */
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyRow.java // public class OrcLazyRow extends OrcLazyStruct { // // private OrcLazyObject[] fields; // private final List<String> fieldNames; // // public OrcLazyRow(OrcLazyObject[] fields, List<String> fieldNames) { // super(null); // this.fields = fields; // this.fieldNames = fieldNames; // } // // @Override // public void next() { // super.next(); // for (OrcLazyObject field : fields) { // if (field != null) { // field.next(); // } // } // } // // @Override // public void startStripe(Map<StreamName, InStream> streams, List<OrcProto.ColumnEncoding> encodings, // RowIndex[] indexes, long rowBaseInStripe) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.startStripe(streams, encodings, indexes, rowBaseInStripe); // } // } // } // // @Override // public Object materialize(long row, Object previous) throws IOException { // OrcStruct previousRow; // if (previous != null) { // previousRow = (OrcStruct) previous; // previousRow.setFieldNames(fieldNames); // } else { // previousRow = new OrcStruct(fieldNames); // } // for (int i = 0; i < fields.length; i++) { // previousRow.setFieldValue(i, fields[i]); // } // return previousRow; // } // // @Override // public void seekToRow(long rowNumber) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.seekToRow(rowNumber); // } // } // } // // public int getNumFields() { // return fields.length; // } // // public OrcLazyObject getFieldValue(int index) { // if (index >= fields.length) { // return null; // } // // return fields[index]; // } // // public void reset(OrcLazyRow other) throws IOException { // this.fields = other.getRawFields(); // seekToRow(0); // } // // public OrcLazyObject[] getRawFields() { // return fields; // } // // @Override // public void close() throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.close(); // } // } // } // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/RecordReader.java import com.facebook.hive.orc.lazy.OrcLazyRow; import java.io.IOException; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * A row-by-row iterator for ORC files. */ public interface RecordReader { /** * Does the reader have more rows available. * @return true if there are more rows * @throws java.io.IOException */ boolean hasNext() throws IOException; /** * Read the next row. * @param previous a row object that can be reused by the reader * @return the row that was read * @throws java.io.IOException */ Object next(Object previous) throws IOException; /** * Get the row number of the row that will be returned by the following * call to next(). * @return the row number from 0 to the number of rows in the file * @throws java.io.IOException */ long getRowNumber() throws IOException; /** * Get the progress of the reader through the rows. * @return a fraction between 0.0 and 1.0 of rows read * @throws java.io.IOException */ float getProgress() throws IOException; /** * Release the resources associated with the given reader. * @throws java.io.IOException */ void close() throws IOException; /** * Seek to a particular row number. * The row number here refers to row number in that particular file. * We might be reading only a part of the file but the rowCount will still be the count with respect to the * complete file. */ void seekToRow(long rowCount) throws IOException; /** * Get the underlying reader. */
OrcLazyRow getReader();
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestZlib.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // }
import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail;
/** * 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.facebook.hive.orc; public class TestZlib { @Test public void testNoOverflow() throws Exception { ByteBuffer in = ByteBuffer.allocate(10); ByteBuffer out = ByteBuffer.allocate(10); in.put(new byte[]{1,2,3,4,5,6,7,10}); in.flip();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestZlib.java import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; /** * 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.facebook.hive.orc; public class TestZlib { @Test public void testNoOverflow() throws Exception { ByteBuffer in = ByteBuffer.allocate(10); ByteBuffer out = ByteBuffer.allocate(10); in.put(new byte[]{1,2,3,4,5,6,7,10}); in.flip();
CompressionCodec codec = new ZlibCodec();
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestZlib.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // }
import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail;
/** * 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.facebook.hive.orc; public class TestZlib { @Test public void testNoOverflow() throws Exception { ByteBuffer in = ByteBuffer.allocate(10); ByteBuffer out = ByteBuffer.allocate(10); in.put(new byte[]{1,2,3,4,5,6,7,10}); in.flip();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestZlib.java import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; /** * 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.facebook.hive.orc; public class TestZlib { @Test public void testNoOverflow() throws Exception { ByteBuffer in = ByteBuffer.allocate(10); ByteBuffer out = ByteBuffer.allocate(10); in.put(new byte[]{1,2,3,4,5,6,7,10}); in.flip();
CompressionCodec codec = new ZlibCodec();
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/InStream.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // }
import com.facebook.hive.orc.OrcProto.RowIndexEntry; import org.apache.hadoop.fs.FSDataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.OrcProto.RowIndexEntry;
@Override public void seek(int index) throws IOException { offset = (int) base + indeces[index]; } @Override public String toString() { return "uncompressed stream " + name + " base: " + base + " offset: " + offset + " limit: " + limit; } @Override public int loadIndeces(List<RowIndexEntry> rowIndexEntries, int startIndex) { indeces = new int[rowIndexEntries.size()]; int i = 0; for (RowIndexEntry rowIndexEntry : rowIndexEntries) { indeces[i] = (int) rowIndexEntry.getPositions(startIndex); i++; } return startIndex + 1; } } private static class CompressedStream extends InStream { private final String name; private byte[] array; private final int compressionBlockSize; private ByteBuffer uncompressed = null;
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/InStream.java import com.facebook.hive.orc.OrcProto.RowIndexEntry; import org.apache.hadoop.fs.FSDataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.OrcProto.RowIndexEntry; @Override public void seek(int index) throws IOException { offset = (int) base + indeces[index]; } @Override public String toString() { return "uncompressed stream " + name + " base: " + base + " offset: " + offset + " limit: " + limit; } @Override public int loadIndeces(List<RowIndexEntry> rowIndexEntries, int startIndex) { indeces = new int[rowIndexEntries.size()]; int i = 0; for (RowIndexEntry rowIndexEntry : rowIndexEntries) { indeces[i] = (int) rowIndexEntry.getPositions(startIndex); i++; } return startIndex + 1; } } private static class CompressedStream extends InStream { private final String name; private byte[] array; private final int compressionBlockSize; private ByteBuffer uncompressed = null;
private final CompressionCodec codec;
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestColumnStatistics.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/DoubleColumnStatistics.java // public interface DoubleColumnStatistics extends ColumnStatistics { // // /** // * Get the smallest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the minimum // */ // double getMinimum(); // // /** // * Get the largest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the maximum // */ // double getMaximum(); // // /** // * Get the sum of the values in the column. // * @return the sum // */ // double getSum(); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/StringColumnStatistics.java // public interface StringColumnStatistics extends ColumnStatistics { // /** // * Get the minimum string. // * @return the minimum // */ // String getMinimum(); // // /** // * Get the maximum string. // * @return the maximum // */ // String getMaximum(); // }
import com.facebook.hive.orc.statistics.ColumnStatisticsImpl; import com.facebook.hive.orc.statistics.DoubleColumnStatistics; import com.facebook.hive.orc.statistics.IntegerColumnStatistics; import com.facebook.hive.orc.statistics.StringColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.junit.Test; import static junit.framework.Assert.assertEquals;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * Test ColumnStatisticsImpl for ORC. */ public class TestColumnStatistics { @Test public void testIntegerStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateInteger(10); stats1.updateInteger(10); stats2.updateInteger(1); stats2.updateInteger(1000); stats1.merge(stats2); IntegerColumnStatistics typed = (IntegerColumnStatistics) stats1; assertEquals(1, typed.getMinimum()); assertEquals(1000, typed.getMaximum()); } @Test public void testDoubleStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateDouble(10.0); stats1.updateDouble(100.0); stats2.updateDouble(1.0); stats2.updateDouble(1000.0); stats1.merge(stats2);
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/DoubleColumnStatistics.java // public interface DoubleColumnStatistics extends ColumnStatistics { // // /** // * Get the smallest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the minimum // */ // double getMinimum(); // // /** // * Get the largest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the maximum // */ // double getMaximum(); // // /** // * Get the sum of the values in the column. // * @return the sum // */ // double getSum(); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/StringColumnStatistics.java // public interface StringColumnStatistics extends ColumnStatistics { // /** // * Get the minimum string. // * @return the minimum // */ // String getMinimum(); // // /** // * Get the maximum string. // * @return the maximum // */ // String getMaximum(); // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestColumnStatistics.java import com.facebook.hive.orc.statistics.ColumnStatisticsImpl; import com.facebook.hive.orc.statistics.DoubleColumnStatistics; import com.facebook.hive.orc.statistics.IntegerColumnStatistics; import com.facebook.hive.orc.statistics.StringColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.junit.Test; import static junit.framework.Assert.assertEquals; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * Test ColumnStatisticsImpl for ORC. */ public class TestColumnStatistics { @Test public void testIntegerStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateInteger(10); stats1.updateInteger(10); stats2.updateInteger(1); stats2.updateInteger(1000); stats1.merge(stats2); IntegerColumnStatistics typed = (IntegerColumnStatistics) stats1; assertEquals(1, typed.getMinimum()); assertEquals(1000, typed.getMaximum()); } @Test public void testDoubleStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateDouble(10.0); stats1.updateDouble(100.0); stats2.updateDouble(1.0); stats2.updateDouble(1000.0); stats1.merge(stats2);
DoubleColumnStatistics typed = (DoubleColumnStatistics) stats1;
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestColumnStatistics.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/DoubleColumnStatistics.java // public interface DoubleColumnStatistics extends ColumnStatistics { // // /** // * Get the smallest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the minimum // */ // double getMinimum(); // // /** // * Get the largest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the maximum // */ // double getMaximum(); // // /** // * Get the sum of the values in the column. // * @return the sum // */ // double getSum(); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/StringColumnStatistics.java // public interface StringColumnStatistics extends ColumnStatistics { // /** // * Get the minimum string. // * @return the minimum // */ // String getMinimum(); // // /** // * Get the maximum string. // * @return the maximum // */ // String getMaximum(); // }
import com.facebook.hive.orc.statistics.ColumnStatisticsImpl; import com.facebook.hive.orc.statistics.DoubleColumnStatistics; import com.facebook.hive.orc.statistics.IntegerColumnStatistics; import com.facebook.hive.orc.statistics.StringColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.junit.Test; import static junit.framework.Assert.assertEquals;
@Test public void testDoubleStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateDouble(10.0); stats1.updateDouble(100.0); stats2.updateDouble(1.0); stats2.updateDouble(1000.0); stats1.merge(stats2); DoubleColumnStatistics typed = (DoubleColumnStatistics) stats1; assertEquals(1.0, typed.getMinimum(), 0.001); assertEquals(1000.0, typed.getMaximum(), 0.001); } @Test public void testStringStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateString("bob"); stats1.updateString("david"); stats1.updateString("charles"); stats2.updateString("anne"); stats2.updateString("erin"); stats1.merge(stats2);
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/DoubleColumnStatistics.java // public interface DoubleColumnStatistics extends ColumnStatistics { // // /** // * Get the smallest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the minimum // */ // double getMinimum(); // // /** // * Get the largest value in the column. Only defined if getNumberOfValues // * is non-zero. // * @return the maximum // */ // double getMaximum(); // // /** // * Get the sum of the values in the column. // * @return the sum // */ // double getSum(); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/StringColumnStatistics.java // public interface StringColumnStatistics extends ColumnStatistics { // /** // * Get the minimum string. // * @return the minimum // */ // String getMinimum(); // // /** // * Get the maximum string. // * @return the maximum // */ // String getMaximum(); // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestColumnStatistics.java import com.facebook.hive.orc.statistics.ColumnStatisticsImpl; import com.facebook.hive.orc.statistics.DoubleColumnStatistics; import com.facebook.hive.orc.statistics.IntegerColumnStatistics; import com.facebook.hive.orc.statistics.StringColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.junit.Test; import static junit.framework.Assert.assertEquals; @Test public void testDoubleStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateDouble(10.0); stats1.updateDouble(100.0); stats2.updateDouble(1.0); stats2.updateDouble(1000.0); stats1.merge(stats2); DoubleColumnStatistics typed = (DoubleColumnStatistics) stats1; assertEquals(1.0, typed.getMinimum(), 0.001); assertEquals(1000.0, typed.getMaximum(), 0.001); } @Test public void testStringStatisticsMerge() throws Exception { ObjectInspector inspector = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ColumnStatisticsImpl stats1 = ColumnStatisticsImpl.create(inspector); ColumnStatisticsImpl stats2 = ColumnStatisticsImpl.create(inspector); stats1.updateString("bob"); stats1.updateString("david"); stats1.updateString("charles"); stats2.updateString("anne"); stats2.updateString("erin"); stats1.merge(stats2);
StringColumnStatistics strStats = (StringColumnStatistics) stats1;
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/OutStream.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // }
import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import com.facebook.hive.orc.compression.CompressionCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; class OutStream extends PositionedOutputStream { interface OutputReceiver { /** * Output the given buffer to the final destination * @param buffer the buffer to output * @throws IOException */ void output(ByteBuffer buffer) throws IOException; } static final int HEADER_SIZE = 3; // If the OutStream is flushing the last compressed ByteBuffer, we don't need to reallocate // a new one, we can just share the same one over and over between streams because it gets // cleared right away. It is a mapping from the size of the buffer to the buffer. private static final Map<Integer, ByteBuffer> COMPRESSED_FOR_REUSE = new HashMap<Integer, ByteBuffer>(); private final String name; private final OutputReceiver receiver; /** * Stores the uncompressed bytes that have been serialized, but not * compressed yet. When this fills, we compress the entire buffer. */ private ByteBuffer current = null; /** * Stores the compressed bytes until we have a full buffer and then outputs * them to the receiver. If no compression is being done, this (and overflow) * will always be null and the current buffer will be sent directly to the * receiver. */ private ByteBuffer compressed = null; /** * Since the compressed buffer may start with contents from previous * compression blocks, we allocate an overflow buffer so that the * output of the codec can be split between the two buffers. After the * compressed buffer is sent to the receiver, the overflow buffer becomes * the new compressed buffer. */ private ByteBuffer overflow = null; private final int bufferSize;
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/OutStream.java import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import com.facebook.hive.orc.compression.CompressionCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; class OutStream extends PositionedOutputStream { interface OutputReceiver { /** * Output the given buffer to the final destination * @param buffer the buffer to output * @throws IOException */ void output(ByteBuffer buffer) throws IOException; } static final int HEADER_SIZE = 3; // If the OutStream is flushing the last compressed ByteBuffer, we don't need to reallocate // a new one, we can just share the same one over and over between streams because it gets // cleared right away. It is a mapping from the size of the buffer to the buffer. private static final Map<Integer, ByteBuffer> COMPRESSED_FOR_REUSE = new HashMap<Integer, ByteBuffer>(); private final String name; private final OutputReceiver receiver; /** * Stores the uncompressed bytes that have been serialized, but not * compressed yet. When this fills, we compress the entire buffer. */ private ByteBuffer current = null; /** * Stores the compressed bytes until we have a full buffer and then outputs * them to the receiver. If no compression is being done, this (and overflow) * will always be null and the current buffer will be sent directly to the * receiver. */ private ByteBuffer compressed = null; /** * Since the compressed buffer may start with contents from previous * compression blocks, we allocate an overflow buffer so that the * output of the codec can be split between the two buffers. After the * compressed buffer is sent to the receiver, the overflow buffer becomes * the new compressed buffer. */ private ByteBuffer overflow = null; private final int bufferSize;
private final CompressionCodec codec;
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/WriterImplWithForceFlush.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // }
import com.facebook.hive.orc.compression.CompressionKind; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.io.IOException;
package com.facebook.hive.orc; public class WriterImplWithForceFlush extends WriterImpl { public WriterImplWithForceFlush(FileSystem fs, Path path, Configuration conf,
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/WriterImplWithForceFlush.java import com.facebook.hive.orc.compression.CompressionKind; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.io.IOException; package com.facebook.hive.orc; public class WriterImplWithForceFlush extends WriterImpl { public WriterImplWithForceFlush(FileSystem fs, Path path, Configuration conf,
ObjectInspector inspector, long stripeSize, CompressionKind compress, int bufferSize,
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthByteReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/SnappyCodec.java // public class SnappyCodec implements CompressionCodec { // // @Override // public void reloadConfigurations(Configuration conf) { // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // int inBytes = in.remaining(); // // I should work on a patch for Snappy to support an overflow buffer // // to prevent the extra buffer copy. // byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)]; // int outBytes = // Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, // compressed, 0); // if (outBytes < inBytes) { // int remaining = out.remaining(); // if (remaining >= outBytes) { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), outBytes); // out.position(out.position() + outBytes); // } else { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), remaining); // out.position(out.limit()); // System.arraycopy(compressed, remaining, overflow.array(), // overflow.arrayOffset(), outBytes - remaining); // overflow.position(outBytes - remaining); // } // return true; // } else { // return false; // } // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // int inOffset = in.position(); // int uncompressLen = // Snappy.uncompress(in.array(), in.arrayOffset() + inOffset, // in.limit() - inOffset, out.array(), out.arrayOffset() + out.position()); // out.position(uncompressLen + out.position()); // out.flip(); // } // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.SnappyCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
/** * 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.facebook.hive.orc; public class TestRunLengthByteReader { @Test public void testUncompressedSeek() throws Exception { TestInStream.OutputCollector collect = new TestInStream.OutputCollector(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthByteWriter out = new RunLengthByteWriter(new OutStream("test", 100, null, collect, new MemoryEstimate())); RowIndex.Builder rowIndex = OrcProto.RowIndex.newBuilder(); RowIndexEntry.Builder rowIndexEntry = OrcProto.RowIndexEntry.newBuilder();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/SnappyCodec.java // public class SnappyCodec implements CompressionCodec { // // @Override // public void reloadConfigurations(Configuration conf) { // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // int inBytes = in.remaining(); // // I should work on a patch for Snappy to support an overflow buffer // // to prevent the extra buffer copy. // byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)]; // int outBytes = // Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, // compressed, 0); // if (outBytes < inBytes) { // int remaining = out.remaining(); // if (remaining >= outBytes) { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), outBytes); // out.position(out.position() + outBytes); // } else { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), remaining); // out.position(out.limit()); // System.arraycopy(compressed, remaining, overflow.array(), // overflow.arrayOffset(), outBytes - remaining); // overflow.position(outBytes - remaining); // } // return true; // } else { // return false; // } // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // int inOffset = in.position(); // int uncompressLen = // Snappy.uncompress(in.array(), in.arrayOffset() + inOffset, // in.limit() - inOffset, out.array(), out.arrayOffset() + out.position()); // out.position(uncompressLen + out.position()); // out.flip(); // } // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthByteReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.SnappyCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; /** * 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.facebook.hive.orc; public class TestRunLengthByteReader { @Test public void testUncompressedSeek() throws Exception { TestInStream.OutputCollector collect = new TestInStream.OutputCollector(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthByteWriter out = new RunLengthByteWriter(new OutStream("test", 100, null, collect, new MemoryEstimate())); RowIndex.Builder rowIndex = OrcProto.RowIndex.newBuilder(); RowIndexEntry.Builder rowIndexEntry = OrcProto.RowIndexEntry.newBuilder();
WriterImpl.RowIndexPositionRecorder rowIndexPosition = new RowIndexPositionRecorder(rowIndexEntry);
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthByteReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/SnappyCodec.java // public class SnappyCodec implements CompressionCodec { // // @Override // public void reloadConfigurations(Configuration conf) { // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // int inBytes = in.remaining(); // // I should work on a patch for Snappy to support an overflow buffer // // to prevent the extra buffer copy. // byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)]; // int outBytes = // Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, // compressed, 0); // if (outBytes < inBytes) { // int remaining = out.remaining(); // if (remaining >= outBytes) { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), outBytes); // out.position(out.position() + outBytes); // } else { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), remaining); // out.position(out.limit()); // System.arraycopy(compressed, remaining, overflow.array(), // overflow.arrayOffset(), outBytes - remaining); // overflow.position(outBytes - remaining); // } // return true; // } else { // return false; // } // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // int inOffset = in.position(); // int uncompressLen = // Snappy.uncompress(in.array(), in.arrayOffset() + inOffset, // in.limit() - inOffset, out.array(), out.arrayOffset() + out.position()); // out.position(uncompressLen + out.position()); // out.flip(); // } // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.SnappyCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
} out.flush(); ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthByteReader in = new RunLengthByteReader(InStream.create("test", inBuf, null, 100)); for(int i=0; i < 2048; ++i) { int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=2047; i >= 0; --i) { in.seek(i); int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } } @Test public void testCompressedSeek() throws Exception {
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/SnappyCodec.java // public class SnappyCodec implements CompressionCodec { // // @Override // public void reloadConfigurations(Configuration conf) { // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // int inBytes = in.remaining(); // // I should work on a patch for Snappy to support an overflow buffer // // to prevent the extra buffer copy. // byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)]; // int outBytes = // Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, // compressed, 0); // if (outBytes < inBytes) { // int remaining = out.remaining(); // if (remaining >= outBytes) { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), outBytes); // out.position(out.position() + outBytes); // } else { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), remaining); // out.position(out.limit()); // System.arraycopy(compressed, remaining, overflow.array(), // overflow.arrayOffset(), outBytes - remaining); // overflow.position(outBytes - remaining); // } // return true; // } else { // return false; // } // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // int inOffset = in.position(); // int uncompressLen = // Snappy.uncompress(in.array(), in.arrayOffset() + inOffset, // in.limit() - inOffset, out.array(), out.arrayOffset() + out.position()); // out.position(uncompressLen + out.position()); // out.flip(); // } // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthByteReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.SnappyCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; } out.flush(); ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthByteReader in = new RunLengthByteReader(InStream.create("test", inBuf, null, 100)); for(int i=0; i < 2048; ++i) { int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=2047; i >= 0; --i) { in.seek(i); int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } } @Test public void testCompressedSeek() throws Exception {
CompressionCodec codec = new SnappyCodec();
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthByteReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/SnappyCodec.java // public class SnappyCodec implements CompressionCodec { // // @Override // public void reloadConfigurations(Configuration conf) { // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // int inBytes = in.remaining(); // // I should work on a patch for Snappy to support an overflow buffer // // to prevent the extra buffer copy. // byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)]; // int outBytes = // Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, // compressed, 0); // if (outBytes < inBytes) { // int remaining = out.remaining(); // if (remaining >= outBytes) { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), outBytes); // out.position(out.position() + outBytes); // } else { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), remaining); // out.position(out.limit()); // System.arraycopy(compressed, remaining, overflow.array(), // overflow.arrayOffset(), outBytes - remaining); // overflow.position(outBytes - remaining); // } // return true; // } else { // return false; // } // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // int inOffset = in.position(); // int uncompressLen = // Snappy.uncompress(in.array(), in.arrayOffset() + inOffset, // in.limit() - inOffset, out.array(), out.arrayOffset() + out.position()); // out.position(uncompressLen + out.position()); // out.flip(); // } // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.SnappyCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
} out.flush(); ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthByteReader in = new RunLengthByteReader(InStream.create("test", inBuf, null, 100)); for(int i=0; i < 2048; ++i) { int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=2047; i >= 0; --i) { in.seek(i); int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } } @Test public void testCompressedSeek() throws Exception {
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/SnappyCodec.java // public class SnappyCodec implements CompressionCodec { // // @Override // public void reloadConfigurations(Configuration conf) { // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // int inBytes = in.remaining(); // // I should work on a patch for Snappy to support an overflow buffer // // to prevent the extra buffer copy. // byte[] compressed = new byte[Snappy.maxCompressedLength(inBytes)]; // int outBytes = // Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, // compressed, 0); // if (outBytes < inBytes) { // int remaining = out.remaining(); // if (remaining >= outBytes) { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), outBytes); // out.position(out.position() + outBytes); // } else { // System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + // out.position(), remaining); // out.position(out.limit()); // System.arraycopy(compressed, remaining, overflow.array(), // overflow.arrayOffset(), outBytes - remaining); // overflow.position(outBytes - remaining); // } // return true; // } else { // return false; // } // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // int inOffset = in.position(); // int uncompressLen = // Snappy.uncompress(in.array(), in.arrayOffset() + inOffset, // in.limit() - inOffset, out.array(), out.arrayOffset() + out.position()); // out.position(uncompressLen + out.position()); // out.flip(); // } // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestRunLengthByteReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.SnappyCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; } out.flush(); ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size()); collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size()); inBuf.flip(); ReaderWriterProfiler.setProfilerOptions(null); RunLengthByteReader in = new RunLengthByteReader(InStream.create("test", inBuf, null, 100)); for(int i=0; i < 2048; ++i) { int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=2047; i >= 0; --i) { in.seek(i); int x = in.next() & 0xff; if (i < 1024) { assertEquals((i/4) & 0xff, x); } else { assertEquals(i & 0xff, x); } } } @Test public void testCompressedSeek() throws Exception {
CompressionCodec codec = new SnappyCodec();
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/OrcFile.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // }
import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.io.WritableComparable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * Contains factory methods to read or write ORC files. */ public final class OrcFile { public static final String MAGIC = "ORC"; public static final String COMPRESSION = "orc.compress"; public static final String COMPRESSION_BLOCK_SIZE = "orc.compress.size"; public static final String STRIPE_SIZE = "orc.stripe.size"; public static final String ROW_INDEX_STRIDE = "orc.row.index.stride"; public static final String ENABLE_INDEXES = "orc.create.index"; // unused private OrcFile() {} public static class KeyWrapper implements WritableComparable<KeyWrapper> { public StripeInformation key; public Path inputPath; public ObjectInspector objectInspector;
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/OrcFile.java import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.io.WritableComparable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * Contains factory methods to read or write ORC files. */ public final class OrcFile { public static final String MAGIC = "ORC"; public static final String COMPRESSION = "orc.compress"; public static final String COMPRESSION_BLOCK_SIZE = "orc.compress.size"; public static final String STRIPE_SIZE = "orc.stripe.size"; public static final String ROW_INDEX_STRIDE = "orc.row.index.stride"; public static final String ENABLE_INDEXES = "orc.create.index"; // unused private OrcFile() {} public static class KeyWrapper implements WritableComparable<KeyWrapper> { public StripeInformation key; public Path inputPath; public ObjectInspector objectInspector;
public CompressionKind compression;
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/OrcFile.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // }
import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.io.WritableComparable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * Contains factory methods to read or write ORC files. */ public final class OrcFile { public static final String MAGIC = "ORC"; public static final String COMPRESSION = "orc.compress"; public static final String COMPRESSION_BLOCK_SIZE = "orc.compress.size"; public static final String STRIPE_SIZE = "orc.stripe.size"; public static final String ROW_INDEX_STRIDE = "orc.row.index.stride"; public static final String ENABLE_INDEXES = "orc.create.index"; // unused private OrcFile() {} public static class KeyWrapper implements WritableComparable<KeyWrapper> { public StripeInformation key; public Path inputPath; public ObjectInspector objectInspector; public CompressionKind compression; public int compressionSize; public int rowIndexStride;
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/OrcFile.java import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.io.WritableComparable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * Contains factory methods to read or write ORC files. */ public final class OrcFile { public static final String MAGIC = "ORC"; public static final String COMPRESSION = "orc.compress"; public static final String COMPRESSION_BLOCK_SIZE = "orc.compress.size"; public static final String STRIPE_SIZE = "orc.stripe.size"; public static final String ROW_INDEX_STRIDE = "orc.row.index.stride"; public static final String ENABLE_INDEXES = "orc.create.index"; // unused private OrcFile() {} public static class KeyWrapper implements WritableComparable<KeyWrapper> { public StripeInformation key; public Path inputPath; public ObjectInspector objectInspector; public CompressionKind compression; public int compressionSize; public int rowIndexStride;
public ColumnStatistics[] columnStats;
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestBitFieldReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
/** * 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.facebook.hive.orc; public class TestBitFieldReader { public void runSeekTest(CompressionCodec codec) throws Exception { TestInStream.OutputCollector collect = new TestInStream.OutputCollector(); final int COUNT = 16384; BitFieldWriter out = new BitFieldWriter( new OutStream("test", 500, codec, collect, new MemoryEstimate()), 1); RowIndex.Builder rowIndex = OrcProto.RowIndex.newBuilder(); RowIndexEntry.Builder rowIndexEntry = OrcProto.RowIndexEntry.newBuilder();
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestBitFieldReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; /** * 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.facebook.hive.orc; public class TestBitFieldReader { public void runSeekTest(CompressionCodec codec) throws Exception { TestInStream.OutputCollector collect = new TestInStream.OutputCollector(); final int COUNT = 16384; BitFieldWriter out = new BitFieldWriter( new OutStream("test", 500, codec, collect, new MemoryEstimate()), 1); RowIndex.Builder rowIndex = OrcProto.RowIndex.newBuilder(); RowIndexEntry.Builder rowIndexEntry = OrcProto.RowIndexEntry.newBuilder();
WriterImpl.RowIndexPositionRecorder rowIndexPosition = new RowIndexPositionRecorder(rowIndexEntry);
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestBitFieldReader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // }
import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder;
BitFieldReader in = new BitFieldReader(InStream.create("test", inBuf, codec, 500)); for(int i=0; i < COUNT; ++i) { int x = in.next(); if (i < COUNT / 2) { assertEquals(i & 1, x); } else { assertEquals((i/3) & 1, x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=COUNT-1; i >= 0; --i) { in.seek(i); int x = in.next(); if (i < COUNT / 2) { assertEquals(i & 1, x); } else { assertEquals((i/3) & 1, x); } } } @Test public void testUncompressedSeek() throws Exception { ReaderWriterProfiler.setProfilerOptions(null); runSeekTest(null); } @Test public void testCompressedSeek() throws Exception { ReaderWriterProfiler.setProfilerOptions(null);
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionCodec.java // public interface CompressionCodec { // /** // * Compress the in buffer to the out buffer. // * @param in the bytes to compress // * @param out the uncompressed bytes // * @param overflow put any additional bytes here // * @return true if the output is smaller than input // * @throws IOException // */ // boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow // ) throws IOException; // // /** // * Decompress the in buffer to the out buffer. // * @param in the bytes to decompress // * @param out the decompressed bytes // * @throws IOException // */ // void decompress(ByteBuffer in, ByteBuffer out) throws IOException; // // void reloadConfigurations(Configuration conf); // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/ZlibCodec.java // public class ZlibCodec implements CompressionCodec { // // private int compressionLevel; // // public ZlibCodec() { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } // // public ZlibCodec(Configuration conf) { // if (conf == null) { // compressionLevel = Deflater.DEFAULT_COMPRESSION; // } else { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // } // // public void reloadConfigurations(Configuration conf) { // compressionLevel = OrcConf.getIntVar(conf, OrcConf.ConfVars.HIVE_ORC_ZLIB_COMPRESSION_LEVEL); // } // // @Override // public boolean compress(ByteBuffer in, ByteBuffer out, // ByteBuffer overflow) throws IOException { // Deflater deflater = new Deflater(compressionLevel, true); // int length = in.remaining(); // deflater.setInput(in.array(), in.arrayOffset() + in.position(), length); // deflater.finish(); // int outSize = 0; // int offset = out.arrayOffset() + out.position(); // while (!deflater.finished() && (length > outSize)) { // int size = deflater.deflate(out.array(), offset, out.remaining()); // out.position(size + out.position()); // outSize += size; // offset += size; // // if we run out of space in the out buffer, use the overflow // if (out.remaining() == 0) { // if (overflow == null) { // deflater.end(); // return false; // } // out = overflow; // offset = out.arrayOffset() + out.position(); // } // } // deflater.end(); // return length > outSize; // } // // @Override // public void decompress(ByteBuffer in, ByteBuffer out) throws IOException { // Inflater inflater = new Inflater(true); // inflater.setInput(in.array(), in.arrayOffset() + in.position(), // in.remaining()); // while (!(inflater.finished() || inflater.needsDictionary() || // inflater.needsInput())) { // try { // int count = inflater.inflate(out.array(), // out.arrayOffset() + out.position(), // out.remaining()); // out.position(count + out.position()); // } catch (DataFormatException dfe) { // throw new IOException("Bad compression data", dfe); // } // } // out.flip(); // inflater.end(); // in.position(in.limit()); // } // // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/WriterImpl.java // static class RowIndexPositionRecorder implements PositionRecorder { // private final OrcProto.RowIndexEntry.Builder builder; // // RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { // this.builder = builder; // } // // @Override // public void addPosition(long position) { // builder.addPositions(position); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestBitFieldReader.java import static junit.framework.Assert.assertEquals; import java.nio.ByteBuffer; import com.facebook.hive.orc.compression.CompressionCodec; import com.facebook.hive.orc.compression.ZlibCodec; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.junit.Test; import com.facebook.hive.orc.OrcProto.RowIndex; import com.facebook.hive.orc.OrcProto.RowIndexEntry; import com.facebook.hive.orc.WriterImpl.RowIndexPositionRecorder; BitFieldReader in = new BitFieldReader(InStream.create("test", inBuf, codec, 500)); for(int i=0; i < COUNT; ++i) { int x = in.next(); if (i < COUNT / 2) { assertEquals(i & 1, x); } else { assertEquals((i/3) & 1, x); } } in.loadIndeces(rowIndex.build().getEntryList(), 0); for(int i=COUNT-1; i >= 0; --i) { in.seek(i); int x = in.next(); if (i < COUNT / 2) { assertEquals(i & 1, x); } else { assertEquals((i/3) & 1, x); } } } @Test public void testUncompressedSeek() throws Exception { ReaderWriterProfiler.setProfilerOptions(null); runSeekTest(null); } @Test public void testCompressedSeek() throws Exception { ReaderWriterProfiler.setProfilerOptions(null);
runSeekTest(new ZlibCodec());
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/Reader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // }
import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * The interface for reading ORC files. * * One Reader can support multiple concurrent RecordReader. */ public interface Reader { /** * Get the number of rows in the file. * @return the number of rows */ long getNumberOfRows(); /** * Get the raw size of the data in the file * @return the raw size */ long getRawDataSize(); /** * Get the user metadata keys. * @return the set of metadata keys */ Iterable<String> getMetadataKeys(); /** * Get a user metadata value. * @param key a key given by the user * @return the bytes associated with the given key */ ByteBuffer getMetadataValue(String key); /** * Get the compression kind. * @return the kind of compression in the file */
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/Reader.java import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * The interface for reading ORC files. * * One Reader can support multiple concurrent RecordReader. */ public interface Reader { /** * Get the number of rows in the file. * @return the number of rows */ long getNumberOfRows(); /** * Get the raw size of the data in the file * @return the raw size */ long getRawDataSize(); /** * Get the user metadata keys. * @return the set of metadata keys */ Iterable<String> getMetadataKeys(); /** * Get a user metadata value. * @param key a key given by the user * @return the bytes associated with the given key */ ByteBuffer getMetadataValue(String key); /** * Get the compression kind. * @return the kind of compression in the file */
CompressionKind getCompression();
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/Reader.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // }
import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List;
// Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * The interface for reading ORC files. * * One Reader can support multiple concurrent RecordReader. */ public interface Reader { /** * Get the number of rows in the file. * @return the number of rows */ long getNumberOfRows(); /** * Get the raw size of the data in the file * @return the raw size */ long getRawDataSize(); /** * Get the user metadata keys. * @return the set of metadata keys */ Iterable<String> getMetadataKeys(); /** * Get a user metadata value. * @param key a key given by the user * @return the bytes associated with the given key */ ByteBuffer getMetadataValue(String key); /** * Get the compression kind. * @return the kind of compression in the file */ CompressionKind getCompression(); /** * Get the buffer size for the compression. * @return number of bytes to buffer for the compression codec. */ int getCompressionSize(); /** * Get the number of rows per a entry in the row index. * @return the number of rows per an entry in the row index or 0 if there * is no row index. */ int getRowIndexStride(); /** * Get the list of stripes. * @return the information about the stripes sorted in order of how they occur in the file physically. */ Iterable<StripeInformation> getStripes(); /** * Get the object inspector for looking at the objects. * @return an object inspector for each row returned */ ObjectInspector getObjectInspector(); /** * Get the length of the file. * @return the number of bytes in the file */ long getContentLength(); /** * Get the statistics about the columns in the file. * @return the information about the column */
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/statistics/ColumnStatistics.java // public interface ColumnStatistics { // /** // * Get the number of values in this column. It will differ from the number // * of rows because of NULL values and repeated values. // * @return the number of values // */ // long getNumberOfValues(); // } // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/Reader.java import com.facebook.hive.orc.compression.CompressionKind; import com.facebook.hive.orc.statistics.ColumnStatistics; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; // Copyright (c) 2013, Facebook, Inc. All rights reserved. /** * 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.facebook.hive.orc; /** * The interface for reading ORC files. * * One Reader can support multiple concurrent RecordReader. */ public interface Reader { /** * Get the number of rows in the file. * @return the number of rows */ long getNumberOfRows(); /** * Get the raw size of the data in the file * @return the raw size */ long getRawDataSize(); /** * Get the user metadata keys. * @return the set of metadata keys */ Iterable<String> getMetadataKeys(); /** * Get a user metadata value. * @param key a key given by the user * @return the bytes associated with the given key */ ByteBuffer getMetadataValue(String key); /** * Get the compression kind. * @return the kind of compression in the file */ CompressionKind getCompression(); /** * Get the buffer size for the compression. * @return number of bytes to buffer for the compression codec. */ int getCompressionSize(); /** * Get the number of rows per a entry in the row index. * @return the number of rows per an entry in the row index or 0 if there * is no row index. */ int getRowIndexStride(); /** * Get the list of stripes. * @return the information about the stripes sorted in order of how they occur in the file physically. */ Iterable<StripeInformation> getStripes(); /** * Get the object inspector for looking at the objects. * @return an object inspector for each row returned */ ObjectInspector getObjectInspector(); /** * Get the length of the file. * @return the number of bytes in the file */ long getContentLength(); /** * Get the statistics about the columns in the file. * @return the information about the column */
ColumnStatistics[] getStatistics();
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestMapTreeWriter.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyStruct.java // public class OrcLazyStruct extends OrcLazyObject { // // public OrcLazyStruct(LazyStructTreeReader treeReader) { // super(treeReader); // } // }
import static junit.framework.Assert.assertEquals; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import com.facebook.hive.orc.lazy.OrcLazyMap; import com.facebook.hive.orc.lazy.OrcLazyStruct;
return ObjectInspectorUtils.getStandardStructFieldRef(fieldName, fields); } @Override public Object getStructFieldData(Object data, StructField fieldRef) { if (data == null) { return null; } return ((MapStruct) data).getMap(); } @Override public List<Object> getStructFieldsDataAsList(Object data) { return Arrays.asList((Object) ((MapStruct) data).getMap()); } } @Test /** * Tests writing a Map containing only an entry with a null key. */ public void testIntegerEnterLowMemoryModeAndOnNotCarriedOverStripe() throws Exception { ObjectInspector inspector; synchronized (TestMapTreeWriter.class) { inspector = new MapStructObjectInspector(); } ReaderWriterProfiler.setProfilerOptions(conf); Writer writer = new WriterImpl(fs, testFilePath, conf, inspector,
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyStruct.java // public class OrcLazyStruct extends OrcLazyObject { // // public OrcLazyStruct(LazyStructTreeReader treeReader) { // super(treeReader); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestMapTreeWriter.java import static junit.framework.Assert.assertEquals; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import com.facebook.hive.orc.lazy.OrcLazyMap; import com.facebook.hive.orc.lazy.OrcLazyStruct; return ObjectInspectorUtils.getStandardStructFieldRef(fieldName, fields); } @Override public Object getStructFieldData(Object data, StructField fieldRef) { if (data == null) { return null; } return ((MapStruct) data).getMap(); } @Override public List<Object> getStructFieldsDataAsList(Object data) { return Arrays.asList((Object) ((MapStruct) data).getMap()); } } @Test /** * Tests writing a Map containing only an entry with a null key. */ public void testIntegerEnterLowMemoryModeAndOnNotCarriedOverStripe() throws Exception { ObjectInspector inspector; synchronized (TestMapTreeWriter.class) { inspector = new MapStructObjectInspector(); } ReaderWriterProfiler.setProfilerOptions(conf); Writer writer = new WriterImpl(fs, testFilePath, conf, inspector,
1000000, CompressionKind.NONE, 100, 10000, new MemoryManager(conf));
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestMapTreeWriter.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyStruct.java // public class OrcLazyStruct extends OrcLazyObject { // // public OrcLazyStruct(LazyStructTreeReader treeReader) { // super(treeReader); // } // }
import static junit.framework.Assert.assertEquals; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import com.facebook.hive.orc.lazy.OrcLazyMap; import com.facebook.hive.orc.lazy.OrcLazyStruct;
} @Override public List<Object> getStructFieldsDataAsList(Object data) { return Arrays.asList((Object) ((MapStruct) data).getMap()); } } @Test /** * Tests writing a Map containing only an entry with a null key. */ public void testIntegerEnterLowMemoryModeAndOnNotCarriedOverStripe() throws Exception { ObjectInspector inspector; synchronized (TestMapTreeWriter.class) { inspector = new MapStructObjectInspector(); } ReaderWriterProfiler.setProfilerOptions(conf); Writer writer = new WriterImpl(fs, testFilePath, conf, inspector, 1000000, CompressionKind.NONE, 100, 10000, new MemoryManager(conf)); Map<String, String> map = new HashMap<String, String>(); map.put(null, null); // Write a map containing only a null key writer.addRow(new MapStruct(map)); writer.close(); Reader reader = OrcFile.createReader(fs, testFilePath, conf); RecordReader rows = reader.rows(null);
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/compression/CompressionKind.java // public enum CompressionKind { // NONE, ZLIB, SNAPPY, LZO // } // // Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyStruct.java // public class OrcLazyStruct extends OrcLazyObject { // // public OrcLazyStruct(LazyStructTreeReader treeReader) { // super(treeReader); // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestMapTreeWriter.java import static junit.framework.Assert.assertEquals; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.facebook.hive.orc.compression.CompressionKind; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import com.facebook.hive.orc.lazy.OrcLazyMap; import com.facebook.hive.orc.lazy.OrcLazyStruct; } @Override public List<Object> getStructFieldsDataAsList(Object data) { return Arrays.asList((Object) ((MapStruct) data).getMap()); } } @Test /** * Tests writing a Map containing only an entry with a null key. */ public void testIntegerEnterLowMemoryModeAndOnNotCarriedOverStripe() throws Exception { ObjectInspector inspector; synchronized (TestMapTreeWriter.class) { inspector = new MapStructObjectInspector(); } ReaderWriterProfiler.setProfilerOptions(conf); Writer writer = new WriterImpl(fs, testFilePath, conf, inspector, 1000000, CompressionKind.NONE, 100, 10000, new MemoryManager(conf)); Map<String, String> map = new HashMap<String, String>(); map.put(null, null); // Write a map containing only a null key writer.addRow(new MapStruct(map)); writer.close(); Reader reader = OrcFile.createReader(fs, testFilePath, conf); RecordReader rows = reader.rows(null);
OrcLazyStruct lazyRow = null;
facebookarchive/hive-dwrf
hive-dwrf/src/test/java/com/facebook/hive/orc/TestRecordReaderImpl.java
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyRow.java // public class OrcLazyRow extends OrcLazyStruct { // // private OrcLazyObject[] fields; // private final List<String> fieldNames; // // public OrcLazyRow(OrcLazyObject[] fields, List<String> fieldNames) { // super(null); // this.fields = fields; // this.fieldNames = fieldNames; // } // // @Override // public void next() { // super.next(); // for (OrcLazyObject field : fields) { // if (field != null) { // field.next(); // } // } // } // // @Override // public void startStripe(Map<StreamName, InStream> streams, List<OrcProto.ColumnEncoding> encodings, // RowIndex[] indexes, long rowBaseInStripe) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.startStripe(streams, encodings, indexes, rowBaseInStripe); // } // } // } // // @Override // public Object materialize(long row, Object previous) throws IOException { // OrcStruct previousRow; // if (previous != null) { // previousRow = (OrcStruct) previous; // previousRow.setFieldNames(fieldNames); // } else { // previousRow = new OrcStruct(fieldNames); // } // for (int i = 0; i < fields.length; i++) { // previousRow.setFieldValue(i, fields[i]); // } // return previousRow; // } // // @Override // public void seekToRow(long rowNumber) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.seekToRow(rowNumber); // } // } // } // // public int getNumFields() { // return fields.length; // } // // public OrcLazyObject getFieldValue(int index) { // if (index >= fields.length) { // return null; // } // // return fields[index]; // } // // public void reset(OrcLazyRow other) throws IOException { // this.fields = other.getRawFields(); // seekToRow(0); // } // // public OrcLazyObject[] getRawFields() { // return fields; // } // // @Override // public void close() throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.close(); // } // } // } // }
import com.facebook.hive.orc.lazy.OrcLazyRow; import com.facebook.presto.hadoop.shaded.com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordWriter; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue;
jobConf.setLong(OrcConf.ConfVars.HIVE_ORC_STRIPE_SIZE.varname, 1024L); final Path filePath = new Path(this.stagingDir.toString(), fileName); final RecordWriter hiveRecordWriter = (RecordWriter) (new OrcOutputFormat().getHiveRecordWriter( jobConf, filePath, null, true, new Properties(), null)); final OrcSerde orcSerde = new OrcSerde(); ObjectInspector objectInspector = getObjectInspectorFor( ImmutableList.of("col1"), ImmutableList.of("bigint")); final Random rand = new Random(); for (int i = 0; i < 1000; i++) { final List<Object> allColumns = new ArrayList<>(); allColumns.add(rand.nextLong()); Object obj = orcSerde.serialize(allColumns, objectInspector); hiveRecordWriter.write(NullWritable.get(), obj); } hiveRecordWriter.close(null); // Get all the stripes in the file written. final Configuration configuration = new Configuration(); final FileSystem fileSystem = filePath.getFileSystem(configuration); final ReaderImpl readerImpl = new ReaderImpl(fileSystem, filePath, configuration); final ArrayList<StripeInformation> stripes = Lists.newArrayList(readerImpl.getStripes()); assertTrue("Number of stripes produced should be >= 2", stripes.size() >= 2); // Read the file back and read with ReaderImpl over only the 2nd stripe. final boolean[] toRead = {true, true}; final RecordReader recordReader = new ReaderImpl(fileSystem, filePath, configuration).rows( stripes.get(1).getOffset(), stripes.get(1).getDataLength(), toRead);
// Path: hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/OrcLazyRow.java // public class OrcLazyRow extends OrcLazyStruct { // // private OrcLazyObject[] fields; // private final List<String> fieldNames; // // public OrcLazyRow(OrcLazyObject[] fields, List<String> fieldNames) { // super(null); // this.fields = fields; // this.fieldNames = fieldNames; // } // // @Override // public void next() { // super.next(); // for (OrcLazyObject field : fields) { // if (field != null) { // field.next(); // } // } // } // // @Override // public void startStripe(Map<StreamName, InStream> streams, List<OrcProto.ColumnEncoding> encodings, // RowIndex[] indexes, long rowBaseInStripe) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.startStripe(streams, encodings, indexes, rowBaseInStripe); // } // } // } // // @Override // public Object materialize(long row, Object previous) throws IOException { // OrcStruct previousRow; // if (previous != null) { // previousRow = (OrcStruct) previous; // previousRow.setFieldNames(fieldNames); // } else { // previousRow = new OrcStruct(fieldNames); // } // for (int i = 0; i < fields.length; i++) { // previousRow.setFieldValue(i, fields[i]); // } // return previousRow; // } // // @Override // public void seekToRow(long rowNumber) throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.seekToRow(rowNumber); // } // } // } // // public int getNumFields() { // return fields.length; // } // // public OrcLazyObject getFieldValue(int index) { // if (index >= fields.length) { // return null; // } // // return fields[index]; // } // // public void reset(OrcLazyRow other) throws IOException { // this.fields = other.getRawFields(); // seekToRow(0); // } // // public OrcLazyObject[] getRawFields() { // return fields; // } // // @Override // public void close() throws IOException { // for (OrcLazyObject field : fields) { // if (field != null) { // field.close(); // } // } // } // } // Path: hive-dwrf/src/test/java/com/facebook/hive/orc/TestRecordReaderImpl.java import com.facebook.hive.orc.lazy.OrcLazyRow; import com.facebook.presto.hadoop.shaded.com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.serde2.ReaderWriterProfiler; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordWriter; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; jobConf.setLong(OrcConf.ConfVars.HIVE_ORC_STRIPE_SIZE.varname, 1024L); final Path filePath = new Path(this.stagingDir.toString(), fileName); final RecordWriter hiveRecordWriter = (RecordWriter) (new OrcOutputFormat().getHiveRecordWriter( jobConf, filePath, null, true, new Properties(), null)); final OrcSerde orcSerde = new OrcSerde(); ObjectInspector objectInspector = getObjectInspectorFor( ImmutableList.of("col1"), ImmutableList.of("bigint")); final Random rand = new Random(); for (int i = 0; i < 1000; i++) { final List<Object> allColumns = new ArrayList<>(); allColumns.add(rand.nextLong()); Object obj = orcSerde.serialize(allColumns, objectInspector); hiveRecordWriter.write(NullWritable.get(), obj); } hiveRecordWriter.close(null); // Get all the stripes in the file written. final Configuration configuration = new Configuration(); final FileSystem fileSystem = filePath.getFileSystem(configuration); final ReaderImpl readerImpl = new ReaderImpl(fileSystem, filePath, configuration); final ArrayList<StripeInformation> stripes = Lists.newArrayList(readerImpl.getStripes()); assertTrue("Number of stripes produced should be >= 2", stripes.size() >= 2); // Read the file back and read with ReaderImpl over only the 2nd stripe. final boolean[] toRead = {true, true}; final RecordReader recordReader = new ReaderImpl(fileSystem, filePath, configuration).rows( stripes.get(1).getOffset(), stripes.get(1).getDataLength(), toRead);
OrcLazyRow row = null;
ppeccin/javatari
javatari/src/org/javatari/parameters/Parameters.java
// Path: javatari/src/org/javatari/utils/Terminator.java // public final class Terminator { // // public static void terminate() { // if (Room.currentRoom() != null) Room.currentRoom().exit(); // throw new IllegalStateException("Emulator terminated"); // } // // }
import java.awt.event.KeyEvent; import java.io.InputStream; import java.security.AccessControlException; import java.util.Properties; import java.util.prefs.Preferences; import java.util.regex.Pattern; import org.javatari.utils.Terminator;
JOY_P1_YAXIS_SIGNAL = DEFAULT_JOY_AXIS_SIGNAL; JOY_P1_PAD_AXIS = DEFAULT_JOY_PAD_AXIS; JOY_P1_PAD_AXIS_SIGNAL = DEFAULT_JOY_AXIS_SIGNAL; JOY_P1_BUTTON = DEFAULT_JOY_BUTTON; JOY_P1_BUTTON2 = DEFAULT_JOY_BUTTON2; JOY_P1_SELECT = DEFAULT_JOY_SELECT; JOY_P1_RESET = DEFAULT_JOY_RESET; JOY_P1_PAUSE = DEFAULT_JOY_PAUSE; JOY_P1_FAST_SPPED = DEFAULT_JOY_FAST_SPPED; JOY_P1_DEADZONE = DEFAULT_JOY_DEADZONE; JOY_P1_PADDLE_CENTER = DEFAULT_JOY_PADDLE_CENTER; JOY_P1_PADDLE_SENS = DEFAULT_JOY_PADDLE_SENS; } private static void parseMainArg(String[] args) { for (String arg : args) if (!arg.startsWith("-")) { mainArg = arg; return; } } private static void parseOptions(String[] args) { for (String arg : args) { if (!arg.startsWith("-")) continue; String opt = arg.substring(1); Pattern p = Pattern.compile("="); String[] params = p.split(opt); if (params == null || params.length != 2 || params[0].isEmpty() || params[1].isEmpty()) { System.out.println("Invalid option format: " + arg);
// Path: javatari/src/org/javatari/utils/Terminator.java // public final class Terminator { // // public static void terminate() { // if (Room.currentRoom() != null) Room.currentRoom().exit(); // throw new IllegalStateException("Emulator terminated"); // } // // } // Path: javatari/src/org/javatari/parameters/Parameters.java import java.awt.event.KeyEvent; import java.io.InputStream; import java.security.AccessControlException; import java.util.Properties; import java.util.prefs.Preferences; import java.util.regex.Pattern; import org.javatari.utils.Terminator; JOY_P1_YAXIS_SIGNAL = DEFAULT_JOY_AXIS_SIGNAL; JOY_P1_PAD_AXIS = DEFAULT_JOY_PAD_AXIS; JOY_P1_PAD_AXIS_SIGNAL = DEFAULT_JOY_AXIS_SIGNAL; JOY_P1_BUTTON = DEFAULT_JOY_BUTTON; JOY_P1_BUTTON2 = DEFAULT_JOY_BUTTON2; JOY_P1_SELECT = DEFAULT_JOY_SELECT; JOY_P1_RESET = DEFAULT_JOY_RESET; JOY_P1_PAUSE = DEFAULT_JOY_PAUSE; JOY_P1_FAST_SPPED = DEFAULT_JOY_FAST_SPPED; JOY_P1_DEADZONE = DEFAULT_JOY_DEADZONE; JOY_P1_PADDLE_CENTER = DEFAULT_JOY_PADDLE_CENTER; JOY_P1_PADDLE_SENS = DEFAULT_JOY_PADDLE_SENS; } private static void parseMainArg(String[] args) { for (String arg : args) if (!arg.startsWith("-")) { mainArg = arg; return; } } private static void parseOptions(String[] args) { for (String arg : args) { if (!arg.startsWith("-")) continue; String opt = arg.substring(1); Pattern p = Pattern.compile("="); String[] params = p.split(opt); if (params == null || params.length != 2 || params[0].isEmpty() || params[1].isEmpty()) { System.out.println("Invalid option format: " + arg);
Terminator.terminate();
ppeccin/javatari
javatari/src/org/javatari/pc/room/EmbeddedRoom.java
// Path: javatari/src/org/javatari/pc/screen/PanelScreen.java // public final class PanelScreen extends JPanel implements Screen { // // public PanelScreen(boolean screenFixedSize) { // super(); // monitorPanel = new MonitorPanel(); // monitorPanel.monitor().setFixedSize(screenFixedSize); // if (CONSOLE_PANEL) consolePanel = new ConsolePanel(monitorPanel.monitor(), null); // monitorPanel.monitor().addControlInputComponents(keyControlsInputComponents()); // setup(); // } // // @Override // public void connect(VideoSignal videoSignal, ConsoleControlsSocket controlsSocket, CartridgeSocket cartridgeSocket, SaveStateSocket savestateSocket) { // monitorPanel.connect(videoSignal, controlsSocket, cartridgeSocket, savestateSocket); // if (consolePanel != null) consolePanel.connect(controlsSocket, cartridgeSocket); // } // // @Override // public void powerOn() { // setVisible(true); // monitorPanel.powerOn(); // monitorPanel.requestFocus(); // } // // @Override // public void powerOff() { // monitorPanel.powerOff(); // } // // @Override // public void destroy() { // close(); // monitorPanel.destroy(); // } // // @Override // public void close() { // setVisible(false); // } // // @Override // public Monitor monitor() { // return monitorPanel.monitor(); // } // // @Override // public List<Component> keyControlsInputComponents() { // List<Component> comps = new ArrayList<Component>(Arrays.asList((Component)this)); // comps.addAll(monitorPanel.keyControlsInputComponents()); // if (consolePanel != null) comps.add(consolePanel); // return comps; // } // // private void setup() { // setTransferHandler(new ROMDropTransferHandler()); // monitorPanel.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // if (e.getComponent() == monitorPanel) validate(); // }}); // setLayout(new FlowLayout( // FlowLayout.CENTER, // 0, 0 // )); // setOpaque(false); // add(monitorPanel); // if (consolePanel != null) add(consolePanel); // validate(); // } // // public MonitorPanel monitorPanel; // public ConsolePanel consolePanel; // // private static final boolean CONSOLE_PANEL = Parameters.SCREEN_CONSOLE_PANEL; // // private static final long serialVersionUID = 1L; // // // // To handle drag and drop of ROM files and links // private class ROMDropTransferHandler extends TransferHandler { // @Override // public boolean canImport(TransferSupport support) { // if (!monitorPanel.monitor().isCartridgeChangeEnabled()) return false; // Transferable transf = support.getTransferable(); // if (!ROMTransferHandlerUtil.canAccept(transf)) return false; // if (support.isDrop() && support.getUserDropAction() != LINK) support.setDropAction(COPY); // return true; // } // @Override // public boolean importData(TransferSupport support) { // if (!canImport(support)) return false; // monitorPanel.monitor().showOSD("LOADING CARTRIDGE...", true); // Cartridge cart = ROMTransferHandlerUtil.importCartridgeData(support.getTransferable()); // monitorPanel.monitor().showOSD(null, true); // if (cart == null) return false; // // LINK Action means load Cartridge without auto power! :-) // boolean autoPower = !support.isDrop() || support.getDropAction() != LINK; // monitorPanel.monitor().cartridgeInsert(cart, autoPower); // return true; // } // private static final long serialVersionUID = 1L; // } // // }
import org.javatari.pc.screen.Screen; import javax.swing.RootPaneContainer; import org.javatari.pc.screen.DesktopScreenWindow; import org.javatari.pc.screen.PanelScreen;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.pc.room; public class EmbeddedRoom extends Room { private EmbeddedRoom(RootPaneContainer rootPaneContainer) { super(); this.parentContainer = rootPaneContainer; } @Override protected Screen buildScreenPeripheral() {
// Path: javatari/src/org/javatari/pc/screen/PanelScreen.java // public final class PanelScreen extends JPanel implements Screen { // // public PanelScreen(boolean screenFixedSize) { // super(); // monitorPanel = new MonitorPanel(); // monitorPanel.monitor().setFixedSize(screenFixedSize); // if (CONSOLE_PANEL) consolePanel = new ConsolePanel(monitorPanel.monitor(), null); // monitorPanel.monitor().addControlInputComponents(keyControlsInputComponents()); // setup(); // } // // @Override // public void connect(VideoSignal videoSignal, ConsoleControlsSocket controlsSocket, CartridgeSocket cartridgeSocket, SaveStateSocket savestateSocket) { // monitorPanel.connect(videoSignal, controlsSocket, cartridgeSocket, savestateSocket); // if (consolePanel != null) consolePanel.connect(controlsSocket, cartridgeSocket); // } // // @Override // public void powerOn() { // setVisible(true); // monitorPanel.powerOn(); // monitorPanel.requestFocus(); // } // // @Override // public void powerOff() { // monitorPanel.powerOff(); // } // // @Override // public void destroy() { // close(); // monitorPanel.destroy(); // } // // @Override // public void close() { // setVisible(false); // } // // @Override // public Monitor monitor() { // return monitorPanel.monitor(); // } // // @Override // public List<Component> keyControlsInputComponents() { // List<Component> comps = new ArrayList<Component>(Arrays.asList((Component)this)); // comps.addAll(monitorPanel.keyControlsInputComponents()); // if (consolePanel != null) comps.add(consolePanel); // return comps; // } // // private void setup() { // setTransferHandler(new ROMDropTransferHandler()); // monitorPanel.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // if (e.getComponent() == monitorPanel) validate(); // }}); // setLayout(new FlowLayout( // FlowLayout.CENTER, // 0, 0 // )); // setOpaque(false); // add(monitorPanel); // if (consolePanel != null) add(consolePanel); // validate(); // } // // public MonitorPanel monitorPanel; // public ConsolePanel consolePanel; // // private static final boolean CONSOLE_PANEL = Parameters.SCREEN_CONSOLE_PANEL; // // private static final long serialVersionUID = 1L; // // // // To handle drag and drop of ROM files and links // private class ROMDropTransferHandler extends TransferHandler { // @Override // public boolean canImport(TransferSupport support) { // if (!monitorPanel.monitor().isCartridgeChangeEnabled()) return false; // Transferable transf = support.getTransferable(); // if (!ROMTransferHandlerUtil.canAccept(transf)) return false; // if (support.isDrop() && support.getUserDropAction() != LINK) support.setDropAction(COPY); // return true; // } // @Override // public boolean importData(TransferSupport support) { // if (!canImport(support)) return false; // monitorPanel.monitor().showOSD("LOADING CARTRIDGE...", true); // Cartridge cart = ROMTransferHandlerUtil.importCartridgeData(support.getTransferable()); // monitorPanel.monitor().showOSD(null, true); // if (cart == null) return false; // // LINK Action means load Cartridge without auto power! :-) // boolean autoPower = !support.isDrop() || support.getDropAction() != LINK; // monitorPanel.monitor().cartridgeInsert(cart, autoPower); // return true; // } // private static final long serialVersionUID = 1L; // } // // } // Path: javatari/src/org/javatari/pc/room/EmbeddedRoom.java import org.javatari.pc.screen.Screen; import javax.swing.RootPaneContainer; import org.javatari.pc.screen.DesktopScreenWindow; import org.javatari.pc.screen.PanelScreen; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.pc.room; public class EmbeddedRoom extends Room { private EmbeddedRoom(RootPaneContainer rootPaneContainer) { super(); this.parentContainer = rootPaneContainer; } @Override protected Screen buildScreenPeripheral() {
embeddedScreen = new PanelScreen(true);
ppeccin/javatari
javatari/src/org/javatari/general/m6502/instructions/CLx.java
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6;
import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() {
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6; // Path: javatari/src/org/javatari/general/m6502/instructions/CLx.java import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() {
if (bit == bCARRY) { cpu.CARRY = false; }
ppeccin/javatari
javatari/src/org/javatari/general/m6502/instructions/CLx.java
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6;
import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() { if (bit == bCARRY) { cpu.CARRY = false; }
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6; // Path: javatari/src/org/javatari/general/m6502/instructions/CLx.java import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() { if (bit == bCARRY) { cpu.CARRY = false; }
else if (bit == bDECIMAL_MODE) { cpu.DECIMAL_MODE = false; }
ppeccin/javatari
javatari/src/org/javatari/general/m6502/instructions/CLx.java
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6;
import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() { if (bit == bCARRY) { cpu.CARRY = false; } else if (bit == bDECIMAL_MODE) { cpu.DECIMAL_MODE = false; }
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6; // Path: javatari/src/org/javatari/general/m6502/instructions/CLx.java import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() { if (bit == bCARRY) { cpu.CARRY = false; } else if (bit == bDECIMAL_MODE) { cpu.DECIMAL_MODE = false; }
else if (bit == bINTERRUPT_DISABLE) { cpu.INTERRUPT_DISABLE = false; }
ppeccin/javatari
javatari/src/org/javatari/general/m6502/instructions/CLx.java
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6;
import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() { if (bit == bCARRY) { cpu.CARRY = false; } else if (bit == bDECIMAL_MODE) { cpu.DECIMAL_MODE = false; } else if (bit == bINTERRUPT_DISABLE) { cpu.INTERRUPT_DISABLE = false; }
// Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bCARRY = 0; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bDECIMAL_MODE = 3; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bINTERRUPT_DISABLE = 2; // // Path: javatari/src/org/javatari/general/m6502/StatusBit.java // public static final int bOVERFLOW = 6; // Path: javatari/src/org/javatari/general/m6502/instructions/CLx.java import static org.javatari.general.m6502.StatusBit.bCARRY; import static org.javatari.general.m6502.StatusBit.bDECIMAL_MODE; import static org.javatari.general.m6502.StatusBit.bINTERRUPT_DISABLE; import static org.javatari.general.m6502.StatusBit.bOVERFLOW; import org.javatari.general.m6502.Instruction; import org.javatari.general.m6502.M6502; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.general.m6502.instructions; public final class CLx extends Instruction { public CLx(M6502 cpu, int bit) { super(cpu); this.bit = bit; } @Override public int fetch() { return 2; } @Override public void execute() { if (bit == bCARRY) { cpu.CARRY = false; } else if (bit == bDECIMAL_MODE) { cpu.DECIMAL_MODE = false; } else if (bit == bINTERRUPT_DISABLE) { cpu.INTERRUPT_DISABLE = false; }
else if (bit == bOVERFLOW) { cpu.OVERFLOW = false; }
ppeccin/javatari
javatari/src/org/javatari/atari/network/ControlChange.java
// Path: javatari/src/org/javatari/atari/controls/ConsoleControls.java // public static enum Control { // JOY0_UP, JOY0_DOWN, JOY0_LEFT, JOY0_RIGHT, JOY0_BUTTON, // JOY1_UP, JOY1_DOWN, JOY1_LEFT, JOY1_RIGHT, JOY1_BUTTON, // PADDLE0_POSITION, PADDLE1_POSITION, // Position from 380 (Left) to 190 (Center) to 0 (Right); -1 = disconnected, won't charge POTs // PADDLE0_BUTTON, PADDLE1_BUTTON, // POWER, BLACK_WHITE, SELECT, RESET, // DIFFICULTY0, DIFFICULTY1, // DEBUG, NO_COLLISIONS, TRACE, PAUSE, FRAME, FAST_SPEED, // CARTRIDGE_FORMAT, CARTRIDGE_CLOCK_DEC, CARTRIDGE_CLOCK_INC, // VIDEO_STANDARD, POWER_FRY, // // // TODO Migrate State controls out of the Console (to Monitor) // SAVE_STATE_0(0), SAVE_STATE_1(1), SAVE_STATE_2(2), SAVE_STATE_3(3), SAVE_STATE_4(4), SAVE_STATE_5(5), // SAVE_STATE_6(6), SAVE_STATE_7(7), SAVE_STATE_8(8), SAVE_STATE_9(9), SAVE_STATE_10(10), SAVE_STATE_11(11), SAVE_STATE_12(12), // LOAD_STATE_0(0), LOAD_STATE_1(1), LOAD_STATE_2(2), LOAD_STATE_3(3), LOAD_STATE_4(4), LOAD_STATE_5(5), // LOAD_STATE_6(6), LOAD_STATE_7(7), LOAD_STATE_8(8), LOAD_STATE_9(9), LOAD_STATE_10(10), LOAD_STATE_11(11), LOAD_STATE_12(12); // // Control() { // this(-1); // } // Control(int slot) { // this.slot = slot; // } // public boolean isStateControl() { // return slot >= 0; // } // public final int slot; // };
import java.io.Serializable; import org.javatari.atari.controls.ConsoleControls.Control;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.atari.network; public class ControlChange implements Serializable { protected ControlChange() { super(); }
// Path: javatari/src/org/javatari/atari/controls/ConsoleControls.java // public static enum Control { // JOY0_UP, JOY0_DOWN, JOY0_LEFT, JOY0_RIGHT, JOY0_BUTTON, // JOY1_UP, JOY1_DOWN, JOY1_LEFT, JOY1_RIGHT, JOY1_BUTTON, // PADDLE0_POSITION, PADDLE1_POSITION, // Position from 380 (Left) to 190 (Center) to 0 (Right); -1 = disconnected, won't charge POTs // PADDLE0_BUTTON, PADDLE1_BUTTON, // POWER, BLACK_WHITE, SELECT, RESET, // DIFFICULTY0, DIFFICULTY1, // DEBUG, NO_COLLISIONS, TRACE, PAUSE, FRAME, FAST_SPEED, // CARTRIDGE_FORMAT, CARTRIDGE_CLOCK_DEC, CARTRIDGE_CLOCK_INC, // VIDEO_STANDARD, POWER_FRY, // // // TODO Migrate State controls out of the Console (to Monitor) // SAVE_STATE_0(0), SAVE_STATE_1(1), SAVE_STATE_2(2), SAVE_STATE_3(3), SAVE_STATE_4(4), SAVE_STATE_5(5), // SAVE_STATE_6(6), SAVE_STATE_7(7), SAVE_STATE_8(8), SAVE_STATE_9(9), SAVE_STATE_10(10), SAVE_STATE_11(11), SAVE_STATE_12(12), // LOAD_STATE_0(0), LOAD_STATE_1(1), LOAD_STATE_2(2), LOAD_STATE_3(3), LOAD_STATE_4(4), LOAD_STATE_5(5), // LOAD_STATE_6(6), LOAD_STATE_7(7), LOAD_STATE_8(8), LOAD_STATE_9(9), LOAD_STATE_10(10), LOAD_STATE_11(11), LOAD_STATE_12(12); // // Control() { // this(-1); // } // Control(int slot) { // this.slot = slot; // } // public boolean isStateControl() { // return slot >= 0; // } // public final int slot; // }; // Path: javatari/src/org/javatari/atari/network/ControlChange.java import java.io.Serializable; import org.javatari.atari.controls.ConsoleControls.Control; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.atari.network; public class ControlChange implements Serializable { protected ControlChange() { super(); }
public ControlChange(Control control, boolean state) {
ppeccin/javatari
javatari/src/org/javatari/pc/cartridge/BuiltInROM.java
// Path: javatari/src/org/javatari/utils/Terminator.java // public final class Terminator { // // public static void terminate() { // if (Room.currentRoom() != null) Room.currentRoom().exit(); // throw new IllegalStateException("Emulator terminated"); // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import javax.swing.JOptionPane; import org.javatari.utils.Terminator;
// Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.pc.cartridge; public class BuiltInROM { public BuiltInROM(String label, String labelColors, URL romURL) { super(); this.label = label; this.labelColors = labelColors; this.url = romURL; } public static ArrayList<BuiltInROM> all() { ArrayList<BuiltInROM> result = new ArrayList<BuiltInROM>(); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ROMS_FOLDER + "/" + ROMS_LIST_FILE); if (stream == null) return result; BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { try { String line; while((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) continue; String[] specs = line.split("@"); if (specs.length == 0) continue; String location = specs[specs.length -1].trim(); if (location.isEmpty()) continue; // First try to find as resource URL url = fileNameAsResourceURL(location); if (url == null) { // If not try as URL directly try { url = new URL(location); } catch (Exception e) { errorMessage(location);
// Path: javatari/src/org/javatari/utils/Terminator.java // public final class Terminator { // // public static void terminate() { // if (Room.currentRoom() != null) Room.currentRoom().exit(); // throw new IllegalStateException("Emulator terminated"); // } // // } // Path: javatari/src/org/javatari/pc/cartridge/BuiltInROM.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import javax.swing.JOptionPane; import org.javatari.utils.Terminator; // Copyright 2011-2012 Paulo Augusto Peccin. See licence.txt distributed with this file. package org.javatari.pc.cartridge; public class BuiltInROM { public BuiltInROM(String label, String labelColors, URL romURL) { super(); this.label = label; this.labelColors = labelColors; this.url = romURL; } public static ArrayList<BuiltInROM> all() { ArrayList<BuiltInROM> result = new ArrayList<BuiltInROM>(); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ROMS_FOLDER + "/" + ROMS_LIST_FILE); if (stream == null) return result; BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { try { String line; while((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) continue; String[] specs = line.split("@"); if (specs.length == 0) continue; String location = specs[specs.length -1].trim(); if (location.isEmpty()) continue; // First try to find as resource URL url = fileNameAsResourceURL(location); if (url == null) { // If not try as URL directly try { url = new URL(location); } catch (Exception e) { errorMessage(location);
Terminator.terminate();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/parameters/TestParameters.java
// Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // }
import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import java.util.Arrays; import net.jadler.stubbing.server.StubHttpServer; import net.jadler.stubbing.server.jdk.JdkStubHttpServer;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.parameters; /** * Provides test parameters for the acceptance/integration tests located in the {@code jadler-all} module. */ public class TestParameters { /** * @return parameters for acceptance/integration tests located in this module. The fugly return type * is required by the jUnit parameters mechanism. It basically returns two stub server factories as * test parameters. */ public Iterable<StubHttpServerFactory[]> provide() { return Arrays.asList( singletonArray(new StubHttpServerFactory() { @Override
// Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import java.util.Arrays; import net.jadler.stubbing.server.StubHttpServer; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.parameters; /** * Provides test parameters for the acceptance/integration tests located in the {@code jadler-all} module. */ public class TestParameters { /** * @return parameters for acceptance/integration tests located in this module. The fugly return type * is required by the jUnit parameters mechanism. It basically returns two stub server factories as * test parameters. */ public Iterable<StubHttpServerFactory[]> provide() { return Arrays.asList( singletonArray(new StubHttpServerFactory() { @Override
public StubHttpServer createServer() {
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/parameters/TestParameters.java
// Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // }
import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import java.util.Arrays; import net.jadler.stubbing.server.StubHttpServer; import net.jadler.stubbing.server.jdk.JdkStubHttpServer;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.parameters; /** * Provides test parameters for the acceptance/integration tests located in the {@code jadler-all} module. */ public class TestParameters { /** * @return parameters for acceptance/integration tests located in this module. The fugly return type * is required by the jUnit parameters mechanism. It basically returns two stub server factories as * test parameters. */ public Iterable<StubHttpServerFactory[]> provide() { return Arrays.asList( singletonArray(new StubHttpServerFactory() { @Override public StubHttpServer createServer() {
// Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import java.util.Arrays; import net.jadler.stubbing.server.StubHttpServer; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.parameters; /** * Provides test parameters for the acceptance/integration tests located in the {@code jadler-all} module. */ public class TestParameters { /** * @return parameters for acceptance/integration tests located in this module. The fugly return type * is required by the jUnit parameters mechanism. It basically returns two stub server factories as * test parameters. */ public Iterable<StubHttpServerFactory[]> provide() { return Arrays.asList( singletonArray(new StubHttpServerFactory() { @Override public StubHttpServer createServer() {
return new JettyStubHttpServer();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/parameters/TestParameters.java
// Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // }
import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import java.util.Arrays; import net.jadler.stubbing.server.StubHttpServer; import net.jadler.stubbing.server.jdk.JdkStubHttpServer;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.parameters; /** * Provides test parameters for the acceptance/integration tests located in the {@code jadler-all} module. */ public class TestParameters { /** * @return parameters for acceptance/integration tests located in this module. The fugly return type * is required by the jUnit parameters mechanism. It basically returns two stub server factories as * test parameters. */ public Iterable<StubHttpServerFactory[]> provide() { return Arrays.asList( singletonArray(new StubHttpServerFactory() { @Override public StubHttpServer createServer() { return new JettyStubHttpServer(); } }), singletonArray(new StubHttpServerFactory() { @Override public StubHttpServer createServer() {
// Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import java.util.Arrays; import net.jadler.stubbing.server.StubHttpServer; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.parameters; /** * Provides test parameters for the acceptance/integration tests located in the {@code jadler-all} module. */ public class TestParameters { /** * @return parameters for acceptance/integration tests located in this module. The fugly return type * is required by the jUnit parameters mechanism. It basically returns two stub server factories as * test parameters. */ public Iterable<StubHttpServerFactory[]> provide() { return Arrays.asList( singletonArray(new StubHttpServerFactory() { @Override public StubHttpServer createServer() { return new JettyStubHttpServer(); } }), singletonArray(new StubHttpServerFactory() { @Override public StubHttpServer createServer() {
return new JdkStubHttpServer();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/ResetJettyIntegrationTest.java
// Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // }
import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import org.junit.BeforeClass;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JettyStubHttpServer} implementation. */ public class ResetJettyIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
// Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // Path: jadler-all/src/test/java/net/jadler/ResetJettyIntegrationTest.java import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import org.junit.BeforeClass; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JettyStubHttpServer} implementation. */ public class ResetJettyIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
initJadlerUsing(new JettyStubHttpServer())
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/ResetJettyIntegrationTest.java
// Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // }
import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import org.junit.BeforeClass;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JettyStubHttpServer} implementation. */ public class ResetJettyIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
// Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java // public class JettyStubHttpServer implements StubHttpServer { // // private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); // private final Server server; // private final Connector httpConnector; // // public JettyStubHttpServer() { // this(0); // } // // // public JettyStubHttpServer(final int port) { // this.server = new Server(); // this.server.setSendServerVersion(false); // this.server.setSendDateHeader(true); // // this.httpConnector = new SelectChannelConnector(); // this.httpConnector.setPort(port); // server.addConnector(this.httpConnector); // } // // // /** // * {@inheritDoc} // */ // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // Validate.notNull(ruleProvider, "ruleProvider cannot be null"); // // server.setHandler(new JadlerHandler(ruleProvider)); // } // // // /** // * {@inheritDoc} // */ // @Override // public void start() throws Exception { // logger.debug("starting jetty"); // server.start(); // logger.debug("jetty started"); // } // // // /** // * {@inheritDoc} // */ // @Override // public void stop() throws Exception { // logger.debug("stopping jetty"); // server.stop(); // logger.debug("jetty stopped"); // } // // // /** // * {@inheritDoc} // */ // @Override // public int getPort() { // return httpConnector.getLocalPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // Path: jadler-all/src/test/java/net/jadler/ResetJettyIntegrationTest.java import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jetty.JettyStubHttpServer; import org.junit.BeforeClass; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JettyStubHttpServer} implementation. */ public class ResetJettyIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
initJadlerUsing(new JettyStubHttpServer())
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * A base implementation of the {@link RequestMatching} interface. Collects all request predicates to a protected * collection available in extending classes. * * @param <T> type (either class or interface) of the class extending this abstract class. This type will be returned * by all methods introduced in {@link RequestMatching} implemented by this class so fluid request matching * is possible. */ public abstract class AbstractRequestMatching<T extends RequestMatching<T>> implements RequestMatching<T> { protected final List<Matcher<? super Request>> predicates; protected AbstractRequestMatching() { this.predicates = new ArrayList<Matcher<? super Request>>(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public T that(final Matcher<? super Request> predicate) { Validate.notNull(predicate, "predicate cannot be null"); this.predicates.add(predicate); return (T) this; } /** * {@inheritDoc} */ @Override public T havingMethodEqualTo(final String method) { Validate.notEmpty(method, "method cannot be empty"); return havingMethod(equalToIgnoringCase(method)); } /** * {@inheritDoc} */ @Override public T havingMethod(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null");
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * A base implementation of the {@link RequestMatching} interface. Collects all request predicates to a protected * collection available in extending classes. * * @param <T> type (either class or interface) of the class extending this abstract class. This type will be returned * by all methods introduced in {@link RequestMatching} implemented by this class so fluid request matching * is possible. */ public abstract class AbstractRequestMatching<T extends RequestMatching<T>> implements RequestMatching<T> { protected final List<Matcher<? super Request>> predicates; protected AbstractRequestMatching() { this.predicates = new ArrayList<Matcher<? super Request>>(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public T that(final Matcher<? super Request> predicate) { Validate.notNull(predicate, "predicate cannot be null"); this.predicates.add(predicate); return (T) this; } /** * {@inheritDoc} */ @Override public T havingMethodEqualTo(final String method) { Validate.notEmpty(method, "method cannot be empty"); return havingMethod(equalToIgnoringCase(method)); } /** * {@inheritDoc} */ @Override public T havingMethod(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null");
return that(requestMethod(predicate));
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * A base implementation of the {@link RequestMatching} interface. Collects all request predicates to a protected * collection available in extending classes. * * @param <T> type (either class or interface) of the class extending this abstract class. This type will be returned * by all methods introduced in {@link RequestMatching} implemented by this class so fluid request matching * is possible. */ public abstract class AbstractRequestMatching<T extends RequestMatching<T>> implements RequestMatching<T> { protected final List<Matcher<? super Request>> predicates; protected AbstractRequestMatching() { this.predicates = new ArrayList<Matcher<? super Request>>(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public T that(final Matcher<? super Request> predicate) { Validate.notNull(predicate, "predicate cannot be null"); this.predicates.add(predicate); return (T) this; } /** * {@inheritDoc} */ @Override public T havingMethodEqualTo(final String method) { Validate.notEmpty(method, "method cannot be empty"); return havingMethod(equalToIgnoringCase(method)); } /** * {@inheritDoc} */ @Override public T havingMethod(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestMethod(predicate)); } /** * {@inheritDoc} */ @Override
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * A base implementation of the {@link RequestMatching} interface. Collects all request predicates to a protected * collection available in extending classes. * * @param <T> type (either class or interface) of the class extending this abstract class. This type will be returned * by all methods introduced in {@link RequestMatching} implemented by this class so fluid request matching * is possible. */ public abstract class AbstractRequestMatching<T extends RequestMatching<T>> implements RequestMatching<T> { protected final List<Matcher<? super Request>> predicates; protected AbstractRequestMatching() { this.predicates = new ArrayList<Matcher<? super Request>>(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public T that(final Matcher<? super Request> predicate) { Validate.notNull(predicate, "predicate cannot be null"); this.predicates.add(predicate); return (T) this; } /** * {@inheritDoc} */ @Override public T havingMethodEqualTo(final String method) { Validate.notEmpty(method, "method cannot be empty"); return havingMethod(equalToIgnoringCase(method)); } /** * {@inheritDoc} */ @Override public T havingMethod(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestMethod(predicate)); } /** * {@inheritDoc} */ @Override
public T havingBodyEqualTo(final String requestBody) {
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
/** * {@inheritDoc} */ @Override public T havingBodyEqualTo(final String requestBody) { Validate.notNull(requestBody, "requestBody cannot be null, use an empty string instead"); return havingBody(equalTo(requestBody)); } /** * {@inheritDoc} */ @Override public T havingBody(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestBody(predicate)); } /** * {@inheritDoc} */ @Override public T havingRawBodyEqualTo(final byte[] requestBody) { Validate.notNull(requestBody, "requestBody cannot be null, use an empty array instead");
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; /** * {@inheritDoc} */ @Override public T havingBodyEqualTo(final String requestBody) { Validate.notNull(requestBody, "requestBody cannot be null, use an empty string instead"); return havingBody(equalTo(requestBody)); } /** * {@inheritDoc} */ @Override public T havingBody(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestBody(predicate)); } /** * {@inheritDoc} */ @Override public T havingRawBodyEqualTo(final byte[] requestBody) { Validate.notNull(requestBody, "requestBody cannot be null, use an empty array instead");
return that(requestRawBody(equalTo(requestBody)));
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
/** * {@inheritDoc} */ @Override public T havingRawBodyEqualTo(final byte[] requestBody) { Validate.notNull(requestBody, "requestBody cannot be null, use an empty array instead"); return that(requestRawBody(equalTo(requestBody))); } /** * {@inheritDoc} */ @Override public T havingPathEqualTo(final String path) { Validate.notEmpty(path, "path cannot be empty"); return havingPath(equalTo(path)); } /** * {@inheritDoc} */ @Override public T havingPath(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null");
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; /** * {@inheritDoc} */ @Override public T havingRawBodyEqualTo(final byte[] requestBody) { Validate.notNull(requestBody, "requestBody cannot be null, use an empty array instead"); return that(requestRawBody(equalTo(requestBody))); } /** * {@inheritDoc} */ @Override public T havingPathEqualTo(final String path) { Validate.notEmpty(path, "path cannot be empty"); return havingPath(equalTo(path)); } /** * {@inheritDoc} */ @Override public T havingPath(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null");
return that(requestPath(predicate));
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
} /** * {@inheritDoc} */ @Override public T havingPath(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestPath(predicate)); } /** * {@inheritDoc} */ @Override public T havingQueryStringEqualTo(final String queryString) { return havingQueryString(equalTo(queryString)); } /** * {@inheritDoc} */ @Override public T havingQueryString(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null");
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; } /** * {@inheritDoc} */ @Override public T havingPath(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestPath(predicate)); } /** * {@inheritDoc} */ @Override public T havingQueryStringEqualTo(final String queryString) { return havingQueryString(equalTo(queryString)); } /** * {@inheritDoc} */ @Override public T havingQueryString(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null");
return that(requestQueryString(predicate));
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
/** * {@inheritDoc} */ @Override public T havingQueryString(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestQueryString(predicate)); } /** * {@inheritDoc} */ @Override public T havingParameterEqualTo(final String name, final String value) { Validate.notNull(value, "value cannot be null"); return havingParameter(name, hasItem(value)); } /** * {@inheritDoc} */ @Override public T havingParameter(final String name, final Matcher<? super List<String>> predicate) { Validate.notEmpty(name, "name cannot be empty"); Validate.notNull(predicate, "predicate cannot be null");
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; /** * {@inheritDoc} */ @Override public T havingQueryString(final Matcher<? super String> predicate) { Validate.notNull(predicate, "predicate cannot be null"); return that(requestQueryString(predicate)); } /** * {@inheritDoc} */ @Override public T havingParameterEqualTo(final String name, final String value) { Validate.notNull(value, "value cannot be null"); return havingParameter(name, hasItem(value)); } /** * {@inheritDoc} */ @Override public T havingParameter(final String name, final Matcher<? super List<String>> predicate) { Validate.notEmpty(name, "name cannot be empty"); Validate.notNull(predicate, "predicate cannot be null");
return that(requestParameter(name, predicate));