Example usage for java.security InvalidParameterException InvalidParameterException

List of usage examples for java.security InvalidParameterException InvalidParameterException

Introduction

In this page you can find the example usage for java.security InvalidParameterException InvalidParameterException.

Prototype

public InvalidParameterException(String msg) 

Source Link

Document

Constructs an InvalidParameterException with the specified detail message.

Usage

From source file:com.android.camera.one.v2.OneCameraZslImpl.java

/**
 * @param originalWidth the width of the original image captured from the
 *            camera/*from w ww  .j a v  a 2  s  .co m*/
 * @param originalHeight the height of the original image captured from the
 *            camera
 * @param orientation the rotation to apply, in degrees.
 * @return The size of the final rotated image
 */
private Size getImageSizeForOrientation(int originalWidth, int originalHeight, int orientation) {
    if (orientation == 0 || orientation == 180) {
        return new Size(originalWidth, originalHeight);
    } else if (orientation == 90 || orientation == 270) {
        return new Size(originalHeight, originalWidth);
    } else {
        throw new InvalidParameterException("Orientation not supported.");
    }
}

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Deploys an REST virtual service from an uploaded RAML file
 * <p>/*from ww  w .  j  av  a2  s . c o m*/
 * @param uploadedInputStream the file content associated with the RAML file upload
 * @param fileDetail the file details associated with the RAML file upload
 * @param baseUri the baseUri to use in the returned WADL file.  Optionally provided, this will override that which is defined in the uploaded RAML.
 * @param authorization basic authorization string (user:password) used to grant access to LISA/DevTest REST APIs (when required)
 * @return HTTP response containing a status of REST virtual service deployed from uploaded RAML file
 */
@POST
@Path("restVs")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response deployRestVS(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("false") @FormDataParam("generateServiceDocument") Boolean generateServiceDocument,
        @DefaultValue("") @FormDataParam("authorization") String authorization) {

    log.info("POST raml/restVs");

    Response response = null;
    File uploadedFile = null;
    File ramlFile = null;
    FileInputStream ramlFileStream = null;

    try {

        if (fileDetail == null || fileDetail.getFileName() == null || fileDetail.getName() == null) {
            throw new InvalidParameterException("file");
        }

        if (!baseUri.isEmpty()) { // validate URI syntax
            try {

                new URI(baseUri);

            } catch (URISyntaxException uriEx) {

                throw new InvalidParameterException(String.format("baseUri - %s", uriEx.getMessage()));

            }
        }

        uploadedFile = FileUtil.getUploadedFile(uploadedInputStream, fileDetail);

        if (uploadedFile.isDirectory()) { // find RAML file in directory

            // First, look for a raml file that has the same base name as the uploaded file
            String targetName = Files.getNameWithoutExtension(fileDetail.getFileName()) + ".raml";

            ramlFile = FileUtil.selectRamlFile(uploadedFile, targetName);

        } else {

            ramlFile = uploadedFile;

        }

        List<ValidationResult> results = null;

        try {

            results = RamlUtil.validateRaml(ramlFile);

        } catch (IOException e) {

            String msg = String.format("RAML validation failed catastrophically for %s", ramlFile.getName());
            throw new Exception(msg, e.getCause());
        }

        // If the RAML file is valid, get to work...
        if (ValidationResult.areValid(results)) {

            try {

                ramlFileStream = new FileInputStream(ramlFile.getAbsolutePath());

            } catch (FileNotFoundException e) {

                String msg = String.format("Failed to open input stream from %s", ramlFile.getAbsolutePath());

                throw new Exception(msg, e.getCause());

            }

            FileResourceLoader resourceLoader = new FileResourceLoader(ramlFile.getParentFile());
            RamlDocumentBuilder rdb = new RamlDocumentBuilder(resourceLoader);
            Raml raml = rdb.build(ramlFileStream, ramlFile.getAbsolutePath());

            ramlFileStream.close();
            ramlFileStream = null;

            if (!baseUri.isEmpty()) {
                raml.setBaseUri(baseUri);
            }

            try {

                Context initialContext = new InitialContext();
                Context envContext = (Context) initialContext.lookup("java:comp/env");

                String vseServerUrl = (String) envContext.lookup("vseServerUrl");
                String vseServicePortRange = (String) envContext.lookup("vseServicePortRange");
                int vseServiceReadyWaitSeconds = (Integer) envContext.lookup("vseServiceReadyWaitSeconds");

                // Generate mar and deploy VS
                VirtualServiceBuilder vs = new VirtualServiceBuilder(vseServerUrl, vseServicePortRange,
                        vseServiceReadyWaitSeconds, generateServiceDocument, authorization);
                response = vs.setInputFile(raml, ramlFile.getParentFile(), true);

            } catch (Exception e) {

                String msg = String.format("Failed to deploy service - %s", e.getMessage());

                throw new Exception(msg, e.getCause());

            }

        } else { // RAML file failed validation

            StringBuilder sb = new StringBuilder();

            for (ValidationResult result : results) {

                sb.append(result.getLevel());

                if (result.getLine() > 0) {

                    sb.append(String.format(" (line %d)", result.getLine()));

                }

                sb.append(String.format(" - %s\n", result.getMessage()));
            }

            response = Response.status(Status.BAD_REQUEST).entity(sb.toString()).build();

        }

    } catch (Exception ex) {

        ex.printStackTrace();

        String msg = ex.getMessage();

        log.error(msg, ex);

        if (ex instanceof JsonSyntaxException) {

            response = Response.status(Status.BAD_REQUEST).entity(msg).build();

        } else if (ex instanceof InvalidParameterException) {

            response = Response.status(Status.BAD_REQUEST)
                    .entity(String.format("Invalid form parameter - %s", ex.getMessage())).build();

        } else {

            response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build();

        }

        return response;

    } finally {

        if (null != ramlFileStream) {

            try {

                ramlFileStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        if (null != uploadedFile) {

            if (uploadedFile.isDirectory()) {

                try {

                    System.gc(); // To help release files that snakeyaml abandoned open streams on -- otherwise, some files may not delete

                    // Wait a bit for the system to close abandoned streams
                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    FileUtils.deleteDirectory(uploadedFile);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                uploadedFile.delete();
            }

        }
    }

    return response;
}

From source file:petascope.wcst.transaction.executeTransaction.java

private Metadata updateImageCrsBoundingBox(Metadata meta, BoundingBoxType bbox) throws WCPSException {
    List<Double> lower = bbox.getLowerCorner();
    List<Double> upper = bbox.getUpperCorner();

    if (lower.size() != 2) {
        throw new InvalidParameterException("LowerCorner. Explanation: Should contain only two numbers.");
    }//from  w w w .ja va2 s  .co m
    if (upper.size() != 2) {
        throw new InvalidParameterException("UpperCorder. Explanation: Should contain only two numbers.");
    }
    long loX = lower.get(0).longValue();
    long loY = lower.get(1).longValue();
    long hiX = upper.get(0).longValue();
    long hiY = upper.get(1).longValue();

    CellDomainElement cellX = new CellDomainElement(BigInteger.valueOf(loX), BigInteger.valueOf(hiX),
            AxisTypes.X_AXIS);
    CellDomainElement cellY = new CellDomainElement(BigInteger.valueOf(loY), BigInteger.valueOf(hiY),
            AxisTypes.Y_AXIS);

    List<CellDomainElement> list = new ArrayList<CellDomainElement>();
    list.add(cellX);
    list.add(cellY);

    meta.setCellDomain(list);
    return meta.clone();
}

From source file:com.yunguchang.data.ApplicationRepository.java

public TBusApproveSugEntity getApplyApproveInfoByApplyNo(String applyNo) {
    if (applyNo == null) {
        throw new InvalidParameterException("Apply No can not be null!");
    }//  w  w w . j a v  a  2s.c  om
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApproveSugEntity> cq = cb.createQuery(TBusApproveSugEntity.class);
    Root<TBusApproveSugEntity> approveRoot = cq.from(TBusApproveSugEntity.class);
    approveRoot.fetch(TBusApproveSugEntity_.application);
    cq.where(cb.equal(approveRoot.get(TBusApproveSugEntity_.application).get(TBusApplyinfoEntity_.applyno),
            applyNo));
    return Iterables.getFirst(em.createQuery(cq).getResultList(), null);
}

From source file:com.yunguchang.data.ApplicationRepository.java

public TBusApproveSugEntity getApplyApproveInfo(String uuid) {
    if (uuid == null) {
        throw new InvalidParameterException("ID can not be null!");
    }//  www.j a  va  2 s .co  m
    return em.find(TBusApproveSugEntity.class, uuid);
}

From source file:com.yunguchang.data.ApplicationRepository.java

@TransactionAttribute(REQUIRES_NEW)
public TBusApproveSugEntity approveApplication(String applyId, String applyNo,
        TBusApproveSugEntity approveSugInfo, PrincipalExt principalExtOrNull) {
    if (StringUtils.isBlank(applyId) && (StringUtils.isBlank(applyNo)
            && (approveSugInfo == null || approveSugInfo.getApplication() == null
                    || StringUtils.isBlank(approveSugInfo.getApplication().getApplyno())))) {
        throw new InvalidParameterException("Approve info can not be null!");
    }/*from   www .  j  a  v a 2s .c om*/

    TSysUserEntity userEntity;
    if (approveSugInfo.getUser() != null) {
        userEntity = em.find(TSysUserEntity.class, approveSugInfo.getUser().getUserid());
        if (userEntity == null) {
            throw new EntityNotFoundException("User is not found!");
        }
    } else {
        userEntity = em.find(TSysUserEntity.class, principalExtOrNull.getUserIdOrNull());
    }
    approveSugInfo.setUser(userEntity);
    approveSugInfo.setDepartment(userEntity.getDepartment());
    approveSugInfo.setOperatedate(new Timestamp(DateTime.now().getMillis()));

    if (StringUtils.isNotBlank(approveSugInfo.getUuid())) {
        TBusApproveSugEntity approveSugEntity = em.find(TBusApproveSugEntity.class, approveSugInfo.getUuid());
        if (approveSugEntity != null) {
            TBusApplyinfoEntity applyinfoEntity = getApplicationByNo(applyNo, principalExtOrNull);
            if (applyinfoEntity == null) {
                throw new EntityNotFoundException("Apply is not found!");
            }
            approveSugInfo.setApplication(applyinfoEntity);
            return updateApproveInfo(approveSugEntity.getUuid(), approveSugInfo, principalExtOrNull);
        }
    }

    TBusApplyinfoEntity applyinfoEntity;
    if (StringUtils.isNotBlank(applyId)) {
        applyinfoEntity = em.find(TBusApplyinfoEntity.class, applyId);
        if (applyinfoEntity == null && StringUtils.isBlank(applyNo)) {
            throw new EntityNotFoundException("Apply info is not found!");
        }
    } else {
        applyinfoEntity = getApplicationByNo(applyNo, principalExtOrNull);
    }
    if (applyinfoEntity == null) {
        throw new EntityNotFoundException("Apply is not found!");
    }
    String applyNewStatus = ApplyStatus.APPLY.toStringValue(); // 
    if (!"01".equals(approveSugInfo.getSuggest())) {
        applyNewStatus = ApplyStatus.APPLY_REJECT.toStringValue(); // 
    }
    if (approveSugInfo.getUpdateBySync() != null && approveSugInfo.getUpdateBySync()) {
        approveSugInfo.setUpdateBySync(true);
    } else {
        approveSugInfo.setUpdateBySync(false);
    }
    updateApplicationStatus(applyinfoEntity.getUuid(), applyNewStatus, approveSugInfo.getUpdateBySync(),
            principalExtOrNull);

    approveSugInfo.setApplication(applyinfoEntity);
    if (StringUtils.isNotBlank(approveSugInfo.getUuid())) {
        approveSugInfo = em.merge(approveSugInfo);
    } else {
        em.persist(approveSugInfo);
    }

    return approveSugInfo;
}

From source file:org.parosproxy.paros.model.Session.java

/**
 * Returns the specified parameters for the given message based on the parser associated with the
 * first context found that includes the URL for the message, or the default parser if it is not
 * in a context//w ww  . ja  va  2 s  .  c om
 * @param msg
 * @param type
 * @return
 */
public Map<String, String> getParams(HttpMessage msg, HtmlParameter.Type type) {
    switch (type) {
    case form:
        return this.getFormParamParser(msg.getRequestHeader().getURI().toString()).getParams(msg, type);
    case url:
        return this.getUrlParamParser(msg.getRequestHeader().getURI().toString()).getParams(msg, type);
    default:
        throw new InvalidParameterException("Type not supported: " + type);
    }
}

From source file:weave.utils.SQLUtils.java

private static String getCSVNullValue(Connection conn) {
    try {/*from   w w  w .  j a  v a  2 s . c  o m*/
        String dbms = conn.getMetaData().getDatabaseProductName();

        if (MYSQL.equalsIgnoreCase(dbms))
            return "\\N";
        else if (POSTGRESQL.equalsIgnoreCase(dbms) || SQLSERVER.equalsIgnoreCase(dbms)
                || ORACLE.equalsIgnoreCase(dbms))
            return ""; // empty string (no quotes)
        else
            throw new InvalidParameterException("Unsupported DBMS type: " + dbms);
    } catch (Exception e) {
        // this should never happen
        throw new RuntimeException(e);
    }
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

@Override
public OcspResponseInformation getOcspResponse(final byte[] request,
        final X509Certificate[] requestCertificates, String remoteAddress, String remoteHost,
        StringBuffer requestUrl, final AuditLogger auditLogger, final TransactionLogger transactionLogger)
        throws MalformedRequestException, OCSPException {
    //Check parameters
    if (auditLogger == null) {
        throw new InvalidParameterException(
                "Illegal to pass a null audit logger to OcspResponseSession.getOcspResponse");
    }//from ww w.j a v a 2 s . c om
    if (transactionLogger == null) {
        throw new InvalidParameterException(
                "Illegal to pass a null transaction logger to OcspResponseSession.getOcspResponse");
    }
    // Validate byte array.
    if (request.length > MAX_REQUEST_SIZE) {
        final String msg = intres.getLocalizedMessage("request.toolarge", MAX_REQUEST_SIZE, request.length);
        throw new MalformedRequestException(msg);
    }
    byte[] respBytes = null;
    final Date startTime = new Date();
    OCSPResp ocspResponse = null;
    // Start logging process time after we have received the request
    if (transactionLogger.isEnabled()) {
        transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
    }
    if (auditLogger.isEnabled()) {
        auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        auditLogger.paramPut(AuditLogger.OCSPREQUEST, new String(Hex.encode(request)));
    }
    OCSPReq req;
    long maxAge = OcspConfiguration.getMaxAge(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);
    OCSPRespBuilder responseGenerator = new OCSPRespBuilder();
    try {
        req = translateRequestFromByteArray(request, remoteAddress, transactionLogger);
        // Get the certificate status requests that are inside this OCSP req
        Req[] ocspRequests = req.getRequestList();
        if (ocspRequests.length <= 0) {
            String infoMsg = intres.getLocalizedMessage("ocsp.errornoreqentities");
            log.info(infoMsg);
            throw new MalformedRequestException(infoMsg);
        }
        final int maxRequests = 100;
        if (ocspRequests.length > maxRequests) {
            String infoMsg = intres.getLocalizedMessage("ocsp.errortoomanyreqentities", maxRequests);
            log.info(infoMsg);
            throw new MalformedRequestException(infoMsg);
        }
        if (log.isDebugEnabled()) {
            log.debug("The OCSP request contains " + ocspRequests.length + " simpleRequests.");
        }
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.NUM_CERT_ID, ocspRequests.length);
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
        }
        OcspSigningCacheEntry ocspSigningCacheEntry = null;
        long nextUpdate = OcspConfiguration
                .getUntilNextUpdate(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);
        // Add standard response extensions
        Map<ASN1ObjectIdentifier, Extension> responseExtensions = getStandardResponseExtensions(req);
        // Look for extension OIDs
        final Collection<String> extensionOids = OcspConfiguration.getExtensionOids();
        // Look over the status requests
        List<OCSPResponseItem> responseList = new ArrayList<OCSPResponseItem>();
        boolean addExtendedRevokedExtension = false;
        Date producedAt = null;
        for (Req ocspRequest : ocspRequests) {
            CertificateID certId = ocspRequest.getCertID();
            ASN1ObjectIdentifier certIdhash = certId.getHashAlgOID();
            if (!OIWObjectIdentifiers.idSHA1.equals(certIdhash)
                    && !NISTObjectIdentifiers.id_sha256.equals(certIdhash)) {
                throw new InvalidAlgorithmException(
                        "CertID with SHA1 and SHA256 are supported, not: " + certIdhash.getId());
            }
            if (transactionLogger.isEnabled()) {
                transactionLogger.paramPut(TransactionLogger.SERIAL_NOHEX,
                        certId.getSerialNumber().toByteArray());
                transactionLogger.paramPut(TransactionLogger.DIGEST_ALGOR, certId.getHashAlgOID().toString());
                transactionLogger.paramPut(TransactionLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash());
                transactionLogger.paramPut(TransactionLogger.ISSUER_KEY, certId.getIssuerKeyHash());
            }
            if (auditLogger.isEnabled()) {
                auditLogger.paramPut(AuditLogger.ISSUER_KEY, certId.getIssuerKeyHash());
                auditLogger.paramPut(AuditLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray());
                auditLogger.paramPut(AuditLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash());
            }
            byte[] hashbytes = certId.getIssuerNameHash();
            String hash = null;
            if (hashbytes != null) {
                hash = new String(Hex.encode(hashbytes));
            }
            String infoMsg = intres.getLocalizedMessage("ocsp.inforeceivedrequest",
                    certId.getSerialNumber().toString(16), hash, remoteAddress);
            log.info(infoMsg);
            // Locate the CA which gave out the certificate
            ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(certId);
            if (ocspSigningCacheEntry == null) {
                //Could it be that we haven't updated the OCSP Signing Cache?
                ocspSigningCacheEntry = findAndAddMissingCacheEntry(certId);
            }
            if (ocspSigningCacheEntry != null) {
                if (transactionLogger.isEnabled()) {
                    // This will be the issuer DN of the signing certificate, whether an OCSP responder or an internal CA  
                    String issuerNameDn = CertTools
                            .getIssuerDN(ocspSigningCacheEntry.getFullCertificateChain().get(0));
                    transactionLogger.paramPut(TransactionLogger.ISSUER_NAME_DN, issuerNameDn);
                }
            } else {
                /*
                 * if the certId was issued by an unknown CA 
                 * 
                 * The algorithm here: 
                 * We will sign the response with the CA that issued the last certificate(certId) in the request. If the issuing CA is not available on 
                 * this server, we sign the response with the default responderId (from params in web.xml). We have to look up the ca-certificate for 
                 * each certId in the request though, as we will check for revocation on the ca-cert as well when checking for revocation on the certId.
                 */
                // We could not find certificate for this request so get certificate for default responder
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry();
                if (ocspSigningCacheEntry != null) {
                    String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacertusedefault",
                            new String(Hex.encode(certId.getIssuerNameHash())));
                    log.info(errMsg);
                    // If we can not find the CA, answer UnknowStatus
                    responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate));
                    if (transactionLogger.isEnabled()) {
                        transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                OCSPResponseItem.OCSP_UNKNOWN);
                        transactionLogger.writeln();
                    }
                    continue;
                } else {
                    GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession
                            .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID);
                    String defaultResponder = ocspConfiguration.getOcspDefaultResponderReference();
                    String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacert",
                            new String(Hex.encode(certId.getIssuerNameHash())), defaultResponder);
                    log.error(errMsg);
                    // If we are responding to multiple requests, the last found ocspSigningCacheEntry will be used in the end
                    // so even if there are not any one now, it might be later when it is time to sign the responses.
                    // Since we only will sign the entire response once if there is at least one valid ocspSigningCacheEntry
                    // we might as well include the unknown requests.
                    responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate));
                    continue;
                }
            }

            final org.bouncycastle.cert.ocsp.CertificateStatus certStatus;
            // Check if the cacert (or the default responderid) is revoked
            X509Certificate caCertificate = ocspSigningCacheEntry.getIssuerCaCertificate();
            final CertificateStatus signerIssuerCertStatus = ocspSigningCacheEntry
                    .getIssuerCaCertificateStatus();
            final String caCertificateSubjectDn = CertTools.getSubjectDN(caCertificate);
            CertificateStatusHolder certificateStatusHolder = null;
            if (signerIssuerCertStatus.equals(CertificateStatus.REVOKED)) {
                /*
                 * According to chapter 2.7 in RFC2560:
                 * 
                 * 2.7 CA Key Compromise If an OCSP responder knows that a particular CA's private key has been compromised, it MAY return the revoked
                 * state for all certificates issued by that CA.
                 */
                // If we've ended up here it's because the signer issuer certificate was revoked. 
                certStatus = new RevokedStatus(
                        new RevokedInfo(new ASN1GeneralizedTime(signerIssuerCertStatus.revocationDate),
                                CRLReason.lookup(signerIssuerCertStatus.revocationReason)));
                infoMsg = intres.getLocalizedMessage("ocsp.signcertissuerrevoked",
                        CertTools.getSerialNumberAsString(caCertificate),
                        CertTools.getSubjectDN(caCertificate));
                log.info(infoMsg);
                responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate));
                if (transactionLogger.isEnabled()) {
                    transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_REVOKED);
                    transactionLogger.writeln();
                }
            } else {
                /**
                 * Here is the actual check for the status of the sought certificate (easy to miss). Here we grab just the status if there aren't
                 * any OIDs defined (default case), but if there are we'll probably need the certificate as well. If that's the case, we'll grab
                 * the certificate in the same transaction.
                 */
                final CertificateStatus status;
                if (extensionOids.isEmpty()) {
                    status = certificateStoreSession.getStatus(caCertificateSubjectDn,
                            certId.getSerialNumber());
                } else {
                    certificateStatusHolder = certificateStoreSession
                            .getCertificateAndStatus(caCertificateSubjectDn, certId.getSerialNumber());
                    status = certificateStatusHolder.getCertificateStatus();
                }
                // If we have an OcspKeyBinding configured for this request, we override the default value
                if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                    nextUpdate = ocspSigningCacheEntry.getOcspKeyBinding().getUntilNextUpdate() * 1000L;
                }
                // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                        && OcspConfiguration.isUntilNextUpdateConfigured(status.certificateProfileId)) {
                    nextUpdate = OcspConfiguration.getUntilNextUpdate(status.certificateProfileId);
                }
                // If we have an OcspKeyBinding configured for this request, we override the default value
                if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                    maxAge = ocspSigningCacheEntry.getOcspKeyBinding().getMaxAge() * 1000L;
                }
                // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                        && OcspConfiguration.isMaxAgeConfigured(status.certificateProfileId)) {
                    maxAge = OcspConfiguration.getMaxAge(status.certificateProfileId);
                }

                final String sStatus;
                boolean addArchiveCutoff = false;
                if (status.equals(CertificateStatus.NOT_AVAILABLE)) {
                    // No revocation info available for this cert, handle it
                    if (log.isDebugEnabled()) {
                        log.debug("Unable to find revocation information for certificate with serial '"
                                + certId.getSerialNumber().toString(16) + "'" + " from issuer '"
                                + caCertificateSubjectDn + "'");
                    }
                    /* 
                     * If we do not treat non existing certificates as good or revoked
                     * OR
                     * we don't actually handle requests for the CA issuing the certificate asked about
                     * then we return unknown 
                     * */
                    if (OcspConfigurationCache.INSTANCE.isNonExistingGood(requestUrl,
                            ocspSigningCacheEntry.getOcspKeyBinding())
                            && OcspSigningCache.INSTANCE.getEntry(certId) != null) {
                        sStatus = "good";
                        certStatus = null; // null means "good" in OCSP
                        if (transactionLogger.isEnabled()) {
                            transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                    OCSPResponseItem.OCSP_GOOD);
                        }
                    } else if (OcspConfigurationCache.INSTANCE.isNonExistingRevoked(requestUrl,
                            ocspSigningCacheEntry.getOcspKeyBinding())
                            && OcspSigningCache.INSTANCE.getEntry(certId) != null) {
                        sStatus = "revoked";
                        certStatus = new RevokedStatus(new RevokedInfo(new ASN1GeneralizedTime(new Date(0)),
                                CRLReason.lookup(CRLReason.certificateHold)));
                        if (transactionLogger.isEnabled()) {
                            transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                    OCSPResponseItem.OCSP_REVOKED);
                        }
                        addExtendedRevokedExtension = true;
                    } else {
                        sStatus = "unknown";
                        certStatus = new UnknownStatus();
                        if (transactionLogger.isEnabled()) {
                            transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                    OCSPResponseItem.OCSP_UNKNOWN);
                        }
                    }
                } else if (status.equals(CertificateStatus.REVOKED)) {
                    // Revocation info available for this cert, handle it
                    sStatus = "revoked";
                    certStatus = new RevokedStatus(
                            new RevokedInfo(new ASN1GeneralizedTime(status.revocationDate),
                                    CRLReason.lookup(status.revocationReason)));
                    if (transactionLogger.isEnabled()) {
                        transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                OCSPResponseItem.OCSP_REVOKED);
                    }
                    // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                    if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                            && OcspConfiguration
                                    .isRevokedUntilNextUpdateConfigured(status.certificateProfileId)) {
                        nextUpdate = OcspConfiguration.getRevokedUntilNextUpdate(status.certificateProfileId);
                    }
                    // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                    if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                            && OcspConfiguration.isRevokedMaxAgeConfigured(status.certificateProfileId)) {
                        maxAge = OcspConfiguration.getRevokedMaxAge(status.certificateProfileId);
                    }
                } else {
                    sStatus = "good";
                    certStatus = null;
                    if (transactionLogger.isEnabled()) {
                        transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_GOOD);
                    }
                    addArchiveCutoff = checkAddArchiveCuttoff(caCertificateSubjectDn, certId);
                }

                if (log.isDebugEnabled()) {
                    log.debug("Set nextUpdate=" + nextUpdate + ", and maxAge=" + maxAge
                            + " for certificateProfileId=" + status.certificateProfileId);
                }

                infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", sStatus,
                        certId.getSerialNumber().toString(16), caCertificateSubjectDn);
                log.info(infoMsg);
                OCSPResponseItem respItem = new OCSPResponseItem(certId, certStatus, nextUpdate);
                if (addArchiveCutoff) {
                    addArchiveCutoff(respItem);
                    producedAt = new Date();
                }
                responseList.add(respItem);
                if (transactionLogger.isEnabled()) {
                    transactionLogger.writeln();
                }
            }
            for (String oidstr : extensionOids) {
                boolean useAlways = false;
                if (oidstr.startsWith("*")) {
                    oidstr = oidstr.substring(1, oidstr.length());
                    useAlways = true;
                }
                ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(oidstr);
                Extension extension = null;
                if (!useAlways) {
                    // Only check if extension exists if we are not already bound to use it
                    if (req.hasExtensions()) {
                        extension = req.getExtension(oid);
                    }
                }
                //If found, or if it should be used anyway
                if (useAlways || extension != null) {
                    // We found an extension, call the extension class
                    if (log.isDebugEnabled()) {
                        log.debug("Found OCSP extension oid: " + oidstr);
                    }
                    OCSPExtension extObj = OcspExtensionsCache.INSTANCE.getExtensions().get(oidstr);
                    if (extObj != null) {
                        // Find the certificate from the certId
                        if (certificateStatusHolder != null
                                && certificateStatusHolder.getCertificate() != null) {
                            X509Certificate cert = (X509Certificate) certificateStatusHolder.getCertificate();
                            // Call the OCSP extension
                            Map<ASN1ObjectIdentifier, Extension> retext = extObj.process(requestCertificates,
                                    remoteAddress, remoteHost, cert, certStatus);
                            if (retext != null) {
                                // Add the returned X509Extensions to the responseExtension we will add to the basic OCSP response
                                responseExtensions.putAll(retext);
                            } else {
                                String errMsg = intres.getLocalizedMessage("ocsp.errorprocessextension",
                                        extObj.getClass().getName(),
                                        Integer.valueOf(extObj.getLastErrorCode()));
                                log.error(errMsg);
                            }
                        }
                    }
                }
            }
        }
        if (addExtendedRevokedExtension) {
            // id-pkix-ocsp-extended-revoke OBJECT IDENTIFIER ::= {id-pkix-ocsp 9}
            final ASN1ObjectIdentifier extendedRevokedOID = new ASN1ObjectIdentifier(
                    OCSPObjectIdentifiers.id_pkix_ocsp + ".9");
            try {
                responseExtensions.put(extendedRevokedOID,
                        new Extension(extendedRevokedOID, false, DERNull.INSTANCE.getEncoded()));
            } catch (IOException e) {
                throw new IllegalStateException("Could not get encodig from DERNull.", e);
            }
        }
        if (ocspSigningCacheEntry != null) {
            // Add responseExtensions
            Extensions exts = new Extensions(responseExtensions.values().toArray(new Extension[0]));
            // generate the signed response object
            BasicOCSPResp basicresp = signOcspResponse(req, responseList, exts, ocspSigningCacheEntry,
                    producedAt);
            ocspResponse = responseGenerator.build(OCSPRespBuilder.SUCCESSFUL, basicresp);
            if (auditLogger.isEnabled()) {
                auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
            }
            if (transactionLogger.isEnabled()) {
                transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
            }
        } else {
            // Only unknown CAs in requests and no default responder's cert, return an unsigned response
            if (log.isDebugEnabled()) {
                log.debug(intres.getLocalizedMessage("ocsp.errornocacreateresp"));
            }
            ocspResponse = responseGenerator.build(OCSPRespBuilder.UNAUTHORIZED, null);
            if (auditLogger.isEnabled()) {
                auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
            }
            if (transactionLogger.isEnabled()) {
                transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
            }
        }
    } catch (SignRequestException e) {
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage());
        log.info(errMsg); // No need to log the full exception here
        // RFC 2560: responseBytes are not set on error.
        ocspResponse = responseGenerator.build(OCSPRespBuilder.SIG_REQUIRED, null);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SIG_REQUIRED);
            transactionLogger.writeln();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SIG_REQUIRED);
        }
    } catch (SignRequestSignatureException e) {
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage());
        log.info(errMsg); // No need to log the full exception here
        // RFC 2560: responseBytes are not set on error.
        ocspResponse = responseGenerator.build(OCSPRespBuilder.UNAUTHORIZED, null);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
            transactionLogger.writeln();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
        }
    } catch (InvalidAlgorithmException e) {
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage());
        log.info(errMsg); // No need to log the full exception here
        // RFC 2560: responseBytes are not set on error.
        ocspResponse = responseGenerator.build(OCSPRespBuilder.MALFORMED_REQUEST, null);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST);
            transactionLogger.writeln();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST);
        }
    } catch (NoSuchAlgorithmException e) {
        ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e);
    } catch (CertificateException e) {
        ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e);
    } catch (CryptoTokenOfflineException e) {
        ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e);
    }
    try {
        respBytes = ocspResponse.getEncoded();
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.OCSPRESPONSE, new String(Hex.encode(respBytes)));
            auditLogger.writeln();
            auditLogger.flush();
        }
        if (transactionLogger.isEnabled()) {
            transactionLogger.flush();
        }
        if (OcspConfiguration.getLogSafer()) {
            // See if the Errorhandler has found any problems
            if (hasErrorHandlerFailedSince(startTime)) {
                log.info("ProbableErrorhandler reported error, cannot answer request");
                // RFC 2560: responseBytes are not set on error.
                ocspResponse = responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null);

            }
            // See if the Appender has reported any problems
            if (!CanLogCache.INSTANCE.canLog()) {
                log.info("SaferDailyRollingFileAppender reported error, cannot answer request");
                // RFC 2560: responseBytes are not set on error.
                ocspResponse = responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null);
            }
        }
    } catch (IOException e) {
        log.error("Unexpected IOException caught.", e);
        if (transactionLogger.isEnabled()) {
            transactionLogger.flush();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.flush();
        }
    }
    return new OcspResponseInformation(ocspResponse, maxAge);
}

From source file:com.cloud.hypervisor.vmware.mo.HypervisorHostHelper.java

public static Pair<ManagedObjectReference, String> prepareNetwork(String vSwitchName, String namePrefix,
        HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs,
        boolean syncPeerHosts, BroadcastDomainType broadcastDomainType, String nicUuid,
        Map<NetworkOffering.Detail, String> nicDetails) throws Exception {

    HostVirtualSwitch vSwitch;//from  www .j a v a 2  s.co m
    if (vSwitchName == null) {
        s_logger.info("Detected vswitch name as undefined. Defaulting to vSwitch0");
        vSwitchName = "vSwitch0";
    }
    vSwitch = hostMo.getHostVirtualSwitchByName(vSwitchName);

    if (vSwitch == null) {
        String msg = "Unable to find vSwitch" + vSwitchName;
        s_logger.error(msg);
        throw new Exception(msg);
    }

    boolean createGCTag = false;
    String networkName;
    Integer vid = null;

    /** This is the list of BroadcastDomainTypes we can actually
     * prepare networks for in this function.
     */
    BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch,
            BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan,
            BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan,
            BroadcastDomainType.Vsp };

    if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {
        throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType
                + " it not supported on a VMWare hypervisor at this time.");
    }

    if (broadcastDomainType == BroadcastDomainType.Lswitch) {
        /**
         * Nicira NVP requires each vm to have its own port-group with a dedicated
         * vlan. We'll set the name of the pg to the uuid of the nic.
         */
        networkName = nicUuid;
        // No doubt about this, depending on vid=null to avoid lots of code below
        vid = null;
    } else {
        networkName = composeCloudNetworkName(namePrefix, vlanId, null, networkRateMbps, vSwitchName);

        if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
            createGCTag = true;
            vid = Integer.parseInt(vlanId);
        }
    }

    HostNetworkSecurityPolicy secPolicy = createVSSecurityPolicy(nicDetails);

    HostNetworkTrafficShapingPolicy shapingPolicy = null;
    if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
        shapingPolicy = new HostNetworkTrafficShapingPolicy();
        shapingPolicy.setEnabled(true);
        shapingPolicy.setAverageBandwidth(networkRateMbps.intValue() * 1024L * 1024L);

        //
        // TODO : people may have different opinion on how to set the following
        //

        // give 50% premium to peek
        shapingPolicy.setPeakBandwidth((long) (shapingPolicy.getAverageBandwidth() * 1.5));

        // allow 5 seconds of burst transfer
        shapingPolicy.setBurstSize(5 * shapingPolicy.getAverageBandwidth() / 8);
    }

    boolean bWaitPortGroupReady = false;
    if (broadcastDomainType == BroadcastDomainType.Lswitch) {
        //if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
        if (NiciraNvpApiVersion.isApiVersionLowerThan("4.2")) {
            //Previous behaviour
            if (!hostMo.hasPortGroup(vSwitch, networkName)) {
                createNvpPortGroup(hostMo, vSwitch, networkName, shapingPolicy);

                bWaitPortGroupReady = true;
            } else {
                bWaitPortGroupReady = false;
            }
        }
    } else {
        if (!hostMo.hasPortGroup(vSwitch, networkName)) {
            hostMo.createPortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy, timeOutMs);
            // Setting flag "bWaitPortGroupReady" to false.
            // This flag indicates whether we need to wait for portgroup on vCenter.
            // Above createPortGroup() method itself ensures creation of portgroup as well as wait for portgroup.
            bWaitPortGroupReady = false;
        } else {
            HostPortGroupSpec spec = hostMo.getPortGroupSpec(networkName);
            if (!isSpecMatch(spec, vid, secPolicy, shapingPolicy)) {
                hostMo.updatePortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy);
                bWaitPortGroupReady = true;
            }
        }
    }

    ManagedObjectReference morNetwork = null;

    if (broadcastDomainType != BroadcastDomainType.Lswitch
            || (broadcastDomainType == BroadcastDomainType.Lswitch
                    && NiciraNvpApiVersion.isApiVersionLowerThan("4.2"))) {
        if (bWaitPortGroupReady)
            morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);
        else
            morNetwork = hostMo.getNetworkMor(networkName);
        if (morNetwork == null) {
            String msg = "Failed to create guest network " + networkName;
            s_logger.error(msg);
            throw new Exception(msg);
        }

        if (createGCTag) {
            NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
            networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true");
        }
    }

    if (syncPeerHosts) {
        ManagedObjectReference morParent = hostMo.getParentMor();
        if (morParent != null && morParent.getType().equals("ClusterComputeResource")) {
            // to be conservative, lock cluster
            GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.getValue());
            try {
                if (lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {
                    try {
                        List<ManagedObjectReference> hosts = hostMo.getContext().getVimClient()
                                .getDynamicProperty(morParent, "host");
                        if (hosts != null) {
                            for (ManagedObjectReference otherHost : hosts) {
                                if (!otherHost.getValue().equals(hostMo.getMor().getValue())) {
                                    HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);
                                    try {
                                        if (s_logger.isDebugEnabled())
                                            s_logger.debug("Prepare network on other host, vlan: " + vlanId
                                                    + ", host: " + otherHostMo.getHostName());
                                        prepareNetwork(vSwitchName, namePrefix, otherHostMo, vlanId,
                                                networkRateMbps, networkRateMulticastMbps, timeOutMs, false,
                                                broadcastDomainType, nicUuid, nicDetails);
                                    } catch (Exception e) {
                                        s_logger.warn("Unable to prepare network on other host, vlan: " + vlanId
                                                + ", host: " + otherHostMo.getHostName());
                                    }
                                }
                            }
                        }
                    } finally {
                        lock.unlock();
                    }
                } else {
                    s_logger.warn("Unable to lock cluster to prepare guest network, vlan: " + vlanId);
                }
            } finally {
                lock.releaseRef();
            }
        }
    }

    s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName);
    return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
}