Example usage for javax.ejb EJBException getMessage

List of usage examples for javax.ejb EJBException getMessage

Introduction

In this page you can find the example usage for javax.ejb EJBException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.sfs.ucm.controller.ProjectPackageAction.java

/**
 * save action/*from w w w.j  av  a2s . c o  m*/
 * 
 * @throws UCMException
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void save() throws UCMException {
    try {
        if (validate()) {
            if (this.projectPackage.getId() == null) {
                this.project.addProjectPackage(this.projectPackage);
            }

            try {
                em.persist(this.project);
            } catch (javax.ejb.EJBException e) {
                if (e.getCausedByException().equals(OptimisticLockException.class)) {
                    logger.error("OptimisticLockException {}", e.getMessage());
                    this.facesContextMessage.warningMessage("Another user is modifying this Artifact");
                }
                throw new UCMException(e);
            }

            logger.info("saved {}", this.projectPackage.getName());
            this.facesContextMessage.infoMessage("{0} saved successfully",
                    StringUtils.abbreviate(this.projectPackage.getName(), 25));

            // refresh list
            loadList();
            this.selected = true;
        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

From source file:com.sfs.captor.controller.ProjectPackageAction.java

/**
 * save action/*from  ww w .j av  a  2 s.  c o m*/
 * 
 * @throws UCMException
 */
public void save() throws UCMException {
    try {
        if (validate()) {
            configure();
            if (this.projectPackage.getId() == null) {
                this.project.addProjectPackage(this.projectPackage);
            }

            try {
                em.persist(this.project);
            } catch (javax.ejb.EJBException e) {
                if (e.getCausedByException().equals(OptimisticLockException.class)) {
                    logger.error("OptimisticLockException {}", e.getMessage());
                    this.facesContextMessage.warningMessage("Another user is modifying this Artifact");
                }
                throw new UCMException(e);
            }

            logger.info("saved {}", this.projectPackage.getName());
            this.facesContextMessage.infoMessage("{0} saved successfully",
                    StringUtils.abbreviate(this.projectPackage.getName(), 25));

            // update producers
            projectEvent.fire(this.project);
            projectPackageSrc.fire(this.project);

            // refresh list
            loadList();
            this.selected = true;
        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

From source file:edu.harvard.iq.dataverse.GuestbookPage.java

public String save() {
    boolean create = false;
    if (!(guestbook.getCustomQuestions() == null)) {
        for (CustomQuestion cq : guestbook.getCustomQuestions()) {
            if (cq.getQuestionType().equals("text")) {
                cq.setCustomQuestionValues(null);
            }//from w ww .  ja  v a 2  s.com
        }

        Iterator<CustomQuestion> cqIt = guestbook.getCustomQuestions().iterator();
        while (cqIt.hasNext()) {
            CustomQuestion cq = cqIt.next();
            if (StringUtils.isBlank(cq.getQuestionString())) {
                cqIt.remove();
            }
        }

        for (CustomQuestion cq : guestbook.getCustomQuestions()) {
            if (cq != null && cq.getQuestionType().equals("options")) {
                Iterator<CustomQuestionValue> cqvIt = cq.getCustomQuestionValues().iterator();
                while (cqvIt.hasNext()) {
                    CustomQuestionValue cqv = cqvIt.next();
                    if (StringUtils.isBlank(cqv.getValueString())) {
                        cqvIt.remove();
                    }
                }
            }
        }

        for (CustomQuestion cq : guestbook.getCustomQuestions()) {
            if (cq != null && cq.getQuestionType().equals("options")) {
                if (cq.getCustomQuestionValues() == null || cq.getCustomQuestionValues().isEmpty()) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                            FacesMessage.SEVERITY_ERROR, "Guestbook Save Failed",
                            " - An Option question requires multiple options. Please complete before saving."));
                    return null;
                }
                if (cq.getCustomQuestionValues().size() == 1) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                            FacesMessage.SEVERITY_ERROR, "Guestbook Save Failed",
                            " - An Option question requires multiple options. Please complete before saving."));
                    return null;
                }
            }
        }
        int i = 0;
        for (CustomQuestion cq : guestbook.getCustomQuestions()) {
            int j = 0;
            cq.setDisplayOrder(i);
            if (cq.getCustomQuestionValues() != null && !cq.getCustomQuestionValues().isEmpty()) {
                for (CustomQuestionValue cqv : cq.getCustomQuestionValues()) {
                    cqv.setDisplayOrder(j);
                    j++;
                }
            }
            i++;
        }
    }

    Command<Dataverse> cmd;
    try {
        if (editMode == EditMode.CREATE || editMode == EditMode.CLONE) {
            guestbook.setCreateTime(new Timestamp(new Date().getTime()));
            guestbook.setUsageCount(new Long(0));
            guestbook.setEnabled(true);
            dataverse.getGuestbooks().add(guestbook);
            cmd = new UpdateDataverseCommand(dataverse, null, null, dvRequestService.getDataverseRequest(),
                    null);
            commandEngine.submit(cmd);
            create = true;
        } else {
            cmd = new UpdateDataverseGuestbookCommand(dataverse, guestbook,
                    dvRequestService.getDataverseRequest());
            commandEngine.submit(cmd);
        }

    } catch (EJBException ex) {
        StringBuilder error = new StringBuilder();
        error.append(ex).append(" ");
        error.append(ex.getMessage()).append(" ");
        Throwable cause = ex;
        while (cause.getCause() != null) {
            cause = cause.getCause();
            error.append(cause).append(" ");
            error.append(cause.getMessage()).append(" ");
        }
        //
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL,
                "Guestbook Save Failed", " - " + error.toString()));
        logger.info("Guestbook Page EJB Exception. Dataverse: " + dataverse.getName());
        logger.info(error.toString());
        return null;
    } catch (CommandException ex) {
        logger.info("Guestbook Page Command Exception. Dataverse: " + dataverse.getName());
        logger.info(ex.toString());
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_FATAL, "Guestbook Save Failed", " - " + ex.toString()));
        //logger.severe(ex.getMessage());
    }
    editMode = null;
    String msg = (create) ? "The guestbook has been created." : "The guestbook has been edited and saved.";
    JsfHelper.addFlashMessage(msg);
    return "/manage-guestbooks.xhtml?dataverseId=" + dataverse.getId() + "&faces-redirect=true";
}

From source file:io.hops.hopsworks.common.project.ProjectController.java

/**
 * Creates a new project(project), the related DIR, the different services in
 * the project, and the master of the//from   w w w .jav  a  2 s.  c o m
 * project.
 * <p>
 * This needs to be an atomic operation (all or nothing) REQUIRES_NEW will
 * make sure a new transaction is created even
 * if this method is called from within a transaction.
 *
 * @param projectDTO
 * @param owner
 * @param failedMembers
 * @param sessionId
 * @return
 */
public Project createProject(ProjectDTO projectDTO, Users owner, List<String> failedMembers, String sessionId)
        throws DatasetException, GenericException, KafkaException, ProjectException, UserException,
        HopsSecurityException, ServiceException {

    Long startTime = System.currentTimeMillis();

    //check that the project name is ok
    String projectName = projectDTO.getProjectName();
    FolderNameValidator.isValidProjectName(projectName, false);

    List<ProjectServiceEnum> projectServices = new ArrayList<>();
    if (projectDTO.getServices() != null) {
        for (String s : projectDTO.getServices()) {
            ProjectServiceEnum se = ProjectServiceEnum.valueOf(s.toUpperCase());
            projectServices.add(se);
        }
    }
    LOGGER.log(Level.FINE, () -> "PROJECT CREATION TIME. Step 1: " + (System.currentTimeMillis() - startTime));

    DistributedFileSystemOps dfso = null;
    Project project = null;
    try {
        dfso = dfs.getDfsOps();
        /*
         * create a project in the database
         * if the creation go through it means that there is no other project with
         * the same name.
         * this project creation act like a lock, no other project can be created
         * with the same name
         * until this project is removed from the database
         */
        try {
            project = createProject(projectName, owner, projectDTO.getDescription(), dfso);
        } catch (EJBException ex) {
            LOGGER.log(Level.WARNING, null, ex);
            Path dummy = new Path("/tmp/" + projectName);
            try {
                dfso.rm(dummy, true);
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, null, e);
            }
            throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_EXISTS, Level.SEVERE,
                    "project: " + projectName, ex.getMessage(), ex);
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 2 (hdfs): {0}",
                System.currentTimeMillis() - startTime);

        verifyProject(project, dfso, sessionId);

        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 3 (verify): {0}",
                System.currentTimeMillis() - startTime);

        // Run the handlers.
        for (ProjectHandler projectHandler : projectHandlers) {
            try {
                projectHandler.preCreate(project);
            } catch (Exception e) {
                throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_HANDLER_PRECREATE_ERROR,
                        Level.SEVERE,
                        "project: " + project.getName() + ", handler: " + projectHandler.getClassName(),
                        e.getMessage(), e);
            }
        }

        //create certificate for this user
        // User's certificates should be created before making any call to
        // Hadoop clients. Otherwise the client will fail if RPC TLS is enabled
        // This is an async call
        List<Future<?>> projectCreationFutures = new ArrayList<>();
        try {
            projectCreationFutures.add(certificatesController.generateCertificates(project, owner, true));
        } catch (Exception ex) {
            cleanup(project, sessionId, projectCreationFutures);
            throw new HopsSecurityException(RESTCodes.SecurityErrorCode.CERT_CREATION_ERROR, Level.SEVERE,
                    "project: " + project.getName() + "owner: " + owner.getUsername(), ex.getMessage(), ex);
        }

        String username = hdfsUsersController.getHdfsUserName(project, owner);
        if (username == null || username.isEmpty()) {
            cleanup(project, sessionId, projectCreationFutures);
            throw new UserException(RESTCodes.UserErrorCode.USER_WAS_NOT_FOUND, Level.SEVERE,
                    "project: " + project.getName() + "owner: " + owner.getUsername());
        }

        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 4 (certs): {0}",
                System.currentTimeMillis() - startTime);

        //all the verifications have passed, we can now create the project  
        //create the project folder
        try {
            mkProjectDIR(projectName, dfso);
        } catch (IOException | EJBException ex) {
            cleanup(project, sessionId, projectCreationFutures);
            throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_FOLDER_NOT_CREATED, Level.SEVERE,
                    "project: " + projectName, ex.getMessage(), ex);
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 5 (folders): {0}",
                System.currentTimeMillis() - startTime);
        //update the project with the project folder inode
        try {
            setProjectInode(project, dfso);
        } catch (IOException | EJBException ex) {
            cleanup(project, sessionId, projectCreationFutures);
            throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_INODE_CREATION_ERROR, Level.SEVERE,
                    "project: " + projectName, ex.getMessage(), ex);
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 6 (inodes): {0}",
                System.currentTimeMillis() - startTime);

        //set payment and quotas
        try {
            setProjectOwnerAndQuotas(project, settings.getHdfsDefaultQuotaInMBs(), dfso, owner);
        } catch (IOException | EJBException ex) {
            cleanup(project, sessionId, projectCreationFutures);
            throw new ProjectException(RESTCodes.ProjectErrorCode.QUOTA_ERROR, Level.SEVERE,
                    "project: " + project.getName(), ex.getMessage(), ex);
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 7 (quotas): {0}",
                System.currentTimeMillis() - startTime);

        try {
            hdfsUsersController.addProjectFolderOwner(project, dfso);
            createProjectLogResources(owner, project, dfso);
        } catch (IOException | EJBException ex) {
            cleanup(project, sessionId, projectCreationFutures);
            throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_SET_PERMISSIONS_ERROR, Level.SEVERE,
                    "project: " + projectName, ex.getMessage(), ex);
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 8 (logs): {0}",
                System.currentTimeMillis() - startTime);

        logProject(project, OperationType.Add);

        // enable services
        for (ProjectServiceEnum service : projectServices) {
            try {
                projectCreationFutures.addAll(addService(project, service, owner, dfso));
            } catch (RESTException ex) {
                cleanup(project, sessionId, projectCreationFutures);
                throw ex;
            }
        }

        //add members of the project   
        try {
            failedMembers = new ArrayList<>();
            failedMembers.addAll(addMembers(project, owner.getEmail(), projectDTO.getProjectTeam()));
        } catch (KafkaException | UserException | ProjectException | EJBException ex) {
            cleanup(project, sessionId, projectCreationFutures);
            throw ex;
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 9 (members): {0}",
                System.currentTimeMillis() - startTime);

        if (projectCreationFutures != null) {
            try {
                for (Future f : projectCreationFutures) {
                    if (f != null) {
                        f.get();
                    }
                }
            } catch (InterruptedException | ExecutionException ex) {
                LOGGER.log(Level.SEVERE, "Error while waiting for the certificate "
                        + "generation thread to finish. Will try to cleanup...", ex);
                cleanup(project, sessionId, projectCreationFutures);
            }
        }

        // Run the handlers.
        for (ProjectHandler projectHandler : projectHandlers) {
            try {
                projectHandler.postCreate(project);
            } catch (Exception e) {
                cleanup(project, sessionId, projectCreationFutures);
                throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_HANDLER_POSTCREATE_ERROR,
                        Level.SEVERE, "project: " + projectName, e.getMessage(), e);
            }
        }

        return project;

    } finally {
        if (dfso != null) {
            dfso.close();
        }
        LOGGER.log(Level.FINE, "PROJECT CREATION TIME. Step 10 (close): {0}",
                System.currentTimeMillis() - startTime);
    }

}

From source file:edu.harvard.iq.dataverse.DatasetPage.java

public String save() {
    // Validate/*from   w  w  w.ja v  a2 s . c o m*/
    Set<ConstraintViolation> constraintViolations = workingVersion.validate();
    if (!constraintViolations.isEmpty()) {
        //JsfHelper.addFlashMessage(JH.localize("dataset.message.validationError"));
        JH.addMessage(FacesMessage.SEVERITY_ERROR, JH.localize("dataset.message.validationError"));
        //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Validation Error", "See below for details."));
        return "";
    }

    // Use the API to save the dataset: 
    Command<Dataset> cmd;
    try {
        if (editMode == EditMode.CREATE) {
            if (selectedTemplate != null) {
                if (isSessionUserAuthenticated()) {
                    cmd = new CreateDatasetCommand(dataset, dvRequestService.getDataverseRequest(), false, null,
                            selectedTemplate);
                } else {
                    JH.addMessage(FacesMessage.SEVERITY_FATAL,
                            JH.localize("dataset.create.authenticatedUsersOnly"));
                    return null;
                }
            } else {
                cmd = new CreateDatasetCommand(dataset, dvRequestService.getDataverseRequest());
            }

        } else {
            cmd = new UpdateDatasetCommand(dataset, dvRequestService.getDataverseRequest(), filesToBeDeleted);
            ((UpdateDatasetCommand) cmd).setValidateLenient(true);
        }
        dataset = commandEngine.submit(cmd);
        if (editMode == EditMode.CREATE) {
            if (session.getUser() instanceof AuthenticatedUser) {
                userNotificationService.sendNotification((AuthenticatedUser) session.getUser(),
                        dataset.getCreateDate(), UserNotification.Type.CREATEDS,
                        dataset.getLatestVersion().getId());
            }
        }
        logger.fine("Successfully executed SaveDatasetCommand.");
    } catch (EJBException ex) {
        StringBuilder error = new StringBuilder();
        error.append(ex).append(" ");
        error.append(ex.getMessage()).append(" ");
        Throwable cause = ex;
        while (cause.getCause() != null) {
            cause = cause.getCause();
            error.append(cause).append(" ");
            error.append(cause.getMessage()).append(" ");
        }
        logger.log(Level.FINE, "Couldn''t save dataset: {0}", error.toString());
        populateDatasetUpdateFailureMessage();
        return returnToDraftVersion();
    } catch (CommandException ex) {
        //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dataset Save Failed", " - " + ex.toString()));
        logger.severe("CommandException, when attempting to update the dataset: " + ex.getMessage());
        populateDatasetUpdateFailureMessage();
        return returnToDraftVersion();
    }

    newFiles.clear();
    if (editMode != null) {
        if (editMode.equals(EditMode.CREATE)) {
            JsfHelper.addSuccessMessage(JH.localize("dataset.message.createSuccess"));
        }
        if (editMode.equals(EditMode.METADATA)) {
            JsfHelper.addSuccessMessage(JH.localize("dataset.message.metadataSuccess"));
        }
        if (editMode.equals(EditMode.LICENSE)) {
            JsfHelper.addSuccessMessage(JH.localize("dataset.message.termsSuccess"));
        }
        if (editMode.equals(EditMode.FILE)) {
            JsfHelper.addSuccessMessage(JH.localize("dataset.message.filesSuccess"));
        }

    } else {
        // must have been a bulk file update or delete:
        if (bulkFileDeleteInProgress) {
            JsfHelper.addSuccessMessage(JH.localize("dataset.message.bulkFileDeleteSuccess"));
        } else {
            JsfHelper.addSuccessMessage(JH.localize("dataset.message.bulkFileUpdateSuccess"));
        }
    }

    editMode = null;
    bulkFileDeleteInProgress = false;

    // Call Ingest Service one more time, to 
    // queue the data ingest jobs for asynchronous execution: 
    ingestService.startIngestJobs(dataset, (AuthenticatedUser) session.getUser());

    logger.fine("Redirecting to the Dataset page.");

    return returnToDraftVersion();
}

From source file:org.signserver.admin.cli.defaultimpl.AbstractWSClientsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {/* w  w w .  j a v a  2s .com*/
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    } catch (IllegalCommandArgumentsException e) {
        throw e;
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, getClientsProperty());
        final Set<ClientEntry> entries;

        if (admins != null) {
            entries = ClientEntry.clientEntriesFromProperty(admins);
        } else {
            entries = new HashSet<ClientEntry>();
        }

        if (LIST.equals(operation)) {
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized auditors:");
            buff.append("\n");
            for (ClientEntry entry : entries) {
                buff.append(
                        String.format("%-20s %s", entry.getSerialNumber().toString(16), entry.getIssuerDN()));
                buff.append("\n");
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            final boolean added;

            if (cert == null) {
                // serial number and issuer DN was entered manually
                added = entries.add(new ClientEntry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);

                added = entries.add(new ClientEntry(certificate.getSerialNumber(),
                        SignServerUtil.getTokenizedIssuerDNFromCert(certificate)));
            }

            if (added) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL,
                        getClientsProperty(), ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Auditor added");
            } else {
                getOutputStream().println("Auditor already exists");
            }
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new ClientEntry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL,
                        getClientsProperty(), ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Auditor removed");
            } else {
                getErrorStream().println("No such auditor");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.signserver.admin.cli.defaultimpl.GenerateKeyCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    if (args.length < 1) {
        throw new IllegalCommandArgumentsException("Missing arguments");
    }/*w ww  . j  ava2s.c om*/
    try {
        try {
            // Parse the command line
            parseCommandLine(new GnuParser().parse(OPTIONS, args));
        } catch (ParseException ex) {
            throw new IllegalCommandArgumentsException(ex.getMessage());
        }
        validateOptions();

        int signerId = getWorkerId(args[0]);
        checkThatWorkerIsProcessable(signerId);

        LOG.info("Requesting key generation...");

        String newAlias = getWorkerSession().generateSignerKey(signerId, keyAlg, keySpec, alias, null);

        if (newAlias == null) {
            out.println("Could not generate key");
        } else {
            out.println("Created key : " + newAlias);
        }
        return 0;
    } catch (IllegalCommandArgumentsException ex) {
        throw ex;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            err.println(eJBException.getMessage());
            return -1;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.signserver.admin.cli.defaultimpl.RenewSignerCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {/*from w  w  w.ja  v a2 s  .  c o m*/
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    }
    validateOptions();

    if (args.length < 2) {
        throw new IllegalCommandArgumentsException(USAGE);
    }
    try {

        if (authCode == null) {
            getOutputStream().print("Enter authorization code: ");
            // Read the password, but mask it so we don't display it on the console
            ConsolePasswordReader r = new ConsolePasswordReader();
            authCode = String.valueOf(r.readPassword());
        }

        String workerName = args[0];
        checkThatWorkerIsProcessable(getWorkerId(workerName));

        final Properties requestProperties = new Properties();
        requestProperties.setProperty(RenewalWorkerProperties.REQUEST_WORKER, workerName);
        requestProperties.setProperty(RenewalWorkerProperties.REQUEST_AUTHCODE, String.valueOf(authCode));
        //                    requestProperties.setProperty(
        //                            RenewalWorkerProperties.REQUEST_RENEWKEY,
        //                            RenewalWorkerProperties.REQUEST_RENEWKEY_TRUE);
        final GenericPropertiesRequest request = new GenericPropertiesRequest(requestProperties);

        final GenericPropertiesResponse response = (GenericPropertiesResponse) getWorkerSession()
                .process(getWorkerId(renewalWorker), request, new RequestContext(true));

        final Properties responseProperties = response.getProperties();

        if (RenewalWorkerProperties.RESPONSE_RESULT_OK
                .equals(responseProperties.getProperty(RenewalWorkerProperties.RESPONSE_RESULT))) {
            out.println("Renewed successfully");
            return 0;
        } else {
            err.println("Renewal failed: "
                    + responseProperties.getProperty(RenewalWorkerProperties.RESPONSE_MESSAGE));
            return -2;
        }
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            err.println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (IllegalCommandArgumentsException ex) {
        throw ex;
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.signserver.admin.cli.defaultimpl.WSAdminsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    final CommandLine line;
    try {/*from w  ww.  j  a  v a 2  s. c o  m*/
        // Parse the command line
        line = new GnuParser().parse(OPTIONS, args);
        parseCommandLine(line);
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    } catch (IllegalCommandArgumentsException e) {
        throw e;
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSADMINS");
        final Set<ClientEntry> entries;

        if (admins != null) {
            entries = ClientEntry.clientEntriesFromProperty(admins);
        } else {
            entries = new HashSet<ClientEntry>();
        }

        if (LIST.equals(operation)) {
            final String allowAnyWSAdminProp = getGlobalConfigurationSession().getGlobalConfiguration()
                    .getProperty(GlobalConfiguration.SCOPE_GLOBAL, ALLOWANYWSADMIN);
            final boolean allowAnyWSAdmin = allowAnyWSAdminProp != null
                    ? Boolean.parseBoolean(allowAnyWSAdminProp)
                    : false;
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized administrators:");
            buff.append("\n");

            if (allowAnyWSAdmin) {
                buff.append("ANY CERTIFICATE ACCEPTED FOR WS ADMINISTRATORS");
                buff.append("\n");
                buff.append(
                        "Use the command \"signserver wsadmins -allowany false\" to enable the administrator list");
                buff.append("\n");
            } else {
                for (ClientEntry entry : entries) {
                    buff.append(String.format("%-20s %s", entry.getSerialNumber().toString(16),
                            entry.getIssuerDN()));
                    buff.append("\n");
                }
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            final boolean added;
            if (cert == null) {
                // serial number and issuer DN was entered manually
                added = entries.add(new ClientEntry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);

                added = entries.add(new ClientEntry(certificate.getSerialNumber(),
                        SignServerUtil.getTokenizedIssuerDNFromCert(certificate)));
            }

            if (added) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSADMINS",
                        ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Administrator added");
            } else {
                getOutputStream().println("Administrator already exists");
            }
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new ClientEntry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSADMINS",
                        ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Administrator removed");
            } else {
                getErrorStream().println("No such administrator");
            }
        } else if (ALLOWANY.equals(operation)) {
            boolean allowAny = true;
            final String value = line.getOptionValue(ALLOWANY);

            if (value != null) {
                allowAny = Boolean.parseBoolean(value);
            }

            if (allowAny) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, ALLOWANYWSADMIN,
                        "true");
                getOutputStream().println("Set to allow any WS admin");
            } else {
                getGlobalConfigurationSession().removeProperty(GlobalConfiguration.SCOPE_GLOBAL,
                        ALLOWANYWSADMIN);
                getOutputStream().println("Set to not allow any WS admin");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.signserver.admin.cli.defaultimpl.WSAuditorsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {/*from  www .j  a va  2  s .  c  o  m*/
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS");
        final List<Entry> entries = parseAdmins(admins);

        if (LIST.equals(operation)) {
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized auditors:");
            buff.append("\n");
            for (Entry entry : entries) {
                buff.append(String.format("%-20s %s", entry.getCertSerialNo(), entry.getIssuerDN()));
                buff.append("\n");
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            if (cert == null) {
                // serial number and issuer DN was entered manually
                entries.add(new Entry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);
                String sn = certificate.getSerialNumber().toString(16);
                String dn = certificate.getIssuerX500Principal().getName();

                CertTools.BasicX509NameTokenizer tok = new CertTools.BasicX509NameTokenizer(dn);
                StringBuilder buf = new StringBuilder();

                while (tok.hasMoreTokens()) {
                    final String token = tok.nextToken();
                    buf.append(token);
                    if (tok.hasMoreTokens()) {
                        buf.append(", ");
                    }
                }

                entries.add(new Entry(sn, buf.toString()));
            }
            getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS",
                    serializeAdmins(entries));
            getOutputStream().println("Auditor added");
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new Entry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS",
                        serializeAdmins(entries));
                getOutputStream().println("Auditor removed");
            } else {
                getErrorStream().println("No such auditor");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}