Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static Certificate pemToCert(Reader r) throws IOException, CertificateException {
    String header = "-----BEGIN CERTIFICATE-----";
    String footer = "-----END CERTIFICATE-----";

    BufferedReader reader = new BufferedReader(r);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);

    String line;//w  w w.j a va2s  .co m

    // ignore up to the header
    while ((line = reader.readLine()) != null && !line.equals(header)) {
    }

    // no header found
    if (line == null) {
        throw new IOException("Error reading certificate, missing BEGIN boundary");
    }

    // in between the header and footer is the actual certificate
    while ((line = reader.readLine()) != null && !line.equals(footer)) {
        line = line.replaceAll("\\s", "");
        ps.print(line);
    }

    // no footer found
    if (line == null) {
        throw new IOException("Error reading certificate, missing END boundary");
    }
    ps.close();

    // decode the buffer to a X509Certificate

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    byte[] certBytes = Base64.decodeBase64(baos.toByteArray());
    return cf.generateCertificate(new ByteArrayInputStream(certBytes));
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

/**
 * Main constructor./*from   www.  j  a va  2 s.  c  o m*/
 * 
 * @param timeStampService
 *            the time-stamp service used for XAdES-T and XAdES-X.
 * @param revocationDataService
 *            the optional revocation data service used for XAdES-C and
 *            XAdES-X-L. When <code>null</code> the signature will be
 *            limited to XAdES-T only.
 * @param digestAlgorithm
 *            the digest algorithm to be used for construction of the
 *            XAdES-X-L elements.
 */
public XAdESXLSignatureFacet(TimeStampService timeStampService, RevocationDataService revocationDataService,
        DigestAlgo digestAlgorithm) {
    this.objectFactory = new ObjectFactory();
    this.c14nAlgoId = CanonicalizationMethod.EXCLUSIVE;
    this.digestAlgorithm = digestAlgorithm;
    this.timeStampService = timeStampService;
    this.revocationDataService = revocationDataService;
    this.xmldsigObjectFactory = new be.fedict.eid.applet.service.signer.jaxb.xmldsig.ObjectFactory();
    this.xades141ObjectFactory = new be.fedict.eid.applet.service.signer.jaxb.xades141.ObjectFactory();

    try {
        JAXBContext context = JAXBContext
                .newInstance(be.fedict.eid.applet.service.signer.jaxb.xades141.ObjectFactory.class);
        this.marshaller = context.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new XAdESNamespacePrefixMapper());
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 JCA error: " + e.getMessage(), e);
    }

    try {
        this.datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("datatype config error: " + e.getMessage(), e);
    }
}

From source file:org.browsermob.proxy.jetty.http.ajp.AJP13Connection.java

public boolean handleNext() {
    AJP13RequestPacket packet = null;//  w ww  .  j av a 2 s  .  co  m
    HttpRequest request = getRequest();
    HttpResponse response = getResponse();
    HttpContext context = null;
    boolean gotRequest = false;
    _persistent = true;
    _keepAlive = true;

    try {
        try {
            packet = null;
            packet = _ajpIn.nextPacket();
            if (packet == null)
                return false;
            if (packet.getDataSize() == 0)
                return true;
        } catch (IOException e) {
            LogSupport.ignore(log, e);
            return false;
        }

        int type = packet.getByte();
        if (log.isDebugEnabled())
            log.debug("AJP13 type=" + type + " size=" + packet.unconsumedData());

        switch (type) {
        case AJP13Packet.__FORWARD_REQUEST:
            request.setTimeStamp(System.currentTimeMillis());

            request.setState(HttpMessage.__MSG_EDITABLE);
            request.setMethod(packet.getMethod());
            request.setVersion(packet.getString());
            String version = packet.getString();
            try {
                request.setVersion(version);
            } catch (Exception e) {
                log.warn("Bad version" + version, e);
                log.warn(packet.toString());
            }

            String path = packet.getString();
            int sc = path.lastIndexOf(";");
            if (sc < 0)
                request.setPath(URI.encodePath(path));
            else
                request.setPath(URI.encodePath(path.substring(0, sc)) + path.substring(sc));

            _remoteAddr = packet.getString();
            _remoteHost = packet.getString();
            _serverName = packet.getString();
            _serverPort = packet.getInt();
            _isSSL = packet.getBoolean();

            // Check keep alive
            _keepAlive = request.getDotVersion() >= 1;

            // Headers
            int h = packet.getInt();
            for (int i = 0; i < h; i++) {
                String hdr = packet.getHeader();
                String val = packet.getString();
                request.addField(hdr, val);
                if (!_keepAlive && hdr.equalsIgnoreCase(HttpFields.__Connection)
                        && val.equalsIgnoreCase(HttpFields.__KeepAlive))
                    _keepAlive = true;
            }

            // Handler other attributes
            byte attr = packet.getByte();
            while ((0xFF & attr) != 0xFF) {
                String value = (attr == 11) ? null : packet.getString();
                switch (attr) {
                case 11: // key size
                    request.setAttribute("javax.servlet.request.key_size", new Integer(packet.getInt()));
                    break;
                case 10: // request attribute
                    request.setAttribute(value, packet.getString());
                    break;
                case 9: // SSL session
                    request.setAttribute("javax.servlet.request.ssl_session", value);
                    break;
                case 8: // SSL cipher
                    request.setAttribute("javax.servlet.request.cipher_suite", value);
                    break;
                case 7: // SSL cert
                    // request.setAttribute("javax.servlet.request.X509Certificate",value);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream certstream = new ByteArrayInputStream(value.getBytes());
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(certstream);
                    X509Certificate certs[] = { cert };
                    request.setAttribute("javax.servlet.request.X509Certificate", certs);
                    break;
                case 6: // JVM Route
                    request.setAttribute("org.browsermob.proxy.jetty.http.ajp.JVMRoute", value);
                    break;
                case 5: // Query String
                    request.setQuery(value);
                    break;
                case 4: // AuthType
                    request.setAuthType(value);
                    break;
                case 3: // Remote User
                    request.setAuthUser(value);
                    break;

                case 2: // servlet path not implemented
                case 1: // _context not implemented
                default:
                    log.warn("Unknown attr: " + attr + "=" + value);
                }

                attr = packet.getByte();
            }

            _listener.customizeRequest(this, request);

            gotRequest = true;
            statsRequestStart();
            request.setState(HttpMessage.__MSG_RECEIVED);

            // Complete response
            if (request.getContentLength() == 0 && request.getField(HttpFields.__TransferEncoding) == null)
                _ajpIn.close();

            // Prepare response
            response.setState(HttpMessage.__MSG_EDITABLE);
            response.setVersion(HttpMessage.__HTTP_1_1);
            response.setDateField(HttpFields.__Date, _request.getTimeStamp());
            if (!Version.isParanoid())
                response.setField(HttpFields.__Server, Version.getDetail());

            // Service request
            if (log.isDebugEnabled())
                log.debug("REQUEST:\n" + request);
            context = service(request, response);
            if (log.isDebugEnabled())
                log.debug("RESPONSE:\n" + response);

            break;

        default:
            if (log.isDebugEnabled())
                log.debug("Ignored: " + packet);
            _persistent = false;
        }

    } catch (SocketException e) {
        LogSupport.ignore(log, e);
        _persistent = false;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        _persistent = false;
        try {
            if (gotRequest)
                _ajpOut.close();
        } catch (IOException e2) {
            LogSupport.ignore(log, e2);
        }
    } finally {
        // abort if nothing received.
        if (packet == null || !gotRequest)
            return false;

        // flush and end the output
        try {
            // Consume unread input.
            // while(_ajpIn.skip(4096)>0 || _ajpIn.read()>=0);

            // end response
            getOutputStream().close();
            if (!_persistent)
                _ajpOut.end();

            // Close the outout
            _ajpOut.close();

            // reset streams
            getOutputStream().resetStream();
            getOutputStream().addObserver(this);
            getInputStream().resetStream();
            _ajpIn.resetStream();
            _ajpOut.resetStream();
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            _persistent = false;
        } finally {
            statsRequestEnd();
            if (context != null)
                context.log(request, response, -1);
        }
    }
    return _persistent;
}

From source file:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Connection.java

public boolean handleNext() {
    AJP13RequestPacket packet = null;// w ww  .  ja v a  2s. c  o m
    HttpRequest request = getRequest();
    HttpResponse response = getResponse();
    HttpContext context = null;
    boolean gotRequest = false;
    _persistent = true;
    _keepAlive = true;

    try {
        try {
            packet = null;
            packet = _ajpIn.nextPacket();
            if (packet == null)
                return false;
            if (packet.getDataSize() == 0)
                return true;
        } catch (IOException e) {
            LogSupport.ignore(log, e);
            return false;
        }

        int type = packet.getByte();
        if (log.isDebugEnabled())
            log.debug("AJP13 type=" + type + " size=" + packet.unconsumedData());

        switch (type) {
        case AJP13Packet.__FORWARD_REQUEST:
            request.setTimeStamp(System.currentTimeMillis());

            request.setState(HttpMessage.__MSG_EDITABLE);
            request.setMethod(packet.getMethod());
            request.setVersion(packet.getString());
            String version = packet.getString();
            try {
                request.setVersion(version);
            } catch (Exception e) {
                log.warn("Bad version" + version, e);
                log.warn(packet.toString());
            }

            String path = packet.getString();
            int sc = path.lastIndexOf(";");
            if (sc < 0)
                request.setPath(URI.encodePath(path));
            else
                request.setPath(URI.encodePath(path.substring(0, sc)) + path.substring(sc));

            _remoteAddr = packet.getString();
            _remoteHost = packet.getString();
            _serverName = packet.getString();
            _serverPort = packet.getInt();
            _isSSL = packet.getBoolean();

            // Check keep alive
            _keepAlive = request.getDotVersion() >= 1;

            // Headers
            int h = packet.getInt();
            for (int i = 0; i < h; i++) {
                String hdr = packet.getHeader();
                String val = packet.getString();
                request.addField(hdr, val);
                if (!_keepAlive && hdr.equalsIgnoreCase(HttpFields.__Connection)
                        && val.equalsIgnoreCase(HttpFields.__KeepAlive))
                    _keepAlive = true;
            }

            // Handler other attributes
            byte attr = packet.getByte();
            while ((0xFF & attr) != 0xFF) {
                String value = (attr == 11) ? null : packet.getString();
                switch (attr) {
                case 11: // key size
                    request.setAttribute("javax.servlet.request.key_size", new Integer(packet.getInt()));
                    break;
                case 10: // request attribute
                    request.setAttribute(value, packet.getString());
                    break;
                case 9: // SSL session
                    request.setAttribute("javax.servlet.request.ssl_session", value);
                    break;
                case 8: // SSL cipher
                    request.setAttribute("javax.servlet.request.cipher_suite", value);
                    break;
                case 7: // SSL cert
                    // request.setAttribute("javax.servlet.request.X509Certificate",value);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream certstream = new ByteArrayInputStream(value.getBytes());
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(certstream);
                    X509Certificate certs[] = { cert };
                    request.setAttribute("javax.servlet.request.X509Certificate", certs);
                    break;
                case 6: // JVM Route
                    request.setAttribute("net.lightbody.bmp.proxy.jetty.http.ajp.JVMRoute", value);
                    break;
                case 5: // Query String
                    request.setQuery(value);
                    break;
                case 4: // AuthType
                    request.setAuthType(value);
                    break;
                case 3: // Remote User
                    request.setAuthUser(value);
                    break;

                case 2: // servlet path not implemented
                case 1: // _context not implemented
                default:
                    log.warn("Unknown attr: " + attr + "=" + value);
                }

                attr = packet.getByte();
            }

            _listener.customizeRequest(this, request);

            gotRequest = true;
            statsRequestStart();
            request.setState(HttpMessage.__MSG_RECEIVED);

            // Complete response
            if (request.getContentLength() == 0 && request.getField(HttpFields.__TransferEncoding) == null)
                _ajpIn.close();

            // Prepare response
            response.setState(HttpMessage.__MSG_EDITABLE);
            response.setVersion(HttpMessage.__HTTP_1_1);
            response.setDateField(HttpFields.__Date, _request.getTimeStamp());
            if (!Version.isParanoid())
                response.setField(HttpFields.__Server, Version.getDetail());

            // Service request
            if (log.isDebugEnabled())
                log.debug("REQUEST:\n" + request);
            context = service(request, response);
            if (log.isDebugEnabled())
                log.debug("RESPONSE:\n" + response);

            break;

        default:
            if (log.isDebugEnabled())
                log.debug("Ignored: " + packet);
            _persistent = false;
        }

    } catch (SocketException e) {
        LogSupport.ignore(log, e);
        _persistent = false;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        _persistent = false;
        try {
            if (gotRequest)
                _ajpOut.close();
        } catch (IOException e2) {
            LogSupport.ignore(log, e2);
        }
    } finally {
        // abort if nothing received.
        if (packet == null || !gotRequest)
            return false;

        // flush and end the output
        try {
            // Consume unread input.
            // while(_ajpIn.skip(4096)>0 || _ajpIn.read()>=0);

            // end response
            getOutputStream().close();
            if (!_persistent)
                _ajpOut.end();

            // Close the outout
            _ajpOut.close();

            // reset streams
            getOutputStream().resetStream();
            getOutputStream().addObserver(this);
            getInputStream().resetStream();
            _ajpIn.resetStream();
            _ajpOut.resetStream();
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            _persistent = false;
        } finally {
            statsRequestEnd();
            if (context != null)
                context.log(request, response, -1);
        }
    }
    return _persistent;
}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

/**
 * Validates the specified certificate path incl. OCSP revocation check
 * /*from   ww  w . j a  va  2  s .  co m*/
 * @param truststore
 * @return true if all certificate is valid
 * @throws Exception 
 */
private boolean isCertValid(KeyStore truststore) throws Exception {
    List<X509Certificate> certlist = new ArrayList<X509Certificate>();
    certlist.add(signerCert);

    PKIXParameters params = new PKIXParameters(truststore);

    // Activate certificate revocation checking
    params.setRevocationEnabled(true);

    // Activate OCSP
    Security.setProperty("ocsp.enable", "true");

    // Activate CRLDP
    System.setProperty("com.sun.security.enableCRLDP", "true");

    // Ensure that the ocsp.responderURL property is not set.
    if (Security.getProperty("ocsp.responderURL") != null) {
        throw new Exception("The ocsp.responderURL property must not be set");
    }

    CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType());

    cpv.validate(CertificateFactory.getInstance("X.509").generateCertPath(certlist), params);

    return true; // No Exception, all fine..
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

private KeyStore createKeyStore(KeyPair keyPair, HttpResponse response) throws Exception {
    Log.i("registration", "Got status from registration server: " + response.getStatusLine());

    HttpEntity entity = response.getEntity();
    byte[] contents = getBytes(entity.getContent());
    Collection<?> certs = extractCerts(contents);
    Certificate[] certificates = new Certificate[certs.size()];
    Log.i("registration", "Extracted out " + certs.size() + " certs");

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    Iterator<?> it = certs.iterator();
    int i = 0;//from   www  .  j ava2s  .c o  m
    while (it.hasNext()) {
        byte[] encoded = ((X509CertificateHolder) it.next()).getEncoded();
        certificates[i++] = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(encoded));
    }

    Log.d("registration", "Creating local keystore");
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setKeyEntry("Cert", keyPair.getPrivate(), "changeit".toCharArray(), certificates);

    return keyStore;
}

From source file:eu.eidas.auth.engine.core.impl.SignP12.java

/**
 * Validate signature./*from   w ww . j  a  va  2  s. com*/
 * 
 * @param tokenSaml token SAML
 * 
 * @return the SAMLObject validated.
 * 
 * @throws SAMLEngineException error validate signature
 * 
 */
public SAMLObject validateSignature(final SignableSAMLObject tokenSaml, String messageFormat)
        throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        validateProfileSignature(tokenSaml);

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) trustStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        // Validate trust certificates
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();
        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate it is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        LOG.info("Key algorithm {}",
                SecurityHelper.getKeyAlgorithmFromURI(tokenSaml.getSignature().getSignatureAlgorithm()));
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.info("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    return tokenSaml;
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

private X509Certificate getCertificate(String certificate) {
    if (certificate.isEmpty()) {
        return null;
    }/*  www  .ja v a 2 s. co m*/

    if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) {
        final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE)
                + KeyStoreConstant.BEGIN_CERTIFICATE.length();
        final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE);
        certificate = certificate.substring(fIdx, sIdx);
    }
    final byte[] byteCert = Base64.decodeBase64(certificate);
    final InputStream inputStreamCert = new ByteArrayInputStream(byteCert);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert);
        newCert.checkValidity();
        return newCert;
    } catch (final CertificateException e) {
        LOG.error("Failed to get certificate {}", e.getMessage());
        return null;
    }
}

From source file:org.openqa.jetty.http.ajp.AJP13Connection.java

public boolean handleNext() {
    AJP13RequestPacket packet = null;//from  www  .j a va  2 s.  co  m
    HttpRequest request = getRequest();
    HttpResponse response = getResponse();
    HttpContext context = null;
    boolean gotRequest = false;
    _persistent = true;
    _keepAlive = true;

    try {
        try {
            packet = null;
            packet = _ajpIn.nextPacket();
            if (packet == null)
                return false;
            if (packet.getDataSize() == 0)
                return true;
        } catch (IOException e) {
            LogSupport.ignore(log, e);
            return false;
        }

        int type = packet.getByte();
        if (log.isDebugEnabled())
            log.debug("AJP13 type=" + type + " size=" + packet.unconsumedData());

        switch (type) {
        case AJP13Packet.__FORWARD_REQUEST:
            request.setTimeStamp(System.currentTimeMillis());

            request.setState(HttpMessage.__MSG_EDITABLE);
            request.setMethod(packet.getMethod());
            request.setVersion(packet.getString());
            String version = packet.getString();
            try {
                request.setVersion(version);
            } catch (Exception e) {
                log.warn("Bad version" + version, e);
                log.warn(packet.toString());
            }

            String path = packet.getString();
            int sc = path.lastIndexOf(";");
            if (sc < 0)
                request.setPath(URI.encodePath(path));
            else
                request.setPath(URI.encodePath(path.substring(0, sc)) + path.substring(sc));

            _remoteAddr = packet.getString();
            _remoteHost = packet.getString();
            _serverName = packet.getString();
            _serverPort = packet.getInt();
            _isSSL = packet.getBoolean();

            // Check keep alive
            _keepAlive = request.getDotVersion() >= 1;

            // Headers
            int h = packet.getInt();
            for (int i = 0; i < h; i++) {
                String hdr = packet.getHeader();
                String val = packet.getString();
                request.addField(hdr, val);
                if (!_keepAlive && hdr.equalsIgnoreCase(HttpFields.__Connection)
                        && val.equalsIgnoreCase(HttpFields.__KeepAlive))
                    _keepAlive = true;
            }

            // RestishHandler other attributes
            byte attr = packet.getByte();
            while ((0xFF & attr) != 0xFF) {
                String value = (attr == 11) ? null : packet.getString();
                switch (attr) {
                case 11: // key size
                    request.setAttribute("javax.servlet.request.key_size", new Integer(packet.getInt()));
                    break;
                case 10: // request attribute
                    request.setAttribute(value, packet.getString());
                    break;
                case 9: // SSL session
                    request.setAttribute("javax.servlet.request.ssl_session", value);
                    break;
                case 8: // SSL cipher
                    request.setAttribute("javax.servlet.request.cipher_suite", value);
                    break;
                case 7: // SSL cert
                    // request.setAttribute("javax.servlet.request.X509Certificate",value);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream certstream = new ByteArrayInputStream(value.getBytes());
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(certstream);
                    X509Certificate certs[] = { cert };
                    request.setAttribute("javax.servlet.request.X509Certificate", certs);
                    break;
                case 6: // JVM Route
                    request.setAttribute("org.openqa.jetty.http.ajp.JVMRoute", value);
                    break;
                case 5: // Query String
                    request.setQuery(value);
                    break;
                case 4: // AuthType
                    request.setAuthType(value);
                    break;
                case 3: // Remote User
                    request.setAuthUser(value);
                    break;

                case 2: // servlet path not implemented
                case 1: // _context not implemented
                default:
                    log.warn("Unknown attr: " + attr + "=" + value);
                }

                attr = packet.getByte();
            }

            _listener.customizeRequest(this, request);

            gotRequest = true;
            statsRequestStart();
            request.setState(HttpMessage.__MSG_RECEIVED);

            // Complete response
            if (request.getContentLength() == 0 && request.getField(HttpFields.__TransferEncoding) == null)
                _ajpIn.close();

            // Prepare response
            response.setState(HttpMessage.__MSG_EDITABLE);
            response.setVersion(HttpMessage.__HTTP_1_1);
            response.setDateField(HttpFields.__Date, _request.getTimeStamp());
            if (!Version.isParanoid())
                response.setField(HttpFields.__Server, Version.getDetail());

            // Service request
            if (log.isDebugEnabled())
                log.debug("REQUEST:\n" + request);
            context = service(request, response);
            if (log.isDebugEnabled())
                log.debug("RESPONSE:\n" + response);

            break;

        default:
            if (log.isDebugEnabled())
                log.debug("Ignored: " + packet);
            _persistent = false;
        }

    } catch (SocketException e) {
        LogSupport.ignore(log, e);
        _persistent = false;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        _persistent = false;
        try {
            if (gotRequest)
                _ajpOut.close();
        } catch (IOException e2) {
            LogSupport.ignore(log, e2);
        }
    } finally {
        // abort if nothing received.
        if (packet == null || !gotRequest)
            return false;

        // flush and end the output
        try {
            // Consume unread input.
            // while(_ajpIn.skip(4096)>0 || _ajpIn.read()>=0);

            // end response
            getOutputStream().close();
            if (!_persistent)
                _ajpOut.end();

            // Close the outout
            _ajpOut.close();

            // reset streams
            getOutputStream().resetStream();
            getOutputStream().addObserver(this);
            getInputStream().resetStream();
            _ajpIn.resetStream();
            _ajpOut.resetStream();
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            _persistent = false;
        } finally {
            statsRequestEnd();
            if (context != null)
                context.log(request, response, -1);
        }
    }
    return _persistent;
}

From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

/**
 * Adds a certificate to the KeyStore.//from  www  . j  av a  2  s .c  o m
 * 
 * @param alias
 *            alias for the certificate
 * @param certificate
 *            inputstream delivering the certificate. Stream is used by
 *            {@link CertificateFactory#generateCertificate(InputStream)}.
 * @throws InvalidCertificateException
 *             certificate cannot be found, accessed or identified
 * @throws CertificateStoreException
 *             is thrown when problems occur with the CertificateStore, i.e.
 *             illegal operations
 */
public void addCertificate(String alias, InputStream certificate)
        throws InvalidCertificateException, CertificateStoreException {
    if (!isDefaultCertificate(alias)) {
        loadKeyStore();
        try {
            CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
            Certificate newCertificate = factory.generateCertificate(certificate);
            keyStore.setCertificateEntry(alias, newCertificate);
            storeKeyStore();
        } catch (CertificateException e) {
            String message = "Please choose a valid certificate!";
            throw new InvalidCertificateException(message);
        } catch (KeyStoreException e) {
            String message = "Storing certificate failed!";
            WorkspaceUtil.logException(message, e);
            throw new CertificateStoreException(message, e);
        }
    }
}