Example #1
1
  private void doInit() throws MqttException {
    String server = System.getProperty("knx2mqtt.mqtt.server", "tcp://localhost:1883");
    String clientID = System.getProperty("knx2mqtt.mqtt.clientid", "knx2mqtt");
    mqttc = new MqttClient(server, clientID, new MemoryPersistence());
    mqttc.setCallback(
        new MqttCallback() {
          @Override
          public void messageArrived(String topic, MqttMessage msg) throws Exception {
            try {
              processMessage(topic, msg);
            } catch (Exception e) {
              L.log(Level.WARNING, "Error when processing message " + msg + " for " + topic, e);
            }
          }

          @Override
          public void deliveryComplete(IMqttDeliveryToken token) {
            /* Intentionally ignored */
          }

          @Override
          public void connectionLost(Throwable t) {
            L.log(Level.WARNING, "Connection to MQTT broker lost", t);
            queueConnect();
          }
        });
    doConnect();
    Main.t.schedule(new StateChecker(), 30 * 1000, 30 * 1000);
  }
Example #2
0
  public TestInput(
      Iterable<? extends JavaFileObject> files, Iterable<String> processors, String[] options) {

    this.compiler = ToolProvider.getSystemJavaCompiler();
    this.fileManager = compiler.getStandardFileManager(null, null, null);

    this.files = files;
    this.processors = processors;
    this.options = new LinkedList<String>();

    String classpath = System.getProperty("tests.classpath", "tests" + File.separator + "build");
    String globalclasspath = System.getProperty("java.class.path", "");

    this.options.add("-Xmaxerrs");
    this.options.add("9999");
    this.options.add("-g");
    this.options.add("-d");
    this.options.add(OUTDIR);
    this.options.add("-classpath");
    this.options.add(
        "build"
            + File.pathSeparator
            + "junit.jar"
            + File.pathSeparator
            + classpath
            + File.pathSeparator
            + globalclasspath);
    this.options.addAll(Arrays.asList(options));
  }
  public static void main(String... args) throws Exception {
    jtreg = (System.getProperty("test.src") != null);
    File tmpDir;
    if (jtreg) {
      // use standard jtreg scratch directory: the current directory
      tmpDir = new File(System.getProperty("user.dir"));
    } else {
      tmpDir =
          new File(
              System.getProperty("java.io.tmpdir"),
              MessageInfo.class.getName()
                  + (new SimpleDateFormat("yyMMddHHmmss")).format(new Date()));
    }
    Example.setTempDir(tmpDir);
    Example.Compiler.factory = new ArgTypeCompilerFactory();

    MessageInfo mi = new MessageInfo();

    try {
      if (mi.run(args)) return;
    } finally {
      /* VERY IMPORTANT NOTE. In jtreg mode, tmpDir is set to the
       * jtreg scratch directory, which is the current directory.
       * In case someone is faking jtreg mode, make sure to only
       * clean tmpDir when it is reasonable to do so.
       */
      if (tmpDir.isDirectory() && tmpDir.getName().startsWith(MessageInfo.class.getName())) {
        if (clean(tmpDir)) tmpDir.delete();
      }
    }

    if (jtreg) throw new Exception(mi.errors + " errors occurred");
    else System.exit(1);
  }
  /**
   * A method that would simply send messages to a group of people so that they would get notified
   * that tests are being run.
   */
  public void testSendFunMessages() {
    String hostname = "";

    try {
      hostname = java.net.InetAddress.getLocalHost().getHostName() + ": ";
    } catch (UnknownHostException ex) {
    }

    String message =
        hostname
            + "Hello this is the SIP Communicator (version "
            + System.getProperty("sip-communicator.version")
            + ") build on: "
            + new Date().toString()
            + ". Have a very nice day!";

    String list = System.getProperty("accounts.reporting.ICQ_REPORT_LIST");

    logger.debug("Will send message " + message + " to: " + list);

    // if no property is specified - return
    if (list == null || list.trim().length() == 0) return;

    StringTokenizer tokenizer = new StringTokenizer(list, " ");

    while (tokenizer.hasMoreTokens()) {
      fixture.testerAgent.sendMessage(tokenizer.nextToken(), message);
    }
  }
Example #5
0
  private String parseLibrary(String keyword) throws IOException {
    checkDup(keyword);
    parseEquals();
    String lib = parseLine();
    lib = expand(lib);
    int i = lib.indexOf("/$ISA/");
    if (i != -1) {
      // replace "/$ISA/" with "/sparcv9/" on 64-bit Solaris SPARC
      // and with "/amd64/" on Solaris AMD64.
      // On all other platforms, just turn it into a "/"
      String osName = System.getProperty("os.name", "");
      String osArch = System.getProperty("os.arch", "");
      String prefix = lib.substring(0, i);
      String suffix = lib.substring(i + 5);
      if (osName.equals("SunOS") && osArch.equals("sparcv9")) {
        lib = prefix + "/sparcv9" + suffix;
      } else if (osName.equals("SunOS") && osArch.equals("amd64")) {
        lib = prefix + "/amd64" + suffix;
      } else {
        lib = prefix + suffix;
      }
    }
    debug(keyword + ": " + lib);

    // Check to see if full path is specified to prevent the DLL
    // preloading attack
    if (!(new File(lib)).isAbsolute()) {
      throw new ConfigurationException("Absolute path required for library value: " + lib);
    }
    return lib;
  }
Example #6
0
  /**
   * This method will read the standard input and save the content to a temporary. source file since
   * the source file will be parsed mutiple times. The HTML source file is parsed and checked for
   * Charset in HTML tags at first time, then source file is parsed again for the converting The
   * temporary file is read from standard input and saved in current directory and will be deleted
   * after the conversion has completed.
   *
   * @return the vector of the converted temporary source file name
   */
  public Vector getStandardInput() throws FileAccessException {
    byte[] buf = new byte[2048];
    int len = 0;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    File tempSourceFile;
    String tmpSourceName = ".tmpSource_stdin";

    File outFile = new File(tmpSourceName);

    tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName);
    if (!tempSourceFile.exists()) {
      try {
        fis = new FileInputStream(FileDescriptor.in);
        fos = new FileOutputStream(outFile);
        while ((len = fis.read(buf, 0, 2048)) != -1) fos.write(buf, 0, len);
      } catch (IOException e) {
        System.out.println(ResourceHandler.getMessage("plugin_converter.write_permission"));
        return null;
      }
    } else {
      throw new FileAccessException(ResourceHandler.getMessage("plugin_converter.overwrite"));
    }
    tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName);
    if (tempSourceFile.exists()) {
      fileSpecs.add(tmpSourceName);
      return fileSpecs;
    } else {
      throw new FileAccessException(
          ResourceHandler.getMessage("plugin_converter.write_permission"));
    }
  }
Example #7
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Example #8
0
  public static void main(String... args) throws Throwable {
    String testSrcDir = System.getProperty("test.src");
    String testClassDir = System.getProperty("test.classes");
    String self = T6361619.class.getName();

    JavacTool tool = JavacTool.create();

    final PrintWriter out = new PrintWriter(System.err, true);

    Iterable<String> flags =
        Arrays.asList(
            "-processorpath", testClassDir,
            "-processor", self,
            "-d", ".");
    DiagnosticListener<JavaFileObject> dl =
        new DiagnosticListener<JavaFileObject>() {
          public void report(Diagnostic<? extends JavaFileObject> m) {
            out.println(m);
          }
        };

    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrcDir, self + ".java")));

    JavacTask task = tool.getTask(out, fm, dl, flags, null, f);
    MyTaskListener tl = new MyTaskListener(task);
    task.setTaskListener(tl);

    // should complete, without exceptions
    task.call();
  }
    private static void configureTransportFactory(
        ITransportFactory transportFactory, LoaderOptions opts) {
      Map<String, String> options = new HashMap<>();
      // If the supplied factory supports the same set of options as our SSL impl, set those
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.TRUSTSTORE))
        options.put(SSLTransportFactory.TRUSTSTORE, opts.encOptions.truststore);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.TRUSTSTORE_PASSWORD))
        options.put(SSLTransportFactory.TRUSTSTORE_PASSWORD, opts.encOptions.truststore_password);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.PROTOCOL))
        options.put(SSLTransportFactory.PROTOCOL, opts.encOptions.protocol);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.CIPHER_SUITES))
        options.put(
            SSLTransportFactory.CIPHER_SUITES, Joiner.on(',').join(opts.encOptions.cipher_suites));

      if (transportFactory.supportedOptions().contains(SSLTransportFactory.KEYSTORE)
          && opts.encOptions.require_client_auth)
        options.put(SSLTransportFactory.KEYSTORE, opts.encOptions.keystore);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.KEYSTORE_PASSWORD)
          && opts.encOptions.require_client_auth)
        options.put(SSLTransportFactory.KEYSTORE_PASSWORD, opts.encOptions.keystore_password);

      // Now check if any of the factory's supported options are set as system properties
      for (String optionKey : transportFactory.supportedOptions())
        if (System.getProperty(optionKey) != null)
          options.put(optionKey, System.getProperty(optionKey));

      transportFactory.setOptions(options);
    }
Example #10
0
 static {
   if (Util.checkForWindows()) {
     TMPFILE_NAME = System.getProperty("java.io.tmpdir") + "\\" + "tmp.txt";
   } else {
     TMPFILE_NAME = System.getProperty("java.io.tmpdir") + "/" + "tmp.txt";
   }
 }
Example #11
0
 private ClassLoaderStrategy getClassLoaderStrategy(String fullyQualifiedClassName)
     throws Exception {
   try {
     // Get just the package name
     StringBuffer sb = new StringBuffer(fullyQualifiedClassName);
     sb.delete(sb.lastIndexOf("."), sb.length());
     currentPackage = sb.toString();
     // Retrieve the Java classpath from the system properties
     String cp = System.getProperty("java.class.path");
     String sepChar = System.getProperty("path.separator");
     String[] paths = StringUtils.pieceList(cp, sepChar.charAt(0));
     ClassLoaderStrategy cl =
         ClassLoaderUtil.getClassLoader(ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {});
     // Iterate through paths until class with the specified name is found
     String classpath = StringUtils.replaceChar(currentPackage, '.', File.separatorChar);
     for (int i = 0; i < paths.length; i++) {
       Class[] classes = cl.getClasses(paths[i] + File.separatorChar + classpath, currentPackage);
       for (int j = 0; j < classes.length; j++) {
         if (classes[j].getName().equals(fullyQualifiedClassName)) {
           return ClassLoaderUtil.getClassLoader(
               ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {paths[i]});
         }
       }
     }
     throw new Exception("Class could not be found.");
   } catch (Exception e) {
     System.err.println("Exception creating class loader strategy.");
     System.err.println(e.getMessage());
     throw e;
   }
 }
Example #12
0
  // Velocity init
  public static void initVelocity() {
    if (velocityCatch == null) {
      System.out.println("init VM");
      velocityCatch = new Object();

      Properties props = new Properties();
      props.setProperty("input.encoding", "UTF-8");
      props.setProperty("output.encoding", "UTF-8");

      if (getConfig().getChild("vmtemplatepath") != null) {
        props.setProperty("file.resource.loader.path", getConfig().getChildText("vmtemplatepath"));
      }
      if (System.getProperty("vmtemplatepath") != null) {
        props.setProperty("file.resource.loader.path", System.getProperty("vmtemplatepath"));
        // Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
        // System.getProperty("vmtemplatepath"));//oder new FIle()?
      }
      System.out.println("vmtemplatepath=" + props.getProperty("vmtemplatepath"));
      try {
        Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, VeloLog.getInstance());
        Velocity.init(props);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Example #14
0
  public static void testNSS(PKCS11Test test) throws Exception {
    if (!(new File(NSS_BASE)).exists()) return;

    String libdir = getNSSLibDir();
    if (libdir == null) {
      return;
    }

    if (loadNSPR(libdir) == false) {
      return;
    }

    String libfile = libdir + System.mapLibraryName("softokn3");

    String customDBdir = System.getProperty("CUSTOM_DB_DIR");
    String dbdir = (customDBdir != null) ? customDBdir : NSS_BASE + SEP + "db";
    // NSS always wants forward slashes for the config path
    dbdir = dbdir.replace('\\', '/');

    String customConfig = System.getProperty("CUSTOM_P11_CONFIG");
    String customConfigName = System.getProperty("CUSTOM_P11_CONFIG_NAME", "p11-nss.txt");
    String p11config = (customConfig != null) ? customConfig : NSS_BASE + SEP + customConfigName;

    System.setProperty("pkcs11test.nss.lib", libfile);
    System.setProperty("pkcs11test.nss.db", dbdir);
    Provider p = getSunPKCS11(p11config);
    test.premain(p);
  }
Example #15
0
  public WSAsync() {
    String proxyHost =
        Play.configuration.getProperty("http.proxyHost", System.getProperty("http.proxyHost"));
    String proxyPort =
        Play.configuration.getProperty("http.proxyPort", System.getProperty("http.proxyPort"));
    String proxyUser =
        Play.configuration.getProperty("http.proxyUser", System.getProperty("http.proxyUser"));
    String proxyPassword =
        Play.configuration.getProperty(
            "http.proxyPassword", System.getProperty("http.proxyPassword"));
    String userAgent = Play.configuration.getProperty("http.userAgent");

    Builder confBuilder = new AsyncHttpClientConfig.Builder();
    if (proxyHost != null) {
      int proxyPortInt = 0;
      try {
        proxyPortInt = Integer.parseInt(proxyPort);
      } catch (NumberFormatException e) {
        Logger.error(
            "Cannot parse the proxy port property '%s'. Check property http.proxyPort either in System configuration or in Play config file.",
            proxyPort);
        throw new IllegalStateException("WS proxy is misconfigured -- check the logs for details");
      }
      ProxyServer proxy = new ProxyServer(proxyHost, proxyPortInt, proxyUser, proxyPassword);
      confBuilder.setProxyServer(proxy);
    }
    if (userAgent != null) {
      confBuilder.setUserAgent(userAgent);
    }
    // when using raw urls, AHC does not encode the params in url.
    // this means we can/must encode it(with correct encoding) before passing it to AHC
    confBuilder.setUseRawUrl(true);
    httpClient = new AsyncHttpClient(confBuilder.build());
  }
Example #16
0
  /**
   * Execute the commnad and returns how many rows of commandEva the command had.
   *
   * <p>that : the environment where the command is called commandEva : the whole command Eva
   * indxCommandEva : index of commandEva where the commnad starts
   */
  public int execute(listix that, Eva commandEva, int indxComm) {
    listixCmdStruct cmd = new listixCmdStruct(that, commandEva, indxComm);

    String[] aa = cmd.getArgs(true);
    if (aa.length > 0) aa[0] = org.gastona.commonGastona.getGastConformFileName(aa[0]);

    String[] arrComanda = new String[aa.length + 4];
    arrComanda[0] = System.getProperty("java.home", "") + "/bin/java";
    arrComanda[1] = "-cp";
    arrComanda[2] = System.getProperty("java.class.path", ".");
    arrComanda[3] = "gastona.gastona";
    for (int ii = 0; ii < aa.length; ii++) arrComanda[4 + ii] = aa[ii];

    // copy parameters
    // java -cp classpath gastona.gastona script.gast pa1 pa2
    //

    cmd.getLog().dbg(2, "GAST", "passed parameters " + cmd.getArgSize());

    // for (int ii = 0; ii < arrComanda.length; ii ++)
    //    System.out.println (arrComanda[ii]);
    javaRun.launch(arrComanda);

    cmd.checkRemainingOptions(true);
    return 1;
  }
Example #17
0
  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);
  }
Example #18
0
  public void run(String[] args) {

    DatabaseFactory factory = new DatabaseFactory();
    if (System.getProperty("user.dir").isEmpty()) {
      System.out.println("user.dir is incorrect");
    }
    if (System.getProperty("fizteh.db.dir").isEmpty()) {
      System.out.println("fizteh.db.dir is incorrect");
    }

    Path pathDirection =
        Paths.get(System.getProperty("user.dir")).resolve(System.getProperty("fizteh.db.dir"));

    String dir = pathDirection.toString();

    DatabaseProvider dProvider = factory.create(dir);

    if (args.length == 0) {

      interactiveMode(dProvider);
    } else {

      pocketMode(args, dProvider);
    }
  }
  // Contructor that takes in the usernames of the users
  public ServerFileIO(String username1, String username2) throws IOException {
    // Sets the naming convention for the files
    // The convention is:
    // <Smaller Username><Larger Username>.txt

    user1 = username1;
    user2 = username2;

    if (username1.compareTo(username2) < 0)
      file =
          new File(
              System.getProperty("user.home")
                  + "\\Server Message Files\\"
                  + username1
                  + username2
                  + ".txt");
    else if (username1.compareTo(username2) > 0)
      file =
          new File(
              System.getProperty("user.home")
                  + "\\Server Message Files\\"
                  + username2
                  + username1
                  + ".txt");
    else {
      throw new IllegalArgumentException("Both usernames are the same");
    }

    file.getParentFile().mkdirs();
    file.createNewFile();

    output = new PrintWriter(new FileWriter(file, true));
    input = new Scanner(file);
  }
Example #20
0
  /**
   * Returns JPicEdt's install directory w/o trailing "/", provided the command line looks like :
   *
   * <p><code>java -classpath other-class-paths:jpicedt-install-dir/lib/jpicedt.jar jpicedt.JPicEdt
   * </code> (where <code>/</code> may be replaced by the actual respective separator for files on
   * the underlying platform).
   *
   * <p>For Windows platform, the install directory is tried to be detected 1st with the MSWindows
   * file-separator (<code>\</code>), and if this does not work, a subsequent trial is made with
   * <code>/</code>.
   *
   * <p>That is, the old way (java -jar jpicedt.jar) won't work. However, classpath can contain
   * relative pathname (then user.dir get prepended).
   *
   * <p>Code snippet was adapted from jEdit/JEdit.java (http://www.jedit.org).
   *
   * @return the value of the "user.dir" Java property if "lib/jpicedt.jar" wasn't found in the
   *     command line.
   */
  public static String getJPicEdtHome() {

    String classpath = System.getProperty("java.class.path"); // e.g.
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/lib/jpicedt.jar"
    // File.separator = "/" on Unix, "\\" on Windows,...
    String fileSeparator = File.separator;
    int index;
    // File.pathSeparator = ":" on Unix/MacOS-X platforms, ";" on Windows
    // search ":" backward starting from
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/^lib/jpicedt.jar"

    String homeDir = null;
    int trials = 2;
    do {
      index = classpath.toLowerCase().indexOf("lib" + fileSeparator + "jpicedt.jar");
      int start = classpath.lastIndexOf(File.pathSeparator, index);
      if (start == -1)
        start =
            0; // File.pathSeparator not found => lib/jpicedt.jar probably at beginning of classpath
      else start += File.pathSeparator.length(); // e.g. ":^/home..."

      if (index >= start) {
        homeDir = classpath.substring(start, index);
        if (homeDir.endsWith(fileSeparator)) homeDir = homeDir.substring(0, homeDir.length() - 1);
      }
      switch (trials) {
        case 2:
          if (File.pathSeparator.equals(";") && homeDir == null) {
            // MS-Windows case, this must work both with / and \
            trials = 1;
            fileSeparator = "/";
          } else trials = 0;
          break;
        case 1:
          if (homeDir != null && !fileSeparator.equals(File.separator)) {
            homeDir.replace(fileSeparator, File.separator);
          }
          trials = 0;
          break;

        default:
          trials = 0;
          break;
      }
    } while (trials != 0);

    if (homeDir != null) {
      if (homeDir.equals("")) homeDir = System.getProperty("user.dir");
      else if (!new File(homeDir).isAbsolute())
        homeDir = System.getProperty("user.dir") + File.separator + homeDir;
    } else {
      homeDir = System.getProperty("user.dir");
      if (homeDir.endsWith(
          "lib")) // this is the case if jpicedt run as "java -jar jpicedt.jar" from inside lib/ dir
      homeDir = homeDir.substring(0, homeDir.lastIndexOf("lib"));
    }

    // System.out.println("JPicEdt's home = " + homeDir);
    return homeDir;
  }
Example #21
0
  private static boolean validateArguments(Map<String, String> parsedArguments) {
    List<String> errorMessages = new ArrayList<String>();
    validatePortListArgument(parsedArguments, SERVER_PORT_KEY, errorMessages);
    validatePortArgument(parsedArguments, PROXY_PORT_KEY, errorMessages);
    validatePortArgument(parsedArguments, PROXY_REMOTE_PORT_KEY, errorMessages);
    validateHostnameArgument(parsedArguments, PROXY_REMOTE_HOST_KEY, errorMessages);

    if (!errorMessages.isEmpty()) {
      int maxLengthMessage = 0;
      for (String errorMessage : errorMessages) {
        if (errorMessage.length() > maxLengthMessage) {
          maxLengthMessage = errorMessage.length();
        }
      }
      outputPrintStream.println(
          System.getProperty("line.separator") + "   " + Strings.padEnd("", maxLengthMessage, '='));
      for (String errorMessage : errorMessages) {
        outputPrintStream.println("   " + errorMessage);
      }
      outputPrintStream.println(
          "   " + Strings.padEnd("", maxLengthMessage, '=') + System.getProperty("line.separator"));
      return false;
    }
    return true;
  }
Example #22
0
  private List<String> buildCommandLine(Set<File> classPaths) throws Exception {
    List<String> commandLine = new ArrayList<String>();
    commandLine.add(JavaEnvUtils.getJreExecutable("java"));

    StringBuilder sb = new StringBuilder();
    String pathSeparator = "";
    for (File cp : classPaths) {
      sb.append(pathSeparator);
      pathSeparator = System.getProperty("path.separator");
      sb.append(cp.getAbsolutePath());
    }
    commandLine.add("-classpath");
    commandLine.add(sb.toString());

    if ("true".equalsIgnoreCase(System.getProperty("mps.make.debug"))) {
      commandLine.add("-Xdebug");
      commandLine.add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006");
    } else if ("true".equalsIgnoreCase(System.getProperty("mps.make.profile"))) {
      commandLine.add(
          "-agentpath:/Applications/YourKit_Java_Profiler_10.0.5.app/bin/mac/libyjpagent.jnilib=onexit=snapshot,sampling,disableall");
    }

    commandLine.add(AntBootstrap.class.getCanonicalName());
    commandLine.add(getWorkerClass().getCanonicalName());

    try {
      File cfgFile = myMakeConfiguration.dumpToFile();
      commandLine.add(cfgFile.getAbsolutePath());
    } catch (FileNotFoundException e) {
      LOG.error("Unable to write configuration", e);
      throw new Exception(e);
    }
    return commandLine;
  }
Example #23
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("      val l");
   sb.append(rAlternative());
   sb.append(" = new N");
   sb.append(rAlternative());
   sb.append("(");
   {
     boolean first = true;
     for (Object oNormalParameter_EndParameter : this.eNormalParameter_EndParameter) {
       if (first) {
         first = false;
       } else {
         sb.append(", ");
       }
       sb.append(oNormalParameter_EndParameter.toString());
     }
   }
   sb.append(")");
   sb.append(System.getProperty("line.separator"));
   sb.append("      stack.push(l");
   sb.append(rAlternative());
   sb.append(", stack.state.target(l");
   sb.append(rAlternative());
   sb.append("))");
   sb.append(System.getProperty("line.separator"));
   sb.append("      return null");
   sb.append(System.getProperty("line.separator"));
   return sb.toString();
 }
Example #24
0
 public String getInfo() {
   return version()
       + System.getProperty("os.name")
       + " "
       + System.getProperty("os.version")
       + "; "
       + IJ.freeMemory();
 }
Example #25
0
 public static String getSystemTempDir() {
     String tmp = System.getProperty("java.io.tmpdir");
     String sep = System.getProperty("file.separator");
     if (tmp.endsWith(sep)) {
         return tmp;
     }
     return tmp + sep;
 }
Example #26
0
 public static String dataDirectory() {
   String OS = System.getProperty("os.name").toUpperCase();
   if (OS.contains("WIN")) return System.getenv("APPDATA");
   else if (OS.contains("MAC"))
     return System.getProperty("user.home") + "/Library/Application " + "Support";
   else if (OS.contains("NUX")) return System.getProperty("user.home");
   return System.getProperty("user.dir");
 }
Example #27
0
 private void addCreatedBy(Manifest m) {
   Attributes global = m.getMainAttributes();
   if (global.getValue(new Attributes.Name("Created-By")) == null) {
     String javaVendor = System.getProperty("java.vendor");
     String jdkVersion = System.getProperty("java.version");
     global.put(new Attributes.Name("Created-By"), jdkVersion + " (" + javaVendor + ")");
   }
 }
Example #28
0
 public String lookupEnvironmentForCommand() {
   String fallbackEnv =
       System.getProperty(Environment.KEY) != null
           ? System.getProperty(Environment.KEY)
           : Environment.DEVELOPMENT.getName();
   String env = CommandLineParser.DEFAULT_ENVS.get(commandName);
   return env == null ? fallbackEnv : env;
 }
Example #29
0
  protected static void initSystemProperties(MoquiStart cl, boolean useProperties)
      throws IOException {
    Properties moquiInitProperties = new Properties();
    URL initProps = cl.getResource("MoquiInit.properties");
    if (initProps != null) {
      InputStream is = initProps.openStream();
      moquiInitProperties.load(is);
      is.close();
    }

    // before doing anything else make sure the moqui.runtime system property exists (needed for
    // config of various things)
    String runtimePath = System.getProperty("moqui.runtime");
    if (runtimePath != null && runtimePath.length() > 0)
      System.out.println("Determined runtime from system property: " + runtimePath);
    if (useProperties && (runtimePath == null || runtimePath.length() == 0)) {
      runtimePath = moquiInitProperties.getProperty("moqui.runtime");
      if (runtimePath != null && runtimePath.length() > 0)
        System.out.println("Determined runtime from MoquiInit.properties file: " + runtimePath);
    }
    if (runtimePath == null || runtimePath.length() == 0) {
      // see if runtime directory under the current directory exists, if not default to the current
      // directory
      File testFile = new File("runtime");
      if (testFile.exists()) runtimePath = "runtime";
      if (runtimePath != null && runtimePath.length() > 0)
        System.out.println("Determined runtime from existing runtime directory: " + runtimePath);
    }
    if (runtimePath == null || runtimePath.length() == 0) {
      runtimePath = ".";
      System.out.println("Determined runtime by defaulting to current directory: " + runtimePath);
    }
    File runtimeFile = new File(runtimePath);
    runtimePath = runtimeFile.getCanonicalPath();
    System.out.println("Canonicalized runtimePath: " + runtimePath);
    if (runtimePath.endsWith("/")) runtimePath = runtimePath.substring(0, runtimePath.length() - 1);
    System.setProperty("moqui.runtime", runtimePath);

    /* Don't do this here... loads as lower-level that WEB-INF/lib jars and so can't have dependencies on those,
        and dependencies on those are necessary
    // add runtime/lib jar files to the class loader
    File runtimeLibFile = new File(runtimePath + "/lib");
    for (File jarFile: runtimeLibFile.listFiles()) {
        if (jarFile.getName().endsWith(".jar")) cl.jarFileList.add(new JarFile(jarFile));
    }
    */

    // moqui.conf=conf/development/MoquiDevConf.xml
    String confPath = System.getProperty("moqui.conf");
    if (confPath == null || confPath.length() == 0) {
      confPath = moquiInitProperties.getProperty("moqui.conf");
    }
    if (confPath == null || confPath.length() == 0) {
      File testFile = new File(runtimePath + "/" + defaultConf);
      if (testFile.exists()) confPath = defaultConf;
    }
    if (confPath != null) System.setProperty("moqui.conf", confPath);
  }
 public float getFloat(String envName, String propertyName, float defaultValue) {
   if (System.getenv(envName) != null) {
     return Float.parseFloat(System.getenv(envName));
   }
   if (System.getProperty(propertyName) != null) {
     return Float.parseFloat(System.getProperty(propertyName));
   }
   return getFloatValue(propertyName, defaultValue);
 }