Esempio n. 1
1
  /**
   * Return the value for a given name from the System Properties or the Environmental Variables.
   * The former overrides the latter.
   *
   * @param name - the name of the System Property or Environmental Variable
   * @return the value of the variable or null if it was not found
   */
  public static String getEnvOrProp(String name) {
    // System properties override env. variables
    String envVal = System.getenv(name);
    String sysPropVal = System.getProperty(name);

    if (sysPropVal != null) return sysPropVal;

    return envVal;
  }
Esempio n. 2
0
 void setConfig(Configuration config) {
   log.debug("config: " + config);
   proxyHost = config.get(PARAM_PROXY_HOST);
   proxyPort = config.getInt(PARAM_PROXY_PORT, DEFAULT_PROXY_PORT);
   if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
     String http_proxy = System.getenv("http_proxy");
     if (!StringUtil.isNullString(http_proxy)) {
       try {
         HostPortParser hpp = new HostPortParser(http_proxy);
         proxyHost = hpp.getHost();
         proxyPort = hpp.getPort();
       } catch (HostPortParser.InvalidSpec e) {
         log.warning("Can't parse http_proxy environment var, ignoring: " + http_proxy + ": " + e);
       }
     }
   }
   if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
     proxyHost = null;
   } else {
     log.info("Proxying through " + proxyHost + ":" + proxyPort);
   }
   userAgent = config.get(PARAM_USER_AGENT);
   if (StringUtil.isNullString(userAgent)) {
     userAgent = null;
   } else {
     log.debug("Setting User-Agent to " + userAgent);
   }
 }
  void launchWorkerNode(Container container) throws IOException, YarnException {
    Map<String, String> env = System.getenv();
    ContainerLaunchContext workerContext = Records.newRecord(ContainerLaunchContext.class);

    LocalResource workerJar = Records.newRecord(LocalResource.class);
    setupWorkerJar(workerJar);
    workerContext.setLocalResources(Collections.singletonMap("socialite.jar", workerJar));
    System.out.println("[Master] workerJar:" + workerJar);

    Map<String, String> workerEnv = new HashMap<String, String>(env);
    setupWorkerEnv(workerEnv);
    workerContext.setEnvironment(workerEnv);

    String opts = "-Dsocialite.master=" + NetUtils.getHostname().split("/")[1] + " ";
    opts += "-Dsocialite.worker.num_threads=" + ClusterConf.get().getNumWorkerThreads() + " ";
    workerContext.setCommands(
        Collections.singletonList(
            "$JAVA_HOME/bin/java -ea "
                + env.get("JVM_OPTS")
                + " "
                + env.get("SOCIALITE_OPTS")
                + " "
                + opts
                + " "
                + "socialite.dist.worker.WorkerNode"
                + " 1>"
                + ApplicationConstants.LOG_DIR_EXPANSION_VAR
                + "/stdout"
                + " 2>"
                + ApplicationConstants.LOG_DIR_EXPANSION_VAR
                + "/stderr"));
    nmClient.startContainer(container, workerContext);
    L.info("Launched worker node (container:" + container.getId() + ")");
  }
Esempio n. 4
0
  private void setSvnCredential(CIJob job) throws JDOMException, IOException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential");
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String credentialFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("credentialFilePath ... " + credentialFilePath);
      }
      File credentialFile = new File(credentialFilePath);

      SvnProcessor processor = new SvnProcessor(credentialFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(credentialFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      processor.changeNodeValue("credentials/entry//userName", job.getUserName());
      processor.changeNodeValue("credentials/entry//password", job.getPassword());
      processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName()));

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setSvnCredential "
              + e.getLocalizedMessage());
    }
  }
Esempio n. 5
0
 static {
   dict = null;
   String wnhome = System.getenv("WNHOME");
   String path =
       (new StringBuilder(String.valueOf(wnhome)))
           .append(File.separator)
           .append("dict")
           .toString();
   System.out.println(
       (new StringBuilder("Path to dictionary:")).append(getWNLocation()).toString());
   URL url = null;
   try {
     File f =
         new File(
             (new StringBuilder(String.valueOf(getWNLocation())))
                 .append(File.separator)
                 .append("dict")
                 .toString());
     URI uri = f.toURI();
     url = uri.toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   dict = new Dictionary(url);
   dict.open();
 }
Esempio n. 6
0
 // For war agent needs to be switched on
 private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
   // Check for system props, system env and agent config
   boolean sysProp =
       System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
   boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
   boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
   return sysProp || env || config;
 }
Esempio n. 7
0
  /**
   * Creates a github repository and pushes the files in the working folder into it (respecting
   * -with some restrictions- the .gitignore file)
   *
   * <p>If a repository already exists with the desired name, creates a new commit, maintaining
   * push/commit history.
   */
  private void pushToGitHub() throws RuntimeException {
    // only GitHub implemented in this application
    IRepositoryManager rpm = new GitHubRepositoryManager(repositoryName);
    rpm.setUser(System.getenv("GH_USER"));
    rpm.setPass(System.getenv("GH_PASS"));
    try {
      // create a git repo on github or bitbucket...
      rpm.createRepository();

      // add folder to track
      rpm.setLocalFolder(this.workingFolder);

      // push the files to the repo...
      rpm.push();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 8
0
File: Macro.java Progetto: bramk/bnd
  public String _env(String args[]) {
    verifyCommand(args, "${env;<name>}, get the environmet variable", null, 2, 2);

    try {
      return System.getenv(args[1]);
    } catch (Throwable t) {
      return null;
    }
  }
Esempio n. 9
0
 // Try to find an URL for system props or config
 private String findAgentUrl(Configuration pConfig) {
   // System property has precedence
   String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
   if (url == null) {
     url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
     if (url == null) {
       url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
     }
   }
   return NetworkUtil.replaceExpression(url);
 }
Esempio n. 10
0
  private void setMailCredential(CIJob job) {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    }
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ... " + mailFilePath);
      }
      File mailFile = new File(mailFilePath);

      SvnProcessor processor = new SvnProcessor(mailFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(mailFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      // Mail have to go with jenkins running email address
      InetAddress ownIP = InetAddress.getLocalHost();
      processor.changeNodeValue(
          CI_HUDSONURL,
          HTTP_PROTOCOL
              + PROTOCOL_POSTFIX
              + ownIP.getHostAddress()
              + COLON
              + job.getJenkinsPort()
              + FORWARD_SLASH
              + CI
              + FORWARD_SLASH);
      processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
      processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
      processor.changeNodeValue("adminAddress", job.getSenderEmailId());

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setMailCredential "
              + e.getLocalizedMessage());
    }
  }
Esempio n. 11
0
 private void adjustConfiguration(Element root, File dir) {
   // If this is an ISN installation and the Edge Server
   // keystore and truststore files do not exist, then set the configuration
   // to use the keystore.jks and truststore.jks files instead of the ones
   // in the default installation. If the Edge Server files do exist, then
   // delete the keystore.jks and truststore.jks files, just to avoid
   // confusion.
   if (programName.equals("ISN")) {
     Element server = getFirstNamedChild(root, "Server");
     Element ssl = getFirstNamedChild(server, "SSL");
     String rsnaroot = System.getenv("RSNA_ROOT");
     rsnaroot = (rsnaroot == null) ? "/usr/local/edgeserver" : rsnaroot.trim();
     String keystore = rsnaroot + "/conf/keystore.jks";
     String truststore = rsnaroot + "/conf/truststore.jks";
     File keystoreFile = new File(keystore);
     File truststoreFile = new File(truststore);
     cp.appendln(Color.black, "Looking for " + keystore);
     if (keystoreFile.exists() || truststoreFile.exists()) {
       cp.appendln(Color.black, "...found it [This is an EdgeServer installation]");
       // Delete the default files, just to avoid confusion
       File ks = new File(dir, "keystore.jks");
       File ts = new File(dir, "truststore.jks");
       boolean ksok = ks.delete();
       boolean tsok = ts.delete();
       if (ksok && tsok) cp.appendln(Color.black, "...Unused default SSL files were removed");
       else {
         if (!ksok) cp.appendln(Color.black, "...Unable to delete " + ks);
         if (!tsok) cp.appendln(Color.black, "...Unable to delete " + ts);
       }
     } else {
       cp.appendln(Color.black, "...not found [OK, this is a non-EdgeServer installation]");
       ssl.setAttribute("keystore", "keystore.jks");
       ssl.setAttribute("keystorePassword", "edge1234");
       ssl.setAttribute("truststore", "truststore.jks");
       ssl.setAttribute("truststorePassword", "edge1234");
       cp.appendln(
           Color.black, "...SSL attributes were updated for a non-EdgeServer installation");
     }
   }
 }
Esempio n. 12
0
  /*
   * Accepts a new request from the HTTP server and creates
   * a conventional execution environment for the request.
   * If the application was invoked as a FastCGI server,
   * the first call to FCGIaccept indicates that the application
   * has completed its initialization and is ready to accept
   * a request.  Subsequent calls to FCGI_accept indicate that
   * the application has completed its processing of the
   * current request and is ready to accept a new request.
   * If the application was invoked as a CGI program, the first
   * call to FCGIaccept is essentially a no-op and the second
   * call returns EOF (-1) as does an error. Application should exit.
   *
   * If the application was invoked as a FastCGI server,
   * and this is not the first call to this procedure,
   * FCGIaccept first flushes any buffered output to the HTTP server.
   *
   * On every call, FCGIaccept accepts the new request and
   * reads the FCGI_PARAMS stream into System.props. It also creates
   * streams that understand FastCGI protocol and take input from
   * the HTTP server send output and error output to the HTTP server,
   * and assigns these new streams to System.in, System.out and
   * System.err respectively.
   *
   * For now, we will just return an int to the caller, which is why
   * this method catches, but doen't throw Exceptions.
   *
   */
  public int FCGIaccept() {
    int acceptResult = 0;

    /*
     * If first call, mark it and if fcgi save original system properties,
     * If not first call, and  we are cgi, we should be gone.
     */
    if (!acceptCalled) {
      isFCGI = System.getenv("FCGI_PORT") != null;
      acceptCalled = true;
      if (isFCGI) {
        /*
         * save original system properties (nonrequest)
         * and get a server socket
         */
        startupProps = new Properties(System.getProperties());
        String str = new String(System.getenv("FCGI_PORT"));
        if (str.length() <= 0) {
          return -1;
        }
        int portNum = Integer.parseInt(str);

        try {
          srvSocket = new ServerSocket(portNum);
        } catch (IOException e) {
          if (request != null) {
            request.socket = null;
          }
          srvSocket = null;
          request = null;
          return -1;
        }
      }
    } else {
      if (!isFCGI) {
        return -1;
      }
    }
    /*
     * If we are cgi, just leave everything as is, otherwise set up env
     */
    if (isFCGI) {
      try {
        acceptResult = FCGIAccept();
      } catch (IOException e) {
        return -1;
      }
      if (acceptResult < 0) {
        return -1;
      }

      /*
       * redirect stdin, stdout and stderr to fcgi socket
       */
      System.setIn(new BufferedInputStream(request.inStream, 8192));
      System.setOut(new PrintStream(new BufferedOutputStream(request.outStream, 8192)));
      System.setErr(new PrintStream(new BufferedOutputStream(request.errStream, 512)));
      System.setProperties(request.params);
    }
    return 0;
  }
Esempio n. 13
0
 public static void main(String[] args) throws Exception {
   new Server(Integer.parseInt(args[0]), Utils.base64dec(System.getenv("AUTHKEY")));
 }
Esempio n. 14
0
 /** Return the current user desktop path. */
 public static String getWindowsCurrentUserDesktopPath() {
   return System.getenv("userprofile") + '/' + WINDOWS_DESKTOP;
 }
Esempio n. 15
0
  public JavaGame(String[] args) {
    this.args = args;
    updater = new Updater(this);
    highscore = new Highscore(this);
    eventHandler = new EventHandler(this);
    eventHandler.registerTestEvents();

    setTitle("Survive-JavaGame"); // Fenstertitel setzen
    setSize(1200, 900); // Fenstergröße einstellen
    addWindowListener(new WindowListener());
    setLocationRelativeTo(null);

    try {
      arg = args[0];
    } catch (ArrayIndexOutOfBoundsException e) {
      arg = "nothing";
    }
    if (arg.equals("fullscreen")) {
      setUndecorated(true); // "Vollbild"
      setSize(
          (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() - 200,
          (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth());
      setLocation(0, 0);
    }
    setVisible(true);
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

    try {
      /*URI Path = URLDecoder.decode(getClass().getClassLoader().getResource("texture").toURI();//, "UTF-8"); //Pfad zu den Resourcen
      File F = new File(Path);
      basePath = F;
      System.out.println(basePath);
      */
      File File = new File((System.getenv("APPDATA")));
      basePath = new File(File, "/texture");
      backgroundTexture = new File(basePath, "/hintergrund.jpg");
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    try {
      backgroundImage = ImageIO.read(backgroundTexture);
    } catch (IOException exeption) {

    }

    if (soundan) {
      currentVolume = 80;
    } // end of if

    dbImage = createImage(1920, 1080);
    // dbGraphics = dbImage.getGraphics();

    // Texturen Liste

    // Ebenen Liste

    ebenen[0][0] = 91;
    ebenen[0][1] = 991; // Main Ebene: Kann nicht durchschrittenwerden indem down gedrückt wird
    ebenen[0][2] = 563;

    ebenen[1][0] = 387; // x1
    ebenen[1][1] = 524; // x2
    ebenen[1][2] = 454; // y

    ebenen[2][0] = 525;
    ebenen[2][1] = 645;
    ebenen[2][2] = 350;

    ebenen[3][0] = 246;
    ebenen[3][1] = 365;
    ebenen[3][2] = 351;

    ebenen[4][0] = 760;
    ebenen[4][1] = 870;
    ebenen[4][2] = 294;

    ebenen[5][0] = 835;
    ebenen[5][1] = 969;
    ebenen[5][2] = 441;

    // Spieler

    // I'm in Space! SPACE!
    player[1] =
        new Player(
            (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]),
            0,
            false,
            67,
            100,
            texture[0],
            shottexture[0],
            KeyEvent.VK_A,
            KeyEvent.VK_D,
            KeyEvent.VK_W,
            KeyEvent.VK_S,
            KeyEvent.VK_Q,
            1,
            35,
            highscore.getName(1));
    player[2] =
        new Bot(
            (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]),
            0,
            false,
            67,
            100,
            texture[1],
            shottexture[1],
            KeyEvent.VK_J,
            KeyEvent.VK_L,
            KeyEvent.VK_I,
            KeyEvent.VK_K,
            KeyEvent.VK_U,
            2,
            35,
            highscore.getName(1));
    player[3] =
        new Bot(
            (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]),
            0,
            false,
            67,
            100,
            texture[2],
            shottexture[2],
            KeyEvent.VK_LEFT,
            KeyEvent.VK_RIGHT,
            KeyEvent.VK_UP,
            KeyEvent.VK_DOWN,
            KeyEvent.VK_ENTER,
            3,
            35,
            highscore.getName(1));

    player[1].laden(this);
    player[2].laden(this);
    player[3].laden(this);

    this.addKeyListener(player[1]);
    this.addKeyListener(player[2]);
    this.addKeyListener(player[3]);

    this.addKeyListener(this);

    int result;
    Object[] options = {"SinglePlayer", "MultiPlayer"};
    if (arg.equals("dedicated")) {
      Server server = new Server();
      this.server = true;
      setVisible(false);

    } else {
      if ((result =
              JOptionPane.showOptionDialog(
                  null,
                  "Treffen Sie eine Auswahl",
                  "Alternativen",
                  JOptionPane.DEFAULT_OPTION,
                  JOptionPane.INFORMATION_MESSAGE,
                  null,
                  options,
                  options[0]))
          == 1) {
        client = new Client(this);
        online = true;
        while ((onlinename =
                    JOptionPane.showInputDialog(
                        null,
                        "Geben Sie Ihren Namen ein",
                        "Eine Eingabeaufforderung",
                        JOptionPane.PLAIN_MESSAGE))
                .isEmpty()
            && onlinename != null) {}

        Object[] optionsmp = {"Host", "Client"};
        if ((result =
                JOptionPane.showOptionDialog(
                    null,
                    "Treffen Sie eine Auswahl",
                    "Alternativen",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.INFORMATION_MESSAGE,
                    null,
                    optionsmp,
                    optionsmp[0]))
            == 0) {
          Server server = new Server();
          this.server = true;
        } else if (online) {
          while ((serveradresse =
                      JOptionPane.showInputDialog(
                          null,
                          "Geben Sie die Serveradresse ein",
                          "Eine Eingabeaufforderung",
                          JOptionPane.PLAIN_MESSAGE))
                  .isEmpty()
              && serveradresse != null) {}
        }
      }
    }
    if (!arg.equals("dedicated")) {
      gamerunner = new GameRunner(player, this);
      DamageLogig = new damageLogig(gamerunner);
    }

    if (online) {
      try {
        client.initialise(serveradresse, 9876);
        client.start();
      } catch (SocketException e) {
        e.printStackTrace();
      } catch (UnknownHostException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  } // end of init
Esempio n. 16
0
/**
 * 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] =&gt;
   * 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());
  }
}