Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

In this page you can find the example usage for java.util Date setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:sce.Main.java

public String getJobFireTimes(String jobName, String jobGroup) {
    JSONObject results_obj = new JSONObject();
    try {//  ww w  .  j ava  2  s.  c  o m
        List<Trigger> triggers = (List<Trigger>) sched.getTriggersOfJob(JobKey.jobKey(jobName, jobGroup));

        Date startTime = new Date();
        Date previousFireTime = new Date();
        previousFireTime.setTime(0);
        Date nextFireTime = new Date();
        Date endTime = new Date();
        endTime.setTime(0);

        //trigger state counters
        int blocked = 0;
        int complete = 0;
        int error = 0;
        int none = 0;
        int normal = 0;
        int paused = 0;

        for (Trigger trigger : triggers) {
            if (trigger.getStartTime().before(startTime)) {
                startTime = trigger.getStartTime();
                results_obj.put("startTime", startTime.toString());
            }
            if (trigger.getPreviousFireTime().after(previousFireTime)) {
                previousFireTime = trigger.getPreviousFireTime();
                results_obj.put("previousFireTime", startTime.toString());
            }
            if (trigger.getNextFireTime().before(nextFireTime)) {
                nextFireTime = trigger.getNextFireTime();
                results_obj.put("nextFireTime", startTime.toString());
            }
            if (trigger.getEndTime() != null && trigger.getEndTime().after(endTime)) {
                endTime = trigger.getEndTime();
                results_obj.put("endTime", startTime.toString());
            }

            //count trigger state
            if (sched.getTriggerState(trigger.getKey()).compareTo(TriggerState.ERROR) == 0) {
                error++;
            } else if (sched.getTriggerState(trigger.getKey()).compareTo(TriggerState.BLOCKED) == 0) {
                blocked++;
            } else if (sched.getTriggerState(trigger.getKey()).compareTo(TriggerState.PAUSED) == 0) {
                paused++;
            } else if (sched.getTriggerState(trigger.getKey()).compareTo(TriggerState.NORMAL) == 0) {
                normal++;
            } else if (sched.getTriggerState(trigger.getKey()).compareTo(TriggerState.COMPLETE) == 0) {
                complete++;
            } else if (sched.getTriggerState(trigger.getKey()).compareTo(TriggerState.NONE) == 0) {
                none++;
            }
        }

        if (blocked == triggers.size()) {
            results_obj.put("state", "BLOCKED");
        } else if (complete == triggers.size()) {
            results_obj.put("state", "COMPLETE");
        } else if (error == triggers.size()) {
            results_obj.put("state", "ERROR");
        } else if (none == triggers.size()) {
            results_obj.put("state", "NONE");
        } else if (normal == triggers.size()) {
            results_obj.put("state", "NORMAL");
        } else if (paused == triggers.size()) {
            results_obj.put("state", "PAUSED");
        }

        return results_obj.toJSONString();
    } catch (SchedulerException e) {
        return e.getMessage();
    }
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

protected Date calculateUpdateTime(FeedStatus feedStatus, int minIntervalMinutes) {
    int ttl = feedStatus.mTTL;

    if (ttl > 0) {
        if (ttl < minIntervalMinutes) {
            ttl = minIntervalMinutes;/*from   w  w w  . j a  va2 s .  c  o m*/
        }

        // ignore ttls below 5 minutes
        if (ttl < 5) {
            ttl = 5;
        }
        // ignore ttls above 1 day
        else if (ttl > (24 * 60)) {
            ttl = 24 * 60;
        }
    } else {
        ttl = 60;
    }

    if (mLog.d())
        mLog.d("set ttl from " + feedStatus.mTTL + " to " + ttl);

    Date updateTime = new Date();

    updateTime.setTime(feedStatus.mLastHit.getTime() + ttl * 60000);

    return updateTime;
}

From source file:org.cesecore.certificates.ca.X509CA.java

/**
 * Generate a CRL or a deltaCRL/*from   w  ww. j a va  2  s. c o m*/
 * 
 * @param certs
 *            list of revoked certificates
 * @param crlnumber
 *            CRLNumber for this CRL
 * @param isDeltaCRL
 *            true if we should generate a DeltaCRL
 * @param basecrlnumber
 *            caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile
 *            certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CryptoTokenOfflineException
 * @throws IllegalCryptoTokenException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod,
        int crlnumber, boolean isDeltaCRL, int basecrlnumber)
        throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }

    // Make DNs
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    final X500Name issuer;
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        final X500NameStyle nameStyle;
        if (getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }
        issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    } else {
        issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
    }
    final Date thisUpdate = new Date();
    final Date nextUpdate = new Date();
    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    if (certs != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
        final Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            final RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
        if (log.isDebugEnabled()) {
            log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null);
        if (caSkid != null) {
            // Use subject key id from CA certificate
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid);
            crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
        } else {
            // Generate from SHA1 of public key
            ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken
                    .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN))
                    .getEncoded()));
            try {
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) asn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
            } finally {
                asn1InputStream.close();
            }
        }
    }

    // Authority Information Access  
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    if (getAuthorityInformationAccess() != null) {
        for (String url : getAuthorityInformationAccess()) {
            if (StringUtils.isNotEmpty(url)) {
                GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier,
                        new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }
    if (accessList.size() > 0) {
        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(new DERSequence(accessList));
        // "This CRL extension MUST NOT be marked critical." according to rfc4325
        crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(),
                    idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(Extension.freshestCRL, false, ext);
            }

        }
    }

    final X509CRLHolder crl;
    if (log.isDebugEnabled()) {
        log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN);
    try {
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg)
                .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480);
        crl = crlgen.build(signer);
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    final PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA certificate.");
        }
    } else {
        verifyKey = cryptoToken.getPublicKey(alias);
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA token.");
        }
    }
    try {
        final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey);
        if (!crl.isSignatureValid(verifier)) {
            throw new SignatureException("Error verifying CRL to be returned.");
        }
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    } catch (CertException e) {
        throw new SignatureException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    return crl;
}

From source file:com.att.aro.diagnostics.GraphPanel.java

/**
 * Creating Alarm triggered data for graph plot
 *///from   w w  w . ja  v  a2s. c  o  m
private static void populateAlarmPlot(XYPlot plot, TraceData.Analysis analysis) {

    final XYIntervalSeriesCollection alarmDataCollection = new XYIntervalSeriesCollection();
    if (analysis != null) {

        // Remove old annotation from previous plots
        Iterator<XYPointerAnnotation> pointers = pointerAnnotation.iterator();
        while (pointers.hasNext()) {
            plot.removeAnnotation(pointers.next());
        }
        pointerAnnotation.clear();

        final Map<AlarmType, XYIntervalSeries> seriesMap = new EnumMap<AlarmType, XYIntervalSeries>(
                AlarmType.class);
        for (AlarmType eventType : AlarmType.values()) {
            XYIntervalSeries series = new XYIntervalSeries(eventType);
            seriesMap.put(eventType, series);
            alarmDataCollection.addSeries(series);
        }
        final List<AlarmInfo> alarmInfos = analysis.getAlarmInfos();
        final Map<Double, AlarmInfo> eventMap = new HashMap<Double, AlarmInfo>();
        final Map<Double, ScheduledAlarmInfo> eventMapPending = new HashMap<Double, ScheduledAlarmInfo>();
        List<ScheduledAlarmInfo> pendingAlarms = getHasFiredAlarms(analysis.getScheduledAlarms());
        Iterator<ScheduledAlarmInfo> iterPendingAlarms = pendingAlarms.iterator();
        double firedTime = 0;
        while (iterPendingAlarms.hasNext()) {
            ScheduledAlarmInfo scheduledEvent = iterPendingAlarms.next();
            AlarmType pendingAlarmType = scheduledEvent.getAlarmType();
            if (pendingAlarmType != null) {
                firedTime = (scheduledEvent.getTimeStamp() - scheduledEvent.getRepeatInterval()) / 1000;
                seriesMap.get(pendingAlarmType).add(firedTime, firedTime, firedTime, 1, 0.8, 1);
                eventMapPending.put(firedTime, scheduledEvent);
                logger.fine("populateAlarmScheduledPlot type:\n" + pendingAlarmType + "\ntime "
                        + scheduledEvent.getTimeStamp() + "\nrepeating " + firedTime);
            }
        }

        Iterator<AlarmInfo> iter = alarmInfos.iterator();
        while (iter.hasNext()) {
            AlarmInfo currEvent = iter.next();
            if (currEvent != null) {
                AlarmType alarmType = currEvent.getAlarmType();
                if (alarmType != null) {
                    firedTime = currEvent.getTimeStamp() / 1000;

                    /*
                     * Catching any alarms align to quanta as being
                     * inexactRepeating alarms
                     */
                    if ((currEvent.getTimestampElapsed() / 1000) % 900 < 1) {
                        seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.7);

                        // Adding an arrow to mark these inexactRepeating alarms
                        XYPointerAnnotation xypointerannotation = new XYPointerAnnotation(alarmType.name(),
                                firedTime, 0.6, 3.92699082D);
                        xypointerannotation.setBaseRadius(20D);
                        xypointerannotation.setTipRadius(1D);
                        pointerAnnotation.add(xypointerannotation);
                        plot.addAnnotation(xypointerannotation);

                        logger.info("SetInexactRepeating alarm type: " + alarmType + " time " + firedTime
                                + " epoch " + currEvent.getTimestampEpoch() + " elapsed:\n"
                                + currEvent.getTimestampElapsed() / 1000);
                    } else {
                        seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.5);
                    }
                    eventMap.put(firedTime, currEvent);
                }
            }
        }
        XYItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC_WAKEUP), Color.red);

        renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC), Color.pink);

        renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME_WAKEUP), Color.blue);

        renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME), Color.cyan);

        renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.UNKNOWN), Color.black);

        // Assign ToolTip to renderer
        renderer.setBaseToolTipGenerator(new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset dataset, int series, int item) {
                AlarmInfo info = eventMap.get(dataset.getX(series, item));
                Date epochTime = new Date();
                if (info != null) {

                    epochTime.setTime((long) info.getTimestampEpoch());

                    StringBuffer displayInfo = new StringBuffer(rb.getString("alarm.tooltip.prefix"));
                    displayInfo.append(MessageFormat.format(rb.getString("alarm.tooltip.content"),
                            info.getAlarmType(), info.getTimeStamp() / 1000, epochTime.toString()));
                    if ((info.getTimestampElapsed() / 1000) % 900 < 1) {
                        displayInfo.append(rb.getString("alarm.tooltip.setInexactRepeating"));
                    }
                    displayInfo.append(rb.getString("alarm.tooltip.suffix"));
                    return displayInfo.toString();
                }
                ScheduledAlarmInfo infoPending = eventMapPending.get(dataset.getX(series, item));
                if (infoPending != null) {

                    epochTime.setTime(
                            (long) (infoPending.getTimestampEpoch() - infoPending.getRepeatInterval()));

                    StringBuffer displayInfo = new StringBuffer(rb.getString("alarm.tooltip.prefix"));
                    displayInfo.append(MessageFormat.format(rb.getString("alarm.tooltip.contentWithName"),
                            infoPending.getAlarmType(),
                            (infoPending.getTimeStamp() - infoPending.getRepeatInterval()) / 1000,
                            epochTime.toString(), infoPending.getApplication(),
                            infoPending.getRepeatInterval() / 1000));
                    displayInfo.append(rb.getString("alarm.tooltip.suffix"));
                    return displayInfo.toString();
                }
                return null;
            }
        });

    }

    plot.setDataset(alarmDataCollection);
}

From source file:FBMsgExtractor.MessageFormatting.java

public MessageFormatting() {
    File inFile = new File(
            "J:\\Uni Work Backup\\Dropbox\\Alex Facebook Thread\\After Parsing\\TrimmedMessages.txt");
    try {//from   w  w w .j a v  a2  s  .c o m
        leagueIDs = new HashMap<>();

        leagueIDs.put("36819082", "Ben Beowulf Reid");
        leagueIDs.put("514098273", "Reginald Amukoshi Emvula");
        leagueIDs.put("36818470", "Alex Holehouse");
        leagueIDs.put("61416976", "Gregory van der Donk");
        leagueIDs.put("503074462", "James Rees");
        leagueIDs.put("505420379", "Jonathan Cain");
        leagueIDs.put("286302858", "Nick Cool Swallow");
        leagueIDs.put("502555542", "Ben Morgan");
        leagueIDs.put("500535605", "Vernon Silson");

        Date date = new Date();

        messageDetails = new HashMap<>();

        int counter = 0;

        outPut = new PrintWriter(
                "J:\\Uni Work Backup\\Dropbox\\Alex Facebook Thread\\After Parsing\\CleanedMessages.txt");

        br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile)));
        String line;

        while (((line = br.readLine()) != null)) //&& (count < 100))
        {

            if (line.trim().equals(""))
                continue;

            if (line.startsWith("***LEAGUETHREAD***")) {
                messageDetails.put("*ThreadNumber", line.replace("***LEAGUETHREAD***", "").trim());
                continue;
            }

            if (line.startsWith("***TITLE***")) {
                messageDetails.put("*Title", line.replace("***TITLE***", "").trim());
                continue;
            }

            if (line.startsWith("***MARKER***")) {
                messageDetails.put("*Marker", line.replace("***MARKER***", "").trim());
                continue;
            }

            if (line.startsWith("MessageID:")) {
                messageDetails.put("*MessageID", line.replace("MessageID:", "").trim());
                continue;
            }

            if (line.startsWith("Time:")) {
                line = line.replace("Time: ", "");
                long tempTime = Long.parseLong(line.trim());
                date.setTime(tempTime);
                messageDetails.put("*Time", date.toString());
                continue;
            }

            if (line.startsWith("Author:")) {
                line = line.replace("Author: ", "").trim();
                messageDetails.put("*Author", leagueIDs.get(line));
                continue;
            }

            if (line.startsWith("Message:")) {
                line = line.replace("Message:", "");
                String tempMessage = new String(StringEscapeUtils.unescapeHtml4(line).getBytes("ISO-8859-1"))
                        .trim();

                messageDetails.put("*Message", tempMessage);
            }

            if (line.startsWith("Link:")) {
                line = line.replace("Link: ", "");
                line = line.replace("***LINK: \"", "***LINK: ");
                line = line.replace(" ImageShack</span>", "");
                line = line.replace("</span>", "").trim();

                line = StringEscapeUtils.unescapeHtml4(line);

                line = line.replace("http://lm.facebook.com/l.php?u=", "");
                line = line.replace("https://m.facebook.com/l.php?u=", "");

                String tempLink = "";
                char[] linkArray = line.toCharArray();

                for (int i = (line.indexOf("***LINK:") + 8); i < line.indexOf("||"); i++) {
                    tempLink += linkArray[i];

                }
                tempLink = tempLink.trim();

                line = line.replace(tempLink, "***URL***");

                tempLink = URLDecoder.decode(tempLink, "ISO-8859-1");

                line = line.replace("***URL***", tempLink);

                messageDetails.put("*Link", line);
                messageDetails.put("*LinkURL", tempLink);
                continue;
            }

            if (line.startsWith("Image:")) {
                line = line.replace("Image:", "");
                line = line.replace("***IMAGE: \"", "***IMAGE: ").trim();

                line = StringEscapeUtils.unescapeHtml4(line);

                String tempLink = "";
                char[] linkArray = line.toCharArray();

                for (int i = (line.indexOf("***IMAGE:") + 9); i < line.indexOf("\""); i++) {
                    tempLink += linkArray[i];

                }
                tempLink = tempLink.trim();

                char[] cutLine = line.toCharArray();
                String tempLine = "";

                for (int i = 0; i < line.indexOf(tempLink); i++) {
                    tempLine += cutLine[i];
                }

                tempLink = URLDecoder.decode(tempLink, "ISO-8859-1");
                tempLink = tempLink.replaceAll("s100x100/", "");
                tempLink = tempLink.replaceAll("s75x225/", "");
                tempLink = tempLink.replaceAll("p50x50/", "");
                tempLink = tempLink.replaceAll("&preview=1&width=194&height=194", "");

                tempLine += tempLink;
                tempLine = tempLine.trim();

                messageDetails.put("*Image", tempLine);
                messageDetails.put("*ImageURL", tempLink);
                continue;
            }

            if (line.startsWith("***END***")) {
                if (line.contains(""))
                    System.out.println(messageDetails.get("*Marker"));

                if (messageDetails.containsKey("*ThreadNumber")) {
                    outPut.println("League Thread " + messageDetails.get("*ThreadNumber"));
                    System.out.println(messageDetails.get("*ThreadNumber") + "-" + messageDetails.get("*Time")
                            + "-" + messageDetails.get("*Title"));
                    outPut.println();
                }

                if (messageDetails.containsKey("*Title")) {
                    outPut.println("Title: " + messageDetails.get("*Title"));
                    outPut.println();
                }

                if (messageDetails.containsKey("*Marker")) {
                    outPut.println("*************");
                    outPut.println("Marker: " + messageDetails.get("*Marker"));
                }

                if (messageDetails.containsKey("*MessageID")) {
                    outPut.println("MessageID: " + messageDetails.get("*MessageID"));
                }

                if (messageDetails.containsKey("*Author")) {
                    outPut.println("Author: " + messageDetails.get("*Author"));
                }

                if (messageDetails.containsKey("*Time")) {
                    outPut.println("Time: " + messageDetails.get("*Time"));
                    outPut.println();
                }

                //if(messageDetails.containsKey("*Image") && messageDetails.containsKey("*Link"))
                //System.out.println(messageDetails.get("*Marker"));

                if (messageDetails.containsKey("*Image")) {
                    String tempImage = messageDetails.get("*Image");

                    if (messageDetails.containsKey("*Message")) {
                        tempImage = tempImage.replace(messageDetails.get("*Message"), "").trim();
                    }

                    outPut.println("Image: " + tempImage);
                    outPut.println("ImageURL: " + messageDetails.get("*ImageURL"));
                    outPut.println();
                }

                if (messageDetails.containsKey("*Link")) {
                    String tempLink = messageDetails.get("*Link");

                    if (messageDetails.containsKey("*Message")) {
                        tempLink = tempLink.replace(messageDetails.get("*Message"), "").trim();
                    }

                    outPut.println("Link: " + tempLink);
                    outPut.println("LinkURL: " + messageDetails.get("*LinkURL"));
                    outPut.println();
                }

                if (messageDetails.containsKey("*Message")) {
                    outPut.println("Message: " + messageDetails.get("*Message"));
                    outPut.println();
                }

                messageDetails.clear();
                outPut.println("***END***");
                outPut.println();
            }

            outPut.flush();
        }
        outPut.close();

    } catch (Exception e) {
        System.out.println(e);
    }

}

From source file:com.xunlei.util.DateUtils.java

/**
 * <p>//ww  w.  ja  v  a 2 s  . c  o  m
 * Internal calculation method.
 * </p>
 * 
 * @param val the calendar
 * @param field the field constant
 * @param modType type to truncate, round or ceiling
 * @throws ArithmeticException if the year is over 280 million
 */
static void modify(Calendar val, int field, int modType) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (MODIFY_TRUNCATE == modType || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                // This is our field... we stop looping
                if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) {
                    if (field == DateUtils.SEMI_MONTH) {
                        // This is a special case that's hard to generalize
                        // If the date is 1, we round up to 16, otherwise
                        // we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- START ---------------
                    } else if (field == Calendar.AM_PM) {
                        // This is a special case
                        // If the time is 0, we round up to 12, otherwise
                        // we subtract 12 hours and add 1 day
                        if (val.get(Calendar.HOUR_OF_DAY) == 0) {
                            val.add(Calendar.HOUR_OF_DAY, 12);
                        } else {
                            val.add(Calendar.HOUR_OF_DAY, -12);
                            val.add(Calendar.DATE, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- END ---------------
                    } else {
                        // We need at add one to this field since the
                        // last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        // We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        // These are special types of fields that require different rounding rules
        switch (field) {
        case DateUtils.SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                // If we're going to drop the DATE field's value,
                // we want to do this our own way.
                // We need to subtrace 1 since the date has a minimum of 1
                offset = val.get(Calendar.DATE) - 1;
                // If we're above 15 days adjustment, that means we're in the
                // bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                // Record whether we're in the top or bottom half of that range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                // If we're going to drop the HOUR field's value,
                // we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset >= 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            // Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            // Set roundUp if this is more than half way between the minimum and maximum
            roundUp = offset > ((max - min) / 2);
        }
        // We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

private void parseAsAtom(Document doc, Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems,
        ArrayList<Enclosure> enclosures) {
    // parse all 'item' elements
    NodeList nl = doc.getElementsByTagName("entry");
    for (int i = 0; i < nl.getLength(); i++) {
        FeedItem feedItem = new FeedItem();
        Node node = nl.item(i);/* w  ww .j  a v  a 2s  .  co m*/
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

            feedItem.mTitle = extractValue(eElement, "title");
            feedItem.mGUID = extractValue(eElement, "id");
            feedItem.mCleanDescription = extractValue(eElement, "summary");
            feedItem.mDescription = extractValue(eElement, "content");
            feedItem.mOriginalLink = extractValue(eElement, "feedburner:origLink");

            feedItem.mImageURL = extractAttribute(eElement, "media:thumbnail", "url");

            NodeList authorNodes = eElement.getElementsByTagName("author");
            for (int j = 0; j < authorNodes.getLength(); ++j) {
                if (authorNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    feedItem.mAuthor = extractValue((Element) (authorNodes.item(j)), "name");
                    if (feedItem.mAuthor.length() > 0) {
                        break;
                    }
                }
            }

            Date pubDate = new Date();
            pubDate.setTime(0);

            String pubDateString = extractValue(eElement, "updated");
            try {
                pubDate = parseRFC3339Date(pubDateString);
            } catch (ParseException exc) {
                mLog.e("unable to parse item pubdate:" + pubDateString);
            }
            feedItem.mPubDate = pubDate;

            NodeList linksList = eElement.getElementsByTagName("link");
            if (linksList != null) {
                for (int j = 0; j < linksList.getLength(); ++j) {
                    NamedNodeMap linkAttributes = linksList.item(j).getAttributes();
                    Node relNode = linkAttributes.getNamedItem("rel");
                    if (relNode == null) {
                        continue;
                    }
                    String rel = relNode.getNodeValue();
                    if (rel.equals("alternate") && feedItem.mLink.length() == 0) {
                        feedItem.mLink = extractAttribute(eElement, "link", "href");
                    } else if (rel.equals("enclosure")) {
                        Enclosure enclosure = new Enclosure();

                        Node enclosureURL = linkAttributes.getNamedItem("href");
                        Node enclosureLength = linkAttributes.getNamedItem("length");
                        Node enclosureType = linkAttributes.getNamedItem("type");

                        if (enclosureURL != null) {
                            enclosure.mURL = enclosureURL.getNodeValue();
                        }

                        if (enclosureLength != null) {
                            try {
                                enclosure.mLength = Long.parseLong(enclosureLength.getNodeValue());
                            } catch (NumberFormatException exc) {
                                mLog.e("error parsing enclosure length", exc);
                            }
                        }

                        if (enclosureType != null) {
                            enclosure.mContentType = enclosureType.getNodeValue();
                        }

                        // TODO - find a better way to do this
                        // nuke image enclosures for now
                        if (enclosure.mContentType.startsWith("image/")) {
                            enclosure.mURL = "";
                        }

                        if (enclosure.mURL.length() > 0) {
                            try {
                                URL url = new URL(enclosure.mURL);

                                feedItem.mEnclosureURL = url.toExternalForm();
                                enclosure.mURL = url.toExternalForm();
                                feedItem.mEnclosure = enclosure;

                                enclosures.add(enclosure);
                            } catch (MalformedURLException exc) {
                                mLog.e("error parsing enclosure url", exc);
                            }
                        }
                    }
                }
            }

            if (feedItem.mLink.length() > 0) {
                feedItems.add(feedItem);
            }
        }
    } // proccess all entries

    // parse all 'feed' elements
    nl = doc.getElementsByTagName("feed");
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // extract ttl
            Element eElement = (Element) node;
            if (feed != null) {
                String title = extractValue(eElement, "title");
                String link = extractAttribute(eElement, "link", "href");
                String description = extractValue(eElement, "subtitle");

                feed.mName = title;
                feed.mLink = link;
                feed.mDescription = description;
                feed.mImageURL = extractValue(eElement, "icon");
            }
        }

        feedStatus.mTTL = 10;
    }
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

private void parseAsRss(Document doc, Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems,
        ArrayList<Enclosure> enclosures) {
    // parse all 'item' elements
    NodeList nl = doc.getElementsByTagName("item");
    for (int i = 0; i < nl.getLength(); i++) {
        FeedItem feedItem = new FeedItem();
        Node node = nl.item(i);/*from   ww w.  j  a v a 2 s  .  c om*/
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

            feedItem.mTitle = extractValue(eElement, "title");
            feedItem.mLink = extractValue(eElement, "link");
            feedItem.mGUID = extractValue(eElement, "guid");
            feedItem.mAuthor = extractValue(eElement, "author");
            feedItem.mDescription = extractValue(eElement, "description");
            feedItem.mOriginalLink = extractValue(eElement, "feedburner:origLink");

            feedItem.mImageURL = extractAttribute(eElement, "media:thumbnail", "url");

            if (feedItem.mAuthor.length() == 0) {
                feedItem.mAuthor = extractValue(eElement, "dc:creator");
            }

            Date pubDate = new Date();
            pubDate.setTime(0);

            String pubDateString = extractValue(eElement, "pubDate");
            try {
                pubDate = parseRFC822Date(pubDateString);
            } catch (ParseException exc) {
                mLog.e("unable to parse item pubdate:" + pubDateString);
            }
            feedItem.mPubDate = pubDate;

            NodeList enclosuresList = eElement.getElementsByTagName("enclosure");
            if (enclosuresList != null && enclosuresList.getLength() > 0) {
                NamedNodeMap enclosureAttributes = enclosuresList.item(0).getAttributes();
                if (enclosureAttributes != null) {
                    Enclosure enclosure = new Enclosure();

                    Node enclosureURL = enclosureAttributes.getNamedItem("url");
                    Node enclosureLength = enclosureAttributes.getNamedItem("length");
                    Node enclosureType = enclosureAttributes.getNamedItem("type");

                    if (enclosureURL != null) {
                        enclosure.mURL = enclosureURL.getNodeValue();
                    }

                    if (enclosureLength != null) {
                        try {
                            enclosure.mLength = Long.parseLong(enclosureLength.getNodeValue());
                        } catch (NumberFormatException exc) {
                            mLog.e("error parsing enclosure length", exc);
                        }
                    }

                    if (enclosureType != null) {
                        enclosure.mContentType = enclosureType.getNodeValue();
                    }

                    String duration = extractValue(eElement, "itunes:duration");
                    if (duration != null && duration.length() > 0) {
                        enclosure.mDuration = Utilities.parseDuration(duration) * 1000;
                    }

                    duration = extractAttribute(eElement, "media:content", "duration");
                    if (duration != null && duration.length() > 0) {
                        enclosure.mDuration = Utilities.parseDuration(duration) * 1000;
                    }

                    duration = extractValue(eElement, "blip:runtime");
                    if (duration != null && duration.length() > 0) {
                        enclosure.mDuration = Utilities.parseDuration(duration) * 1000;
                    }

                    // TODO - find a better way to do this
                    // nuke image enclosures for now
                    if (enclosure.mContentType.startsWith("image/")) {
                        enclosure.mURL = "";
                    }

                    if (enclosure.mURL.length() > 0) {
                        try {
                            URL url = new URL(enclosure.mURL);

                            feedItem.mEnclosureURL = url.toExternalForm();
                            enclosure.mURL = url.toExternalForm();
                            feedItem.mEnclosure = enclosure;

                            enclosures.add(enclosure);
                        } catch (MalformedURLException exc) {
                            mLog.e("error parsing enclosure url", exc);
                        }
                    }
                }
            }

            feedItems.add(feedItem);
        }
    }

    // parse all 'channel' elements
    nl = doc.getElementsByTagName("channel");
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // extract ttl
            Element eElement = (Element) node;
            String ttlString = extractValue(eElement, "ttl");

            if (ttlString.length() > 0) {
                try {
                    feedStatus.mTTL = Integer.parseInt(ttlString);
                } catch (NumberFormatException exc) {
                    mLog.e("error parsing ttl: " + ttlString, exc);
                }
            }

            if (feed != null) {
                String title = extractValue(eElement, "title");
                String link = extractValue(eElement, "link");
                String description = extractValue(eElement, "description");

                feed.mName = title;
                feed.mLink = link;
                feed.mDescription = description;

                Node imageNode = eElement.getElementsByTagName("image").item(0);
                if (imageNode != null && imageNode.getNodeType() == Node.ELEMENT_NODE) {
                    String imageUrl = extractValue((Element) imageNode, "url");
                    feed.mImageURL = imageUrl;
                }
            }
        }
    }
}

From source file:com.adito.replacementproxy.RequestProcessor.java

public void processRequest() throws Exception {

    // Create our own map of headers so they can be edited
    headerMap = new HeaderMap();
    for (Enumeration e = request.getFieldNames(); e.hasMoreElements();) {
        String n = (String) e.nextElement();
        for (Enumeration e2 = request.getFieldValues(n); e2.hasMoreElements();) {
            String v = (String) e2.nextElement();
            headerMap.putHeader(n, v);/*w w  w  .ja  v a2 s.  c  om*/
        }
    }

    // Build up the parameter map
    requestParameters = new RequestParameterMap(request);
    proxyURIDetails = requestParameters.getProxiedURIDetails();

    VariableReplacement r = new VariableReplacement();
    r.setRequest(request);
    r.setSession(launchSession.getSession());
    r.setPolicy(launchSession.getPolicy());
    String actualURL = r.replace(webForward.getDestinationURL());

    if (proxyURIDetails.getProxiedURL() == null) {
        throw new Exception("No sslex_url parameter provided.");
    }

    if (log.isDebugEnabled())
        log.debug("Proxying [" + request.getMethod() + "] " + proxyURIDetails.getProxiedURL());

    URL proxiedURLBase = proxyURIDetails.getProxiedURLBase();
    if (log.isDebugEnabled())
        log.debug("Proxied URL base " + proxiedURLBase.toExternalForm());

    // The web forward may restrict access to the target URL
    PropertyList restrictTo = webForward.getRestrictToHosts();
    if (!restrictTo.isEmpty()) {
        boolean found = proxiedURLBase.getHost().equals(new URL(actualURL).getHost());
        for (Iterator i = restrictTo.iterator(); !found && i.hasNext();) {
            String host = (String) i.next();
            if (proxiedURLBase.getHost().matches(Util.parseSimplePatternToRegExp(host))) {
                found = true;
            }
        }
        if (!found) {
            throw new Exception("This resource (" + proxiedURLBase.toExternalForm()
                    + ") is restricted to a list of target hosts. This host is not in the list.");
        }

    }

    // Determine if the page can be retrieved from cache

    getFromCache = false;
    Date expiryDate = null;
    if (cache != null && HttpConstants.METHOD_GET.equals(request.getMethod())
            && cache.contains(proxyURIDetails.getProxiedURL())) {
        getFromCache = true;

        // HTTP 1.0
        String cacheControl = request.getField(HttpConstants.HDR_PRAGMA);
        if (cacheControl != null && cacheControl.equalsIgnoreCase("no-cache")) {
            getFromCache = false;
        } else {
            String ifModifiedSince = request.getField(HttpConstants.HDR_IF_MODIFIED_SINCE);
            if (ifModifiedSince != null) {
                try {
                    // Dont get from cache if
                    getFromCache = false;
                } catch (Exception e) {
                }
            }
        }

        // HTTP 1.1
        if (getFromCache) {
            cacheControl = request.getField(HttpConstants.HDR_CACHE_CONTROL);
            if (cacheControl != null) {
                StringTokenizer tok = new StringTokenizer(cacheControl, ";");
                while (tok.hasMoreTokens()) {
                    String t = tok.nextToken().trim();
                    String tl = t.toLowerCase();
                    if (t.startsWith("no-cache") || t.startsWith("no-store")) {
                        getFromCache = false;
                    } else if (tl.startsWith("max-age")) {
                        expiryDate = new Date();
                        try {
                            expiryDate.setTime(
                                    expiryDate.getTime() - (Integer.parseInt(Util.valueOfNameValuePair(tl))));
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }

        // Check expiry
        if (getFromCache) {
            CacheingOutputStream cos = (CacheingOutputStream) cache.retrieve(proxyURIDetails.getProxiedURL());
            if (expiryDate == null || (expiryDate != null && cos.getCachedDate().after(expiryDate))) {
                // Still ok
            } else {
                if (log.isDebugEnabled())
                    log.debug("Page expired");
                getFromCache = false;
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Not using cached page.");
        }
    }
}

From source file:org.ejbca.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchProviderException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be 
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from  w  ww  .j a  va  2  s.co m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);
    certgen.setSerialNumber(new java.math.BigInteger(serno).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(publicKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey, provider);

    return selfcert;
}