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:org.oscarehr.integration.born.BORNWbXmlGenerator.java

private void populateRBR(RBR rbr) {
    rbr.setFormVersion(FormVersion.X_2014);

    EFormData efd = eformDataDao.find(eformFdidMap.get("RBR"));
    if (efd != null) {
        Date date = new Date();
        date.setTime(efd.getFormDate().getTime() + efd.getFormTime().getTime());
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//from  w w  w .  j av a 2  s .c  om
        rbr.setLastUpdateDate(cal);
    }

    rbr.setSetID(eformFdidMap.get("RBR"));
    rbr.setVersionID(1);

    if (hasValue("RBR", "visit_date_1w")) {
        populateRBRW01(rbr.addNewRBRW01());
    }
    if (hasValue("RBR", "visit_date_2w")) {
        populateRBRW02(rbr.addNewRBRW02());
    }
    if (hasValue("RBR", "visit_date_1w") || hasValue("RBR", "visit_date_2w")
            || hasValue("RBR", "visit_date_1m")) {
        populateRBRW01W02M01(rbr.addNewRBRW01W02M01());
    }
    if (hasValue("RBR", "visit_date_1m")) {
        populateRBRM01(rbr.addNewRBRM01());
    }

    if (hasValue("RBR", "visit_date_2m")) {
        populateRBRM02(rbr.addNewRBRM02());
    }
    if (hasValue("RBR", "visit_date_4m")) {
        populateRBRM04(rbr.addNewRBRM04());
    }
    if (hasValue("RBR", "visit_date_6m")) {
        populateRBRM06(rbr.addNewRBRM06());
    }
    if (hasValue("RBR", "visit_date_2m") || hasValue("RBR", "visit_date_4m")
            || hasValue("RBR", "visit_date_6m")) {
        populateRBRM02M04M06(rbr.addNewRBRM02M04M06());
    }

    if (hasValue("RBR", "visit_date_9m")) {
        populateRBRM09(rbr.addNewRBRM09());
    }
    if (hasValue("RBR", "visit_date_9m") || hasValue("RBR", "visit_date_12m")) {
        populateRBRM09M1213(rbr.addNewRBRM09M1213());
    }
    if (hasValue("RBR", "visit_date_12m")) {
        populateRBRM1213(rbr.addNewRBRM1213());
    }
    if (hasValue("RBR", "visit_date_15m")) {
        populateRBRM15(rbr.addNewRBRM15());
    }
    if (hasValue("RBR", "visit_date_9m") || hasValue("RBR", "visit_date_12m")
            || hasValue("RBR", "visit_date_15m")) {
        populateRBRM09M1213M15(rbr.addNewRBRM09M1213M15());
    }

    if (hasValue("RBR", "visit_date_18m")) {
        populateRBRM18(rbr.addNewRBRM18());
    }

    if (hasValue("RBR", "visit_date_2y")) {
        populateRBRY23(rbr.addNewRBRY23());
    }
    if (hasValue("RBR", "visit_date_2y") || hasValue("RBR", "visit_date_4y")) {
        populateRBRY23Y45(rbr.addNewRBRY23Y45());
    }
    if (hasValue("RBR", "visit_date_4y")) {
        populateRBRY45(rbr.addNewRBRY45());
    }

}

From source file:com.stylovid.fastbattery.LogViewFragment.java

private void exportCSV() {
    if (ContextCompat.checkSelfPermission(getActivity(),
            P_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(), new String[] { P_WRITE_STORAGE },
                BatteryInfoActivity.PR_LVF_WRITE_STORAGE);
        return;//from  w ww.j  a v  a  2  s . c o m
    }

    String state = Environment.getExternalStorageState();

    if (state != null && state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
        Toast.makeText(getActivity(), pfrag.str.read_only_storage, Toast.LENGTH_SHORT).show();
        return;
    } else if (state == null || !state.equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(getActivity(), pfrag.str.inaccessible_w_reason + state, Toast.LENGTH_SHORT).show();
        return;
    }

    Date d = new Date();
    String csvFileName = "FastBattery-Logs-" + d.getTime() + ".csv";

    File root = Environment.getExternalStorageDirectory();
    File csvFile = new File(root, csvFileName);

    String[] csvFields = { pfrag.str.date, pfrag.str.time, pfrag.str.status, pfrag.str.charge,
            pfrag.str.temperature, pfrag.str.temperature_f, pfrag.str.voltage };

    try {
        if (!csvFile.createNewFile() || !csvFile.canWrite()) {
            Toast.makeText(getActivity(), pfrag.str.inaccessible_storage, Toast.LENGTH_SHORT).show();
            return;
        }

        BufferedWriter buf = new BufferedWriter(new FileWriter(csvFile));

        int cols = csvFields.length;
        int i;
        for (i = 0; i < cols; i++) {
            buf.write(csvFields[i]);
            if (i != cols - 1)
                buf.write(",");
        }
        buf.write("\r\n");

        int statusCode;
        int[] statusCodes;
        int status, plugged, status_age;
        String s;

        for (completeCursor.moveToFirst(); !completeCursor.isAfterLast(); completeCursor.moveToNext()) {
            cols = CSV_ORDER.length;
            for (i = 0; i < cols; i++) {
                if (CSV_ORDER[i].equals(LogDatabase.KEY_TIME)) {
                    d.setTime(completeCursor.getLong(mAdapter.timeIndex));
                    buf.write(mAdapter.dateFormat.format(d) + "," + mAdapter.timeFormat.format(d) + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_STATUS_CODE)) {
                    statusCode = completeCursor.getInt(mAdapter.statusCodeIndex);
                    statusCodes = LogDatabase.decodeStatus(statusCode);
                    status = statusCodes[0];
                    plugged = statusCodes[1];
                    status_age = statusCodes[2];

                    if (status == LogDatabase.STATUS_BOOT_COMPLETED)
                        s = pfrag.str.status_boot_completed;
                    else if (status_age == LogDatabase.STATUS_OLD)
                        s = pfrag.str.log_statuses_old[status];
                    else
                        s = pfrag.str.log_statuses[status];

                    if (plugged > 0)
                        s += " " + pfrag.str.pluggeds[plugged];

                    buf.write(s + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_CHARGE)) {
                    buf.write(String.valueOf(completeCursor.getInt(mAdapter.chargeIndex)) + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_TEMPERATURE)) {
                    int temperature = completeCursor.getInt(mAdapter.temperatureIndex);
                    buf.write(String.valueOf(temperature / 10.0) + ",");
                    buf.write(String.valueOf(java.lang.Math.round(temperature * 9 / 5.0) / 10.0 + 32.0) + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_VOLTAGE)) {
                    buf.write(String.valueOf(completeCursor.getInt(mAdapter.voltageIndex) / 1000.0));
                }
            }
            buf.write("\r\n");
        }
        buf.close();
    } catch (Exception e) {
        Toast.makeText(getActivity(), pfrag.str.inaccessible_storage, Toast.LENGTH_SHORT).show();
        return;
    }

    Toast.makeText(getActivity(), pfrag.str.file_written, Toast.LENGTH_SHORT).show();
}

From source file:com.darshancomputing.BatteryIndicatorPro.LogViewFragment.java

private void exportCSV() {
    String state = Environment.getExternalStorageState();

    if (state != null && state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
        Toast.makeText(activity.context, activity.str.read_only_storage, Toast.LENGTH_SHORT).show();
        return;/*from   w  ww  .  jav a  2  s  .  c o  m*/
    } else if (state == null || !state.equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(activity.context, activity.str.inaccessible_w_reason + state, Toast.LENGTH_SHORT).show();
        return;
    }

    Date d = new Date();
    String csvFileName = "BatteryIndicatorPro-Logs-" + d.getTime() + ".csv";

    File root = Environment.getExternalStorageDirectory();
    File csvFile = new File(root, csvFileName);

    String[] csvFields = { activity.str.date, activity.str.time, activity.str.status, activity.str.charge,
            activity.str.temperature, activity.str.temperature_f, activity.str.voltage };

    try {
        if (!csvFile.createNewFile() || !csvFile.canWrite()) {
            Toast.makeText(activity.context, activity.str.inaccessible_storage, Toast.LENGTH_SHORT).show();
            return;
        }

        BufferedWriter buf = new BufferedWriter(new FileWriter(csvFile));

        int cols = csvFields.length;
        int i;
        for (i = 0; i < cols; i++) {
            buf.write(csvFields[i]);
            if (i != cols - 1)
                buf.write(",");
        }
        buf.write("\r\n");

        int statusCode;
        int[] statusCodes;
        int status, plugged, status_age;
        String s;

        for (completeCursor.moveToFirst(); !completeCursor.isAfterLast(); completeCursor.moveToNext()) {
            cols = CSV_ORDER.length;
            for (i = 0; i < cols; i++) {
                if (CSV_ORDER[i].equals(LogDatabase.KEY_TIME)) {
                    d.setTime(completeCursor.getLong(mAdapter.timeIndex));
                    buf.write(mAdapter.dateFormat.format(d) + "," + mAdapter.timeFormat.format(d) + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_STATUS_CODE)) {
                    statusCode = completeCursor.getInt(mAdapter.statusCodeIndex);
                    statusCodes = LogDatabase.decodeStatus(statusCode);
                    status = statusCodes[0];
                    plugged = statusCodes[1];
                    status_age = statusCodes[2];

                    if (status_age == LogDatabase.STATUS_OLD)
                        s = activity.str.log_statuses_old[status];
                    else
                        s = activity.str.log_statuses[status];
                    if (plugged > 0)
                        s += " " + activity.str.pluggeds[plugged];

                    buf.write(s + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_CHARGE)) {
                    buf.write(String.valueOf(completeCursor.getInt(mAdapter.chargeIndex)) + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_TEMPERATURE)) {
                    int temperature = completeCursor.getInt(mAdapter.temperatureIndex);
                    buf.write(String.valueOf(temperature / 10.0) + ",");
                    buf.write(String.valueOf(java.lang.Math.round(temperature * 9 / 5.0) / 10.0 + 32.0) + ",");
                } else if (CSV_ORDER[i].equals(LogDatabase.KEY_VOLTAGE)) {
                    buf.write(String.valueOf(completeCursor.getInt(mAdapter.voltageIndex) / 1000.0));
                }
            }
            buf.write("\r\n");
        }
        buf.close();
    } catch (Exception e) {
        Toast.makeText(activity.context, activity.str.inaccessible_storage, Toast.LENGTH_SHORT).show();
        return;
    }

    Toast.makeText(activity.context, activity.str.file_written, Toast.LENGTH_SHORT).show();
}

From source file:org.apache.ws.security.util.XmlSchemaDateFormat.java

/**
 * This method was snarfed from <tt>org.apache.axis.encoding.ser.CalendarDeserializer</tt>,
 * which was written by Sam Ruby (rubys@us.ibm.com) and Rich Scheuerle (scheu@us.ibm.com).
 * Better error reporting was added./* w ww  .j  av a  2 s .  c o  m*/
 *
 * @see DateFormat#parse(java.lang.String)
 */
public Date parse(String src, ParsePosition parse_pos) {
    Date date;

    // validate fixed portion of format
    int index = 0;
    try {
        if (src != null) {
            if ((src.charAt(0) == '+') || (src.charAt(0) == '-')) {
                src = src.substring(1);
            }

            if (src.length() < 19) {
                parse_pos.setIndex(src.length() - 1);
                handleParseError(parse_pos, "TOO_FEW_CHARS");
            }
            validateChar(src, parse_pos, index = 4, '-', "EXPECTED_DASH");
            validateChar(src, parse_pos, index = 7, '-', "EXPECTED_DASH");
            validateChar(src, parse_pos, index = 10, 'T', "EXPECTED_CAPITAL_T");
            validateChar(src, parse_pos, index = 13, ':', "EXPECTED_COLON_IN_TIME");
            validateChar(src, parse_pos, index = 16, ':', "EXPECTED_COLON_IN_TIME");
        }

        // convert what we have validated so far
        try {
            synchronized (DATEFORMAT_XSD_ZULU) {
                date = DATEFORMAT_XSD_ZULU.parse((src == null) ? null : (src.substring(0, 19) + ".000Z"));
            }
        } catch (Exception e) {
            throw new NumberFormatException(e.toString());
        }

        index = 19;

        // parse optional milliseconds
        if (src != null) {
            if ((index < src.length()) && (src.charAt(index) == '.')) {
                int milliseconds = 0;
                int start = ++index;

                while ((index < src.length()) && Character.isDigit(src.charAt(index))) {
                    index++;
                }

                String decimal = src.substring(start, index);

                if (decimal.length() == 3) {
                    milliseconds = Integer.parseInt(decimal);
                } else if (decimal.length() < 3) {
                    milliseconds = Integer.parseInt((decimal + "000").substring(0, 3));
                } else {
                    milliseconds = Integer.parseInt(decimal.substring(0, 3));

                    if (decimal.charAt(3) >= '5') {
                        ++milliseconds;
                    }
                }

                // add milliseconds to the current date
                date.setTime(date.getTime() + milliseconds);
            }

            // parse optional timezone
            if (((index + 5) < src.length()) && ((src.charAt(index) == '+') || (src.charAt(index) == '-'))) {
                validateCharIsDigit(src, parse_pos, index + 1, "EXPECTED_NUMERAL");
                validateCharIsDigit(src, parse_pos, index + 2, "EXPECTED_NUMERAL");
                validateChar(src, parse_pos, index + 3, ':', "EXPECTED_COLON_IN_TIMEZONE");
                validateCharIsDigit(src, parse_pos, index + 4, "EXPECTED_NUMERAL");
                validateCharIsDigit(src, parse_pos, index + 5, "EXPECTED_NUMERAL");

                final int hours = (((src.charAt(index + 1) - '0') * 10) + src.charAt(index + 2)) - '0';
                final int mins = (((src.charAt(index + 4) - '0') * 10) + src.charAt(index + 5)) - '0';
                int millisecs = ((hours * 60) + mins) * 60 * 1000;

                // subtract millisecs from current date to obtain GMT
                if (src.charAt(index) == '+') {
                    millisecs = -millisecs;
                }

                date.setTime(date.getTime() + millisecs);
                index += 6;
            }

            if ((index < src.length()) && (src.charAt(index) == 'Z')) {
                index++;
            }

            if (index < src.length()) {
                handleParseError(parse_pos, "TOO_MANY_CHARS");
            }
        }
    } catch (ParseException pe) {
        log.error(pe.toString(), pe);
        index = 0; // IMPORTANT: this tells DateFormat.parse() to throw a ParseException
        parse_pos.setErrorIndex(index);
        date = null;
    }
    parse_pos.setIndex(index);
    return (date);
}

From source file:com.topsec.tsm.sim.event.web.EventQueryController.java

/**
 * ??/*from  www  . ja va2  s . c om*/
 * @param condition
 * @return
 * @throws SQLException
 */
private List<Map<String, Object>> formatChart(Condition condition, HttpServletRequest request)
        throws SQLException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    int length = 0;
    long maxShowNumber = 0;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    try {
        if (condition.getStart_time() == null)
            return list;
        Date st = sdf.parse(condition.getStart_time());
        Date et = sdf.parse(condition.getEnd_time());
        long span = ((et.getTime() - st.getTime()) / 60000 / 60);
        Date beginDate = null;
        if (span <= 24 * 3) {
            length = 13;
            maxShowNumber = ((et.getTime() - st.getTime()) / (60000 * 60));
            beginDate = sdf.parse(condition.getStart_time().substring(0, 13) + ":00:00");
        } else {
            length = 10;
            maxShowNumber = ((et.getTime() - st.getTime()) / (60000 * 24 * 60));
            beginDate = sdf.parse(condition.getStart_time().substring(0, 10) + " 00:00:00");
        }
        //?1
        //??????
        condition.setColumnsSet("SUBSTRING(end_time,1," + length + ")");
        List<Map<String, Object>> eventTimeChart = eventQueryService.getEventsTimeChart(condition);
        while (maxShowNumber + 1 > 0) {
            Map<String, Object> chart = new HashMap<String, Object>();
            if (length == 10) {
                String date = sdf.format(beginDate).substring(0, 10);
                boolean hasValue = false;
                for (Map<String, Object> map : eventTimeChart) {
                    if (date.equals(map.get("eTime"))) {
                        chart.put("y", map.get("count(*)"));
                        hasValue = true;
                    }
                }
                chart.put("x", beginDate.getTime() + "&" + (beginDate.getTime() + 24 * 60 * 60 * 1000 - 1000));
                if (!hasValue) {
                    chart.put("y", 0);
                }
                beginDate.setTime(beginDate.getTime() + 24 * 60 * 60 * 1000);
            } else if (length == 13) {
                String date = sdf.format(beginDate).substring(0, 13);
                boolean hasValue = false;
                for (Map<String, Object> map : eventTimeChart) {
                    if (date.equals(map.get("eTime"))) {
                        chart.put("y", map.get("count(*)"));
                        hasValue = true;
                    }
                }
                chart.put("x", beginDate.getTime() + "&" + (beginDate.getTime() + 60 * 60 * 1000 - 1000));
                if (!hasValue) {
                    chart.put("y", 0);
                }
                beginDate.setTime(beginDate.getTime() + 60 * 60 * 1000);
            }
            list.add(chart);
            maxShowNumber--;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:org.openiam.idm.srvc.synch.srcadapter.WSAdapter.java

@Override
public SyncResponse startSynch(SynchConfig config, SynchReviewEntity sourceReview,
        SynchReviewEntity resultReview) {

    LineObject lineHeader = null;//from  w w w  .  j av  a 2  s  .  c o m
    Date mostRecentRecord = null;

    log.debug("WS SYNCH STARTED ^^^^^^^^");

    SyncResponse res = new SyncResponse(ResponseStatus.SUCCESS);
    SynchReview review = null;
    if (sourceReview != null) {
        review = synchReviewDozerConverter.convertToDTO(sourceReview, false);
    }
    LineObject rowHeaderForReport = null;
    InputStream input = null;

    try {
        final ValidationScript validationScript = org.mule.util.StringUtils.isNotEmpty(
                config.getValidationRule()) ? SynchScriptFactory.createValidationScript(config, review) : null;
        final List<TransformScript> transformScripts = SynchScriptFactory.createTransformationScript(config,
                review);
        final MatchObjectRule matchRule = matchRuleFactory.create(config.getCustomMatchRule()); // check if matchRule exists

        if (validationScript == null || transformScripts == null || matchRule == null) {
            res = new SyncResponse(ResponseStatus.FAILURE);
            res.setErrorText("The problem in initialization of RDBMSAdapter, please check validationScript= "
                    + validationScript + ", transformScripts=" + transformScripts + ", matchRule=" + matchRule
                    + " all must be set!");
            res.setErrorCode(ResponseCode.INVALID_ARGUMENTS);
            return res;
        }

        if (sourceReview != null && !sourceReview.isSourceRejected()) {
            return startSynchReview(config, sourceReview, resultReview, validationScript, transformScripts,
                    matchRule);
        }

        WSOperationCommand serviceCmd = getServiceCommand(config.getWsScript());
        if (serviceCmd == null) {
            SyncResponse resp = new SyncResponse(ResponseStatus.FAILURE);
            resp.setErrorCode(ResponseCode.CLASS_NOT_FOUND);
            return resp;
        }
        List<LineObject> lineObjectList = serviceCmd.execute(config);

        if (CollectionUtils.isNotEmpty(lineObjectList)) {
            lineHeader = lineObjectList.get(0);
        }

        for (LineObject rowObj : lineObjectList) {
            log.debug("-SYNCHRONIZING NEW RECORD ---");
            if (mostRecentRecord == null) {
                mostRecentRecord = rowObj.getLastUpdate();

            } else {
                // if current record is newer than what we saved, then update the most recent record value
                if (mostRecentRecord.before(rowObj.getLastUpdate())) {
                    log.debug("- MostRecentRecord value updated to=" + rowObj.getLastUpdate());
                    mostRecentRecord.setTime(rowObj.getLastUpdate().getTime());
                }
            }

            processLineObject(rowObj, config, resultReview, validationScript, transformScripts, matchRule);

        }

    } catch (ClassNotFoundException cnfe) {
        log.error(cnfe);
        res = new SyncResponse(ResponseStatus.FAILURE);
        res.setErrorCode(ResponseCode.CLASS_NOT_FOUND);
        return res;
    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
        log.error(fe);
        //            auditBuilder.addAttribute(AuditAttributeName.DESCRIPTION, "FileNotFoundException: "+fe.getMessage());
        //            auditLogProvider.persist(auditBuilder);
        SyncResponse resp = new SyncResponse(ResponseStatus.FAILURE);
        resp.setErrorCode(ResponseCode.FILE_EXCEPTION);
        log.debug("WS SYNCHRONIZATION COMPLETE WITH ERRORS ^^^^^^^^");
        return resp;
    } catch (IOException io) {
        io.printStackTrace();
        /*
        synchStartLog.updateSynchAttributes("FAIL", ResponseCode.IO_EXCEPTION.toString(), io.toString());
        auditHelper.logEvent(synchStartLog);
        */
        SyncResponse resp = new SyncResponse(ResponseStatus.FAILURE);
        resp.setErrorCode(ResponseCode.IO_EXCEPTION);
        log.debug("WS SYNCHRONIZATION COMPLETE WITH ERRORS ^^^^^^^^");
        return resp;

    } catch (Exception se) {

        log.error(se);
        SyncResponse resp = new SyncResponse(ResponseStatus.FAILURE);
        resp.setErrorCode(ResponseCode.SQL_EXCEPTION);
        resp.setErrorText(se.toString());
        return resp;

    } finally {
        if (resultReview != null) {
            if (CollectionUtils.isNotEmpty(resultReview.getReviewRecords())) { // add header row
                resultReview.addRecord(generateSynchReviewRecord(lineHeader, true));
            }
        }
    }

    log.debug("WS SYNCH COMPLETE.^^^^^^^^");

    SyncResponse resp = new SyncResponse(ResponseStatus.SUCCESS);
    resp.setLastRecordTime(mostRecentRecord);
    return resp;

}

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

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // 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)));

    // 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;/*ww  w .  j  a  va2s .c om*/
    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;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } 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"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } 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;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

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

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:it.infn.ct.nuclemd.Nuclemd.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {//  w w  w. j  a v  a  2 s.  c o m

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException ex) {
        Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.opencastproject.capture.impl.SchedulerImpl.java

/**
 * Adds to the schedule polling the remote calendar for new jobs to add to the scheduler
 * //  w w  w . ja v a 2s  . c o  m
 * @param sched
 *          The scheduler add the polling tasks to.
 * @param immediate
 *          True to start the polling immediately, false to wait one polling period before starting
 */
private void addCalendarPolling(Scheduler sched, boolean immediate) {
    if (sched == null) {
        log.warn("Unable to add polling tasks to null scheduler!");
        return;
    }

    try {
        // Find the remote endpoint for the scheduler and add the agent's name to it
        String remoteBase = StringUtils
                .trimToNull(configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL));
        if (remoteBase != null && remoteBase.charAt(remoteBase.length() - 1) != '/') {
            remoteBase = remoteBase + "/";
        } else if (remoteBase == null) {
            log.error(
                    "Key {} is missing from the config file or invalid, unable to start polling. Result was {}",
                    CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL, StringUtils.trimToNull(
                            configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL)));
            return;
        }
        remoteCalendarURL = new URL(remoteBase);

        // Times are in minutes in the config file
        calendarPollTime = Long
                .parseLong(configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_REMOTE_POLLING_INTERVAL));
        calendarPollTime = calendarPollTime * CaptureParameters.MINUTES * CaptureParameters.MILLISECONDS;

        if (calendarPollTime >= (1 * CaptureParameters.MINUTES * CaptureParameters.MILLISECONDS)) {
            // Setup the polling
            JobDetail job = new JobDetail("calendarUpdate", JobParameters.RECURRING_TYPE,
                    PollCalendarJob.class);

            Date start = null;
            // Possibly add a delay to prevent an infinite recursion:
            // A new calendar creating a new update which creates a new calendar which...
            if (immediate) {
                start = new Date();
            } else {
                start = new Date(System.currentTimeMillis() + calendarPollTime);
            }

            // We are hardcoding the update to fire at least 10 seconds away from a possible capture start to prevent a
            // race condition between firing a capture and updating the internal calendar. The problem lies in the non-
            // deterministic order of execution when the calendar update fires: We first dump the existing schedule then
            // reschedule with the new data, so if somehow we have a capture which should start within that fraction of a
            // second it would be lost. Changing the update time to 10 seconds off of the full minute mark prevents the
            // issue without resorting to keeping two schedulers around (which doesn't work very well, tried it) or having
            // weird logic around either the start capture or poll calendar jobs to delay one or the other if there will
            // be a conflict.
            // If we're within the first 10 seconds push an extra 10 seconds onto the time
            if (start.getSeconds() < 10) {
                start.setTime(start.getTime() + (10 * CaptureParameters.MILLISECONDS));
                // If we're within the last 10 seconds push an extra 20 seconds onto the time
                // (10 for the last 10 seconds, 10 for the first 10 of the next minute)
            } else if (start.getSeconds() > 50) {
                start.setTime(start.getTime() + (20 * CaptureParameters.MILLISECONDS));
            }

            // Create a new trigger Name Group name Start End # of times to repeat Repeat interval
            SimpleTrigger trigger = new SimpleTrigger(calendarPollingJobName, JobParameters.RECURRING_TYPE,
                    start, null, SimpleTrigger.REPEAT_INDEFINITELY, calendarPollTime);

            trigger.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

            trigger.getJobDataMap().put(JobParameters.SCHEDULER, this);

            // Schedule the update
            sched.scheduleJob(job, trigger);
        } else {
            log.info("{} has been set to less than 1 minute, calendar updates disabled.",
                    CaptureParameters.CAPTURE_SCHEDULE_REMOTE_POLLING_INTERVAL);
        }
    } catch (StringIndexOutOfBoundsException e) {
        log.warn(
                "Unable to build valid scheduling data endpoint from key {}: {}.  Value must end in a / character.",
                CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL,
                configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL));
    } catch (MalformedURLException e) {
        log.warn("Invalid location specified for {} unable to retrieve new scheduling data: {}.",
                CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL,
                configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_REMOTE_ENDPOINT_URL));
    } catch (NumberFormatException e) {
        log.warn("Invalid polling interval for {} unable to retrieve new scheduling data: {}.",
                CaptureParameters.CAPTURE_SCHEDULE_REMOTE_POLLING_INTERVAL,
                configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_REMOTE_POLLING_INTERVAL));
    } catch (SchedulerException e) {
        log.warn("Scheduler exception when attempting to start polling tasks: {}", e);
    }
}

From source file:io.realm.RealmTests.java

@Test
public void copyToRealm() {
    Date date = new Date();
    date.setTime(1000); // Remove ms. precision as Realm doesn't support it yet.
    Dog dog = new Dog();
    dog.setName("Fido");
    RealmList<Dog> list = new RealmList<Dog>();
    list.add(dog);//w  w w .j a v  a2 s.  co m

    AllTypes allTypes = new AllTypes();
    allTypes.setColumnString("String");
    allTypes.setColumnLong(1l);
    allTypes.setColumnFloat(1f);
    allTypes.setColumnDouble(1d);
    allTypes.setColumnBoolean(true);
    allTypes.setColumnDate(date);
    allTypes.setColumnBinary(new byte[] { 1, 2, 3 });
    allTypes.setColumnRealmObject(dog);
    allTypes.setColumnRealmList(list);

    realm.beginTransaction();
    AllTypes realmTypes = realm.copyToRealm(allTypes);
    realm.commitTransaction();

    assertNotSame(allTypes, realmTypes); // Objects should not be considered equal
    assertEquals(allTypes.getColumnString(), realmTypes.getColumnString()); // But they contain the same data
    assertEquals(allTypes.getColumnLong(), realmTypes.getColumnLong());
    assertEquals(allTypes.getColumnFloat(), realmTypes.getColumnFloat(), 0);
    assertEquals(allTypes.getColumnDouble(), realmTypes.getColumnDouble(), 0);
    assertEquals(allTypes.isColumnBoolean(), realmTypes.isColumnBoolean());
    assertEquals(allTypes.getColumnDate(), realmTypes.getColumnDate());
    assertArrayEquals(allTypes.getColumnBinary(), realmTypes.getColumnBinary());
    assertEquals(allTypes.getColumnRealmObject().getName(), dog.getName());
    assertEquals(list.size(), realmTypes.getColumnRealmList().size());
    assertEquals(list.get(0).getName(), realmTypes.getColumnRealmList().get(0).getName());
}