Example usage for javax.xml.registry JAXRException JAXRException

List of usage examples for javax.xml.registry JAXRException JAXRException

Introduction

In this page you can find the example usage for javax.xml.registry JAXRException JAXRException.

Prototype

public JAXRException(String reason, Throwable cause) 

Source Link

Document

Constructs a JAXRException object with the given String as the reason for the exception being thrown and the given Throwable object as an embedded Throwable.

Usage

From source file:it.cnr.icar.eric.common.soap.SOAPSender.java

/**
 *
 * Creates a SOAPMessage with bodyDoc as only child.
 */// w  w w  . j a v  a2  s.  com
public SOAPMessage createSOAPMessage(Document bodyDoc) throws JAXRException {
    SOAPMessage msg = null;

    try {
        MessageFactory factory = MessageFactory.newInstance();
        msg = factory.createMessage();
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        //SOAPHeader sh = se.getHeader(); 
        SOAPBody sb = se.getBody();

        sb.addDocument(bodyDoc);
        msg.saveChanges();
    } catch (SOAPException e) {
        e.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.URLNotFound"), e);
    }
    return msg;
}

From source file:it.cnr.icar.eric.common.security.X509Parser.java

/**
 * Parses a X509Certificate from a DER formatted input stream. Uses the 
 * BouncyCastle provider if available.//  w  w  w  .ja va 2s.c o m
 *
 * @param inStream The DER InputStream with the certificate.
 * @return X509Certificate parsed from stream.
 * @throws JAXRException in case of IOException or CertificateException
 *  while parsing the stream.
 */
public static X509Certificate parseX509Certificate(InputStream inStream) throws JAXRException {
    try {
        //possible options
        // - der x509 generated by keytool -export
        // - der x509 generated by openssh x509 (might require BC provider)

        // Get the CertificateFactory to parse the stream
        // if BouncyCastle provider available, use it
        CertificateFactory cf;
        try {
            Class<?> clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            Constructor<?> constructor = clazz.getConstructor(new Class[] {});
            Provider bcProvider = (Provider) constructor.newInstance(new Object[] {});
            Security.addProvider(bcProvider);
            cf = CertificateFactory.getInstance("X.509", "BC");
        } catch (Exception e) {
            // log error if bc present but failed to instanciate/add provider
            if (!(e instanceof ClassNotFoundException)) {
                log.error(CommonResourceBundle.getInstance()
                        .getString("message.FailedToInstantiateBouncyCastleProvider"));
            }
            // fall back to default provider
            cf = CertificateFactory.getInstance("X.509");
        }

        // Read the stream to a local variable
        DataInputStream dis = new DataInputStream(inStream);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream certStream = new ByteArrayInputStream(bytes);

        // Parse the cert stream
        int i = 0;
        Collection<? extends Certificate> c = cf.generateCertificates(certStream);
        X509Certificate[] certs = new X509Certificate[c.toArray().length];
        for (Iterator<? extends Certificate> it = c.iterator(); it.hasNext();) {
            certs[i++] = (X509Certificate) it.next();
        }

        // Some logging..
        if (log.isDebugEnabled()) {
            if (c.size() == 1) {
                log.debug("One certificate, no chain.");
            } else {
                log.debug("Certificate chain length: " + c.size());
            }
            log.debug("Subject DN: " + certs[0].getSubjectDN().getName());
            log.debug("Issuer DN: " + certs[0].getIssuerDN().getName());
        }

        // Do we need to return the chain?
        // do we need to verify if cert is self signed / valid?
        return certs[0];
    } catch (CertificateException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } catch (IOException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            inStream = null;
        }
    }
}

From source file:it.cnr.icar.eric.client.ui.swing.registration.UserManager.java

/** First check if certificate already exists in client keystore. If it does,
  * use it. If not then create a self signed certificate for the user and use it to
  * authenticate with the ebxmlrr server.
  * If the authentication is sucessful, save the user model to the server.
  */*from w w  w.  ja  v  a2s  .c  o m*/
  * @throw Exception
  *     An exception could indicate either a communications problem or an
  *     authentication error.
  */
public static void authenticateAndSaveUser(UserModel userModel) throws Exception {
    @SuppressWarnings("unused")
    boolean generatedCert = false;
    UserRegistrationInfo userRegInfo = userModel.getUserRegistrationInfo();
    try {
        JAXRClient client = RegistryBrowser.getInstance().getClient();
        BusinessLifeCycleManager lcm = client.getBusinessLifeCycleManager();
        RegistryServiceImpl rs = (RegistryServiceImpl) lcm.getRegistryService();
        ConnectionImpl connection = rs.getConnection();

        if (!userRegInfo.isCAIssuedCert()) {
            if (!CertificateUtil.certificateExists(userRegInfo.getAlias(), userRegInfo.getStorePassword())) {
                CertificateUtil.generateRegistryIssuedCertificate(userRegInfo);
            }
        } else {
            try {
                CertificateUtil.importCAIssuedCert(userRegInfo);
            } catch (Exception e) {
                throw new JAXRException(
                        JavaUIResourceBundle.getInstance().getString("error.importCertificateFailed"), e);
            }
        }

        // Force re-authentication in case credentials are already set
        connection.authenticate();

        RegistryBrowser.setWaitCursor();

        // Now save the User
        ArrayList<User> objects = new ArrayList<User>();
        objects.add(userModel.getUser());
        client.saveObjects(objects, false, false);

        // saveObjects uses XML-Security which overwrites the log4j
        // configuration and we never get to see this:
        log.info(JavaUIResourceBundle.getInstance().getString("message.SavedUserOnServer",
                new Object[] { ((PersonNameImpl) (userModel.getUser().getPersonName())).getFormattedName() }));
    } catch (Exception e) {
        // Remove the self-signed certificate from the keystore, if one
        // was created during the self-registration process
        try {
            if (userRegInfo != null) {
                String alias = userRegInfo.getAlias();

                if ((alias != null) && (!userRegInfo.isCAIssuedCert())) {
                    CertificateUtil.removeCertificate(alias, userRegInfo.getStorePassword());
                }
            }
        } catch (Exception removeCertException) {
            log.warn(
                    JavaUIResourceBundle.getInstance()
                            .getString("message.FailedToRemoveTheCertificateFromTheKeystoreGenerated"),
                    removeCertException);
        }

        throw e;
    } finally {
        RegistryBrowser.setDefaultCursor();
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

/**
 * Generate a self signed certificate and store it in the keystore.
 * /*  w  w w  .  jav  a2 s  .  co  m*/
 * @param userRegInfo
 * @throws JAXRException
 */
public static void generateRegistryIssuedCertificate(UserRegistrationInfo userRegInfo) throws JAXRException {
    User user = userRegInfo.getUser();
    LifeCycleManager lcm = user.getLifeCycleManager();
    String dname = getDNameFromUser(userRegInfo);
    File keystoreFile = KeystoreUtil.getKeystoreFile();
    KeystoreUtil.createKeystoreDirectory(keystoreFile);
    String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype", "JKS");
    String storePassStr = new String(userRegInfo.getStorePassword());
    String keyPassStr = new String(userRegInfo.getKeyPassword());
    String alias = userRegInfo.getAlias();
    String keyAlg = "RSA"; // XWSS does not support DSA which is default is
    // KeyTool. Hmm. Weird.

    String[] args = { "-genkey", "-keyAlg", keyAlg, "-alias", alias, "-keypass", keyPassStr, "-keystore",
            keystoreFile.getAbsolutePath(), "-storepass", storePassStr, "-storetype", keystoreType, "-dname",
            dname };

    try {
        KeyTool keytool = new KeyTool();
        keytool.run(args, System.out);

        // Now load the KeyStore and get the cert
        FileInputStream fis = new FileInputStream(keystoreFile);

        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(fis, storePassStr.toCharArray());
        fis.close();

        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        Certificate[] certChain = getCertificateSignedByRegistry(lcm, cert);
        Key key = keyStore.getKey(alias, userRegInfo.getKeyPassword());

        // Now overwrite original cert with signed cert
        keyStore.deleteEntry(alias);

        // keyStore.setCertificateEntry(alias, cert);
        keyStore.setKeyEntry(alias, key, userRegInfo.getKeyPassword(), certChain);
        FileOutputStream fos = new java.io.FileOutputStream(keystoreFile);
        keyStore.store(fos, storePassStr.toCharArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertGenFailed"), e);
    }

    log.debug(JAXRResourceBundle.getInstance().getString("message.StoredUserInKeyStore",
            new Object[] { alias, keystoreFile.getAbsolutePath() }));

    try {
        // Export registry issued cert to certFile so it can be available
        // for import into a web browser for SSL access to registry
        exportRegistryIssuedCert(userRegInfo);
    } catch (Exception e) {
        String msg = JAXRResourceBundle.getInstance().getString(
                "message.UnableToExportCertificateSeeNextExceptionNoteThatThisFeatureRequiresUseOfJDK5");
        log.warn(msg, e);
        // Do not throw exception as user reg can be done despite not
        // exporting the p12 file for the web browser.
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.ExtrinsicObjectImpl.java

public void removeRepositoryItem() throws javax.xml.registry.JAXRException {
    //TODO: mark object as dirty and remove RepositoryItem only on save
    // For now, removin repositoryItem from server immediatelly!
    BulkResponse resp = lcm.deleteObjects(Collections.singletonList(getKey()), null,
            BindingUtility.CANONICAL_DELETION_SCOPE_TYPE_ID_DeleteRepositoryItemOnly);
    if (BulkResponse.STATUS_SUCCESS == resp.getStatus()) {
        // This should be defined in JAXR 2.0 spec
        this.mimeType = null;
        this.repositoryItem = null;
    } else {/*from  w  w w .j a va  2 s . c om*/
        Exception e = (Exception) resp.getExceptions().iterator().next();
        throw new JAXRException(i18nUtil.getString("repositoryitem.removefailed", new String[] { getId() }), e);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

public static void importCAIssuedCert(UserRegistrationInfo userRegInfo) throws JAXRException {
    try {//from w  w  w.  j a  v  a  2  s  .  c  o m
        String storePassStr = new String(userRegInfo.getStorePassword());
        String keyPassStr = new String(userRegInfo.getKeyPassword());
        File keystoreFile = KeystoreUtil.getKeystoreFile();
        String alias = userRegInfo.getAlias();

        // Import CA issued cert to certFile into client keystore
        KeystoreMover ksm = new KeystoreMover();
        ksm.move("PKCS12", userRegInfo.getP12File(), keyPassStr, null, keyPassStr, "JKS",
                keystoreFile.getAbsolutePath(), storePassStr, alias, keyPassStr);
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.ImportCAIssuedCertFailed"),
                e);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

public static void exportRegistryIssuedCert(UserRegistrationInfo userRegInfo) throws JAXRException {
    try {/*  w w w . ja v  a2s .  c  o m*/
        String storePassStr = new String(userRegInfo.getStorePassword());
        String keyPassStr = new String(userRegInfo.getKeyPassword());
        File keystoreFile = KeystoreUtil.getKeystoreFile();
        String alias = userRegInfo.getAlias();

        // Delete existing p12 file if any otherwise new cert will not be
        // written
        File p12File = new File(userRegInfo.getP12File());
        if (p12File.exists()) {
            p12File.delete();
        }

        // Export registry issued cert to certFile so it can be available
        // for import into a web browser for SSL access to registry
        KeystoreMover ksm = new KeystoreMover();

        // xxx pa 120217
        // exported *.p12 filename is not allowed to have colons inside.
        // fixed replace statement
        ksm.move("JKS", keystoreFile.getAbsolutePath(), storePassStr, alias, keyPassStr, "PKCS12",
                userRegInfo.getP12File().replace("urn:uuid:", ""), keyPassStr, alias, keyPassStr);
    } catch (Exception e) {
        e.printStackTrace();

        throw new JAXRException(
                JAXRResourceBundle.getInstance().getString("message.ExportRegistryIssuedCertFailed"), e);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

/**
 * Remove an alias from the keystore.//  w ww .  j  a  v  a  2 s .  c o m
 * <p>
 * Currently, this is only used to "backout" a generated key when self
 * registration fails.
 */
public static void removeCertificate(String alias, char[] storePass) throws JAXRException {

    try {
        File keystoreFile = KeystoreUtil.getKeystoreFile();
        String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype",
                "JKS");

        String[] args = { "-delete", "-alias", alias, "-keystore", keystoreFile.getAbsolutePath(), "-storepass",
                new String(storePass), "-storetype", keystoreType, "-validity", "365" };
        KeyTool keytool = new KeyTool();
        keytool.run(args, System.out);
        log.debug(JAXRResourceBundle.getInstance().getString("message.RemovedUserFromKeyStore",
                new Object[] { alias, keystoreFile.getAbsolutePath() }));
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.RemoveCertFailed"), e);
    }
}

From source file:it.cnr.icar.eric.common.BindingUtility.java

/**
 * Gets the binding object representing the request from specufied XML file.
 *//*from w  ww  .java2 s. c o  m*/
public Object getRequestObject(File file) throws JAXRException {
    Object req = null;

    try {
        Unmarshaller unmarshaller = getUnmarshaller();
        req = unmarshaller.unmarshal(file);
    } catch (JAXBException e) {
        e.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.unmarshallRequest"), e);
    }

    return req;
}

From source file:it.cnr.icar.eric.common.BindingUtility.java

public Object getRequestObject(String rootElement, String message) throws JAXRException {
    //TODO: Consider removing String rootElement. Currently not used.
    Object req = null;//from   www .j  a va  2  s . co  m

    try {
        StreamSource ss = new StreamSource(new StringReader(message));
        Unmarshaller unmarshaller = getUnmarshaller();
        req = unmarshaller.unmarshal(ss);
    } catch (JAXBException e) {
        e.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.unmarshallRequest"), e);
    }

    return req;
}