List of usage examples for javax.ejb EJBException EJBException
public EJBException(Exception ex)
From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public Study importHarvestStudy(File xmlFile, Long vdcId, Long userId, String harvestIdentifier) { VDC vdc = em.find(VDC.class, vdcId); em.refresh(vdc); // workaround to get correct value for harvesting dataverse (to be investigated) if (vdc.getHarvestingDataverse() == null) { throw new EJBException("importHarvestStudy(...) should only be called for a harvesting dataverse."); }//from w w w . jav a 2s .c om Study study = doImportStudy(xmlFile, vdc.getHarvestingDataverse().getHarvestFormatType().getId(), vdcId, userId, harvestIdentifier, null); // new create exports files for these studies studyService.exportStudy(study); logger.info("completed importHarvestStudy() returning study" + study.getGlobalId()); return study; }
From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionBean.java
@Override public boolean verifyPassword(AuthenticationToken admin, String username, String password) throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException { if (log.isTraceEnabled()) { log.trace(">verifyPassword(" + username + ", hiddenpwd)"); }/*from w w w . j av a 2 s.com*/ boolean ret = false; // Find user final UserData data = UserData.findByUsername(entityManager, username); if (data == null) { throw new FinderException("Could not find user " + username); } final int caid = data.getCaId(); if (getGlobalConfiguration().getEnableEndEntityProfileLimitations()) { // Check if administrator is authorized to edit user. assertAuthorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AccessRulesConstants.EDIT_END_ENTITY, caid); } assertAuthorizedToCA(admin, caid); try { ret = data.comparePassword(password); } catch (NoSuchAlgorithmException nsae) { log.debug("NoSuchAlgorithmException while verifying password for user " + username); throw new EJBException(nsae); } if (log.isTraceEnabled()) { log.trace("<verifyPassword(" + username + ", hiddenpwd)"); } return ret; }
From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java
private File transformToDDI(File xmlFile, String xslFileName) { File ddiFile = null;// www . j a v a 2 s .com InputStream in = null; OutputStream out = null; try { // prepare source in = new FileInputStream(xmlFile); StreamSource source = new StreamSource(in); // prepare result ddiFile = File.createTempFile("ddi", ".xml"); out = new FileOutputStream(ddiFile); StreamResult result = new StreamResult(out); // now transform StreamSource xslSource = new StreamSource(new File(xslFileName)); Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); throw new EJBException("Error occurred while attempting to transform file: " + ex.getMessage()); } finally { try { if (in != null) { in.close(); } } catch (Exception e) { } try { if (out != null) { out.close(); } } catch (Exception e) { } } return ddiFile; }
From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java
public File transformToDDI(String xml, String xslFileName, String tmpDirPath) { File uploadDir = new File(tmpDirPath); if (!uploadDir.exists()) { if (!uploadDir.mkdirs()) { throw new EJBException("Could not create directory: " + uploadDir.getAbsolutePath()); }/*from w ww . ja v a2 s. co m*/ } String tmpFilePath = tmpDirPath + File.separator + "study.xml"; File tmpFile = new File(tmpFilePath); try { FileUtils.writeStringToFile(tmpFile, xml); } catch (IOException ex) { throw new EJBException("Could not write temporary file"); } finally { uploadDir.delete(); } File ddiFile = transformToDDI(tmpFile, xslFileName); tmpFile.delete(); uploadDir.delete(); return ddiFile; }
From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java
private void copyXMLFile(Study study, File xmlFile, String xmlFileName) { try {//from w w w. j a v a2s .c om // create, if needed, the directory File newDir = FileUtil.getStudyFileDir(study); if (!newDir.exists()) { newDir.mkdirs(); } FileUtil.copyFile(xmlFile, new File(newDir, xmlFileName)); } catch (IOException ex) { ex.printStackTrace(); String msg = "ImportStudy failed: "; if (ex.getMessage() != null) { msg += ex.getMessage(); } EJBException e = new EJBException(msg); e.initCause(ex); throw e; } }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
private void writeFile(File fileIn, String dataIn, int bufSize) { ByteBuffer dataByteBuffer = ByteBuffer.wrap(dataIn.getBytes()); try {/*from w w w .jav a 2 s . co m*/ FileOutputStream outputFile = new FileOutputStream(fileIn, true); WritableByteChannel outChannel = outputFile.getChannel(); try { outChannel.write(dataByteBuffer); outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); } } catch (IOException e) { throw new EJBException(e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void receiveResponse(AuthenticationToken authenticationToken, int caid, ResponseMessage responsemessage, Collection<?> cachain, String nextKeyAlias) throws AuthorizationDeniedException, CertPathValidatorException, EjbcaException, CesecoreException { if (log.isTraceEnabled()) { log.trace(">receiveResponse: " + caid); }/*w w w.jav a2s. c o m*/ if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", Integer.valueOf(caid)); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } try { final CA ca = caSession.getCAForEdit(authenticationToken, caid); if (!(responsemessage instanceof X509ResponseMessage)) { String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg", responsemessage != null ? responsemessage.getClass().getName() : "null"); log.info(msg); throw new EjbcaException(msg); } final Certificate cacert = ((X509ResponseMessage) responsemessage).getCertificate(); // Receiving a certificate for an internal CA will transform it into an externally signed CA if (ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA) { ca.setSignedBy(CAInfo.SIGNEDBYEXTERNALCA); } // Check that CA DN is equal to the certificate response. if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) { String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN(cacert), ca.getSubjectDN()); log.info(msg); throw new EjbcaException(msg); } List<Certificate> tmpchain = new ArrayList<Certificate>(); tmpchain.add(cacert); Collection<Certificate> reqchain = null; if (cachain != null && cachain.size() > 0) { // 1. If we have a chain given as parameter, we will use that. reqchain = CertTools.createCertChain(cachain); log.debug("Using CA certificate chain from parameter of size: " + reqchain.size()); } else { // 2. If no parameter is given we assume that the request chain was stored when the request was created. reqchain = ca.getRequestCertificateChain(); if (reqchain == null) { // 3. Lastly, if that failed we'll check if the certificate chain in it's entirety already exists in the database. reqchain = new ArrayList<Certificate>(); Certificate issuer = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(cacert)); if (issuer != null) { reqchain.add(issuer); while (!CertTools.isSelfSigned(issuer)) { issuer = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(issuer)); if (issuer != null) { reqchain.add(issuer); } else { String msg = intres.getLocalizedMessage("caadmin.errorincompleterequestchain", caid, ca.getSubjectDN()); log.info(msg); throw new CertPathValidatorException(msg); } } } if (reqchain.size() == 0) { String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid, ca.getSubjectDN()); log.info(msg); throw new CertPathValidatorException(msg); } } else { if (log.isDebugEnabled()) { log.debug("Using pre-stored CA certificate chain."); } } } log.debug("Picked up request certificate chain of size: " + reqchain.size()); tmpchain.addAll(reqchain); final List<Certificate> chain = CertTools.createCertChain(tmpchain); log.debug("Storing certificate chain of size: " + chain.size()); // Before importing the certificate we want to make sure that the public key matches the CAs private key PublicKey caCertPublicKey = cacert.getPublicKey(); // If it is a DV certificate signed by a CVCA, enrich the public key for EC parameters from the CVCA's certificate if (StringUtils.equals(cacert.getType(), "CVC")) { if (caCertPublicKey.getAlgorithm().equals("ECDSA")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert; try { if (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate() .getAuthorizationField().getAuthRole().isDV()) { log.debug("Enriching DV public key with EC parameters from CVCA"); Certificate cvcacert = (Certificate) reqchain.iterator().next(); caCertPublicKey = KeyTools.getECPublicKeyWithParams(caCertPublicKey, cvcacert.getPublicKey()); } } catch (InvalidKeySpecException e) { log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...", e); } catch (NoSuchFieldException e) { log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e); } } else { log.debug("Key is not ECDSA, don't try to enrich with EC parameters."); } } else { log.debug("Cert is not CVC, no need to enrich with EC parameters."); } final CAToken catoken = ca.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId()); boolean activatedNextSignKey = false; if (nextKeyAlias != null) { try { if (log.isDebugEnabled()) { log.debug("SubjectKeyId for CA cert public key: " + new String( Hex.encode(KeyTools.createSubjectKeyId(caCertPublicKey).getKeyIdentifier()))); log.debug("SubjectKeyId for CA next public key: " + new String(Hex.encode(KeyTools .createSubjectKeyId(cryptoToken.getPublicKey(nextKeyAlias)).getKeyIdentifier()))); } KeyTools.testKey(cryptoToken.getPrivateKey(nextKeyAlias), caCertPublicKey, cryptoToken.getSignProviderName()); } catch (InvalidKeyException e) { throw new EjbcaException(ErrorCode.INVALID_KEY, e); } catoken.setNextCertSignKey(nextKeyAlias); catoken.activateNextSignKey(); activatedNextSignKey = true; } else { // Since we don't specified the nextSignKey, we will just try the current or next CA sign key try { KeyTools.testKey( cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)), caCertPublicKey, cryptoToken.getSignProviderName()); } catch (Exception e1) { log.debug( "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT..."); if (e1 instanceof InvalidKeyException) { log.trace(e1); } else { // If it's not invalid key, we want to see more of the error log.debug("Error: ", e1); } try { KeyTools.testKey( cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT)), caCertPublicKey, cryptoToken.getSignProviderName()); // This was OK, so we must also activate the next signing key when importing this certificate catoken.activateNextSignKey(); activatedNextSignKey = true; } catch (Exception e2) { log.debug( "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up."); if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) { log.trace(e2); } else { // If it's not invalid key or missing authentication code, we want to see more of the error log.debug("Error: ", e2); } throw new EjbcaException(ErrorCode.INVALID_KEY, e2); } } } if (activatedNextSignKey) { // Activated the next signing key(s) so generate audit log final Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", intres.getLocalizedMessage("catoken.activatednextkey", caid)); details.put("certSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); details.put("crlSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); details.put("sequence", catoken.getKeySequence()); auditSession.log(EventTypes.CA_KEYACTIVATE, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, details); } ca.setCAToken(catoken); ca.setCertificateChain(chain); // Set status to active, so we can sign certificates for the external services below. ca.setStatus(CAConstants.CA_ACTIVE); // activate External CA Services for (int type : ca.getExternalCAServiceTypes()) { try { ca.initExtendedService(cryptoToken, type, ca); final ExtendedCAServiceInfo info = ca.getExtendedCAServiceInfo(type); if (info instanceof BaseSigningCAServiceInfo) { // Publish the extended service certificate, but only for active services if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) { final List<Certificate> extcacertificate = new ArrayList<Certificate>(); extcacertificate.add(((BaseSigningCAServiceInfo) info).getCertificatePath().get(0)); publishCACertificate(authenticationToken, extcacertificate, ca.getCRLPublishers(), ca.getSubjectDN()); } } } catch (Exception fe) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid)); auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); throw new EJBException(fe); } } // Set expire time ca.setExpireTime(CertTools.getNotAfter(cacert)); // Save CA caSession.editCA(authenticationToken, ca, true); // Publish CA Certificate publishCACertificate(authenticationToken, chain, ca.getCRLPublishers(), ca.getSubjectDN()); // Create initial CRL publishingCrlSession.forceCRL(authenticationToken, caid); publishingCrlSession.forceDeltaCRL(authenticationToken, caid); // All OK String detailsMsg = intres.getLocalizedMessage("caadmin.certrespreceived", Integer.valueOf(caid)); auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } catch (CryptoTokenOfflineException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CADoesntExistsException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CertificateEncodingException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (CertificateException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (InvalidAlgorithmParameterException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (NoSuchAlgorithmException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (NoSuchProviderException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } if (log.isTraceEnabled()) { log.trace("<receiveResponse: " + caid); } }
From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void exportStudyToFormat(Study study, String exportFormat) { // only export released studies // TODO: we should clean up the export logic to handle export of versions if (study.getReleasedVersion() == null) { return;// w w w . ja v a 2 s .co m } File studyDir = FileUtil.getStudyFileDir(study); StudyExporter studyExporter = studyExporterFactory.getStudyExporter(exportFormat); String fileName = "export_" + exportFormat; if (studyExporter.isXmlFormat()) { fileName += ".xml"; } File exportFile = new File(studyDir, fileName); OutputStream os = null; try { exportFile.createNewFile(); os = new FileOutputStream(exportFile); studyExporter.exportStudy(study, os); } catch (IOException e) { throw new EJBException(e); } finally { try { if (os != null) { os.close(); } } catch (IOException ex) { } } // study.setLastExportTime(new Date()); }
From source file:io.hops.hopsworks.common.project.ProjectController.java
/** * Adds new team members to a project(project) - bulk persist if team role not * specified or not in (Data owner or Data * scientist)defaults to Data scientist// ww w .java 2s . c o m * * * @param project * @param ownerEmail * @param projectTeams * @return a list of user names that could not be added to the project team * list. */ @TransactionAttribute(TransactionAttributeType.NEVER) public List<String> addMembers(Project project, String ownerEmail, List<ProjectTeam> projectTeams) throws KafkaException, ProjectException, UserException { List<String> failedList = new ArrayList<>(); if (projectTeams == null) { return failedList; } Users owner = userFacade.findByEmail(ownerEmail); Users newMember; for (ProjectTeam projectTeam : projectTeams) { try { if (!projectTeam.getProjectTeamPK().getTeamMember().equals(owner.getEmail())) { //if the role is not properly set set it to the default role (Data Scientist). if (projectTeam.getTeamRole() == null || (!projectTeam.getTeamRole().equals(ProjectRoleTypes.DATA_SCIENTIST.getRole()) && !projectTeam.getTeamRole().equals(ProjectRoleTypes.DATA_OWNER.getRole()))) { projectTeam.setTeamRole(ProjectRoleTypes.DATA_SCIENTIST.getRole()); } projectTeam.setTimestamp(new Date()); newMember = userFacade.findByEmail(projectTeam.getProjectTeamPK().getTeamMember()); if (newMember != null && !projectTeamFacade.isUserMemberOfProject(project, newMember)) { //this makes sure that the member is added to the project sent as the //first param b/c the securty check was made on the parameter sent as path. projectTeam.getProjectTeamPK().setProjectId(project.getId()); projectTeamFacade.persistProjectTeam(projectTeam); hdfsUsersController.addNewProjectMember(project, projectTeam); //Add user to kafka topics ACLs by default if (projectServicesFacade.isServiceEnabledForProject(project, ProjectServiceEnum.KAFKA)) { kafkaController.addProjectMemberToTopics(project, newMember.getEmail()); } // TODO: This should now be a REST call Future<CertificatesController.CertsResult> certsResultFuture = null; try { certsResultFuture = certificatesController.generateCertificates(project, newMember, false); certsResultFuture.get(); if (settings.isPythonKernelEnabled()) { jupyterProcessFacade.createPythonKernelForProjectUser(project, newMember); } } catch (Exception ex) { try { if (certsResultFuture != null) { certsResultFuture.get(); } certificatesController.deleteUserSpecificCertificates(project, newMember); } catch (IOException | InterruptedException | ExecutionException | CAException e) { String failedUser = project.getName() + HdfsUsersController.USER_NAME_DELIMITER + newMember.getUsername(); LOGGER.log(Level.SEVERE, "Could not delete user certificates for user " + failedUser + ". Manual cleanup is needed!!! ", e); } LOGGER.log(Level.SEVERE, "error while creating certificates, jupyter kernel: " + ex.getMessage(), ex); projectTeamFacade.removeProjectTeam(project, newMember); try { hdfsUsersController.removeProjectMember(newMember, project); } catch (IOException ex1) { LOGGER.log(Level.SEVERE, null, ex1); throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_MEMBER_NOT_REMOVED, Level.SEVERE, "user: " + newMember, " project: " + project.getName()); } throw new EJBException("Could not create certificates for user"); } LOGGER.log(Level.FINE, "{0} - member added to project : {1}.", new Object[] { newMember.getEmail(), project.getName() }); logActivity(ActivityFacade.NEW_MEMBER + projectTeam.getProjectTeamPK().getTeamMember(), ActivityFacade.FLAG_PROJECT, owner, project); } else if (newMember == null) { failedList.add( projectTeam.getProjectTeamPK().getTeamMember() + " was not found in the system."); } else { failedList.add(newMember.getEmail() + " is already a member in this project."); } } else { failedList.add(projectTeam.getProjectTeamPK().getTeamMember() + " is already a member in this project."); } } catch (EJBException ejb) { failedList.add( projectTeam.getProjectTeamPK().getTeamMember() + "could not be added. Try again later."); LOGGER.log(Level.SEVERE, "Adding team member {0} to members failed", projectTeam.getProjectTeamPK().getTeamMember()); } } return failedList; }
From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java
/** * Performs the search on the solr server and returns the results */*from w w w . j a v a2s.c o m*/ * * @param userId * @param query * @param luceneQuery * @return a List of FileHeader objects */ public SearchResult search(Long userId, String query, int start, boolean luceneQuery) throws ObjectNotFoundException { if (userId == null) throw new ObjectNotFoundException("No user specified"); if (query == null) throw new ObjectNotFoundException("No query specified"); final int maxRows = getConfiguration().getInt("searchResultsPerPage", 25); List<FileHeader> result = new ArrayList<FileHeader>(); try { CommonsHttpSolrServer solr = new CommonsHttpSolrServer(getConfiguration().getString("solr.url")); List<Group> groups = dao.getGroupsContainingUser(userId); String escapedQuery = luceneQuery ? normalizeSearchQuery(query) : escapeCharacters(normalizeSearchQuery(query)); String constructedQuery = escapedQuery + " AND (public: true OR ureaders: " + userId; if (!groups.isEmpty()) { constructedQuery += " OR ("; for (int i = 0; i < groups.size(); i++) { Group g = groups.get(i); constructedQuery += "greaders :" + g.getId(); if (i < groups.size() - 1) constructedQuery += " OR "; } constructedQuery += ")"; } constructedQuery += ")"; SolrQuery solrQuery = new SolrQuery(constructedQuery); solrQuery.setRows(maxRows); if (start > 0) solrQuery.setStart(start); QueryResponse response = solr.query(solrQuery); SolrDocumentList results = response.getResults(); if (results.getNumFound() > maxRows && start < 0) { solrQuery.setRows(Integer.valueOf((int) results.getNumFound())); response = solr.query(solrQuery); results = response.getResults(); } for (SolrDocument d : results) { Long id = Long.valueOf((String) d.getFieldValue("id")); try { FileHeader f = dao.getEntityById(FileHeader.class, id); result.add(f); } catch (ObjectNotFoundException e) { logger.warn("Search result id " + id + " cannot be found", e); } } return new SearchResult(results.getNumFound(), result); } catch (MalformedURLException e) { logger.error(e); throw new EJBException(e); } catch (SolrServerException e) { logger.error(e); throw new EJBException(e); } }