public synchronized void saveProperties() {
   if (ownLock()) {
     try {
       FileOutputStream out = new FileOutputStream(propertyFile);
       try {
         fontProps.store(out, "-- ICEpf Font properties --");
       } finally {
         out.close();
       }
       recordMofifTime();
     } catch (IOException ex) {
       // check to make sure the storage relate dialogs can be shown
       if (getBoolean("application.showLocalStorageDialogs", true)) {
         Resources.showMessageDialog(
             null,
             JOptionPane.ERROR_MESSAGE,
             messageBundle,
             "fontManager.properties.title",
             "manager.properties.saveError",
             ex);
       }
       // log the error
       if (logger.isLoggable(Level.WARNING)) {
         logger.log(Level.WARNING, "Error saving font properties cache", ex);
       }
     }
   }
 }
 public static void save(Properties properties, File file) throws IOException {
   Assert.notNull(properties, "存储的属性为空!");
   OutputStream outputStream = new FileOutputStream(file);
   properties.store(outputStream, "saved on " + DateHelper.getStringDate());
   outputStream.flush();
   outputStream.close();
 }
  public SaikuDatasource addDatasource(SaikuDatasource datasource) {
    try {
      String uri = repoURL.toURI().toString();
      if (uri != null && datasource != null) {
        uri += datasource.getName().replace(" ", "_");
        File dsFile = new File(new URI(uri));
        if (dsFile.exists()) {
          dsFile.delete();
        } else {
          dsFile.createNewFile();
        }
        FileWriter fw = new FileWriter(dsFile);
        Properties props = datasource.getProperties();
        props.store(fw, null);
        fw.close();
        datasources.put(datasource.getName(), datasource);
        return datasource;

      } else {
        throw new SaikuServiceException(
            "Cannot save datasource because uri or datasource is null uri(" + (uri == null) + ")");
      }
    } catch (Exception e) {
      throw new SaikuServiceException("Error saving datasource", e);
    }
  }
  private synchronized void save() {
    myDir.mkdirs();

    Properties props = new Properties();

    props.setProperty(KIND_KEY, myKind.toString());
    props.setProperty(ID_KEY, myRepositoryId);
    props.setProperty(PATH_OR_URL_KEY, myRepositoryPathOrUrl);
    props.setProperty(INDEX_VERSION_KEY, CURRENT_VERSION);
    if (myUpdateTimestamp != null)
      props.setProperty(TIMESTAMP_KEY, String.valueOf(myUpdateTimestamp));
    if (myDataDirName != null) props.setProperty(DATA_DIR_NAME_KEY, myDataDirName);
    if (myFailureMessage != null) props.setProperty(FAILURE_MESSAGE_KEY, myFailureMessage);

    try {
      FileOutputStream s = new FileOutputStream(new File(myDir, INDEX_INFO_FILE));
      try {
        props.store(s, null);
      } finally {
        s.close();
      }
    } catch (IOException e) {
      MavenLog.LOG.warn(e);
    }
  }
Example #5
0
 /**
  * Method used to save the configuration in a specific file
  *
  * @param propertiesFile configuration file
  */
 public static void store(String propertiesFile) {
   try {
     FileOutputStream cfgOutStream = new FileOutputStream(propertiesFile);
     prop.store(cfgOutStream, "jim configuration file");
   } catch (Exception e) {
     logger.error("error opening propertiesFile: " + propertiesFile, e);
   }
 }
Example #6
0
 private void shellWidgetDisposed(DisposeEvent evt) {
   try {
     // Save app settings to file
     appSettings.store(new FileOutputStream("appsettings.ini"), "");
   } catch (FileNotFoundException e) {
   } catch (IOException e) {
   }
 }
Example #7
0
 private void exitMenuItemWidgetSelected(SelectionEvent evt) {
   try {
     // Save app settings to file
     appSettings.store(new FileOutputStream("appsettings.ini"), "");
   } catch (FileNotFoundException e) {
   } catch (IOException e) {
   }
   getShell().dispose();
   System.exit(1);
 }
 private void saveUserSettingsMap(String username, Map userMap) {
   File userFile = new File(users, username + "_settings.properties");
   Properties props = (Properties) userMap;
   try {
     props.store(new FileOutputStream(userFile), null);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #9
0
 public void save(ActionEvent e) {
   if (file == null) {
     saveAs(e);
   }
   try {
     OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
     wordList.store(out, "Generated by JWordPlay");
     out.flush();
     out.close();
   } catch (IOException ex) {
     handleException(ex);
   }
 }
Example #10
0
  public void save() {
    final Properties properties = new Properties();
    Optional.ofNullable(username).ifPresent(s -> properties.setProperty("username", s));
    Optional.ofNullable(password).ifPresent(s -> properties.setProperty("password", s));
    Optional.ofNullable(from)
        .ifPresent(d -> properties.setProperty("from", d.format(DateTimeFormatter.ISO_DATE)));

    try {
      properties.store(getConfigurationWriter(), null);
    } catch (IOException e) {
      e.printStackTrace(); // TODO logging
    }
  }
Example #11
0
 public void writeProperties(Map<?, ?> properties) {
   Properties props = new Properties();
   props.putAll(properties);
   try {
     FileOutputStream stream = new FileOutputStream(this);
     try {
       props.store(stream, "comment");
     } finally {
       stream.close();
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Example #12
0
  /**
   * Generate an ant script that can be run to generate final p2 metadata for a product. Returns
   * null if p2 bundles aren't available.
   *
   * <p>If no product file is given, the generated p2 call generates final metadata for a
   * ${p2.root.name}_${p2.root.version} IU.
   *
   * <p>versionAdvice is a properties file with bsn=3.2.1.xyz entries
   *
   * @param workingDir - the directory in which to generate the script
   * @param productFileLocation - the location of a .product file (can be null)
   * @param versionAdvice - version advice (can be null)
   * @return The location of the generated script, or null
   * @throws CoreException
   */
  public static String generateP2ProductScript(
      String workingDir, String productFileLocation, Properties versionAdvice)
      throws CoreException {
    if (!loadP2Class()) return null;

    File working = new File(workingDir);
    working.mkdirs();

    File adviceFile = null;
    if (versionAdvice != null) {
      adviceFile = new File(working, "versionAdvice.properties"); // $NON-NLS-1$
      try {
        OutputStream os = new BufferedOutputStream(new FileOutputStream(adviceFile));
        try {
          versionAdvice.store(os, null);
        } finally {
          os.close();
        }
      } catch (IOException e) {
        String message = NLS.bind(Messages.exception_writingFile, adviceFile.toString());
        throw new CoreException(
            new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_FILE, message, e));
      }
    }

    AntScript p2Script = null;
    try {
      p2Script = newAntScript(workingDir, "p2product.xml"); // $NON-NLS-1$
      p2Script.printProjectDeclaration(
          "P2 Product IU Generation", "main", "."); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      p2Script.println();
      p2Script.printProperty(PROPERTY_P2_APPEND, "true"); // $NON-NLS-1$
      p2Script.printProperty(PROPERTY_P2_COMPRESS, "false"); // $NON-NLS-1$
      p2Script.printProperty(PROPERTY_P2_METADATA_REPO_NAME, ""); // $NON-NLS-1$
      p2Script.printProperty(PROPERTY_P2_ARTIFACT_REPO_NAME, ""); // $NON-NLS-1$
      p2Script.printTargetDeclaration(
          "main",
          null,
          TARGET_P2_METADATA,
          null,
          "Generate the final Product IU"); //$NON-NLS-1$//$NON-NLS-2$
      generateP2FinalCall(
          p2Script, productFileLocation, adviceFile != null ? adviceFile.getAbsolutePath() : null);
      p2Script.printTargetEnd();
      p2Script.printProjectEnd();
    } finally {
      if (p2Script != null) p2Script.close();
    }
    return workingDir + "/p2product.xml"; // $NON-NLS-1$
  }
 public static void main(String[] args) throws Exception {
   Properties props = new Properties();
   // 向Properties中增加属性
   props.setProperty("username", "yeeku");
   props.setProperty("password", "123456");
   // 将Properties中的属性保存到a.ini文件中
   props.store(new FileOutputStream("a.ini"), "comment line");
   // 新建一个Properties对象
   Properties props2 = new Properties();
   // 向Properties中增加属性
   props2.setProperty("gender", "male");
   // 将a.ini文件中的属性名-属性值追加到props2中
   props2.load(new FileInputStream("a.ini"));
   System.out.println(props2);
 }
  private static File dumpModulesPaths(@NotNull Project project) throws IOException {
    ApplicationManager.getApplication().assertReadAccessAllowed();

    Properties res = new Properties();

    MavenProjectsManager manager = MavenProjectsManager.getInstance(project);

    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (manager.isMavenizedModule(module)) {
        MavenProject mavenProject = manager.findProject(module);
        if (mavenProject != null && !manager.isIgnored(mavenProject)) {
          res.setProperty(
              mavenProject.getMavenId().getGroupId()
                  + ':'
                  + mavenProject.getMavenId().getArtifactId()
                  + ":pom"
                  + ':'
                  + mavenProject.getMavenId().getVersion(),
              mavenProject.getFile().getPath());

          res.setProperty(
              mavenProject.getMavenId().getGroupId()
                  + ':'
                  + mavenProject.getMavenId().getArtifactId()
                  + ':'
                  + mavenProject.getPackaging()
                  + ':'
                  + mavenProject.getMavenId().getVersion(),
              mavenProject.getOutputDirectory());
        }
      }
    }

    File file =
        new File(
            PathManager.getSystemPath(),
            "Maven/idea-projects-state-" + project.getLocationHash() + ".properties");
    file.getParentFile().mkdirs();

    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    try {
      res.store(out, null);
    } finally {
      out.close();
    }

    return file;
  }
 /**
  * saves the parameters to a file so that they can be used again next time the application starts.
  */
 private void saveParametersToFile() {
   try {
     synchronized (savedOptionsFile) {
       if (savedOptionsFile.exists()) {
         savedOptionsFile.delete();
       }
       savedOptionsFile.createNewFile();
       FileOutputStream fos = new FileOutputStream(savedOptionsFile);
       parameters.store(fos, "Denny's DVDs configuration");
       fos.close();
     }
   } catch (IOException e) {
     ApplicationRunner.handleException(
         "Unable to save user parameters to file. "
             + "They wont be remembered next time you start.");
   }
 }
Example #16
0
 public void saveUpdateProperties(Properties updateProperties) {
   File propertiesDirectory;
   propertiesDirectory = new File(System.getProperty("user.home"), PROPERTIES_DIRECTORY_NAME);
   if (!propertiesDirectory.exists()) {
     propertiesDirectory.mkdir();
   }
   BufferedOutputStream outStream = null;
   try {
     outStream =
         new BufferedOutputStream(
             new FileOutputStream(
                 new File(propertiesDirectory, getProperty("checkUpdate.fileName"))));
     updateProperties.store(outStream, "Tangara update properties");
   } catch (Exception ex) {
     LOG.error("Failed to write lastlaunch property", ex);
   } finally {
     IOUtils.closeQuietly(outStream);
   }
 }
 /*
  * Create a link file in the links folder. Point it to the given extension location.
  */
 public void createLinkFile(String message, String filename, String extensionLocation) {
   File file = new File(output, getRootFolder() + "links/" + filename + ".link");
   file.getParentFile().mkdirs();
   Properties properties = new Properties();
   properties.put("path", extensionLocation);
   OutputStream stream = null;
   try {
     stream = new BufferedOutputStream(new FileOutputStream(file));
     properties.store(stream, null);
   } catch (IOException e) {
     fail(message, e);
   } finally {
     try {
       if (stream != null) stream.close();
     } catch (IOException e) {
       // ignore
     }
   }
 }
 static void saveAuIdProperties(String location, Properties props) {
   // XXX these AU_ID_FILE entries need to be backed up elsewhere to avoid
   // single-point corruption
   File propDir = new File(location);
   if (!propDir.exists()) {
     logger.debug("Creating directory '" + propDir.getAbsolutePath() + "'");
     propDir.mkdirs();
   }
   File propFile = new File(propDir, AU_ID_FILE);
   try {
     logger.debug3("Saving au id properties at '" + location + "'.");
     OutputStream os = new BufferedOutputStream(new FileOutputStream(propFile));
     props.store(os, "ArchivalUnit id info");
     os.close();
     propFile.setReadOnly();
   } catch (IOException ioe) {
     logger.error("Couldn't write properties for " + propFile.getPath() + ".", ioe);
     throw new LockssRepository.RepositoryStateException("Couldn't write au id properties file.");
   }
 }
Example #19
0
  private void speichern(Path saveName) {
    Properties prop = new Properties();

    if (!quellListModel.isEmpty())
      for (int i = 0; i < quellListModel.getSize(); i++)
        prop.setProperty(
            String.format("quellMenu%d", i),
            quellListModel.getElementAt(i).getValueMember().toString());

    if (!zielListModel.isEmpty())
      for (int i = 0; i < zielListModel.getSize(); i++)
        prop.setProperty(
            String.format("zielMenu%d", i),
            zielListModel.getElementAt(i).getValueMember().toString());

    try {
      FileOutputStream out = new FileOutputStream(saveName.toString());
      prop.store(out, null);
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void save(File f) {
    Properties save = new Properties();
    OutputStream output = null;

    try {
      save.setProperty("provider", selectProviderCb.getValue());
      save.setProperty("grain", selectGrainCb.getValue());
      save.setProperty("weight", weightTf.getText());
      save.setProperty("info", infoTa.getText());

      for (Entry<String, TextField> entry : propertiesTf.entrySet()) {
        TextField tf = entry.getValue();
        String propertyName = entry.getKey();

        save.setProperty(propertyName, tf.getText());
        if (tf.isDisable()) {
          save.setProperty(propertyName + "_ENABLED", "OFF");
        } else {
          save.setProperty(propertyName + "_ENABLED", "ON");
        }
      }

      output = new FileOutputStream(f);
      save.store(output, null);
      mainStage.setTitle(f.getName());
    } catch (Exception ex) {
      infoTa.setText("Не могу сохранить в файл");
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  private void rememberSharedBundlesInfoTimestamp(URI installArea, File outputFolder) {
    if (installArea == null) return;

    File sharedBundlesInfo = new File(URIUtil.append(installArea, SHARED_BUNDLES_INFO));
    if (!sharedBundlesInfo.exists()) return;

    Properties timestampToPersist = new Properties();
    timestampToPersist.put(
        SimpleConfiguratorImpl.KEY_BUNDLESINFO_TIMESTAMP,
        Long.toString(sharedBundlesInfo.lastModified()));
    OutputStream os = null;
    try {
      try {
        File outputFile =
            new File(outputFolder, SimpleConfiguratorImpl.BASE_TIMESTAMP_FILE_BUNDLESINFO);
        os = new BufferedOutputStream(new FileOutputStream(outputFile));
        timestampToPersist.store(os, "Written by " + this.getClass()); // $NON-NLS-1$
      } finally {
        if (os != null) os.close();
      }
    } catch (IOException e) {
      return;
    }
  }
  public void generateResourceBundle(String baseName, Path bundleDir)
      throws GenerationException, IOException {
    HashMap<String, Properties> bundles = generateResourceBundle(baseName);

    for (String bKey : bundles.keySet()) {
      final Properties bundle = bundles.get(bKey);

      final Path file = bundleDir.resolve(bKey + ".properties");
      try (Writer w = Files.newBufferedWriter(file, Charset.forName("utf8"))) {
        bundle.store(
            w,
            String.format(
                "ResourceBundle (%s) for %s, generated by %s v%s",
                bKey,
                baseName,
                "com.github.tkurz.sesame:vocab-builder",
                MavenUtil.loadVersion(
                    "com.github.tkurz.sesame", "vocab-builder", "0.0.0-DEVELOP")));
      } catch (IOException e) {
        log.error("Could not write Bundle {} to {}: {}", bKey, file, e);
        throw e;
      }
    }
  }
Example #23
0
  public void CrawlRT(String RTPage) throws IOException {
    ArrayList<String> t = new ArrayList<String>();
    String crawlData;
    String crawlData2;
    String crawlData3;

    FileReader freader = new FileReader("Crawl.txt");
    BufferedReader br = new BufferedReader(freader);
    FileReader freader2 = new FileReader("Tocrawl.txt");
    BufferedReader br2 = new BufferedReader(freader2);
    FileWriter fwriter2 = new FileWriter("Tocrawl.txt", true);
    BufferedWriter bw2 = new BufferedWriter(fwriter2);
    FileWriter fwriter = new FileWriter("Crawl.txt", true);
    BufferedWriter bw = new BufferedWriter(fwriter);

    /*while(null != (crawlData2 = br.readLine()))
    {
    	if(crawlData2 !=null)
    		Crawl.add(crawlData2);
    }
    t = collectLinks(RTPage);
    Iterator<String> e3= t.iterator();
    while(e3.hasNext())
    {
    	String ee = e3.next();

    		if(!Crawl.contains(ee))
    		{
    			bw2.write(ee+"\r\n");
    		}



    }
    br.close();
    br2.close();
    bw.close();
    bw2.close();*/

    if (null == (crawlData = br.readLine()))
    // if(true)
    {
      // initial iteration
      bw.write(RTPage + "\r\n");
      Crawl.add(RTPage);
      t = collectLinks(RTPage);
      ToCrawl.addAll(t);
    } else {
      // collect data from files and load to array lists
      while (null != (crawlData2 = br.readLine())) {
        if (crawlData2 != null) Crawl.add(crawlData2);
      }

      while (null != (crawlData3 = br2.readLine())) {
        if (crawlData3 != null) ToCrawl.add(crawlData3);
      }
    }
    System.out.println("Crawlled");

    // Number of movies to be crawled
    for (int i = 0; i < 1000; i++) {
      if (ToCrawl.size() > 0) {
        Crawl.removeAll(Collections.singleton(null));
        ToCrawl.removeAll(Collections.singleton(null));
        String c = ToCrawl.get(0);
        if (Crawl.contains(c)) ToCrawl.remove(c);
        else {
          // collect links and collect data from a particular link
          Crawl.add(c);
          t = collectLinks(c);
          CollectData(c);
          ToCrawl.remove(c);
          Iterator<String> e3 = t.iterator();
          while (e3.hasNext()) {
            String ee = e3.next();
            if (!ToCrawl.contains(ee)) {
              if (!Crawl.contains(ee)) {
                ToCrawl.add(ee);
              }
            }
          }
          bw.write(c + "\r\n");
        }
      }
    }

    System.out.println("To Be Crawlled");
    Iterator<String> e2 = ToCrawl.iterator();
    while (e2.hasNext()) {
      // write to file the movies still to be crawled.
      bw2.write(e2.next() + "\r\n");
    }

    prop.setProperty("Id", Integer.toString(n));
    prop.store(new FileOutputStream("config.properties"), null);
    br.close();
    br2.close();
    bw.close();
    bw2.close();
  }
Example #24
0
  public static void main(String[] args) throws Exception {
    boolean isInteractive = false;
    classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString();
    isJar = (classUrl.indexOf("jar") == 0);
    if (!isJar) {
      System.err.println("Installer can only be run from inside a Myna distribution war file");
      System.exit(1);
    }

    Thread.sleep(1000);

    Console console = System.console();
    String response = null;
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption(
        "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx);
    options.addOption("h", "help", false, "Displays help.");
    options.addOption(
        "w",
        "webroot",
        true,
        "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot);
    options.addOption(
        "l",
        "logfile",
        true,
        "Log file to use. Will be created if it does not exist. Default: ./<context>.log");
    options.addOption(
        "s",
        "servername",
        true,
        "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined");
    // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc.
    // Defaults to DEV" );

    options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port);
    options.addOption(
        "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0");

    options.addOption(
        "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore");
    options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass);
    options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias);

    modeOptions.add("upgrade");
    modeOptions.add("install");
    options.addOption(
        "m",
        "mode",
        true,
        "Mode: one of "
            + modeOptions.toString()
            + ". \n"
            + "\"upgrade\": Upgrades myna installation in webroot and exits. "
            + "\"install\": Unpacks to webroot, and installs startup files");
    options.addOption(
        "u",
        "user",
        true,
        "User to own and run the Myna installation. Only applies to unix installs. Default: nobody");

    HelpFormatter formatter = new HelpFormatter();

    String cmdSyntax = "java -jar myna-X.war -m <mode> [options]";
    try {
      CommandLine line = parser.parse(options, args);
      Option option;
      if (args.length == 0) {
        formatter.printHelp(cmdSyntax, options);
        response = console.readLine("\nContinue with Interactive Install? (y/N)");
        if (response.toLowerCase().equals("y")) {
          isInteractive = true;

        } else System.exit(1);
      }
      // Help
      if (line.hasOption("help")) {
        formatter.printHelp(cmdSyntax, options);
        System.exit(1);
      }
      // mode
      if (line.hasOption("mode")) {
        mode = line.getOptionValue("mode");
        if (!modeOptions.contains(mode)) {
          System.err.println(
              "Invalid Arguments.  Reason: Mode must be in " + modeOptions.toString());
          formatter.printHelp(cmdSyntax, options);
          System.exit(1);
        }
      } else if (isInteractive) {
        option = options.getOption("mode");
        console.printf("\n" + option.getDescription());

        do {
          response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): ");
          if (!response.isEmpty()) mode = response;
        } while (!modeOptions.contains(mode));
      }
      // webroot
      if (line.hasOption("webroot")) {
        webroot = line.getOptionValue("webroot");
      } else if (isInteractive) {
        option = options.getOption("webroot");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): ");
        if (!response.isEmpty()) webroot = response;
      }
      // port
      if (line.hasOption("port")) {
        port = Integer.parseInt(line.getOptionValue("port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): ");
        if (!response.isEmpty()) port = Integer.parseInt(response);
      }
      // context
      if (line.hasOption("context")) {
        webctx = line.getOptionValue("context");

      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("context");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): ");
        if (!response.isEmpty()) webctx = response;
      }
      if (!webctx.startsWith("/")) {
        webctx = "/" + webctx;
      }
      // servername (depends on context)
      if (!webctx.equals("/")) {
        serverName = webctx.substring(1);
      }
      if (line.hasOption("servername")) {
        serverName = line.getOptionValue("servername");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("servername");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): ");
        if (!response.isEmpty()) serverName = response;
      }
      // user
      if (line.hasOption("user")) {
        user = line.getOptionValue("user");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("user");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): ");
        if (!response.isEmpty()) user = response;
      }
      // logfile
      logFile = "myna.log";
      if (!webctx.equals("/")) {
        logFile = webctx.substring(1) + ".log";
      }
      if (line.hasOption("logfile")) {
        logFile = line.getOptionValue("logfile");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("logfile");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): ");
        if (!response.isEmpty()) logFile = response;
      }

      // ssl-port
      if (line.hasOption("ssl-port")) {
        sslPort = Integer.parseInt(line.getOptionValue("ssl-port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ssl-port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): ");
        if (!response.isEmpty()) sslPort = Integer.parseInt(response);
      }
      // ks-pass
      if (line.hasOption("ks-pass")) {
        ksPass = line.getOptionValue("ks-pass");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-pass");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): ");
        if (!response.isEmpty()) ksPass = response;
      }
      // ks-alias
      if (line.hasOption("ks-alias")) {
        ksAlias = line.getOptionValue("ks-alias");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-alias");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): ");
        if (!response.isEmpty()) ksAlias = response;
      }
      // keystore
      String appBase = new File(webroot).getCanonicalPath();
      if (keystore == null) {
        keystore = appBase + "/WEB-INF/myna/myna_keystore";
      }
      if (line.hasOption("keystore")) {
        keystore = line.getOptionValue("keystore");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("keystore");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): ");
        if (!response.isEmpty()) keystore = response;
      }

      javaOpts = line.getArgList();
    } catch (ParseException exp) {
      System.err.println("Invalid Arguments.	Reason: " + exp.getMessage());

      formatter.printHelp(cmdSyntax, options);
      System.exit(1);
    }

    if (isInteractive) {
      System.out.println("\nProceeed with the following settings?:\n");
      System.out.println("mode        = " + mode);
      System.out.println("webroot     = " + webroot);
      if (mode.equals("install")) {
        System.out.println("port        = " + port);
        System.out.println("context     = " + webctx);
        System.out.println("servername  = " + serverName);
        System.out.println("user        = "******"logfile     = " + logFile);
        System.out.println("ssl-port    = " + sslPort);
        System.out.println("ks-pass     = "******"ks-alias    = " + ksAlias);
        System.out.println("keystore    = " + keystore);
      }
      response = console.readLine("Continue? (Y/n)");
      if (response.toLowerCase().equals("n")) System.exit(1);
    }
    File wrFile = new File(webroot);
    webroot = wrFile.toString();
    if (mode.equals("install")) {
      adminPassword = console.readLine("\nCreate an Admin password for this installation: ");
    }
    // unpack myna if necessary
    if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) {
      upgrade(wrFile);
    }

    if (mode.equals("install")) {
      File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties"));
      FileInputStream propertiesFileIS = new FileInputStream(propertiesFile);
      Properties generalProperties = new Properties();
      generalProperties.load(propertiesFileIS);
      propertiesFileIS.close();
      if (!adminPassword.isEmpty()) {
        org.jasypt.util.password.StrongPasswordEncryptor cryptTool =
            new org.jasypt.util.password.StrongPasswordEncryptor();
        generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword));
      }
      generalProperties.setProperty("instance_id", serverName);

      generalProperties.store(
          new java.io.FileOutputStream(propertiesFile), "Myna General Properties");

      String javaHome = System.getProperty("java.home");
      webroot = new File(webroot).getCanonicalPath();
      if (serverName.length() == 0) serverName = "myna";
      if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(
                wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd"));

        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName))
                .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot))
                .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile))
                .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome))
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore))
                .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass))
                .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias));

        File scriptFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd"));

        FileUtils.writeStringToFile(scriptFile, initScript);

        // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor();

        System.out.println(
            "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n");
        System.out.println(
            "\nInit script '" + scriptFile + "' created with the following settings:\n");
        System.out.println("memory=256MB");
        System.out.println("serverName=" + serverName);
        System.out.println("javaHome=" + javaHome);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println(
            "\nEdit and and run the command file in " + scriptFile + " to update this service");

      } else {
        String curUser = java.lang.System.getProperty("user.name");
        if (!curUser.equals("root")) {
          System.out.println("Install mode must be run as root.");
          System.exit(1);
        }

        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script"));
        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", serverName)
                .replaceAll("\\{user\\}", user)
                .replaceAll("\\{webroot\\}", webroot)
                .replaceAll("\\{javahome\\}", javaHome)
                .replaceAll("\\{logfile\\}", logFile)
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", keystore)
                .replaceAll("\\{ksPass\\}", ksPass)
                .replaceAll("\\{ksAlias\\}", ksAlias);

        File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName));

        FileUtils.writeStringToFile(scriptFile, initScript);

        if (new File("/etc/init.d").exists()) {

          exec("chown  -R " + user + " " + webroot);
          exec("chown root " + scriptFile.toString());
          exec("chmod 700 " + scriptFile.toString());
          exec("cp " + scriptFile.toString() + " /etc/init.d/");

          System.out.println(
              "\nInit script '/etc/init.d/"
                  + serverName
                  + "' created with the following settings:\n");
        } else {
          System.out.println(
              "\nInit script '" + scriptFile + "' created with the following settings:\n");
        }

        System.out.println("user="******"memory=256MB");
        System.out.println("server=" + serverName);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println("\nEdit this file to customize startup behavior");
      }
    }
  }
Example #25
0
 void save() throws IOException {
   File dir = getStorageDirectory();
   dir.mkdirs();
   File index = new File(dir, FILE_INDEX);
   props.store(new FileOutputStream(index), null);
 }