void test(String[] opts, String className) throws Exception { count++; System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className); Path testSrcDir = Paths.get(System.getProperty("test.src")); Path testClassesDir = Paths.get(System.getProperty("test.classes")); Path classes = Paths.get("classes." + count); classes.createDirectory(); Context ctx = new Context(); PathFileManager fm = new JavacPathFileManager(ctx, true, null); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); List<String> options = new ArrayList<String>(); options.addAll(Arrays.asList(opts)); options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString())); Iterable<? extends JavaFileObject> compilationUnits = fm.getJavaFileObjects(testSrcDir.resolve(className + ".java")); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); JavaCompiler.CompilationTask t = compiler.getTask(out, fm, null, options, null, compilationUnits); boolean ok = t.call(); System.err.println(sw.toString()); if (!ok) { throw new Exception("compilation failed"); } File expect = new File("classes." + count + "/" + className + ".class"); if (!expect.exists()) throw new Exception("expected file not found: " + expect); long expectedSize = new File(testClassesDir.toString(), className + ".class").length(); long actualSize = expect.length(); if (expectedSize != actualSize) throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize); }
private void updateLinuxServiceInstaller() { try { File dir = new File(directory, "CTP"); if (suppressFirstPathElement) dir = dir.getParentFile(); Properties props = new Properties(); String ctpHome = dir.getAbsolutePath(); cp.appendln(Color.black, "...CTP_HOME: " + ctpHome); ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\"); props.put("CTP_HOME", ctpHome); File javaHome = new File(System.getProperty("java.home")); String javaBin = (new File(javaHome, "bin")).getAbsolutePath(); cp.appendln(Color.black, "...JAVA_BIN: " + javaBin); javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\"); props.put("JAVA_BIN", javaBin); File linux = new File(dir, "linux"); File install = new File(linux, "ctpService-ubuntu.sh"); cp.appendln(Color.black, "Linux service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); String bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); setFileText(install, bat); // If this is an ISN installation, put the script in the correct place. String osName = System.getProperty("os.name").toLowerCase(); if (programName.equals("ISN") && !osName.contains("windows")) { install = new File(linux, "ctpService-red.sh"); cp.appendln(Color.black, "ISN service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); File initDir = new File("/etc/init.d"); File initFile = new File(initDir, "ctpService"); if (initDir.exists()) { setOwnership(initDir, "edge", "edge"); setFileText(initFile, bat); initFile.setReadable(true, false); // everybody can read //Java 1.6 initFile.setWritable(true); // only the owner can write //Java 1.6 initFile.setExecutable(true, false); // everybody can execute //Java 1.6 } } } catch (Exception ex) { ex.printStackTrace(); System.err.println("Unable to update the Linux service ctpService.sh file"); } }
public void run() throws Exception { File rtDir = new File("rt.dir"); File javaHome = new File(System.getProperty("java.home")); if (javaHome.getName().equals("jre")) javaHome = javaHome.getParentFile(); File rtJar = new File(new File(new File(javaHome, "jre"), "lib"), "rt.jar"); expand(rtJar, rtDir); String[] rtDir_opts = { "-bootclasspath", rtDir.toString(), "-classpath", "", "-sourcepath", "", "-extdirs", "" }; test(rtDir_opts, "HelloPathWorld"); if (isJarFileSystemAvailable()) { String[] rtJar_opts = { "-bootclasspath", rtJar.toString(), "-classpath", "", "-sourcepath", "", "-extdirs", "" }; test(rtJar_opts, "HelloPathWorld"); String[] default_opts = {}; test(default_opts, "HelloPathWorld"); // finally, a non-trivial program test(default_opts, "CompileTest"); } else System.err.println("jar file system not available: test skipped"); }
private boolean istWindows() { boolean retValue = false; if (System.getProperty("os.name").contains("Windows")) { retValue = true; } return retValue; }
public static void main(String[] args) throws Exception { Path dir1 = TestUtil.createTemporaryDirectory(); try { // Same directory testCopyFileToFile(dir1, dir1, TestUtil.supportsLinks(dir1)); testMove(dir1, dir1, TestUtil.supportsLinks(dir1)); // Different directories. Use test.dir if possible as it might be // a different volume/file system and so improve test coverage. String testDir = System.getProperty("test.dir", "."); Path dir2 = TestUtil.createTemporaryDirectory(testDir); try { boolean testSymbolicLinks = TestUtil.supportsLinks(dir1) && TestUtil.supportsLinks(dir2); testCopyFileToFile(dir1, dir2, testSymbolicLinks); testMove(dir1, dir2, testSymbolicLinks); } finally { TestUtil.removeAll(dir2); } // Target is location associated with custom provider Path dir3 = PassThroughFileSystem.create().getPath(dir1.toString()); testCopyFileToFile(dir1, dir3, false); testMove(dir1, dir3, false); // Test copy(InputStream,Path) and copy(Path,OutputStream) testCopyInputStreamToFile(); testCopyFileToOuputStream(); } finally { TestUtil.removeAll(dir1); } }
// copy source to target with verification static void copyAndVerify(Path source, Path target, CopyOption... options) throws IOException { Path result = copy(source, target, options); assertTrue(result == target); // get attributes of source and target file to verify copy boolean followLinks = true; LinkOption[] linkOptions = new LinkOption[0]; boolean copyAttributes = false; for (CopyOption opt : options) { if (opt == NOFOLLOW_LINKS) { followLinks = false; linkOptions = new LinkOption[] {NOFOLLOW_LINKS}; } if (opt == COPY_ATTRIBUTES) copyAttributes = true; } BasicFileAttributes basicAttributes = readAttributes(source, BasicFileAttributes.class, linkOptions); // check hash if regular file if (basicAttributes.isRegularFile()) assertTrue(computeHash(source) == computeHash(target)); // check link target if symbolic link if (basicAttributes.isSymbolicLink()) assert (readSymbolicLink(source).equals(readSymbolicLink(target))); // check that attributes are copied if (copyAttributes && followLinks) { checkBasicAttributes( basicAttributes, readAttributes(source, BasicFileAttributes.class, linkOptions)); // verify other attributes when same provider if (source.getFileSystem().provider() == target.getFileSystem().provider()) { // check POSIX attributes are copied String os = System.getProperty("os.name"); if ((os.equals("SunOS") || os.equals("Linux")) && testPosixAttributes) { checkPosixAttributes( readAttributes(source, PosixFileAttributes.class, linkOptions), readAttributes(target, PosixFileAttributes.class, linkOptions)); } // check DOS attributes are copied if (os.startsWith("Windows")) { checkDosAttributes( readAttributes(source, DosFileAttributes.class, linkOptions), readAttributes(target, DosFileAttributes.class, linkOptions)); } // check named attributes are copied if (followLinks && getFileStore(source).supportsFileAttributeView("xattr") && getFileStore(target).supportsFileAttributeView("xattr")) { checkUserDefinedFileAttributes( readUserDefinedFileAttributes(source), readUserDefinedFileAttributes(target)); } } } }
private static void extractAndLoadNativeLibs() throws IOException { Path target = Paths.get(ioTmpDir, "/tklib"); if (!target.toFile().exists()) { Files.createDirectories(target); } final boolean windows = System.getProperty("os.name").equalsIgnoreCase("windows"); String fileExtension = windows ? "dll" : "so"; String prefix = windows ? "" : "lib"; String libPattern = fileExtension.equals("dll") ? "-windows" : "-linux" + "-x86"; if (System.getProperty("sun.arch.data.model").equals("64")) { libPattern += "_64"; } libPattern += "." + fileExtension; // System.err.println(libPattern); System.setProperty("java.library.path", target.toString()); // System.err.println(System.getProperty("java.library.path")); extractAndLoadNativeLib(prefix + "JCudaDriver" + libPattern, target); extractAndLoadNativeLib(prefix + "JCudaRuntime" + libPattern, target); extractAndLoadNativeLib(prefix + "JCurand" + libPattern, target); }
// "randomize" the file attributes of the given file. static void randomizeAttributes(Path file) throws IOException { String os = System.getProperty("os.name"); boolean isWindows = os.startsWith("Windows"); boolean isUnix = os.equals("SunOS") || os.equals("Linux"); boolean isDirectory = isDirectory(file, NOFOLLOW_LINKS); if (isUnix) { Set<PosixFilePermission> perms = getPosixFilePermissions(file, NOFOLLOW_LINKS); PosixFilePermission[] toChange = { PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_EXECUTE }; for (PosixFilePermission perm : toChange) { if (heads()) { perms.add(perm); } else { perms.remove(perm); } } setPosixFilePermissions(file, perms); } if (isWindows) { DosFileAttributeView view = getFileAttributeView(file, DosFileAttributeView.class, NOFOLLOW_LINKS); // only set or unset the hidden attribute view.setHidden(heads()); } boolean addUserDefinedFileAttributes = heads() && getFileStore(file).supportsFileAttributeView("xattr"); // remove this when copying a direcory copies its named streams if (isWindows && isDirectory) addUserDefinedFileAttributes = false; if (addUserDefinedFileAttributes) { UserDefinedFileAttributeView view = getFileAttributeView(file, UserDefinedFileAttributeView.class); int n = rand.nextInt(16); while (n > 0) { byte[] value = new byte[1 + rand.nextInt(100)]; view.write("user." + Integer.toString(n), ByteBuffer.wrap(value)); n--; } } }
private void fixRSNAROOT(Element server) { if (programName.equals("ISN")) { Element ssl = getFirstNamedChild(server, "SSL"); if (ssl != null) { if (System.getProperty("os.name").contains("Windows")) { ssl.setAttribute( "keystore", ssl.getAttribute("keystore").replace("RSNA_HOME", "RSNA_ROOT")); ssl.setAttribute( "truststore", ssl.getAttribute("truststore").replace("RSNA_HOME", "RSNA_ROOT")); } else { ssl.setAttribute("keystore", "${RSNA_ROOT}/conf/keystore.jks"); ssl.setAttribute("truststore", "${RSNA_ROOT}/conf/truststore.jks"); } } } }
// If this is a new installation, ask the user for a // port for the server; otherwise, return the negative // of the configured port. If the user selects an illegal // port, return zero. private int getPort() { // Note: directory points to the parent of the CTP directory. File ctp = new File(directory, "CTP"); if (suppressFirstPathElement) ctp = ctp.getParentFile(); File config = new File(ctp, "config.xml"); if (!config.exists()) { // No config file - must be a new installation. // Figure out whether this is Windows or something else. String os = System.getProperty("os.name").toLowerCase(); int defPort = ((os.contains("windows") && !programName.equals("ISN")) ? 80 : 1080); int userPort = 0; while (userPort == 0) { String port = JOptionPane.showInputDialog( null, "This is a new " + programName + " installation.\n\n" + "Select a port number for the web server.\n\n", Integer.toString(defPort)); try { userPort = Integer.parseInt(port.trim()); } catch (Exception ex) { userPort = -1; } if ((userPort < 80) || (userPort > 32767)) userPort = 0; } return userPort; } else { try { Document doc = getDocument(config); Element root = doc.getDocumentElement(); Element server = getFirstNamedChild(root, "Server"); String port = server.getAttribute("port"); return -Integer.parseInt(port); } catch (Exception ex) { } } return 0; }
List<URL> urls() { List<URL> urls = new ArrayList<>(); if (version != null) { // Elasticsearch new download service uses groupId org.elasticsearch.plugin from 2.0.0 if (user == null) { if (!Strings.isNullOrEmpty(System.getProperty(PROPERTY_SUPPORT_STAGING_URLS))) { addUrl( urls, String.format( Locale.ROOT, "https://download.elastic.co/elasticsearch/staging/%s-%s/org/elasticsearch/plugin/%s/%s/%s-%s.zip", version, Build.CURRENT.hashShort(), name, version, name, version)); } addUrl( urls, String.format( Locale.ROOT, "https://download.elastic.co/elasticsearch/release/org/elasticsearch/plugin/%s/%s/%s-%s.zip", name, version, name, version)); } else { // Elasticsearch old download service addUrl( urls, String.format( Locale.ROOT, "https://download.elastic.co/%1$s/%2$s/%2$s-%3$s.zip", user, name, version)); // Maven central repository addUrl( urls, String.format( Locale.ROOT, "https://search.maven.org/remotecontent?filepath=%1$s/%2$s/%3$s/%2$s-%3$s.zip", user.replace('.', '/'), name, version)); // Sonatype repository addUrl( urls, String.format( Locale.ROOT, "https://oss.sonatype.org/service/local/repositories/releases/content/%1$s/%2$s/%3$s/%2$s-%3$s.zip", user.replace('.', '/'), name, version)); // Github repository addUrl( urls, String.format( Locale.ROOT, "https://github.com/%1$s/%2$s/archive/%3$s.zip", user, name, version)); } } if (user != null) { // Github repository for master branch (assume site) addUrl( urls, String.format( Locale.ROOT, "https://github.com/%1$s/%2$s/archive/master.zip", user, name)); } return urls; }
public boolean isJar() { Path pth = Paths.get(System.getProperty("user.dir") + "/Advent.jar"); if (pth.toFile().exists()) return true; return false; }
public class GameCharacter { // Position and Size public double X = 0, Y = 0; public double W = 0, H = 0; // Frames public int FX = 0, FY = 0; // Where to find character sprites String DIRECT = System.getProperty("user.dir") + "\\Graphics\\Character\\"; String DIRECT2 = System.getProperty("user.dir") + "\\Graphics\\Effects\\"; // Max number of frames int SIZE = 0; // Used for delay in framechange() int COUNTER = 0; // Sprite Type int TYPE = 1; // Sprite BufferedImage imgCHARAC, imgBLOOD, imgQStart, imgQEnd; // Collision maps Vector<GridMap> MAP = new Vector<GridMap>(); // Collision objects Vector<GameObject> OBJECTS = new Vector<GameObject>(); // Collision characters Vector<GameCharacter> CHARACTERS = new Vector<GameCharacter>(); // Collision characters Vector<Building> BUILD = new Vector<Building>(); // Spells Vector<MagicAttack[]> SPELL_LIST = new Vector<MagicAttack[]>(); Vector<Quest> QUEST_LIST = new Vector<Quest>(); // Size double GROWTHFACTOR = 1; // Create character inventory ItemList INVENTORY = new ItemList(); // Character class String CLASS = "", Cl = ""; // Basic stats double MAX_HEALTH = 100, MAX_MANA = 100; int HEALTH = (int) MAX_HEALTH, MANA = (int) MAX_MANA, GOLD = 0; // Movement int REGEN_COUNTER = 0, SPEED = 1; // Used for magic attacks int MAGIC_COUNTER = 0; // Possible AIs NPCAI NAI; EnemyAI EAI; // Restrictions boolean ISDEAD = false, COLL_LISTENER = false, CANMOVE = true; // List of available magic attacks MagicAttack[] FIREBALL = new MagicAttack[11], SHOCK = new MagicAttack[11], DARKNESS = new MagicAttack[11], LIFE_DRAIN = new MagicAttack[11]; // Character Stats Stats STATS = new Stats(this); // Weapons and armor MeeleAttack MEELE_WEAPON = new MeeleAttack(0, 0, "Sword_1.png", this); Image SHIELD = null; // Death sound AudioEffects audDEATH = new AudioEffects(false); // Progress bar used for basic tasks ProgressBar BASIC_PROCESS, BASIC_EFFECTS; int SPAWN_X = -1, SPAWN_Y = -1; /** * Constructor to create a character * * @param x X Position * @param y Y Position * @param w Width of Image * @param h Height of Image * @param FileN Name of image file * @param S Max number of frames */ public GameCharacter( double x, double y, double w, double h, String FileN, int S, int Ty, String c) { // Set position and size X = x; Y = y; W = w; H = h; BASIC_PROCESS = new ProgressBar(new Font("Arial", 36, 36), this); BASIC_EFFECTS = new ProgressBar(new Font("Arial", 36, 36), this); // Add magic attacks // Fireball for (int i = 0; i < FIREBALL.length; i++) { FIREBALL[i] = new MagicAttack(-500, -500, 39, 41, "Fireball.png", 3, 1, 2, "Fireball"); FIREBALL[i].STATS.setStats(new String[] {"Damage=10", "Points=10"}); FIREBALL[i].CASTER = this; } // Shock for (int i = 0; i < SHOCK.length; i++) { SHOCK[i] = new MagicAttack(-500, -500, 39, 41, "Shock.png", 2, 1, 0, "Shock"); SHOCK[i].STATS.setStats(new String[] {"Damage=20", "Points=15"}); SHOCK[i].CASTER = this; } // Darkness for (int i = 0; i < DARKNESS.length; i++) { DARKNESS[i] = new MagicAttack(-500, -500, 165, 164, "Darkness.png", 3, 1, 2, "Darkness"); DARKNESS[i].STATS.setStats(new String[] {"Damage=100", "Points=50"}); DARKNESS[i].CASTER = this; } // Life Drain for (int i = 0; i < LIFE_DRAIN.length; i++) { LIFE_DRAIN[i] = new MagicAttack(-500, -500, 32, 32, "Life Drain.png", 7, 1, 0, "Life Drain"); LIFE_DRAIN[i].STATS.setStats(new String[] {"Damage=50", "Points=25"}); LIFE_DRAIN[i].CASTER = this; } // Get Image try { if (isJar()) { // Character imgCHARAC = getImage("/Graphics/Character/", FileN); // Blood int BloodType = (int) Math.round(Math.random() * 3) + 1; imgBLOOD = getImage("/Graphics/Effects/", "Dead" + BloodType + ".png"); // Quest imgQStart = getImage("/Graphics/Effects/", "Quest_Start.png"); imgQEnd = getImage("/Graphics/Effects/", "Quest_Complete.png"); } else { // Character imgCHARAC = ImageIO.read(Paths.get(DIRECT + FileN).toFile()); // Blood int BloodType = (int) Math.round(Math.random() * 3) + 1; imgBLOOD = ImageIO.read(Paths.get(DIRECT2 + "Dead" + BloodType + ".png").toFile()); // Quest imgQStart = ImageIO.read(Paths.get(DIRECT2 + "Quest_Start.png").toFile()); imgQEnd = ImageIO.read(Paths.get(DIRECT2 + "Quest_Complete.png").toFile()); } } catch (Exception e) { } // Max number of frames SIZE = S; // Sprite type TYPE = Ty; // Assign class CLASS = c; Cl = c; // Add items and attacks according to class if (CLASS.equals("Player")) { // Add items INVENTORY.addItem( "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"}); INVENTORY.addItem( "Rusted Dagger", 20, 1, "Dagger_4.png", "Meele", new String[] {"Damage=10", "Attack Speed=1"}); INVENTORY.addItem( "Wooden Staff", 20, 1, "Staff_1.png", "Meele", new String[] {"Damage=5", "Attack Speed=1"}); // Equip items INVENTORY.ItemEffect(1, this); // MEELE_WEAPON=null; // Assign Magic SPELL_LIST.add(FIREBALL); // Inventory type INVENTORY.Type = "Player"; } else if (CLASS.equals("Citizen")) { // Add items INVENTORY.addItem( "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"}); // Add Ai NAI = new NPCAI(this); // Add Gold this.GOLD = (int) Math.round(Math.random() * 15 + 5); INVENTORY.Type = "Friendly"; } else if (CLASS.equals("Blacksmith")) { // Add items INVENTORY.addItem( "Silver Dagger", 250, 1, "Dagger_3.png", "Meele", new String[] {"Damage=10", "Attack Speed=1"}); INVENTORY.addItem( "Steel Dagger", 450, 1, "Dagger_5.png", "Meele", new String[] {"Damage=35", "Attack Speed=1"}); // INVENTORY.addItem("Assassin blade", 750,1, "Dagger_6.png","Meele",new // String[]{"Damage=45","Attack Speed=1"}); // INVENTORY.addItem("Serpent Dagger", 5000,1, "Dagger_2.png","Meele",new // String[]{"Damage=50","Attack Speed=1"}); // INVENTORY.addItem("Dagger of Time", 5050,1, "Dagger_1.png","Meele",new // String[]{"Damage=75","Attack Speed=1"}); INVENTORY.addItem( "Steel Sword", 450, 1, "Sword_1.png", "Meele", new String[] {"Damage=30", "Attack Speed=0.65"}); INVENTORY.addItem( "Iron Sword", 50, 1, "Sword_2.png", "Meele", new String[] {"Damage=15", "Attack Speed=0.65"}); INVENTORY.addItem( "Silver Sword", 100, 1, "Sword_5.png", "Meele", new String[] {"Damage=20", "Attack Speed=0.5"}); // INVENTORY.addItem("Iron Scimitar", 150,1, "Sword_7.png","Meele",new // String[]{"Damage=15","Attack Speed=0.75"}); // INVENTORY.addItem("Steel Scimitar", 500,1, "Sword_4.png","Meele",new // String[]{"Damage=50","Attack Speed=0.75"}); // INVENTORY.addItem("Steel Katana", 450,1, "Sword_6.png","Meele",new // String[]{"Damage=40","Attack Speed=0.95"}); // INVENTORY.addItem("Butcher's Sword", 5000,1, "Sword_3.png","Meele",new // String[]{"Damage=100","Attack Speed=0.55"}); // INVENTORY.addItem("Blood Thirster", 6000,1, "Sword_8.png","Meele",new // String[]{"Damage=200","Attack Speed=0.75"}); INVENTORY.addItem( "Iron Hammer", 150, 1, "Hammer_1.png", "Meele", new String[] {"Damage=40", "Attack Speed=0.15"}); // INVENTORY.addItem("Steel Hammer", 450,1, "Hammer_0.png","Meele",new // String[]{"Damage=60","Attack Speed=0.15"}); // INVENTORY.addItem("Iron Mace", 50,1, "Mace_1.png","Meele",new String[]{"Damage=15","Attack // Speed=0.5"}); INVENTORY.addItem("Steel Helmet", 250, 1, "Head_1.png", "H_armor", new String[] {"Armor=20"}); INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"}); // INVENTORY.addItem("Iron Horn Helmet", 350,1, "Head_6.png","H_armor",new // String[]{"Armor=50","Magic Resist=0"}); // INVENTORY.addItem("Steel Horn Helmet", 500,1, "Head_7.png","H_armor",new // String[]{"Armor=80","Magic Resist=0"}); // INVENTORY.addItem("Skysteel Helmet", 4000,1, "Head_4.png","H_armor",new // String[]{"Armor=60","Magic Resist=25"}); INVENTORY.addItem( "Iron Cuirass", 250, 1, "Chest_4.png", "C_armor", new String[] {"Armor=20"}); INVENTORY.addItem( "Steel Cuirass", 350, 1, "Chest_1.png", "C_armor", new String[] {"Armor=30"}); // INVENTORY.addItem("Scale Cuirass", 550,1, "Chest_3.png","C_armor",new // String[]{"Armor=50"}); // INVENTORY.addItem("Dark metal Cuirass", 750,1, "Chest_6.png","C_armor",new // String[]{"Armor=70"}); // INVENTORY.addItem("Master Cuirass", 3050,1, "Chest_5.png","C_armor",new // String[]{"Armor=80","Magic Resist=25"}); // INVENTORY.addItem("Legendary Cuirass", 3050,1, "Chest_2.png","C_armor",new // String[]{"Armor=100","Magic Resist=100"}); INVENTORY.addItem( "Wooden Shield", 50, 1, "Shield_1.png", "Shield", new String[] {"Armor=5", "Magic Resist=0"}); // Add AI NAI = new NPCAI(this); // Identify as trader INVENTORY.Type = "Trader"; // Set Stats STATS.setStats(new String[] {"Level = 5 "}); MAX_HEALTH = 200; HEALTH = (int) MAX_HEALTH; } else if (CLASS.equals("Alchemist")) { // Add Items INVENTORY.addItem( "Health Potion", 25, 50, "Health Pot.png", "Potion", new String[] {"Points=50"}); INVENTORY.addItem( "Mana Potion", 20, 50, "Mana Pot.png", "Potion", new String[] {"Points=50"}); INVENTORY.addItem( "Speed Potion", 10, 50, "Speed Pot.png", "Potion", new String[] {"Points=5"}); // INVENTORY.addItem("Invisib Potion", 50, 10, "Invisibility Pot.png","Potion",new // String[]{"Points=5"}); // Add AI NAI = new NPCAI(this); // Identify as trader INVENTORY.Type = "Trader"; } else if (CLASS.equals("Inn Keeper")) { // Add Items INVENTORY.addItem("Roasted Fish", 15, 10, "Fish.png", "Food", new String[] {"Points=5"}); INVENTORY.addItem("Apple", 15, 10, "Apple.png", "Food", new String[] {"Points=2"}); // Add AI NAI = new NPCAI(this); // Identify as trader INVENTORY.Type = "Trader"; } else if (CLASS.equals("Mage")) { INVENTORY.addItem( "Leather Cap", 250, 1, "Head_8.png", "H_armor", new String[] {"Armor=5", "Magic Resist=25"}); INVENTORY.addItem( "Dark Leather Cap", 300, 1, "Head_9.png", "H_armor", new String[] {"Armor=5", "Magic Resist=50"}); // INVENTORY.addItem("Jesters Cap", 500,1, "Head_5.png","H_armor",new // String[]{"Armor=10","Magic Resist=90"}); // INVENTORY.addItem("Skull Helmet", 5000,1, "Head_3.png","H_armor",new // String[]{"Armor=100","Magic Resist=100"}); INVENTORY.addItem( "Shock Spell Stone", 250, 1, "Stone_1.png", "SpellStoner", new String[] {"Damage=" + SHOCK[0].STATS.DAMAGE}); // INVENTORY.addItem("Darkness Spell Stone", 500,1, "Stone_1.png","SpellStoner",new // String[]{"Damage="+DARKNESS[0].STATS.DAMAGE}); INVENTORY.addItem( "Life Drain Spell Stone", 300, 1, "Stone_1.png", "SpellStoner", new String[] {"Damage=" + LIFE_DRAIN[0].STATS.DAMAGE}); // Add AI NAI = new NPCAI(this); // Identify as trader INVENTORY.Type = "Trader"; } else if (CLASS.equals("Skeleton")) { // Add items INVENTORY.addItem( "Bone Club", 5, 1, "Mace_2.png", "Meele", new String[] {"Damage=5", "Attack Speed=1"}); // Add Gold this.GOLD = (int) Math.round(Math.random() * 10 + 2); // Use Item INVENTORY.ItemEffect(0, this); // Add AI EAI = new EnemyAI(this); } else if (CLASS.equals("Skeleton Chieftan")) { // Add Item INVENTORY.addItem( "Iron Sword", 50, 1, "Sword_2.png", "Meele", new String[] {"Damage=15", "Attack Speed=0.65"}); INVENTORY.addItem( "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"}); // Add Gold this.GOLD = (int) Math.round(Math.random() * 50 + 25); // Use Item INVENTORY.ItemEffect(0, this); // Assign Stats STATS.LEVEL = 3; HEALTH = 250; MAX_HEALTH = 250; // Opify Opify(1 / 1.25); // Add AI EAI = new EnemyAI(this); } else if (CLASS.equals("Shaman")) { // Add items INVENTORY.addItem( "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"}); // Add Ai NAI = new NPCAI(this); } else if (CLASS.equals("Dark Elf")) { // Add items INVENTORY.addItem( "Rusted Dagger", 20, 1, "Dagger_4.png", "Meele", new String[] {"Damage=10", "Attack Speed=1"}); INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"}); // Assign Stats STATS.LEVEL = 2; HEALTH = 150; MAX_HEALTH = 150; // Add Gold this.GOLD = (int) Math.round(Math.random() * 15 + 2); // Use Item INVENTORY.ItemEffect(0, this); INVENTORY.ItemEffect(1, this); // Add Ai EAI = new EnemyAI(this); } else if (CLASS.equals("Prisoner")) { INVENTORY.addItem("Key", 0, 1, "Key.png", "Key", new String[] {}); // NAI= new NPCAI(this); } } /** * do damage to character * * @param Dmg Amount of Damage */ public void Damage(int Dmg, int Type) { // If character is already dead then dont do damage if (ISDEAD) return; // Do damage if (Type == 1) { // DAMAGE FROM PHYSICAL ATTACK if (STATS.ARMOR > Dmg) return; HEALTH = HEALTH - Dmg + STATS.ARMOR; } else if (Type == 2) { // DAMAGE FROM MAGIC ATTACK if (STATS.MAGIC_RESIST > Dmg) return; HEALTH = HEALTH - Dmg + STATS.MAGIC_RESIST; } // If an Npc then run and hide if (NAI != null) { NAI.State = "alarmed"; } // Death condition if (HEALTH <= 0) { // If player is dead if (this.CLASS.equals("Player")) { HEALTH = 0; // Quit game JOptionPane.showMessageDialog(null, "You are dead"); X = 100; Y = 100; Opify(50); HEALTH = (int) MAX_HEALTH; } else { // If other character // set Death stats ISDEAD = true; HEALTH = 0; // display death CLASS = Cl + " (Dead)"; // Rot effect for (int i = 0; i < imgCHARAC.getWidth(); i++) { for (int j = 0; j < imgCHARAC.getHeight(); j++) { imgCHARAC.setRGB(i, j, imgCHARAC.getRGB(i, j) * (int) Math.pow(3, 3)); } } // Make inventory open to looting INVENTORY.OPEN_INVEN = true; } } } /** Prototype give player a leveled up look */ public void Opify(double Fac) { for (int i = 0; i < imgCHARAC.getWidth(); i++) { for (int j = 0; j < imgCHARAC.getHeight(); j++) { if (imgCHARAC.getRGB(i, j) != imgCHARAC.getRGB(2, 2)) { imgCHARAC.setRGB(i, j, (int) Math.round(imgCHARAC.getRGB(i, j) * Fac)); } } } } /** * Regenerate the players mana * * @param Mn amount to regen */ public void ManaRegen(int Mn) { // Counter REGEN_COUNTER++; if (REGEN_COUNTER > 30) { // Regen if (MANA < MAX_MANA) MANA += Mn; REGEN_COUNTER = 0; } } /** * Move the character * * @param dx x displacement * @param dy y displacement */ public void Move(int dx, int dy) { if (!CANMOVE) return; // Move X += dx * SPEED; Y += dy * SPEED; // Set FY depending on the sprite Type switch (TYPE) { case 1: if (dx > 0) { FY = Type1.RIGHT.ordinal(); } else if (dx < 0) { FY = Type1.LEFT.ordinal(); } else if (dy > 0) { FY = Type1.DOWN.ordinal(); } else if (dy < 0) { FY = Type1.UP.ordinal(); } break; case 2: if (dx > 0) { FY = Type2.RIGHT.ordinal(); } else if (dx < 0) { FY = Type2.LEFT.ordinal(); } else if (dy > 0) { FY = Type2.DOWN.ordinal(); } else if (dy < 0) { FY = Type2.UP.ordinal(); } case 3: if (dx > 0) { FY = Type3.RIGHT.ordinal(); } else if (dx < 0) { FY = Type3.LEFT.ordinal(); } else if (dy > 0) { FY = Type3.DOWN.ordinal(); } else if (dy < 0) { FY = Type3.UP.ordinal(); } break; } // X Frame Change FrameChange(SIZE, 4, 1); } /** * add a Map collision object * * @param M GridMap */ public void addColisionObject(GridMap M) { MAP.add(M); } /** * add a Object collision object * * @param O Object */ public void addColisionObject(GameObject O) { OBJECTS.add(O); } /** * add Character collision object * * @param C Character */ public void addColisionObject(GameCharacter C) { CHARACTERS.add(C); } /** * add Building collision object * * @param B Building */ public void addColisionObject(Building B) { BUILD.add(B); } /** * add an array of Building collision object * * @param M Array of GridMap */ public void addColisionObject(Building[] B) { for (int i = 0; i < B.length; i++) { BUILD.add(B[i]); } } /** * add a Map collision object * * @param M Array of GridMap */ public void addColisionObject(GridMap[] M) { for (int i = 0; i < M.length; i++) { MAP.add(M[i]); } } /** * add a Object collision object * * @param O Array of Objects */ public void addColisionObject(GameObject[] O) { for (int i = 0; i < O.length; i++) { OBJECTS.add(O[i]); } } /** Remove all the collision objects from the player */ public void removeCollisionObject(GameObject[] obj) { for (int i = 0; i < obj.length; i++) { OBJECTS.remove(obj[i]); // OBJECTS.add(obj[i]); } } public void removeCollisionObject(GameObject obj) { // for(int i=0;i<obj.length;i++){ OBJECTS.remove(obj); // OBJECTS.add(obj[i]); // } } public void removeAllColisionObjects() { // Collision maps MAP = new Vector<GridMap>(); // Collision objects OBJECTS = new Vector<GameObject>(); // Collision characters CHARACTERS = new Vector<GameCharacter>(); // Collision characters BUILD = new Vector<Building>(); } /** * add Character collision object * * @param C Array of Characters */ public void addColisionObject(GameCharacter[] C) { for (int i = 0; i < C.length; i++) { CHARACTERS.add(C[i]); } } /** * Allows the character to walk over various surfaces * * @param F Selected fill number * @return whether or not the character can walk on this surface */ public boolean isValidSurface(int F) { // List of valid surfaces int[] fill = {0, 98, 106, 107, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 147, 178}; for (int i = 0; i < fill.length; i++) { if (fill[i] == F) { // If valid return true; } } // If not return false; } /** * Wall Collision * * @param x X Position * @param y Y Position * @param M Map * @return if character is about to collide with the wall */ public boolean WallCollision(double x, double y, GridMap M) { // If invalid coordinate try { if (M.getBlockNum(x, y) == -1) { // Collision check if (isValidSurface(M.Fill[M.getBlockNum(x + 3, y + 3)])) { return false; } return true; } // Collision check if (isValidSurface(M.Fill[M.getBlockNum(x, y)])) { return false; } } catch (Exception e) { return WallCollision(x + M.Size / 2, y + M.Size / 2, M); } return true; } /** * Object Collision * * @param x X Position * @param y Y Position * @param Obj Game Object * @return if character is about to collide with an object */ public boolean ObjectCollision(double x, double y, GameObject Obj) { if ((x > Obj.X) && (x < Obj.X + Obj.W * Obj.GROWTHFACTOR)) { if ((y > Obj.Y) && (y < Obj.Y + Obj.H * Obj.GROWTHFACTOR)) { return true; } } return false; } /** * Character Collision * * @param x X Position * @param y Y Position * @param Charac GameCharacter * @return if character is about to collide with a character */ public boolean CharacterCollision(double x, double y, GameCharacter Charac) { if ((x > Charac.X) && (x < Charac.X + Charac.W * Charac.GROWTHFACTOR)) { if ((y > Charac.Y) && (y < Charac.Y + Charac.H * Charac.GROWTHFACTOR)) { return true; } } return false; } /** * Building Collision * * @param x X Position * @param y Y Position * @param Charac Game Building * @return if character is about to collide with a structure */ public boolean BuildingCollision(double x, double y, Building Charac) { if ((x > Charac.X) && (x < Charac.X + Charac.W * Charac.GROWTHFACTOR)) { if ((y > Charac.Y) && (y < Charac.Y + Charac.H * Charac.GROWTHFACTOR)) { return true; } } return false; } /** * Check character collision with all kinds of objects * * @param x X Coordinate * @param y Y Coordinate * @return if Character is about to collide with something */ public boolean Collision(double x, double y) { boolean blnCol = false; // Wall Collision for (int i = 0; i < MAP.size(); i++) { blnCol = blnCol || WallCollision(x, y, MAP.elementAt(i)); } // Game Object Collision for (int i = 0; i < OBJECTS.size(); i++) { blnCol = blnCol || ObjectCollision(x, y, OBJECTS.elementAt(i)); } // Game Character collision for (int i = 0; i < CHARACTERS.size(); i++) { blnCol = blnCol || CharacterCollision(x, y, CHARACTERS.elementAt(i)); } // Game Building Collision for (int i = 0; i < BUILD.size(); i++) { blnCol = blnCol || BuildingCollision(x, y, BUILD.elementAt(i)); } return blnCol; } /** * Draw character in minimap * * @param g Graphics * @param Dx X Displacement * @param Dy Y Displacement */ public void MapDraw(Graphics g, int Dx, int Dy, double Scale, Color col) { // Color g.setColor(col.darker().darker().darker()); g.drawOval((int) (X * Scale + Dx), (int) (Y * Scale + Dy), 7, 7); g.setColor(col); g.fillOval((int) (X * Scale + Dx), (int) (Y * Scale + Dy), 7, 7); } /** * Draw character in game window * * @param g Graphics * @param Dx X Displacement * @param Dy Y Displacement * @param G Growth factor */ public void Draw(Graphics g, int Dx, int Dy, double G) { // Draw blood if (ISDEAD) { g.drawImage( imgBLOOD, (int) (X + Dx - 25), (int) (Y + Dy - 15), (int) (W * GROWTHFACTOR + 35), (int) (H * GROWTHFACTOR + 35), null); } // Quest Givers if (CLASS != "Player") { for (int i = 0; i < QUEST_LIST.size(); i++) { if (QUEST_LIST.elementAt(i).STATUS == 0) { g.drawImage(imgQStart, (int) (X + Dx + 5), (int) (Y + Dy - 30), (int) W, 35, null); } else if (QUEST_LIST.elementAt(i).STATUS == 2) { g.drawImage(imgQEnd, (int) (X + Dx), (int) (Y + Dy - 30), (int) W + 5, 35, null); } } } // Draw character g.drawImage( imgCHARAC, (int) (X + Dx), (int) (Y + Dy), (int) (X + Dx + W * G), (int) (Y + Dy + H * G), (int) (W * FX), (int) (H * FY), (int) (W * FX + W), (int) (H * FY + H), null); GROWTHFACTOR = G; } /** * Draw Magic Attack * * @param Magic Array of magic attacks * @param g Graphics * @param Dx Draw X displacement * @param Dy Draw Y displacement * @param G Growth Factor */ public void MagicDraw(MagicAttack[] Magic, Graphics g, int Dx, int Dy, double G) { for (int i = 0; i < Magic.length; i++) { Magic[i].Draw(g, Dx, Dy, G); } } /** If the character is dead don't make the magic attacks collide */ public void removeMagicCollision() { // Fireball for (int i = 0; i < FIREBALL.length; i++) { FIREBALL[i].removeAllColisionObjects(); } // Shock for (int i = 0; i < SHOCK.length; i++) { SHOCK[i].removeAllColisionObjects(); } // Darkness for (int i = 0; i < DARKNESS.length; i++) { DARKNESS[i].removeAllColisionObjects(); } // Life Drain for (int i = 0; i < LIFE_DRAIN.length; i++) { LIFE_DRAIN[i].removeAllColisionObjects(); } } /** * Frame Change in X direction * * @param MAX last frame index * @param Delay Delay between frame change * @param Dir moves back or forward through frames */ public void FrameChange(int MAX, int Delay, int Dir) { COUNTER++; if (COUNTER > Delay) { // Change Frame FX += Dir; // Reset when frame number exceeds bounds if (FX < 0) { FX = MAX; } if (FX > MAX) { FX = 0; } // Reset COUNTER = 0; } } /** * Spawn a character on the map * * @param MiX Minimum X value * @param MiY Minimum Y value * @param MaX Maximum X value * @param MaY Maximum Y value */ public void Spawn(int MiX, int MiY, int MaX, int MaY) { double Nx = 0, Ny = 0; // Random coordinate Nx = Math.random() * MaX + MiX; Ny = Math.random() * MaY + MiY; // Store block number int BNum = MAP.elementAt(0).getBlockNum(Nx + W / 2, Ny + H / 2); // if invalid block number if (BNum == -1) { Spawn(MiX, MiY, MaX, MaY); } // if invalid surface else if (!isValidSurface(MAP.elementAt(0).Fill[BNum])) { Spawn(MiX, MiY, MaX, MaY); } // if colliding with something else if (this.Collision(Nx + W / 2, Ny + H / 2)) { Spawn(MiX, MiY, MaX, MaY); } else { X = Nx; Y = Ny; } } /** * Find the distance between two characters * * @param Targ Target character * @return distance */ public double Dist(GameCharacter Targ) { // find x squared and y squared double dx = Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2); double dy = Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2); // find distance return (Math.sqrt(dx + dy)); } /** * Find the distance between two characters * * @param Targ Target character * @return distance */ public double Dist(GameObject Targ) { // find x squared and y squared double dx = Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2); double dy = Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2); // find distance return (Math.sqrt(dx + dy)); } /** * Find the distance between a character and a building * * @param Targ Target Building * @return distance */ public double Dist(Building Targ) { // find x squared and y squared double dx = Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2); double dy = Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2); // find distance return (Math.sqrt(dx + dy)); } /** * Chase another character * * @param Targ Target character * @param Error alignment error allowed */ public void FollowChar(GameCharacter Targ, int Error) { // Find distance double dx = (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR) - (X + W / 2 * GROWTHFACTOR); double dy = (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR) - (Y + H / 2 * GROWTHFACTOR); // Y Movement if (dy > Error) { // Down if (this.Collision(X, Y + H * GROWTHFACTOR)) { EAI.STATE = "calm"; } Move(0, SPEED + 1); } else if (dy < Error) { // Up if (this.Collision(X, Y)) { EAI.STATE = "calm"; } Move(0, -SPEED - 1); } // X Movement if (dx > Error) { // Right if (this.Collision(X + W * GROWTHFACTOR, Y)) { EAI.STATE = "calm"; } Move(SPEED + 1, 0); } else if (dx < -Error) { // Left if (this.Collision(X, Y)) { EAI.STATE = "calm"; } Move(-SPEED - 1, 0); } } /** * Set the direction of the character * * @param Pos String specifying direction */ public void setPos(String Pos) { // Set position switch (TYPE) { case 1: switch (Pos) { case "Up": FY = Type1.UP.ordinal(); break; case "Down": FY = Type1.DOWN.ordinal(); break; case "Left": FY = Type1.LEFT.ordinal(); break; case "Right": FY = Type1.RIGHT.ordinal(); break; } break; case 2: switch (Pos) { case "Up": FY = Type2.UP.ordinal(); break; case "Down": FY = Type2.DOWN.ordinal(); break; case "Left": FY = Type2.LEFT.ordinal(); break; case "Right": FY = Type2.RIGHT.ordinal(); break; } break; case 3: switch (Pos) { case "Up": FY = Type3.UP.ordinal(); break; case "Down": FY = Type3.DOWN.ordinal(); break; case "Left": FY = Type3.LEFT.ordinal(); break; case "Right": FY = Type3.RIGHT.ordinal(); break; } break; } } /** * Sell an item to a shopkeeper * * @param Targ Target Inventory * @param Index Item Index */ public void Sell(ItemList Targ, int Index) { // Un-equip item if (INVENTORY.ITEM_NAME.elementAt(Index).indexOf("<Eq>") != -1) { INVENTORY.ItemEffect(Index, this); } // Give the target this item Targ.addItem( this.INVENTORY.ITEM_NAME.elementAt(Index), this.INVENTORY.ITEM_PRICE.elementAt(Index), 1, this.INVENTORY.ITEM_IMAGE.elementAt(Index), this.INVENTORY.ITEM_TAG.elementAt(Index), this.INVENTORY.STATS.elementAt(Index)); // Get payment from target this.GOLD += this.INVENTORY.ITEM_PRICE.elementAt(Index); // Remove item from the character inventory this.INVENTORY.removeItem(Index, 1); } /** * Buy an item from a shopkeeper * * @param Targ Target Inventory * @param Index Item Index */ public void Buy(ItemList Targ, int Index) { // If item is too expensive if (Targ.ITEM_PRICE.elementAt(Index) > this.GOLD) { JOptionPane.showMessageDialog(null, "Too rich for your blood"); return; } // add Item to character inventory this.INVENTORY.addItem( Targ.ITEM_NAME.elementAt(Index), Targ.ITEM_PRICE.elementAt(Index), 1, Targ.ITEM_IMAGE.elementAt(Index), Targ.ITEM_TAG.elementAt(Index), Targ.STATS.elementAt(Index)); // remove Gold this.GOLD -= Targ.ITEM_PRICE.elementAt(Index); // remove item from target inventory Targ.removeItem(Index, 1); } /** * Loot item from a dead body * * @param Targ Target Inventory * @param Index Item Index */ public void Take(ItemList Targ, int Index) { // Add item to character inventory // unequip item if (Targ.ITEM_NAME.elementAt(Index).indexOf("<Eq>") != -1) { Targ.ItemEffect(Index, this); } this.INVENTORY.addItem( Targ.ITEM_NAME.elementAt(Index), Targ.ITEM_PRICE.elementAt(Index), 1, Targ.ITEM_IMAGE.elementAt(Index), Targ.ITEM_TAG.elementAt(Index), Targ.STATS.elementAt(Index)); // Remove item from target inven Targ.removeItem(Index, 1); } /** * Magic Attack * * @param Magic Array of magic attacks */ public void MAttack(MagicAttack[] Magic) { // If insufficient mana if (MANA - Magic[MAGIC_COUNTER].STATS.POINTS < 0) return; // Stop FIREBALL[MAGIC_COUNTER].ISACTIVE = false; switch (TYPE) { case 1: // set x and y coords depending on the direction the character is facing switch (FY) { case 0: // Down // Set x and y coords Magic[MAGIC_COUNTER].X = X + W / 2 - Magic[MAGIC_COUNTER].W / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR; Magic[MAGIC_COUNTER].Y = Y + H - Magic[MAGIC_COUNTER].H / 4 * Magic[MAGIC_COUNTER].GROWTHFACTOR; // Set frame 0 Magic[MAGIC_COUNTER].FX = 0; // Movement Speed Magic[MAGIC_COUNTER].dX = 0; Magic[MAGIC_COUNTER].dY = 20; break; case 1: // Left // Set x and y coords Magic[MAGIC_COUNTER].X = X - Magic[MAGIC_COUNTER].W / 4 * Magic[MAGIC_COUNTER].GROWTHFACTOR; Magic[MAGIC_COUNTER].Y = Y + H / 2 - Magic[MAGIC_COUNTER].H / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR; // Set frame 0 Magic[MAGIC_COUNTER].FX = 0; // Movement Speed Magic[MAGIC_COUNTER].dX = -20; Magic[MAGIC_COUNTER].dY = 0; break; case 2: // Right // Set x and y coords Magic[MAGIC_COUNTER].X = X + W - Magic[MAGIC_COUNTER].W / 4 * Magic[MAGIC_COUNTER].GROWTHFACTOR; Magic[MAGIC_COUNTER].Y = Y + H / 2 - Magic[MAGIC_COUNTER].H / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR; // Set frame 0 Magic[MAGIC_COUNTER].FX = 0; // Movement Speed Magic[MAGIC_COUNTER].dX = 20; Magic[MAGIC_COUNTER].dY = 0; break; case 3: // Up // Set x and y coords Magic[MAGIC_COUNTER].X = X + W / 2 - Magic[MAGIC_COUNTER].W / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR; Magic[MAGIC_COUNTER].Y = Y - Magic[MAGIC_COUNTER].H / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR; // Set frame 0 Magic[MAGIC_COUNTER].FX = 0; // Movement Speed Magic[MAGIC_COUNTER].dX = 0; Magic[MAGIC_COUNTER].dY = -20; break; } } // Activate Magic[MAGIC_COUNTER].ISACTIVE = true; // Consume mana MANA -= Magic[MAGIC_COUNTER].STATS.POINTS; // Change counter MAGIC_COUNTER++; if (MAGIC_COUNTER == Magic.length) MAGIC_COUNTER = 0; } /** * Physical Meele Attack * * @param Me */ public void PAttack(MeeleAttack Me) { switch (TYPE) { case 1: // Meele Attack if (FY == Type1.UP.ordinal()) { Me.PAttack(Type1.UP.name()); } else if (FY == Type1.DOWN.ordinal()) { Me.PAttack(Type1.DOWN.name()); } else if (FY == Type1.LEFT.ordinal()) { Me.PAttack(Type1.LEFT.name()); } else if (FY == Type1.RIGHT.ordinal()) { Me.PAttack(Type1.RIGHT.name()); } break; case 2: // Meele Attack if (FY == Type2.UP.ordinal()) { Me.PAttack(Type2.UP.name()); } else if (FY == Type2.DOWN.ordinal()) { Me.PAttack(Type2.DOWN.name()); } else if (FY == Type2.LEFT.ordinal()) { Me.PAttack(Type2.LEFT.name()); } else if (FY == Type2.RIGHT.ordinal()) { Me.PAttack(Type2.RIGHT.name()); } break; case 3: // Meele Attack if (FY == Type3.UP.ordinal()) { Me.PAttack(Type3.UP.name()); } else if (FY == Type3.DOWN.ordinal()) { Me.PAttack(Type3.DOWN.name()); } else if (FY == Type3.LEFT.ordinal()) { Me.PAttack(Type3.LEFT.name()); } else if (FY == Type3.RIGHT.ordinal()) { Me.PAttack(Type3.RIGHT.name()); } break; } } /** * get xp and gold from killing characters * * @param Charac collision characters */ public void KillXP(GameCharacter Charac) { // When the character dies if (Charac.ISDEAD && Charac.COLL_LISTENER) { Charac.COLL_LISTENER = false; audDEATH.playAudio("death.wav"); // Remove collision listener for (int j = 0; j < FIREBALL.length; j++) { FIREBALL[j].removeCollChar(Charac); } for (int j = 0; j < SHOCK.length; j++) { SHOCK[j].removeCollChar(Charac); } for (int j = 0; j < DARKNESS.length; j++) { DARKNESS[j].removeCollChar(Charac); } for (int j = 0; j < LIFE_DRAIN.length; j++) { LIFE_DRAIN[j].removeCollChar(Charac); } // Add Xp STATS.IncreaseXP(10 * Charac.STATS.LEVEL); // Add Gold this.GOLD += Charac.GOLD; } } /** * get xp and gold from killing characters * * @param Charac collision characters */ public void KillXP(GameCharacter[] Charac) { // When the character dies for (int i = 0; i < Charac.length; i++) { if (Charac[i].ISDEAD && Charac[i].COLL_LISTENER) { Charac[i].COLL_LISTENER = false; audDEATH.playAudio("death.wav"); // Remove collision listener for (int j = 0; j < FIREBALL.length; j++) { FIREBALL[j].removeCollChar(Charac[i]); } for (int j = 0; j < SHOCK.length; j++) { SHOCK[j].removeCollChar(Charac[i]); } for (int j = 0; j < DARKNESS.length; j++) { DARKNESS[j].removeCollChar(Charac[i]); } for (int j = 0; j < LIFE_DRAIN.length; j++) { LIFE_DRAIN[j].removeCollChar(Charac[i]); } // Add Xp STATS.IncreaseXP(10 * Charac[i].STATS.LEVEL); // Add Gold this.GOLD += Charac[i].GOLD; } } } /** * Check if this x and y coordinate is within the component * * @param x X coordinate * @param y Y coordinate */ public boolean Contains(double x, double y) { // Check collision if ((x > X) && (x < X + W * GROWTHFACTOR)) { if ((y > Y) && (y < Y + H * GROWTHFACTOR)) { return true; } } return false; } /** * Used for debugging get list of spells available to character * * @return List */ public String[] getSpellList() { // Make Array String[] arg = new String[SPELL_LIST.size()]; // Assign names for (int i = 0; i < arg.length; i++) { arg[i] = SPELL_LIST.elementAt(i)[0].NAME; System.out.println(arg[i]); } // Return list return arg; } /** * Spells collide with the given characters * * @param Charac Game character array */ public void addMagicCharacCollision(GameCharacter[] Charac) { // FIREBALL for (int i = 0; i < FIREBALL.length; i++) { FIREBALL[i].addCollChar(Charac); } // SHOCK for (int i = 0; i < SHOCK.length; i++) { SHOCK[i].addCollChar(Charac); } // DARKNESS for (int i = 0; i < DARKNESS.length; i++) { DARKNESS[i].addCollChar(Charac); } // LIFE DRAIN for (int i = 0; i < LIFE_DRAIN.length; i++) { LIFE_DRAIN[i].addCollChar(Charac); } } /** * Spells collide with the given characters * * @param Charac Game character array */ public void addMagicCharacCollision(GameCharacter Charac) { // FIREBALL for (int i = 0; i < FIREBALL.length; i++) { FIREBALL[i].addCollChar(Charac); } // SHOCK for (int i = 0; i < SHOCK.length; i++) { SHOCK[i].addCollChar(Charac); } // DARKNESS for (int i = 0; i < DARKNESS.length; i++) { DARKNESS[i].addCollChar(Charac); } // LIFE DRAIN for (int i = 0; i < LIFE_DRAIN.length; i++) { LIFE_DRAIN[i].addCollChar(Charac); } } /** * Spells collide with walls * * @param Map GridMap */ public void addMagicMapCollision(GridMap Map) { // FIREBALL for (int i = 0; i < FIREBALL.length; i++) { FIREBALL[i].addColisionObject(Map); } // SHOCK for (int i = 0; i < SHOCK.length; i++) { SHOCK[i].addColisionObject(Map); } // DARKNESS for (int i = 0; i < DARKNESS.length; i++) { // DARKNESS[i].addColisionObject(Map); } // LIFE DRAIN for (int i = 0; i < LIFE_DRAIN.length; i++) { LIFE_DRAIN[i].addColisionObject(Map); } } public void Heal(int Amount) { HEALTH += Amount; if (HEALTH > MAX_HEALTH) HEALTH = (int) MAX_HEALTH; } public void giveQuest(GameCharacter Reciever) { if (QUEST_LIST.size() > 0) { if (QUEST_LIST.elementAt(0).STATUS == 0) { Reciever.QUEST_LIST.add(QUEST_LIST.elementAt(0)); QUEST_LIST.elementAt(0).play_UpdateSound(); if (QUEST_LIST.elementAt(0).QTYPE == Quest_Type.DELIVERY) { for (int i = 0; i < QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_NAME.size(); i++) { Reciever.INVENTORY.addItem( QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_NAME.elementAt(i), QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_PRICE.elementAt(i), QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_QUANTITY.elementAt(i), QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_IMAGE.elementAt(i), QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_TAG.elementAt(i), QUEST_LIST.elementAt(0).TARGET_LIST.STATS.elementAt(i)); } } QUEST_LIST.elementAt(0).STATUS = 1; } } } public void CompleteQuest(int Index) { Quest qstComp = QUEST_LIST.elementAt(Index); qstComp.STATUS = 3; qstComp.QUEST_GIVER.QUEST_LIST.elementAt(0).STATUS = 3; qstComp.QUEST_GIVER.QUEST_LIST.removeElementAt(0); STATS.IncreaseXP(qstComp.XP); GOLD += qstComp.GOLD; } public BufferedImage getImage(String Direct, String FName) { // JOptionPane.showMessageDialog(null, "GameCharacter"); try { BufferedImage bg = ImageIO.read(getClass().getResource(Direct + FName)); return bg; } catch (Exception e) { JOptionPane.showMessageDialog(null, getClass().toString()); } return null; } public boolean isJar() { Path pth = Paths.get(System.getProperty("user.dir") + "/Advent.jar"); if (pth.toFile().exists()) return true; return false; } }
public class SketcherConstants { // Path for images public static final String imagePath = "D:/Sketcher/Images/"; // Toolbar icons public static final Icon NEW24 = new ImageIcon(imagePath + "New24.gif"); public static final Icon OPEN24 = new ImageIcon(imagePath + "Open24.gif"); public static final Icon SAVE24 = new ImageIcon(imagePath + "Save24.gif"); public static final Icon SAVEAS24 = new ImageIcon(imagePath + "SaveAs24.gif"); public static final Icon PRINT24 = new ImageIcon(imagePath + "Print24.gif"); public static final Icon LINE24 = new ImageIcon(imagePath + "Line24.gif"); public static final Icon RECTANGLE24 = new ImageIcon(imagePath + "Rectangle24.gif"); public static final Icon CIRCLE24 = new ImageIcon(imagePath + "Circle24.gif"); public static final Icon CURVE24 = new ImageIcon(imagePath + "Curve24.gif"); public static final Icon TEXT24 = new ImageIcon(imagePath + "Text24.gif"); public static final Icon RED24 = new ImageIcon(imagePath + "Red24.gif"); public static final Icon GREEN24 = new ImageIcon(imagePath + "Green24.gif"); public static final Icon BLUE24 = new ImageIcon(imagePath + "Blue24.gif"); public static final Icon YELLOW24 = new ImageIcon(imagePath + "Yellow24.gif"); public static final ImageIcon CUSTOM24 = new ImageIcon(new BufferedImage(24, 24, BufferedImage.TYPE_INT_ARGB)); // Menu item icons public static final Icon NEW16 = new ImageIcon(imagePath + " new16.gif"); public static final Icon OPEN16 = new ImageIcon(imagePath + " Open16.gif"); public static final Icon SAVE16 = new ImageIcon(imagePath + " Save16.gif"); public static final Icon SAVEAS16 = new ImageIcon(imagePath + "SaveAs16.gif"); public static final Icon PRINT16 = new ImageIcon(imagePath + "print16.gif"); public static final Icon LINE16 = new ImageIcon(imagePath + "Line16.gif"); public static final Icon RECTANGLE16 = new ImageIcon(imagePath + "Rectangle16.gif"); public static final Icon CIRCLE16 = new ImageIcon(imagePath + "Circle16.gif"); public static final Icon CURVE16 = new ImageIcon(imagePath + "Curve16.gif"); public static final Icon TEXT16 = new ImageIcon(imagePath + "Text16.gif"); public static final Icon RED16 = new ImageIcon(imagePath + "Red16.gif"); public static final Icon GREEN16 = new ImageIcon(imagePath + "Green16.gif"); public static final Icon BLUE16 = new ImageIcon(imagePath + "Blue16.gif"); public static final Icon YELLOW16 = new ImageIcon(imagePath + "Yellow16.gif"); public static final ImageIcon CUSTOM16 = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)); // Element type definitions public static final int LINE = 101; public static final int RECTANGLE = 102; public static final int CIRCLE = 103; public static final int CURVE = 104; public static final int TEXT = 105; // Initial conditions public static final int DEFAULT_ELEMENT_TYPE = LINE; public static final Color DEFAULT_ELEMENT_COLOR = Color.BLUE; public static final Color HIGHLIGHT_COLOR = Color.MAGENTA; public static final Font DEFAULT_FONT = new Font("Serif", Font.BOLD, 12); // Font point size range specification public static final int POINT_SIZE_MIN = 8; // Minimum font point size public static final int POINT_SIZE_MAX = 24; // Maximum font point size public static final int POINT_SIZE_STEP = 2; // Point size step // Operating modes public static final String NORMAL = "Normal"; public static final String MOVE = "Move"; public static final String ROTATE = "Rotate"; // Default directory and file name for a sketch public static final Path DEFAULT_DIRECTORY = Paths.get(System.getProperty("user.home")).resolve("Sketches"); public static final String DEFAULT_FILENAME = "Sketch.ske"; }
public class CudaEngine { static final Map<Integer, CudaEngine> cudaEngines = new HashMap<>(); private static final String PHEROMONES_CU = "pheromones"; private static final String ioTmpDir = System.getProperty("java.io.tmpdir"); private static int availableDevicesNb = 0; private static ExecutorService initialization; private static int NB_OF_DEVICE_TO_USE = 1; private static AtomicInteger cudaObjectID = new AtomicInteger(0); final HashMap<Kernel, CUfunction> kernels = new HashMap<Kernel, CUfunction>(); protected CUfunction f; protected CUcontext context; private ExecutorService exe; private List<CudaObject> cudaObjects = new ArrayList<CudaObject>(); private int maxThreads; private int Id = -1; private Map<String, CUdeviceptr> neigborsPtrs; private CudaEngine(final int deviceId) { exe = Executors.newSingleThreadExecutor(); // mandatory: Only one cuda thread per context Id = deviceId; try { exe.submit( new Runnable() { @Override public void run() { CUdevice device = new CUdevice(); JCudaDriver.cuDeviceGet(device, deviceId); int array[] = {0}; JCudaDriver.cuDeviceGetAttribute( array, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, device); maxThreads = (int) Math.sqrt(array[0]); context = new CUcontext(); // JCudaDriver.cuCtxCreate(context, CUctx_flags.CU_CTX_SCHED_BLOCKING_SYNC, // device); JCudaDriver.cuCtxCreate(context, 0, device); CUmodule m = new CUmodule(); initModules(m); for (Kernel k : Kernel.values()) { initFunction(m, k); } // JCudaDriver.cuCtxSetCacheConfig(CUfunc_cache.CU_FUNC_CACHE_PREFER_NONE);> // // JCudaDriver.cuCtxSetSharedMemConfig(CUsharedconfig.CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE); } }) .get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e.getMessage()); } neigborsPtrs = new HashMap<>(); } private static void extractAndLoadNativeLib(String nativeLibName, Path target) { // System.err.println("loading "+nativeLibName); final Path path = Paths.get(target.toString(), nativeLibName); if (!path.toFile().exists()) { try (InputStream is = CudaEngine.class .getClassLoader() .getResourceAsStream("/lib/" + nativeLibName)) { // TODO TK property for lib dir Files.copy(is, path); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { // TODO find a way to do it instead of eclipse final Path eclipsePath = FileSystems.getDefault().getPath("lib", nativeLibName); try { Files.copy(eclipsePath, path); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } System.load(path.toString()); // System.load(nativeLibName); } private static void extractAndLoadNativeLibs() throws IOException { Path target = Paths.get(ioTmpDir, "/tklib"); if (!target.toFile().exists()) { Files.createDirectories(target); } final boolean windows = System.getProperty("os.name").equalsIgnoreCase("windows"); String fileExtension = windows ? "dll" : "so"; String prefix = windows ? "" : "lib"; String libPattern = fileExtension.equals("dll") ? "-windows" : "-linux" + "-x86"; if (System.getProperty("sun.arch.data.model").equals("64")) { libPattern += "_64"; } libPattern += "." + fileExtension; // System.err.println(libPattern); System.setProperty("java.library.path", target.toString()); // System.err.println(System.getProperty("java.library.path")); extractAndLoadNativeLib(prefix + "JCudaDriver" + libPattern, target); extractAndLoadNativeLib(prefix + "JCudaRuntime" + libPattern, target); extractAndLoadNativeLib(prefix + "JCurand" + libPattern, target); } public static void main(String[] args) { init(); } /** */ public static boolean init() { synchronized (cudaEngines) { System.err.println("---------Initializing Cuda----------------"); try { extractAndLoadNativeLibs(); JCudaDriver.setExceptionsEnabled(true); JCudaDriver.cuInit(0); compileKernelsPtx(); // Obtain the number of devices int deviceCountArray[] = {0}; JCudaDriver.cuDeviceGetCount(deviceCountArray); availableDevicesNb = deviceCountArray[0]; if (availableDevicesNb == 0) return false; availableDevicesNb = NB_OF_DEVICE_TO_USE; // TODO initialization = Executors.newCachedThreadPool(); System.out.println("Found " + availableDevicesNb + " GPU devices"); for (int i = 0 /*-NB_OF_DEVICE_TO_USE*/; i < availableDevicesNb; i++) { final int index = i; Future<?> initJob = initialization.submit( new Runnable() { public void run() { System.err.println("Initializing device n°" + index); cudaEngines.put(index, new CudaEngine(index)); } }); initJob.get(); initialization.shutdown(); } } catch (InterruptedException | ExecutionException | IOException | CudaException | UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("---------Cannot initialize Cuda !!! ----------------"); return false; } Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { CudaEngine.stop(); } }); System.out.println("---------Cuda Initialized----------------"); return true; } } public static boolean isCudaAvailable() { return availableDevicesNb != 0; } public static CudaEngine getCudaEngine(CudaObject co) { synchronized (cudaEngines) { if (!isCudaAvailable()) throw new CudaException("No cuda device found"); try { initialization.awaitTermination(100, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } Pheromone p = (Pheromone) co; final int pheroID = cudaObjectID.incrementAndGet(); final CudaEngine ce = cudaEngines.get(pheroID % availableDevicesNb); // final CudaEngine ce = cudaEngines.get(1); // final CudaEngine ce = cudaEngines.get(0); // final CudaEngine ce; // if(p.getName().contains("PRE")){ // ce = cudaEngines.get(0); // } // else{ // ce = cudaEngines.get(1); // } // ce.cudaObjects.add(co); System.err.println(co + "ID " + pheroID + " getting cuda engine Id " + ce.Id); return ce; } } static FloatBuffer getUnifiedFloatBuffer(Pointer pinnedMemory, CUdeviceptr devicePtr, long size) { JCudaDriver.cuMemHostAlloc(pinnedMemory, size, JCudaDriver.CU_MEMHOSTALLOC_DEVICEMAP); final ByteBuffer byteBuffer = pinnedMemory.getByteBuffer(0, size); byteBuffer.order(ByteOrder.nativeOrder()); JCudaDriver.cuMemHostGetDevicePointer(devicePtr, pinnedMemory, 0); return byteBuffer.asFloatBuffer(); } public static IntBuffer getUnifiedIntBuffer( Pointer pinnedMemory, CUdeviceptr devicePtr, int size) { JCudaDriver.cuMemHostAlloc(pinnedMemory, size, JCudaDriver.CU_MEMHOSTALLOC_DEVICEMAP); final ByteBuffer byteBuffer = pinnedMemory.getByteBuffer(0, size); byteBuffer.order(ByteOrder.nativeOrder()); JCudaDriver.cuMemHostGetDevicePointer(devicePtr, pinnedMemory, 0); return byteBuffer.asIntBuffer(); } public static int[] getUnifiedIntArray(Pointer pinnedMemory, CUdeviceptr devicePtr, int size) { int[] values = new int[size]; JCudaDriver.cuMemHostAlloc(pinnedMemory, size, JCudaDriver.CU_MEMHOSTALLOC_DEVICEMAP); final ByteBuffer byteBuffer = pinnedMemory.getByteBuffer(0, size); byteBuffer.order(ByteOrder.nativeOrder()); JCudaDriver.cuMemHostGetDevicePointer(devicePtr, pinnedMemory, 0); return values; } public static ByteBuffer getUnifiedByteBuffer( Pointer pinnedMemory, CUdeviceptr devicePtr, int size) { JCudaDriver.cuMemHostAlloc(pinnedMemory, size, JCudaDriver.CU_MEMHOSTALLOC_DEVICEMAP); final ByteBuffer byteBuffer = pinnedMemory.getByteBuffer(0, size); byteBuffer.order(ByteOrder.nativeOrder()); JCudaDriver.cuMemHostGetDevicePointer(devicePtr, pinnedMemory, 0); return byteBuffer; } /** Stop the executors and clean memory on registered CUObject */ public static void stop() { synchronized (cudaEngines) { cuCtxSynchronizeAll(); for (Iterator<CudaEngine> iterator = cudaEngines.values().iterator(); iterator.hasNext(); ) { iterator.next().shutdown(); iterator.remove(); } // for (CudaEngine ce : cudaEngines.values()) { // ce.shutdown(); // } } } /** Stop the executors and clean memory on registered CUObject */ public static synchronized void freeMemory() { for (CudaEngine ce : cudaEngines.values()) { ce.freeCUObjectsMemory(); } } static void initModules(CUmodule module) { JCudaDriver.cuModuleLoad(module, new File(ioTmpDir, PHEROMONES_CU + ".ptx").getAbsolutePath()); } // void compileKernelsPtx() static void compileKernelsPtx() throws IOException { if (!new File(ioTmpDir, PHEROMONES_CU + ".ptx").exists()) { // TODO externalize try (InputStream is = CudaEngine.class.getResourceAsStream( "/turtlekit/cuda/kernels/" + PHEROMONES_CU + ".cu")) { final Path path = Paths.get(ioTmpDir, PHEROMONES_CU + ".cu"); try { Files.copy(is, path); } catch (FileAlreadyExistsException e) { } System.err.println("--------------- Compiling ptx ----------------------"); KernelLauncher.create( path.toString(), Kernel.DIFFUSION_TO_TMP.name(), false, "--use_fast_math", "--prec-div=false"); // ,"--gpu-architecture=sm_20"); } catch (IOException e) { throw e; } } } public static synchronized void cuCtxSynchronizeAll() { for (CudaEngine ce : cudaEngines.values()) { ce.cuCtxSynchronize(); } // List<Future<Void>> futures = new ArrayList<Future<Void>>(); // for (CudaEngine ce : executors) { // futures.add(ce.exe.submit(new Callable<Void>() { // @Override // public Void call() throws Exception { // JCudaDriver.cuCtxSynchronize(); // return null; // } // // })); // } // for (Future<Void> future : futures) { // try { // future.get(); // } catch (InterruptedException | ExecutionException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } } public int cuDeviceGetCount() { return availableDevicesNb; } /** Free memory from the currently registered CUObjects */ public void freeCUObjectsMemory() { exe.submit( new Runnable() { @Override public void run() { cuCtxSynchronize(); for (CudaObject co : cudaObjects) { co.freeMemory(); } JCudaDriver.cuCtxDestroy(context); } }); } private synchronized void shutdown() { if (!exe.isShutdown()) { freeCUObjectsMemory(); } exe.shutdown(); try { System.err.println( "cuda device " + Id + " freed ? " + exe.awaitTermination(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } private void initFunction(CUmodule module, Kernel name) { CUfunction function = new CUfunction(); JCudaDriver.cuModuleGetFunction(function, module, name.name()); kernels.put(name, function); } public int getMaxThreads() { return maxThreads; } public CUfunction getKernelFunction(Kernel f) { CUfunction function = kernels.get(f); if (function == null) throw new CudaException("No such function " + f); return function; } // public static void main(String[] args) { // CudaPheromone cu, cu2; // getCudaEngine(cu = new CudaPheromone(10, 10, 0.1f, 0f, "test")); // getCudaEngine(cu2 = new CudaPheromone(100, 100, 0.3f, 0.5f, "test2")); // cu.set(3, 3, 8); //// cu.diffusion(); // cu.evaporation(); // System.err.println(cu.get(3, 3)); // System.err.println(cu.get(0, 0)); // System.err.println(cu.get(3, 2)); // System.err.println("maxdir " + cu.getMaxDir(3, 2)); // cu.diffusion(); // System.err.println(cu.get(3, 3)); // cu.diffusion(); // System.err.println(cu.get(3, 3)); // cu2.diffusion(); // cu.freeMemory(); // cu2.freeMemory(); // CudaEngine.stop(); // } public void cuCtxSynchronize() { try { exe.submit( new Callable<Void>() { @Override public Void call() throws Exception { JCudaDriver.cuCtxSynchronize(); return null; } }) .get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } public Future<?> submit(Runnable runnable) { if (!exe.isShutdown()) { return exe.submit(runnable); } return null; } public CUdeviceptr getNeighborsPtr(String string) { return neigborsPtrs.get(string); } public void addNeighborsPtr(String string, CUdeviceptr neighborsPtr) { neigborsPtrs.put(string, neighborsPtr); } enum Kernel { DIFFUSION_TO_TMP, DIFFUSION_UPDATE, EVAPORATION, FIELD_MAX_DIR, DIFFUSION_UPDATE_THEN_EVAPORATION, DIFFUSION_UPDATE_THEN_EVAPORATION_THEN_FIELDMAXDIR // ,FILL_NEIGHBORS , TEST, DIFFUSION_UPDATE_THEN_EVAPORATION_THEN_FIELDMAXDIRV2 } }
/** * Class constructor; creates a new Installer object, displays a JFrame introducing the program, * allows the user to select an install directory, and copies files from the jar into the * directory. */ public Installer(String args[]) { // Inputs are --install-dir INSTALL_DIR for (int k = 0; k < args.length; k = k + 2) { switch (args[k]) { case "--install-dir": directory = new File(args[k + 1]); System.out.println(directory); break; case "--port": port = Integer.parseInt(args[k + 1]); break; } } cp = new Stream(); // Find the installer program so we can get to the files. installer = getInstallerProgramFile(); String name = installer.getName(); programName = (name.substring(0, name.indexOf("-"))).toUpperCase(); // Get the installation information thisJava = System.getProperty("java.version"); thisJavaBits = System.getProperty("sun.arch.data.model") + " bits"; // Find the ImageIO Tools and get the version String javaHome = System.getProperty("java.home"); File extDir = new File(javaHome); extDir = new File(extDir, "lib"); extDir = new File(extDir, "ext"); File clib = getFile(extDir, "clibwrapper_jiio", ".jar"); File jai = getFile(extDir, "jai_imageio", ".jar"); imageIOTools = (clib != null) && clib.exists() && (jai != null) && jai.exists(); if (imageIOTools) { Hashtable<String, String> jaiManifest = getManifestAttributes(jai); imageIOVersion = jaiManifest.get("Implementation-Version"); } // Get the CTP.jar parameters Hashtable<String, String> manifest = getJarManifestAttributes("/CTP/libraries/CTP.jar"); programDate = manifest.get("Date"); buildJava = manifest.get("Java-Version"); // Get the util.jar parameters Hashtable<String, String> utilManifest = getJarManifestAttributes("/CTP/libraries/util.jar"); utilJava = utilManifest.get("Java-Version"); // Get the MIRC.jar parameters (if the plugin is present) Hashtable<String, String> mircManifest = getJarManifestAttributes("/CTP/libraries/MIRC.jar"); if (mircManifest != null) { mircJava = mircManifest.get("Java-Version"); mircDate = mircManifest.get("Date"); mircVersion = mircManifest.get("Version"); } // Set up the installation information for display if (imageIOVersion.equals("")) { imageIOVersion = "<b><font color=\"red\">not installed</font></b>"; } else if (imageIOVersion.startsWith("1.0")) { imageIOVersion = "<b><font color=\"red\">" + imageIOVersion + "</font></b>"; } if (thisJavaBits.startsWith("64")) { thisJavaBits = "<b><font color=\"red\">" + thisJavaBits + "</font></b>"; } boolean javaOK = (thisJava.compareTo(buildJava) >= 0); javaOK &= (thisJava.compareTo(utilJava) >= 0); javaOK &= (thisJava.compareTo(mircJava) >= 0); if (!javaOK) { thisJava = "<b><font color=\"red\">" + thisJava + "</font></b>"; } if (directory == null) exit(); // Point to the parent of the directory in which to install the program. // so the copy process works correctly for directory trees. // // If the user has selected a directory named "CTP", // then assume that this is the directory in which // to install the program. // // If the directory is not CTP, see if it is called "RSNA" and contains // the Launcher program, in which case we can assume that it is an // installation that was done with Bill Weadock's all-in-one installer for Windows. // // If neither of those cases is true, then this is already the parent of the // directory in which to install the program if (directory.getName().equals("CTP")) { directory = directory.getParentFile(); } else if (directory.getName().equals("RSNA") && (new File(directory, "Launcher.jar")).exists()) { suppressFirstPathElement = true; } // Cleanup old releases cleanup(directory); // Get a port for the server. if (port < 0) { if (checkServer(-port, false)) { System.err.println( "CTP appears to be running.\nPlease stop CTP and run the installer again."); System.exit(0); } } // Now install the files and report the results. int count = unpackZipFile(installer, "CTP", directory.getAbsolutePath(), suppressFirstPathElement); if (count > 0) { // Create the service installer batch files. updateWindowsServiceInstaller(); updateLinuxServiceInstaller(); // If this was a new installation, set up the config file and set the port installConfigFile(port); // Make any necessary changes in the config file to reflect schema evolution fixConfigSchema(); System.out.println("Installation complete."); System.out.println(programName + " has been installed successfully."); System.out.println(count + " files were installed."); } else { System.err.println("Installation failed."); System.err.println(programName + " could not be fully installed."); } if (!programName.equals("ISN") && startRunner(new File(directory, "CTP"))) System.exit(0); }
// move source to target with verification static void moveAndVerify(Path source, Path target, CopyOption... options) throws IOException { // read attributes before file is moved BasicFileAttributes basicAttributes = null; PosixFileAttributes posixAttributes = null; DosFileAttributes dosAttributes = null; Map<String, ByteBuffer> namedAttributes = null; // get file attributes of source file String os = System.getProperty("os.name"); if (os.startsWith("Windows")) { dosAttributes = readAttributes(source, DosFileAttributes.class, NOFOLLOW_LINKS); basicAttributes = dosAttributes; } else { posixAttributes = readAttributes(source, PosixFileAttributes.class, NOFOLLOW_LINKS); basicAttributes = posixAttributes; } if (basicAttributes == null) basicAttributes = readAttributes(source, BasicFileAttributes.class, NOFOLLOW_LINKS); // hash file contents if regular file int hash = (basicAttributes.isRegularFile()) ? computeHash(source) : 0; // record link target if symbolic link Path linkTarget = null; if (basicAttributes.isSymbolicLink()) linkTarget = readSymbolicLink(source); // read named attributes if available (and file is not a sym link) if (!basicAttributes.isSymbolicLink() && getFileStore(source).supportsFileAttributeView("xattr")) { namedAttributes = readUserDefinedFileAttributes(source); } // move file Path result = move(source, target, options); assertTrue(result == target); // verify source does not exist assertTrue(notExists(source)); // verify file contents if (basicAttributes.isRegularFile()) { if (computeHash(target) != hash) throw new RuntimeException("Failed to verify move of regular file"); } // verify link target if (basicAttributes.isSymbolicLink()) { if (!readSymbolicLink(target).equals(linkTarget)) throw new RuntimeException("Failed to verify move of symbolic link"); } // verify basic attributes checkBasicAttributes( basicAttributes, readAttributes(target, BasicFileAttributes.class, NOFOLLOW_LINKS)); // verify other attributes when same provider if (source.getFileSystem().provider() == target.getFileSystem().provider()) { // verify POSIX attributes if (posixAttributes != null && !basicAttributes.isSymbolicLink() && testPosixAttributes) { checkPosixAttributes( posixAttributes, readAttributes(target, PosixFileAttributes.class, NOFOLLOW_LINKS)); } // verify DOS attributes if (dosAttributes != null && !basicAttributes.isSymbolicLink()) { DosFileAttributes attrs = readAttributes(target, DosFileAttributes.class, NOFOLLOW_LINKS); checkDosAttributes(dosAttributes, attrs); } // verify named attributes if (namedAttributes != null && getFileStore(target).supportsFileAttributeView("xattr")) { checkUserDefinedFileAttributes(namedAttributes, readUserDefinedFileAttributes(target)); } } }
/** * This class contains some static methods to retrieve information on the Pokepon package itself. * THIS IS A VERY DELICATE CLASS: HANDLE WITH CARE! * * @author Giacomo Parolini */ public class Meta { public static final char DIRSEP = '/'; // probably superfluous /** * Working directory of the pokepon class tree; if game is launched from JAR, this is the * directory where the JAR resides; else, it is the directory containing 'pokepon'. */ private static Path cwd; static { String tmp = Meta.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // Strip the leading slash if on windows if (tmp.matches("^/[A-Z]:/.*")) { tmp = tmp.substring(1); } cwd = Paths.get(tmp); } private static URL cwdURL; public static final boolean LAUNCHED_FROM_JAR = cwd.toString().endsWith(".jar"); /** Are we on Windows or on POSIX os? */ public static final boolean IS_WINDOWS = System.getProperty("os.name").toUpperCase().contains("WIN"); /** Directory containing variable data (teams, confs, ...) */ public static final String APPDATA_DIR = (IS_WINDOWS ? System.getenv("APPDATA") + DIRSEP : System.getenv("HOME") + DIRSEP + ".") + "pokepon"; static { // if launched from a jar, use the parent as cwd if (LAUNCHED_FROM_JAR) cwd = cwd.getParent(); if (Debug.on) printDebug("[Meta] cwd: " + cwd + "\nLaunched from jar: " + LAUNCHED_FROM_JAR); } private static String cwdStr = "file://" + cwd.toString(); public static URL getCwd() { if (cwdURL != null) return cwdURL; try { cwdURL = new URL(cwdStr); return cwdURL; } catch (MalformedURLException e) { return null; } } public static Path getCwdPath() { return cwd; } private static URL getSubURL(final String subdir) { if (LAUNCHED_FROM_JAR) { if (Debug.pedantic) printDebug( "[Meta.getSubURL(" + POKEPON_ROOTDIR + DIRSEP + subdir + ")]: " + Meta.class.getClassLoader().getResource(POKEPON_ROOTDIR + DIRSEP + subdir)); return Meta.class.getClassLoader().getResource(POKEPON_ROOTDIR + DIRSEP + subdir); } else { try { return new URL( getCwd().getProtocol() + "://" + getCwd().getPath() + DIRSEP + POKEPON_ROOTDIR + DIRSEP + subdir); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } private static URL getAppDataURL(final String subdir) { try { if (Debug.pedantic) printDebug( "[Meta.getAppDataURL(" + subdir + ")]: " + "file://" + APPDATA_DIR + DIRSEP + subdir); return new URL("file://" + APPDATA_DIR + DIRSEP + subdir); } catch (MalformedURLException e) { throw new RuntimeException(e); } } /** Returns the URL of the package root */ public static URL getRootURL() { return getSubURL(""); } /** Returns the URL of the pony directory. */ public static URL getPonyURL() { return getSubURL(PONY_DIR); } /** Returns the URL of the move directory. */ public static URL getMoveURL() { return getSubURL(MOVE_DIR); } /** Returns the URL of the item directory. */ public static URL getItemURL() { return getSubURL(ITEM_DIR); } /** Returns the URL of the ability directory. */ public static URL getAbilityURL() { return getSubURL(ABILITY_DIR); } /** Returns the URL of the save directory. NOTE: this is in local AppData */ public static URL getSaveURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(SAVE_DIR) : getSubURL("data" + DIRSEP + SAVE_DIR); } /** Returns the URL of the battle directory. */ public static URL getBattleURL() { return getSubURL(BATTLE_DIR); } /** Returns the URL of the data directory. NOTE: this is in local AppData */ public static URL getDataURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(DATA_DIR) : getSubURL("data"); } /** Returns the URL of the resources directory */ public static URL getResourcesURL() { return getSubURL(RESOURCE_DIR); } /** Returns the URL of the sprites directory */ public static URL getSpritesURL() { return getSubURL(SPRITE_DIR); } /** Returns the URL of the tokens directory */ public static URL getTokensURL() { return getSubURL(TOKEN_DIR); } /** Returns the URL of the hazards directory */ public static URL getHazardsURL() { return getSubURL(HAZARD_DIR); } /** Returns the URL of the net directory */ public static URL getNetURL() { return getSubURL(NET_DIR); } /** Returns the URL of the audiofiles directory */ public static URL getAudioURL() { return getSubURL(AUDIO_DIR); } /** Returns the URL of the battle records directory. THIS IS IN APPDATA */ public static URL getBattleRecordsURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(BATTLE_RECORDS_DIR) : getSubURL("data" + DIRSEP + BATTLE_RECORDS_DIR); } /** Takes a string and hides its extension */ public static String hideExtension(final String str) { String[] arr = str.split("\\."); if (arr.length <= 1) return str; // there was no "." in str. StringBuilder sb = new StringBuilder(""); for (int i = 0; i < arr.length - 1; ++i) { if (sb.length() > 0) sb.append("."); sb.append(arr[i]); } return sb.toString(); } /** * Given a simple class name, returns the package to which it belongs (stripped of the initial * "pokepon.") or null if no file is found; NOTE: the only searched packages are pony, move, * ability and item. */ public static String getPackage(final String className) { if (findSubclassesNames(complete(PONY_DIR), Pony.class).contains(className)) return "pony"; if (findSubclassesNames(complete(MOVE_DIR), Move.class).contains(className)) return "move"; if (findSubclassesNames(complete(ABILITY_DIR), Ability.class).contains(className)) return "ability"; if (findSubclassesNames(complete(ITEM_DIR), Item.class).contains(className)) return "item"; return null; } /** * Takes a path name and appends it to POKEPON_ROOTDIR to return a valid "relatively absolute" * path (id est: absolute relatively to the java classpath directory) */ public static String complete(final String path) { return POKEPON_ROOTDIR + DIRSEP + path; } /** * This is used to cross-platform-ly locate resources in JAR file; to safely find a resource, do: * getClass().getResource(Meta.complete2(Meta.SOME_DIR)+"/"+resourceName); */ public static String complete2(String path) { String cmp = DIRSEP + complete(path); if (cmp.matches("^/[A-Z]:/.*")) return cmp.substring(1); else return cmp; } /** * Convert all special tags in a string to local URL (e.g [sprite: NameOfPony] => * file://path/to/local/sprite.png); allowed special tags are: sprite, type, movetype * * @return The converted string */ public static String toLocalURL(final String msg) { StringBuilder converted = new StringBuilder(); boolean parsingTag = false; boolean inTagName = true; StringBuilder tagName = new StringBuilder(10); StringBuilder tagArg = new StringBuilder(30); for (int i = 0; i < msg.length(); ++i) { char c = msg.charAt(i); switch (c) { case '[': if (!parsingTag) { parsingTag = true; } else { if (inTagName) tagName.append(c); else tagArg.append(c); } break; case ']': if (parsingTag) { parsingTag = false; converted.append( convertLocalURLTag(tagName.toString().trim(), tagArg.toString().trim())); tagName.setLength(0); tagArg.setLength(0); inTagName = true; } else { converted.append(c); } break; case ':': if (parsingTag) { if (inTagName) inTagName = false; else tagArg.append(c); } else { converted.append(c); } break; default: if (parsingTag) { if (inTagName) tagName.append(c); else tagArg.append(c); } else { converted.append(c); } } } return converted.toString(); } private static String convertLocalURLTag(final String name, final String arg) { if (name.equals("sprite")) { try { Pony tmp = PonyCreator.create(arg); return "" + tmp.getFrontSprite(); } catch (ReflectiveOperationException e) { printDebug("[Meta.toLocalURL] Error creating pony " + arg + ": " + e); e.printStackTrace(); } } else if (name.equals("type")) { try { return "" + pokepon.enums.Type.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating type " + arg); e.printStackTrace(); } } else if (name.equals("movetype")) { try { return "" + Move.MoveType.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating movetype " + arg); e.printStackTrace(); } } return ""; } /** * Searches for the directory 'dirPath'; if not found, tries to create it, then returns a File * object for that directory. */ public static File ensureDirExists(final String dirPath) { File dirpath = new File(dirPath); if (!dirpath.isDirectory()) { if (!dirpath.exists()) { printDebug("[Meta] " + dirpath + " does not exist: creating it..."); try { Files.createDirectories(Paths.get(dirpath.getPath())); return dirpath; } catch (IOException e) { printDebug("[Meta] Exception while creating directory:"); e.printStackTrace(); return null; } } else { printDebug( "[Meta] Error: path `" + dirpath + "' is not a valid directory path, and could not create it."); return null; } } else return dirpath; } /** * Checks if a given file exists and, if not, create it by copying a default template from * resources; used to create default conf files. * * @param file The path of the file that needs to exist * @param template The path of the template for the file */ public static void ensureFileExists(final String file, final String template) { if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) { if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one."); InputStream stream = Meta.class.getResourceAsStream(template); if (stream == null) { printDebug( "[ WARNING ] template for " + template + " not found. Won't create a default " + file + "."); } else { int readBytes; byte[] buffer = new byte[4096]; try (OutputStream outStream = new FileOutputStream(new File(file))) { while ((readBytes = stream.read(buffer)) > 0) { outStream.write(buffer, 0, readBytes); } if (Debug.on) printDebug("[Meta] created default file " + file + " from " + template + "."); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException ignore) { } } } } else { if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + "."); } } /** Path of the Pokepon root directory, relative to the java classpath */ public static final String POKEPON_ROOTDIR = "pokepon"; // These are relative to POKEPON_ROOTDIR public static final String PONY_DIR = "pony"; public static final String MOVE_DIR = "move"; public static final String HAZARD_DIR = "move" + DIRSEP + "hazard"; public static final String BATTLE_DIR = "battle"; public static final String MAIN_DIR = "main"; public static final String ENUM_DIR = "enums"; public static final String ITEM_DIR = "item"; public static final String ABILITY_DIR = "ability"; public static final String RESOURCE_DIR = "resources"; public static final String SPRITE_DIR = "resources" + DIRSEP + "sprites"; public static final String TOKEN_DIR = "resources" + DIRSEP + "tokens"; public static final String AUDIO_DIR = "resources" + DIRSEP + "audio"; public static final String NET_DIR = "net"; public static final String ANIMATION_DIR = "gui" + DIRSEP + "animation"; // These are in APPDATA when the game is launched from jar (i.e. in release version) public static final String DATA_DIR = ""; public static final String SAVE_DIR = "teams"; public static final String BATTLE_RECORDS_DIR = "battle_records"; public static void main(String[] args) { consoleHeader(" META "); printMsg("Rootdir:\t" + getRootURL()); printMsg("PonyURL:\t" + getPonyURL()); printMsg("MoveURL:\t" + getMoveURL()); printMsg("HazardURL:\t" + getHazardsURL()); printMsg("BattleURL:\t" + getBattleURL()); printMsg("ItemURL:\t" + getItemURL()); printMsg("AbilityURL:\t" + getAbilityURL()); printMsg("ResourcesURL:\t" + getResourcesURL()); printMsg("SpritesURL:\t" + getSpritesURL()); printMsg("TokensURL:\t" + getTokensURL()); printMsg("AudioURL:\t" + getAudioURL()); printMsg("NetURL: \t" + getNetURL()); printMsg("DataURL:\t" + getDataURL()); printMsg("SaveURL:\t" + getSaveURL()); } }
/** Test for AttachmentService */ @RunWith(MockitoJUnitRunner.class) public class AttachmentServiceImplTest { @InjectMocks @Spy private AttachmentServiceImpl attachmentService; @Mock private AttachmentDao attachmentDao; @Mock private AttachmentFactory attachmentFactory; @Captor private ArgumentCaptor<List<Attachment>> argumentCaptor; private MultipartFile multipartFile; private String pathTempFile = System.getProperty("java.io.tmpdir") + "/test_" + Math.random() + ".png"; private String storagePath = System.getProperty("java.io.tmpdir") + "/STORAGE/"; private String pathDefaultPreview = storagePath + "preview/"; @Before public void setUp() throws Exception { // Download file for test URL website = new URL("http://archive.org/web/images/logo_wayback_210x77.png"); ReadableByteChannel resFile = Channels.newChannel(website.openStream()); // Create file File file = new File(pathTempFile); FileOutputStream fos = new FileOutputStream(pathTempFile); fos.getChannel().transferFrom(resFile, 0, Long.MAX_VALUE); // Save to MultipartFile FileInputStream input = new FileInputStream(file); multipartFile = new MockMultipartFile("file", file.getName(), "image/png", IOUtils.toByteArray(input)); fos.close(); input.close(); // Set paths attachmentService.setStoragePath(storagePath); attachmentService.setPathDefaultPreview(pathDefaultPreview); } @After public void tearDown() throws Exception { // Удаляем тестовый фаил Files.delete(Paths.get(pathTempFile)); // Удаляем тестовые папки и файлы Files.walkFileTree( Paths.get(storagePath), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } /** * Check uploading files and create attachments * * @throws Exception */ @Test public void testCreateAttachment() throws Exception { List<MultipartFile> files = new ArrayList<>(); files.add(multipartFile); Mockito.when(attachmentFactory.newAttachment()).thenReturn(null); attachmentService.setAttachment(new Attachment()); attachmentService.setMessageResponse(new MessageResponse()); MessageResponse messageResponse = attachmentService.createAttachment(files); Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture()); Attachment attachment = argumentCaptor.getValue().get(0); boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath())); boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage())); Files.delete(Paths.get(storagePath + attachment.getPreviewPath())); Files.delete(Paths.get(storagePath + attachment.getFilePathInStorage())); Assert.assertTrue( attachment.getMimeType().equals("image/png") && messageResponse.getCode() == 0 && isExistPreview && isExistImage); } @Test public void testRemoveAttachment() throws Exception { // CREATING ATTACHMENT FOR REMOVE List<MultipartFile> files = new ArrayList<>(); files.add(multipartFile); Mockito.when(attachmentFactory.newAttachment()).thenReturn(null); attachmentService.setAttachment(new Attachment()); attachmentService.setMessageResponse(new MessageResponse()); MessageResponse messageResponse1 = attachmentService.createAttachment(files); Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture()); Attachment attachment = argumentCaptor.getValue().get(0); // REMOVE ATTACHMENT Mockito.when(attachmentDao.removeAttachment(attachment.getAttachmentId())) .thenReturn(attachment); MessageResponse messageResponse = attachmentService.removeAttachment(attachment.getAttachmentId()); boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath())); boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage())); Assert.assertTrue(!isExistPreview && !isExistImage && messageResponse.getCode() == 1); } }
/** Tests all possible ways to invoke copy to copy a file to a file */ static void testCopyFileToFile(Path dir1, Path dir2, boolean supportsLinks) throws IOException { Path source, target, link, entry; // -- regular file -- /** Test: move regular file, target does not exist */ source = createSourceFile(dir1); target = getTargetFile(dir2); copyAndVerify(source, target); delete(source); delete(target); /** Test: copy regular file, target exists */ source = createSourceFile(dir1); target = getTargetFile(dir2); createFile(target); try { copyAndVerify(source, target); throw new RuntimeException("FileAlreadyExistsException expected"); } catch (FileAlreadyExistsException x) { } delete(target); createDirectory(target); try { copyAndVerify(source, target); throw new RuntimeException("FileAlreadyExistsException expected"); } catch (FileAlreadyExistsException x) { } delete(source); delete(target); /** Test: copy regular file, target does not exist */ source = createSourceFile(dir1); target = getTargetFile(dir2); copyAndVerify(source, target, REPLACE_EXISTING); delete(source); delete(target); /** Test: copy regular file, target exists */ source = createSourceFile(dir1); target = getTargetFile(dir2); createFile(target); copyAndVerify(source, target, REPLACE_EXISTING); delete(source); delete(target); /** Test: copy regular file, target exists and is empty directory */ source = createSourceFile(dir1); target = getTargetFile(dir2); createDirectory(target); copyAndVerify(source, target, REPLACE_EXISTING); delete(source); delete(target); /** Test: copy regular file, target exists and is non-empty directory */ source = createSourceFile(dir1); target = getTargetFile(dir2); createDirectory(target); entry = target.resolve("foo"); createFile(entry); try { copyAndVerify(source, target); throw new RuntimeException("FileAlreadyExistsException expected"); } catch (FileAlreadyExistsException x) { } delete(entry); delete(source); delete(target); /** Test: copy regular file + attributes */ source = createSourceFile(dir1); target = getTargetFile(dir2); copyAndVerify(source, target, COPY_ATTRIBUTES); delete(source); delete(target); // -- directory -- /* * Test: copy directory, target does not exist */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); copyAndVerify(source, target); delete(source); delete(target); /** Test: copy directory, target exists */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); createFile(target); try { copyAndVerify(source, target); throw new RuntimeException("FileAlreadyExistsException expected"); } catch (FileAlreadyExistsException x) { } delete(target); createDirectory(target); try { copyAndVerify(source, target); throw new RuntimeException("FileAlreadyExistsException expected"); } catch (FileAlreadyExistsException x) { } delete(source); delete(target); /** Test: copy directory, target does not exist */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); copyAndVerify(source, target, REPLACE_EXISTING); delete(source); delete(target); /** Test: copy directory, target exists */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); createFile(target); copyAndVerify(source, target, REPLACE_EXISTING); delete(source); delete(target); /** Test: copy directory, target exists and is empty directory */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); createDirectory(target); copyAndVerify(source, target, REPLACE_EXISTING); delete(source); delete(target); /** Test: copy directory, target exists and is non-empty directory */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); createDirectory(target); entry = target.resolve("foo"); createFile(entry); try { copyAndVerify(source, target, REPLACE_EXISTING); throw new RuntimeException("DirectoryNotEmptyException expected"); } catch (DirectoryNotEmptyException x) { } delete(entry); delete(source); delete(target); /* * Test: copy directory + attributes */ source = createSourceDirectory(dir1); target = getTargetFile(dir2); copyAndVerify(source, target, COPY_ATTRIBUTES); delete(source); delete(target); // -- symbolic links -- /** Test: Follow link */ if (supportsLinks) { source = createSourceFile(dir1); link = dir1.resolve("link"); createSymbolicLink(link, source); target = getTargetFile(dir2); copyAndVerify(link, target); delete(link); delete(source); } /** Test: Copy link (to file) */ if (supportsLinks) { source = createSourceFile(dir1); link = dir1.resolve("link"); createSymbolicLink(link, source); target = getTargetFile(dir2); copyAndVerify(link, target, NOFOLLOW_LINKS); delete(link); delete(source); } /** Test: Copy link (to directory) */ if (supportsLinks) { source = dir1.resolve("mydir"); createDirectory(source); link = dir1.resolve("link"); createSymbolicLink(link, source); target = getTargetFile(dir2); copyAndVerify(link, target, NOFOLLOW_LINKS); delete(link); delete(source); } /** Test: Copy broken link */ if (supportsLinks) { assertTrue(notExists(source)); link = dir1.resolve("link"); createSymbolicLink(link, source); target = getTargetFile(dir2); copyAndVerify(link, target, NOFOLLOW_LINKS); delete(link); } /** Test: Copy link to UNC (Windows only) */ if (supportsLinks && System.getProperty("os.name").startsWith("Windows")) { Path unc = Paths.get("\\\\rialto\\share\\file"); link = dir1.resolve("link"); createSymbolicLink(link, unc); target = getTargetFile(dir2); copyAndVerify(link, target, NOFOLLOW_LINKS); delete(link); } // -- misc. tests -- /** Test nulls */ source = createSourceFile(dir1); target = getTargetFile(dir2); try { copy(source, null); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException x) { } try { copy(source, target, (CopyOption[]) null); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException x) { } try { CopyOption[] opts = {REPLACE_EXISTING, null}; copy(source, target, opts); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException x) { } delete(source); /** Test UOE */ source = createSourceFile(dir1); target = getTargetFile(dir2); try { copy(source, target, new CopyOption() {}); } catch (UnsupportedOperationException x) { } try { copy(source, target, REPLACE_EXISTING, new CopyOption() {}); } catch (UnsupportedOperationException x) { } delete(source); }