Example usage for org.eclipse.jgit.storage.file FileBasedConfig load

List of usage examples for org.eclipse.jgit.storage.file FileBasedConfig load

Introduction

In this page you can find the example usage for org.eclipse.jgit.storage.file FileBasedConfig load.

Prototype

@Override
public void load() throws IOException, ConfigInvalidException 

Source Link

Document

Load the configuration as a Git text style configuration file.

Usage

From source file:com.bacoder.scmtools.git.internal.InMemorySubmoduleWalk.java

License:Apache License

@Override
public SubmoduleWalk loadModulesConfig() throws IOException, ConfigInvalidException {
    File modulesFile = new File(repository.getWorkTree(), Constants.DOT_GIT_MODULES);
    FileBasedConfig config = new FileBasedConfig(modulesFile, repository.getFS()) {
        @Override//from   w  ww.  j av  a  2 s .  c o  m
        protected byte[] readFully() throws IOException {
            return submodulesConfig;
        }
    };
    config.load();
    setModulesConfig(config);
    return this;
}

From source file:com.ericsson.gerrit.plugins.highavailability.SetupLocalHAReplica.java

License:Apache License

void run(SitePaths replica, FileBasedConfig pluginConfig) throws IOException, ConfigInvalidException {
    this.replicaSitePaths = replica;

    FileUtil.mkdirsOrDie(replicaSitePaths.site_path, "cannot create " + replicaSitePaths.site_path);

    configureMainSection(pluginConfig);//www.j a v a  2 s  .  c o  m
    configurePeerInfo(pluginConfig);

    for (Path dir : listDirsForCopy()) {
        copyFiles(dir);
    }

    mkdir(replicaSitePaths.logs_dir);
    mkdir(replicaSitePaths.tmp_dir);
    symlink(Paths.get(masterConfig.getString("gerrit", null, "basePath")));
    symlink(sharedDir);

    FileBasedConfig replicaConfig = new FileBasedConfig(replicaSitePaths.gerrit_config.toFile(), FS.DETECTED);
    replicaConfig.load();

    if ("h2".equals(masterConfig.getString(DATABASE, null, "type"))) {
        masterConfig.setBoolean(DATABASE, "h2", "autoServer", true);
        replicaConfig.setBoolean(DATABASE, "h2", "autoServer", true);
        symlinkH2ReviewDbDir();
    }
}

From source file:com.gitblit.authority.GitblitAuthority.java

License:Apache License

private StoredConfig getConfig() throws IOException, ConfigInvalidException {
    File configFile = new File(folder, X509Utils.CA_CONFIG);
    FileBasedConfig config = new FileBasedConfig(configFile, FS.detect());
    config.load();
    return config;
}

From source file:com.gitblit.authority.GitblitAuthority.java

License:Apache License

private void load(File folder) {
    this.folder = folder;
    this.userService = loadUsers(folder);
    System.out.println(Constants.baseFolder$ + " set to " + folder);
    if (userService == null) {
        JOptionPane.showMessageDialog(this,
                MessageFormat.format("Sorry, {0} doesn't look like a Gitblit GO installation.", folder));
    } else {//from  w  w w. j  a  v  a  2s . c om
        // build empty certificate model for all users
        Map<String, UserCertificateModel> map = new HashMap<String, UserCertificateModel>();
        for (String user : userService.getAllUsernames()) {
            UserModel model = userService.getUserModel(user);
            UserCertificateModel ucm = new UserCertificateModel(model);
            map.put(user, ucm);
        }
        File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
        FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
        if (certificatesConfigFile.exists()) {
            try {
                config.load();
                // replace user certificate model with actual data
                List<UserCertificateModel> list = UserCertificateConfig.KEY.parse(config).list;
                for (UserCertificateModel ucm : list) {
                    ucm.user = userService.getUserModel(ucm.user.username);
                    map.put(ucm.user.username, ucm);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ConfigInvalidException e) {
                e.printStackTrace();
            }
        }

        tableModel.list = new ArrayList<UserCertificateModel>(map.values());
        Collections.sort(tableModel.list);
        tableModel.fireTableDataChanged();
        Utils.packColumns(table, Utils.MARGIN);

        File caKeystore = new File(folder, X509Utils.CA_KEY_STORE);
        if (!caKeystore.exists()) {

            if (!X509Utils.unlimitedStrength) {
                // prompt to confirm user understands JCE Standard Strength encryption
                int res = JOptionPane.showConfirmDialog(GitblitAuthority.this, Translation.get("gb.jceWarning"),
                        Translation.get("gb.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                if (res != JOptionPane.YES_OPTION) {
                    if (Desktop.isDesktopSupported()) {
                        if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                            try {
                                Desktop.getDesktop().browse(URI.create(
                                        "http://www.oracle.com/technetwork/java/javase/downloads/index.html"));
                            } catch (IOException e) {
                            }
                        }
                    }
                    System.exit(1);
                }
            }

            // show certificate defaults dialog
            certificateDefaultsButton.doClick();

            // create "localhost" ssl certificate
            prepareX509Infrastructure();
        }
    }
}

From source file:com.gitblit.authority.GitblitAuthority.java

License:Apache License

private Container getUI() {
    userCertificatePanel = new UserCertificatePanel(this) {

        private static final long serialVersionUID = 1L;

        @Override//from  ww  w  .j  a v  a2s  .c  o  m
        public Insets getInsets() {
            return Utils.INSETS;
        }

        @Override
        public boolean isAllowEmail() {
            return mail.isReady();
        }

        @Override
        public Date getDefaultExpiration() {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, defaultDuration);
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            return c.getTime();
        }

        @Override
        public boolean saveUser(String username, UserCertificateModel ucm) {
            return userService.updateUserModel(username, ucm.user);
        }

        @Override
        public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
            if (!prepareX509Infrastructure()) {
                return false;
            }

            Date notAfter = metadata.notAfter;
            setMetadataDefaults(metadata);
            metadata.notAfter = notAfter;

            // set user's specified OID values
            UserModel user = ucm.user;
            if (!StringUtils.isEmpty(user.organizationalUnit)) {
                metadata.oids.put("OU", user.organizationalUnit);
            }
            if (!StringUtils.isEmpty(user.organization)) {
                metadata.oids.put("O", user.organization);
            }
            if (!StringUtils.isEmpty(user.locality)) {
                metadata.oids.put("L", user.locality);
            }
            if (!StringUtils.isEmpty(user.stateProvince)) {
                metadata.oids.put("ST", user.stateProvince);
            }
            if (!StringUtils.isEmpty(user.countryCode)) {
                metadata.oids.put("C", user.countryCode);
            }

            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            File zip = X509Utils.newClientBundle(user, metadata, caKeystoreFile, caKeystorePassword,
                    GitblitAuthority.this);

            // save latest expiration date
            if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
                ucm.expires = metadata.notAfter;
            }

            updateAuthorityConfig(ucm);

            // refresh user
            ucm.certs = null;
            int selectedIndex = table.getSelectedRow();
            tableModel.fireTableDataChanged();
            table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);

            if (sendEmail) {
                sendEmail(user, metadata, zip);
            }
            return true;
        }

        @Override
        public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
            if (!prepareX509Infrastructure()) {
                return false;
            }

            File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword,
                    GitblitAuthority.this)) {
                File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
                FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
                if (certificatesConfigFile.exists()) {
                    try {
                        config.load();
                    } catch (Exception e) {
                        Utils.showException(GitblitAuthority.this, e);
                    }
                }
                // add serial to revoked list
                ucm.revoke(cert.getSerialNumber(), reason);
                ucm.update(config);
                try {
                    config.save();
                } catch (Exception e) {
                    Utils.showException(GitblitAuthority.this, e);
                }

                // refresh user
                ucm.certs = null;
                int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
                tableModel.fireTableDataChanged();
                table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);

                return true;
            }

            return false;
        }
    };

    table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
    table.setRowSorter(defaultSorter);
    table.setDefaultRenderer(CertificateStatus.class, new CertificateStatusRenderer());
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            int row = table.getSelectedRow();
            if (row < 0) {
                return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ucm.certs == null) {
                ucm.certs = findCerts(folder, ucm.user.username);
            }
            userCertificatePanel.setUserCertificateModel(ucm);
        }
    });

    JPanel usersPanel = new JPanel(new BorderLayout()) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }
    };
    usersPanel.add(new HeaderPanel(Translation.get("gb.users"), "users_16x16.png"), BorderLayout.NORTH);
    usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    usersPanel.setMinimumSize(new Dimension(400, 10));

    certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
    certificateDefaultsButton.setFocusable(false);
    certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
    certificateDefaultsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            X509Metadata metadata = new X509Metadata("whocares", "whocares");
            File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
            FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
            NewCertificateConfig certificateConfig = null;
            if (certificatesConfigFile.exists()) {
                try {
                    config.load();
                } catch (Exception x) {
                    Utils.showException(GitblitAuthority.this, x);
                }
                certificateConfig = NewCertificateConfig.KEY.parse(config);
                certificateConfig.update(metadata);
            }
            InputVerifier verifier = new InputVerifier() {
                @Override
                public boolean verify(JComponent comp) {
                    boolean returnValue;
                    JTextField textField = (JTextField) comp;
                    try {
                        Integer.parseInt(textField.getText());
                        returnValue = true;
                    } catch (NumberFormatException e) {
                        returnValue = false;
                    }
                    return returnValue;
                }
            };

            JTextField siteNameTF = new JTextField(20);
            siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
            JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"), siteNameTF,
                    Translation.get("gb.siteNameDescription"));

            JTextField validityTF = new JTextField(4);
            validityTF.setInputVerifier(verifier);
            validityTF.setVerifyInputWhenFocusTarget(true);
            validityTF.setText("" + certificateConfig.duration);
            JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"), validityTF,
                    Translation.get("gb.duration.days").replace("{0}", "").trim());

            JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
            p1.add(siteNamePanel);
            p1.add(validityPanel);

            DefaultOidsPanel oids = new DefaultOidsPanel(metadata);

            JPanel panel = new JPanel(new BorderLayout());
            panel.add(p1, BorderLayout.NORTH);
            panel.add(oids, BorderLayout.CENTER);

            int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, panel,
                    Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
            if (result == JOptionPane.OK_OPTION) {
                try {
                    oids.update(metadata);
                    certificateConfig.duration = Integer.parseInt(validityTF.getText());
                    certificateConfig.store(config, metadata);
                    config.save();

                    Map<String, String> updates = new HashMap<String, String>();
                    updates.put(Keys.web.siteName, siteNameTF.getText());
                    gitblitSettings.saveSettings(updates);
                } catch (Exception e1) {
                    Utils.showException(GitblitAuthority.this, e1);
                }
            }
        }
    });

    newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
    newSSLCertificate.setFocusable(false);
    newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
    newSSLCertificate.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Date defaultExpiration = new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
            NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this,
                    defaultExpiration);
            dialog.setModal(true);
            dialog.setVisible(true);
            if (dialog.isCanceled()) {
                return;
            }
            final Date expires = dialog.getExpiration();
            final String hostname = dialog.getHostname();
            final boolean serveCertificate = dialog.isServeCertificate();

            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {

                @Override
                protected Boolean doRequest() throws IOException {
                    if (!prepareX509Infrastructure()) {
                        return false;
                    }

                    // read CA private key and certificate
                    File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
                    PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile,
                            caKeystorePassword);
                    X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile,
                            caKeystorePassword);

                    // generate new SSL certificate
                    X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
                    setMetadataDefaults(metadata);
                    metadata.notAfter = expires;
                    File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
                    X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert,
                            serverKeystoreFile, GitblitAuthority.this);
                    boolean hasCert = cert != null;
                    if (hasCert && serveCertificate) {
                        // update Gitblit https connector alias
                        Map<String, String> updates = new HashMap<String, String>();
                        updates.put(Keys.server.certificateAlias, metadata.commonName);
                        gitblitSettings.saveSettings(updates);
                    }
                    return hasCert;
                }

                @Override
                protected void onSuccess() {
                    if (serveCertificate) {
                        JOptionPane.showMessageDialog(GitblitAuthority.this,
                                MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"),
                                        hostname),
                                Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(GitblitAuthority.this,
                                MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname),
                                Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            };

            worker.execute();
        }
    });

    JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
    emailBundle.setFocusable(false);
    emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
    emailBundle.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row < 0) {
                return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            final UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ArrayUtils.isEmpty(ucm.certs)) {
                JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(
                        Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
            }
            final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username
                    + File.separator + ucm.user.username + ".zip");
            if (!zip.exists()) {
                return;
            }

            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
                @Override
                protected Boolean doRequest() throws IOException {
                    X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
                    metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
                    if (StringUtils.isEmpty(metadata.serverHostname)) {
                        metadata.serverHostname = Constants.NAME;
                    }
                    metadata.userDisplayname = ucm.user.getDisplayName();
                    return sendEmail(ucm.user, metadata, zip);
                }

                @Override
                protected void onSuccess() {
                    JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(
                            Translation.get("gb.clientCertificateBundleSent"), ucm.user.getDisplayName()));
                }

            };
            worker.execute();
        }
    });

    JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
    logButton.setFocusable(false);
    logButton.setToolTipText(Translation.get("gb.log"));
    logButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
            if (log.exists()) {
                String content = FileUtils.readContent(log, "\n");
                JTextArea textarea = new JTextArea(content);
                JScrollPane scrollPane = new JScrollPane(textarea);
                scrollPane.setPreferredSize(new Dimension(700, 400));
                JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(),
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
    });

    final JTextField filterTextfield = new JTextField(15);
    filterTextfield.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filterUsers(filterTextfield.getText());
        }
    });
    filterTextfield.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            filterUsers(filterTextfield.getText());
        }
    });

    JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
    buttonControls.setFloatable(false);
    buttonControls.add(certificateDefaultsButton);
    buttonControls.add(newSSLCertificate);
    buttonControls.add(emailBundle);
    buttonControls.add(logButton);

    JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
    userControls.add(new JLabel(Translation.get("gb.filter")));
    userControls.add(filterTextfield);

    JPanel topPanel = new JPanel(new BorderLayout(0, 0));
    topPanel.add(buttonControls, BorderLayout.WEST);
    topPanel.add(userControls, BorderLayout.EAST);

    JPanel leftPanel = new JPanel(new BorderLayout());
    leftPanel.add(topPanel, BorderLayout.NORTH);
    leftPanel.add(usersPanel, BorderLayout.CENTER);

    userCertificatePanel.setMinimumSize(new Dimension(375, 10));

    JLabel statusLabel = new JLabel();
    statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    if (X509Utils.unlimitedStrength) {
        statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
    } else {
        statusLabel.setText("JCE Standard Encryption Policy");
    }

    JPanel root = new JPanel(new BorderLayout()) {
        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }
    };
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
    splitPane.setDividerLocation(1d);
    root.add(splitPane, BorderLayout.CENTER);
    root.add(statusLabel, BorderLayout.SOUTH);
    return root;
}

From source file:com.gitblit.authority.GitblitAuthority.java

License:Apache License

private void setMetadataDefaults(X509Metadata metadata) {
    metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
    if (StringUtils.isEmpty(metadata.serverHostname)) {
        metadata.serverHostname = Constants.NAME;
    }//from w  w  w . java  2s. c o m

    // set default values from config file
    File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
    FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
    if (certificatesConfigFile.exists()) {
        try {
            config.load();
        } catch (Exception e) {
            Utils.showException(GitblitAuthority.this, e);
        }
        NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
        certificateConfig.update(metadata);
    }
}

From source file:com.gitblit.authority.GitblitAuthority.java

License:Apache License

private void updateAuthorityConfig(UserCertificateModel ucm) {
    File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
    FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
    if (certificatesConfigFile.exists()) {
        try {/*from  w  w  w  . ja  va 2s.c o  m*/
            config.load();
        } catch (Exception e) {
            Utils.showException(GitblitAuthority.this, e);
        }
    }
    ucm.update(config);
    try {
        config.save();
    } catch (Exception e) {
        Utils.showException(GitblitAuthority.this, e);
    }
}

From source file:com.gitblit.client.GitblitManager.java

License:Apache License

private StoredConfig getConfig() throws IOException, ConfigInvalidException {
    FileBasedConfig config = new FileBasedConfig(configFile, FS.detect());
    config.load();
    return config;
}

From source file:com.gitblit.GitBlitServer.java

License:Apache License

/**
 * Start Gitblit GO.//ww  w  .j  a  v a2 s . c om
 */
protected final void start(Params params) {
    final File baseFolder = getBaseFolder(params);
    FileSettings settings = params.FILESETTINGS;
    if (!StringUtils.isEmpty(params.settingsfile)) {
        if (new File(params.settingsfile).exists()) {
            settings = new FileSettings(params.settingsfile);
        }
    }

    if (params.dailyLogFile) {
        // Configure log4j for daily log file generation
        InputStream is = null;
        try {
            is = getClass().getResourceAsStream("/log4j.properties");
            Properties loggingProperties = new Properties();
            loggingProperties.load(is);

            loggingProperties.put("log4j.appender.R.File",
                    new File(baseFolder, "logs/gitblit.log").getAbsolutePath());
            loggingProperties.put("log4j.rootCategory", "INFO, R");

            if (settings.getBoolean(Keys.web.debugMode, false)) {
                loggingProperties.put("log4j.logger.com.gitblit", "DEBUG");
            }

            PropertyConfigurator.configure(loggingProperties);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    logger = LoggerFactory.getLogger(GitBlitServer.class);
    logger.info("\n" + Constants.getASCIIArt());

    System.setProperty("java.awt.headless", "true");

    String osname = System.getProperty("os.name");
    String osversion = System.getProperty("os.version");
    logger.info("Running on " + osname + " (" + osversion + ")");

    QueuedThreadPool threadPool = new QueuedThreadPool();
    int maxThreads = settings.getInteger(Keys.server.threadPoolSize, 50);
    if (maxThreads > 0) {
        threadPool.setMaxThreads(maxThreads);
    }

    Server server = new Server(threadPool);
    server.setStopAtShutdown(true);

    // conditionally configure the https connector
    if (params.securePort > 0) {
        File certificatesConf = new File(baseFolder, X509Utils.CA_CONFIG);
        File serverKeyStore = new File(baseFolder, X509Utils.SERVER_KEY_STORE);
        File serverTrustStore = new File(baseFolder, X509Utils.SERVER_TRUST_STORE);
        File caRevocationList = new File(baseFolder, X509Utils.CA_REVOCATION_LIST);

        // generate CA & web certificates, create certificate stores
        X509Metadata metadata = new X509Metadata("localhost", params.storePassword);
        // set default certificate values from config file
        if (certificatesConf.exists()) {
            FileBasedConfig config = new FileBasedConfig(certificatesConf, FS.detect());
            try {
                config.load();
            } catch (Exception e) {
                logger.error("Error parsing " + certificatesConf, e);
            }
            NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
            certificateConfig.update(metadata);
        }

        metadata.notAfter = new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
        X509Utils.prepareX509Infrastructure(metadata, baseFolder, new X509Log() {
            @Override
            public void log(String message) {
                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new FileWriter(
                            new File(baseFolder, X509Utils.CERTS + File.separator + "log.txt"), true));
                    writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
                    writer.newLine();
                    writer.flush();
                } catch (Exception e) {
                    LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e);
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        });

        if (serverKeyStore.exists()) {
            /*
             * HTTPS
             */
            logger.info("Setting up HTTPS transport on port " + params.securePort);
            GitblitSslContextFactory factory = new GitblitSslContextFactory(params.alias, serverKeyStore,
                    serverTrustStore, params.storePassword, caRevocationList);
            if (params.requireClientCertificates) {
                factory.setNeedClientAuth(true);
            } else {
                factory.setWantClientAuth(true);
            }

            ServerConnector connector = new ServerConnector(server, factory);
            connector.setSoLingerTime(-1);
            connector.setIdleTimeout(settings.getLong(Keys.server.httpIdleTimeout, 30000L));
            connector.setPort(params.securePort);
            String bindInterface = settings.getString(Keys.server.httpsBindInterface, null);
            if (!StringUtils.isEmpty(bindInterface)) {
                logger.warn(MessageFormat.format("Binding HTTPS transport on port {0,number,0} to {1}",
                        params.securePort, bindInterface));
                connector.setHost(bindInterface);
            }
            if (params.securePort < 1024 && !isWindows()) {
                logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
            }

            server.addConnector(connector);
        } else {
            logger.warn("Failed to find or load Keystore?");
            logger.warn("HTTPS transport DISABLED.");
        }
    }

    // conditionally configure the http transport
    if (params.port > 0) {
        /*
         * HTTP
         */
        logger.info("Setting up HTTP transport on port " + params.port);

        HttpConfiguration httpConfig = new HttpConfiguration();
        if (params.port > 0 && params.securePort > 0
                && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
            httpConfig.setSecureScheme("https");
            httpConfig.setSecurePort(params.securePort);
        }
        httpConfig.setSendServerVersion(false);
        httpConfig.setSendDateHeader(false);

        ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
        connector.setSoLingerTime(-1);
        connector.setIdleTimeout(settings.getLong(Keys.server.httpIdleTimeout, 30000L));
        connector.setPort(params.port);
        String bindInterface = settings.getString(Keys.server.httpBindInterface, null);
        if (!StringUtils.isEmpty(bindInterface)) {
            logger.warn(MessageFormat.format("Binding HTTP transport on port {0,number,0} to {1}", params.port,
                    bindInterface));
            connector.setHost(bindInterface);
        }
        if (params.port < 1024 && !isWindows()) {
            logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
        }

        server.addConnector(connector);
    }

    // tempDir is where the embedded Gitblit web application is expanded and
    // where Jetty creates any necessary temporary files
    File tempDir = com.gitblit.utils.FileUtils.resolveParameter(Constants.baseFolder$, baseFolder, params.temp);
    if (tempDir.exists()) {
        try {
            FileUtils.delete(tempDir, FileUtils.RECURSIVE | FileUtils.RETRY);
        } catch (IOException x) {
            logger.warn("Failed to delete temp dir " + tempDir.getAbsolutePath(), x);
        }
    }
    if (!tempDir.mkdirs()) {
        logger.warn("Failed to create temp dir " + tempDir.getAbsolutePath());
    }

    // Get the execution path of this class
    // We use this to set the WAR path.
    ProtectionDomain protectionDomain = GitBlitServer.class.getProtectionDomain();
    URL location = protectionDomain.getCodeSource().getLocation();

    // Root WebApp Context
    WebAppContext rootContext = new WebAppContext();
    rootContext.setContextPath(settings.getString(Keys.server.contextPath, "/"));
    rootContext.setServer(server);
    rootContext.setWar(location.toExternalForm());
    rootContext.setTempDirectory(tempDir);

    // Set cookies HttpOnly so they are not accessible to JavaScript engines
    HashSessionManager sessionManager = new HashSessionManager();
    sessionManager.setHttpOnly(true);
    // Use secure cookies if only serving https
    sessionManager.setSecureRequestOnly((params.port <= 0 && params.securePort > 0) || (params.port > 0
            && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)));
    rootContext.getSessionHandler().setSessionManager(sessionManager);

    // Ensure there is a defined User Service
    String realmUsers = params.userService;
    if (StringUtils.isEmpty(realmUsers)) {
        logger.error(MessageFormat.format("PLEASE SPECIFY {0}!!", Keys.realm.userService));
        return;
    }

    // Override settings from the command-line
    settings.overrideSetting(Keys.realm.userService, params.userService);
    settings.overrideSetting(Keys.git.repositoriesFolder, params.repositoriesFolder);
    settings.overrideSetting(Keys.git.daemonPort, params.gitPort);
    settings.overrideSetting(Keys.git.sshPort, params.sshPort);

    // Start up an in-memory LDAP server, if configured
    try {
        if (!StringUtils.isEmpty(params.ldapLdifFile)) {
            File ldifFile = new File(params.ldapLdifFile);
            if (ldifFile != null && ldifFile.exists()) {
                URI ldapUrl = new URI(settings.getRequiredString(Keys.realm.ldap.server));
                String firstLine = new Scanner(ldifFile).nextLine();
                String rootDN = firstLine.substring(4);
                String bindUserName = settings.getString(Keys.realm.ldap.username, "");
                String bindPassword = settings.getString(Keys.realm.ldap.password, "");

                // Get the port
                int port = ldapUrl.getPort();
                if (port == -1)
                    port = 389;

                InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(rootDN);
                config.addAdditionalBindCredentials(bindUserName, bindPassword);
                config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", port));
                config.setSchema(null);

                InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
                ds.importFromLDIF(true, new LDIFReader(ldifFile));
                ds.startListening();

                logger.info("LDAP Server started at ldap://localhost:" + port);
            }
        }
    } catch (Exception e) {
        // Completely optional, just show a warning
        logger.warn("Unable to start LDAP server", e);
    }

    // Set the server's contexts
    server.setHandler(rootContext);

    // redirect HTTP requests to HTTPS
    if (params.port > 0 && params.securePort > 0
            && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
        logger.info(String.format("Configuring automatic http(%1$s) -> https(%2$s) redirects", params.port,
                params.securePort));
        // Create the internal mechanisms to handle secure connections and redirects
        Constraint constraint = new Constraint();
        constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);

        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");

        ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
        sh.setConstraintMappings(new ConstraintMapping[] { cm });

        // Configure this context to use the Security Handler defined before
        rootContext.setHandler(sh);
    }

    // Setup the Gitblit context
    GitblitContext gitblit = newGitblit(settings, baseFolder);
    rootContext.addEventListener(gitblit);

    try {
        // start the shutdown monitor
        if (params.shutdownPort > 0) {
            Thread shutdownMonitor = new ShutdownMonitorThread(server, params);
            shutdownMonitor.start();
        }

        // start Jetty
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(100);
    }
}

From source file:com.gitblit.LuceneExecutor.java

License:Apache License

/**
 * Reads the Lucene config file for the repository to check the index
 * version. If the index version is different, then rebuild the repository
 * index./*from   w w w  .j  a v a  2 s  .  c o m*/
 * 
 * @param repository
 * @return true of the on-disk index format is different than INDEX_VERSION
 */
private boolean shouldReindex(Repository repository) {
    try {
        FileBasedConfig config = getConfig(repository);
        config.load();
        int indexVersion = config.getInt(CONF_INDEX, CONF_VERSION, 0);
        // reindex if versions do not match
        return indexVersion != INDEX_VERSION;
    } catch (Throwable t) {
    }
    return true;
}