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.apache.metron.dataloads.bulk.ElasticsearchDataPrunerTest.java

@Test
public void testDeletesCorrectIndexes() throws Exception {

    //Mock Cluster Admin
    ClusterAdminClient clusterAdminClient = mock(ClusterAdminClient.class);
    ClusterStateRequestBuilder clusterStateRequestBuilder = mock(ClusterStateRequestBuilder.class);
    ClusterStateResponse clusterStateResponse = mock(ClusterStateResponse.class);
    ClusterState clusterState = mock(ClusterState.class);
    ObjectObjectHashMap<String, IndexMetaData> clusterIndexes = new ObjectObjectHashMap();
    MetaData clusterMetadata = mock(MetaData.class);
    when(adminClient.cluster()).thenReturn(clusterAdminClient);
    when(clusterAdminClient.prepareState()).thenReturn(clusterStateRequestBuilder);
    when(clusterStateRequestBuilder.get()).thenReturn(clusterStateResponse);
    when(clusterStateResponse.getState()).thenReturn(clusterState);
    when(clusterState.getMetaData()).thenReturn(clusterMetadata);

    int numDays = 5;

    Date indexDate = new Date();

    indexDate.setTime(testDate.getTime() - TimeUnit.DAYS.toMillis(numDays));

    for (int i = 0; i < numDays * 24; i++) {

        String indexName = "sensor_index_" + dateFormat.format(indexDate);
        clusterIndexes.put(indexName, null);
        indexDate.setTime(indexDate.getTime() + TimeUnit.HOURS.toMillis(1));

    }//from  ww  w.  j  a v  a 2s  .  c o  m

    when(clusterMetadata.getIndices()).thenReturn(ImmutableOpenMap.copyOf(clusterIndexes));

    EasyMock.expect(deleteIndexResponse.isAcknowledged()).andReturn(true);

    replayAll();
    ElasticsearchDataPruner pruner = new ElasticsearchDataPruner(testDate, 1, configuration, indexClient,
            "sensor_index_");
    pruner.indexClient = indexClient;
    Long deleteCount = pruner.prune();
    assertEquals("Should have pruned 24 indices", 24L, deleteCount.longValue());
    verifyAll();

}

From source file:org.apache.rampart.builder.SymmetricBindingBuilder.java

private String getEncryptedKey(RampartMessageData rmd) throws RampartException {

    Vector results = (Vector) rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);

    for (int i = 0; i < results.size(); i++) {
        WSHandlerResult rResult = (WSHandlerResult) results.get(i);

        Vector wsSecEngineResults = rResult.getResults();

        for (int j = 0; j < wsSecEngineResults.size(); j++) {
            WSSecurityEngineResult wser = (WSSecurityEngineResult) wsSecEngineResults.get(j);
            Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION);
            if (actInt.intValue() == WSConstants.ENCR) {

                if (wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID) != null
                        && ((String) wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID)).length() != 0) {

                    try {

                        String encryptedKeyID = (String) wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID);

                        Date created = new Date();
                        Date expires = new Date();
                        expires.setTime(System.currentTimeMillis() + 300000);
                        EncryptedKeyToken tempTok = new EncryptedKeyToken(encryptedKeyID, created, expires);
                        tempTok.setSecret((byte[]) wser.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY));
                        tempTok.setSHA1(
                                getSHA1((byte[]) wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY)));
                        rmd.getTokenStorage().add(tempTok);

                        return encryptedKeyID;

                    } catch (TrustException e) {
                        throw new RampartException("errorInAddingTokenIntoStore");
                    }//  w w w . j av a 2s .  c  o  m

                }
            }
        }
    }
    return null;
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

public List<Position> getPositions(Device device, int hoursAgo) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        List<Position> positions = new LinkedList<Position>();
        TypedQuery<Position> query = null;
        if (hoursAgo > -1) {
            long nowMs = new Date().getTime();
            Date time = new Date();
            time.setTime(nowMs - hoursAgo * 60 * 60 * 1000);
            query = entityManager.createQuery(
                    "SELECT x FROM Position x WHERE x.device = :device AND x.time > :time ORDER BY x.time ASC",
                    Position.class);
            query.setParameter("time", time);
        } else {/*from   www. j av  a2 s. c  o m*/
            query = entityManager.createQuery(
                    "SELECT x FROM Position x WHERE x.device = :device ORDER BY x.time ASC", Position.class);
        }

        query.setParameter("device", device);
        positions.addAll(query.getResultList());
        return positions;
    }
}

From source file:org.wso2.carbon.registry.social.impl.people.userprofile.PersonManagerImpl.java

/**
 * Add the claim values to the Person object as attributes
 *
 * @param claimValues The claim values of the person
 * @param userId      id of the person/* w  w  w . j a v  a2  s  . c  om*/
 * @return The Person object with attribute values added
 */
private Person getPersonWithClaims(Map<String, String> claimValues, String userId) {
    Person person;
    String displayName = claimValues.get(SocialImplConstants.CLAIM_URI_DISPLAY_NAME);
    Name userName = new NameImpl();
    userName.setGivenName(claimValues.get(SocialImplConstants.CLAIM_URI_GIVEN_NAME));
    userName.setFamilyName(claimValues.get(SocialImplConstants.CLAIM_URI_FAMILY_NAME));
    person = new PersonImpl(userId, displayName, userName);
    String value;
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_NICK_NAME)) != null) {
        person.setNickname(value);
    }
    Organization org = new OrganizationImpl();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_ORGANIZATION)) != null) {
        org.setName(value);
    }
    List<Organization> orgsList = new ArrayList<Organization>();
    orgsList.add(org);
    person.setOrganizations(orgsList);
    Address address = new AddressImpl();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_STREET_ADDRESS)) != null) {
        address.setStreetAddress(value);
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_REGION)) != null) {
        address.setRegion(value);
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_COUNTRY)) != null) {
        address.setCountry(value);
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_LATITUDE)) != null) {
        address.setLatitude(Float.valueOf(value));
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_LONGITUDE)) != null) {
        address.setLongitude(Float.valueOf(value));
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_POSTAL_CODE)) != null) {
        address.setPostalCode(value);
    }
    List<Address> addressList = new ArrayList<Address>();
    addressList.add(address);
    person.setAddresses(addressList);
    List<ListField> emailList = new ArrayList<ListField>();
    ListField email = new ListFieldImpl();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_EMAIL)) != null) {
        email.setValue(value);
    }
    emailList.add(email);
    person.setEmails(emailList);
    List<ListField> phoneNumberList = new ArrayList<ListField>();
    ListField phoneNumber = new ListFieldImpl();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_PHONE_NUMBER)) != null) {
        phoneNumber.setValue(value);
    }
    phoneNumberList.add(phoneNumber);
    person.setPhoneNumbers(phoneNumberList);
    List<ListField> imList = new ArrayList<ListField>();
    ListField im = new ListFieldImpl();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_IM)) != null) {
        im.setValue(value);
    }
    imList.add(im);
    person.setIms(imList);
    List<Url> urlList = new ArrayList<Url>();
    Url url = new UrlImpl();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_URL)) != null) {
        url.setValue(value);
    }
    urlList.add(url);
    person.setUrls(urlList);
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_ABOUT_ME)) != null) {
        person.setAboutMe(value);
    }
    Date birthday = new Date();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_BIRTHDAY)) != null) {
        birthday.setTime(Long.valueOf(value));
    }
    person.setBirthday(birthday);
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_RELATIONSHIP_STATUS)) != null) {
        person.setRelationshipStatus(value);
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_RELIGIOUS_VIEW)) != null) {
        person.setReligion(value);
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_ETHNICITY)) != null) {
        person.setEthnicity(value);
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_GENDER)) != null) {
        person.setGender(Person.Gender.valueOf(value));
    }
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_POLITICAL_VIEW)) != null) {
        person.setPoliticalViews(value);
    }
    List<String> interest = new ArrayList<String>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_INTERESTS)) != null) {
        interest.add(value);
    }
    person.setInterests(interest);
    List<String> books = new ArrayList<String>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_BOOKS)) != null) {
        books.add(value);
    }
    person.setBooks(books);
    person.setJobInterests(claimValues.get(SocialImplConstants.CLAIM_URI_JOB_INTERESTS));
    List<String> languageSpoken = new ArrayList<String>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_LANGUAGE_SPOKEN)) != null) {
        languageSpoken.add(value);
    }
    person.setLanguagesSpoken(languageSpoken);
    List<String> movieList = new ArrayList<String>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_MOVIES)) != null) {
        movieList.add(value);
    }
    person.setMovies(movieList);
    List<String> musicList = new ArrayList<String>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_MUSIC)) != null) {
        musicList.add(value);
    }
    person.setMusic(musicList);
    List<String> quotesList = new ArrayList<String>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_QUOTES)) != null) {
        quotesList.add(value);
    }
    person.setQuotes(quotesList);
    person.setHappiestWhen(claimValues.get(SocialImplConstants.CLAIM_URI_HAPPIEST_WHEN));
    List<Enum<LookingFor>> lookingFor = new ArrayList<Enum<LookingFor>>();
    if ((value = claimValues.get(SocialImplConstants.CLAIM_URI_LOOKING_FOR)) != null) {
        lookingFor.add(LookingFor.valueOf(value));
    }
    person.setLookingFor(lookingFor);

    return person;
}

From source file:org.apache.hadoop.chukwa.dataloader.MetricDataLoader.java

public boolean run() {
    boolean first = true;
    log.info("StreamName: " + source.getName());
    SequenceFile.Reader reader = null;

    try {//from  w ww .  ja v  a2 s  .  com
        // The newInstance() call is a work around for some
        // broken Java implementations
        reader = new SequenceFile.Reader(fs, source, conf);
    } catch (Exception ex) {
        // handle the error
        log.error(ex, ex);
    }
    long currentTimeMillis = System.currentTimeMillis();
    boolean isSuccessful = true;
    String recordType = null;

    ChukwaRecordKey key = new ChukwaRecordKey();
    ChukwaRecord record = new ChukwaRecord();
    String cluster = null;
    int numOfRecords = 0;
    try {
        Pattern p = Pattern.compile("(.*)\\-(\\d+)$");
        int batch = 0;
        while (reader.next(key, record)) {
            numOfRecords++;
            if (first) {
                try {
                    cluster = RecordUtil.getClusterName(record);
                    initEnv(cluster);
                    first = false;
                } catch (Exception ex) {
                    log.error("Initialization failed for: " + cluster + ".  Please check jdbc configuration.");
                    return false;
                }
            }
            String sqlTime = DatabaseWriter.formatTimeStamp(record.getTime());
            log.debug("Timestamp: " + record.getTime());
            log.debug("DataType: " + key.getReduceType());

            String[] fields = record.getFields();
            String table = null;
            String[] priKeys = null;
            HashMap<String, HashMap<String, String>> hashReport = new HashMap<String, HashMap<String, String>>();
            StringBuilder normKey = new StringBuilder();
            String node = record.getValue("csource");
            recordType = key.getReduceType().toLowerCase();
            String dbKey = "report.db.name." + recordType;
            Matcher m = p.matcher(recordType);
            if (dbTables.containsKey(dbKey)) {
                String[] tmp = mdlConfig.findTableName(mdlConfig.get(dbKey), record.getTime(),
                        record.getTime());
                table = tmp[0];
            } else if (m.matches()) {
                String timePartition = "_week";
                int timeSize = Integer.parseInt(m.group(2));
                if (timeSize == 5) {
                    timePartition = "_month";
                } else if (timeSize == 30) {
                    timePartition = "_quarter";
                } else if (timeSize == 180) {
                    timePartition = "_year";
                } else if (timeSize == 720) {
                    timePartition = "_decade";
                }
                int partition = (int) (record.getTime() / timeSize);
                StringBuilder tmpDbKey = new StringBuilder();
                tmpDbKey.append("report.db.name.");
                tmpDbKey.append(m.group(1));
                if (dbTables.containsKey(tmpDbKey.toString())) {
                    StringBuilder tmpTable = new StringBuilder();
                    tmpTable.append(dbTables.get(tmpDbKey.toString()));
                    tmpTable.append("_");
                    tmpTable.append(partition);
                    tmpTable.append("_");
                    tmpTable.append(timePartition);
                    table = tmpTable.toString();
                } else {
                    log.debug(tmpDbKey.toString() + " does not exist.");
                    continue;
                }
            } else {
                log.debug(dbKey + " does not exist.");
                continue;
            }
            log.debug("table name:" + table);
            try {
                priKeys = mdlConfig.get("report.db.primary.key." + recordType).split(",");
            } catch (Exception nullException) {
            }
            for (String field : fields) {
                String keyName = escape(field.toLowerCase(), newSpace);
                String keyValue = escape(record.getValue(field).toLowerCase(), newSpace);
                StringBuilder buildKey = new StringBuilder();
                buildKey.append("normalize.");
                buildKey.append(recordType);
                buildKey.append(".");
                buildKey.append(keyName);
                if (normalize.containsKey(buildKey.toString())) {
                    if (normKey.toString().equals("")) {
                        normKey.append(keyName);
                        normKey.append(".");
                        normKey.append(keyValue);
                    } else {
                        normKey.append(".");
                        normKey.append(keyName);
                        normKey.append(".");
                        normKey.append(keyValue);
                    }
                }
                StringBuilder normalizedKey = new StringBuilder();
                normalizedKey.append("metric.");
                normalizedKey.append(recordType);
                normalizedKey.append(".");
                normalizedKey.append(normKey);
                if (hashReport.containsKey(node)) {
                    HashMap<String, String> tmpHash = hashReport.get(node);
                    tmpHash.put(normalizedKey.toString(), keyValue);
                    hashReport.put(node, tmpHash);
                } else {
                    HashMap<String, String> tmpHash = new HashMap<String, String>();
                    tmpHash.put(normalizedKey.toString(), keyValue);
                    hashReport.put(node, tmpHash);
                }
            }
            for (String field : fields) {
                String valueName = escape(field.toLowerCase(), newSpace);
                String valueValue = escape(record.getValue(field).toLowerCase(), newSpace);
                StringBuilder buildKey = new StringBuilder();
                buildKey.append("metric.");
                buildKey.append(recordType);
                buildKey.append(".");
                buildKey.append(valueName);
                if (!normKey.toString().equals("")) {
                    buildKey = new StringBuilder();
                    buildKey.append("metric.");
                    buildKey.append(recordType);
                    buildKey.append(".");
                    buildKey.append(normKey);
                    buildKey.append(".");
                    buildKey.append(valueName);
                }
                String normalizedKey = buildKey.toString();
                if (hashReport.containsKey(node)) {
                    HashMap<String, String> tmpHash = hashReport.get(node);
                    tmpHash.put(normalizedKey, valueValue);
                    hashReport.put(node, tmpHash);
                } else {
                    HashMap<String, String> tmpHash = new HashMap<String, String>();
                    tmpHash.put(normalizedKey, valueValue);
                    hashReport.put(node, tmpHash);

                }

            }
            Iterator<String> i = hashReport.keySet().iterator();
            while (i.hasNext()) {
                Object iteratorNode = i.next();
                HashMap<String, String> recordSet = hashReport.get(iteratorNode);
                Iterator<String> fi = recordSet.keySet().iterator();
                // Map any primary key that was not included in the report keyName
                StringBuilder sqlPriKeys = new StringBuilder();
                try {
                    for (String priKey : priKeys) {
                        if (priKey.equals("timestamp")) {
                            sqlPriKeys.append(priKey);
                            sqlPriKeys.append(" = \"");
                            sqlPriKeys.append(sqlTime);
                            sqlPriKeys.append("\"");
                        }
                        if (!priKey.equals(priKeys[priKeys.length - 1])) {
                            sqlPriKeys.append(sqlPriKeys);
                            sqlPriKeys.append(", ");
                        }
                    }
                } catch (Exception nullException) {
                    // ignore if primary key is empty
                }
                // Map the hash objects to database table columns
                StringBuilder sqlValues = new StringBuilder();
                boolean firstValue = true;
                while (fi.hasNext()) {
                    String fieldKey = fi.next();
                    if (transformer.containsKey(fieldKey)
                            && transformer.get(fieldKey).intern() != "_delete".intern()) {
                        if (!firstValue) {
                            sqlValues.append(", ");
                        }
                        try {
                            if (dbSchema.get(dbTables.get(dbKey))
                                    .get(transformer.get(fieldKey)) == java.sql.Types.VARCHAR
                                    || dbSchema.get(dbTables.get(dbKey))
                                            .get(transformer.get(fieldKey)) == java.sql.Types.BLOB) {
                                String conversionKey = "conversion." + fieldKey;
                                if (conversion.containsKey(conversionKey)) {
                                    sqlValues.append(transformer.get(fieldKey));
                                    sqlValues.append("=");
                                    sqlValues.append(recordSet.get(fieldKey));
                                    sqlValues.append(conversion.get(conversionKey).toString());
                                } else {
                                    sqlValues.append(transformer.get(fieldKey));
                                    sqlValues.append("=\'");
                                    sqlValues.append(escapeQuotes(recordSet.get(fieldKey)));
                                    sqlValues.append("\'");
                                }
                            } else if (dbSchema.get(dbTables.get(dbKey))
                                    .get(transformer.get(fieldKey)) == java.sql.Types.TIMESTAMP) {
                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                Date recordDate = new Date();
                                recordDate.setTime(Long.parseLong(recordSet.get(fieldKey)));
                                sqlValues.append(transformer.get(fieldKey));
                                sqlValues.append("=\"");
                                sqlValues.append(formatter.format(recordDate));
                                sqlValues.append("\"");
                            } else if (dbSchema.get(dbTables.get(dbKey))
                                    .get(transformer.get(fieldKey)) == java.sql.Types.BIGINT
                                    || dbSchema.get(dbTables.get(dbKey))
                                            .get(transformer.get(fieldKey)) == java.sql.Types.TINYINT
                                    || dbSchema.get(dbTables.get(dbKey))
                                            .get(transformer.get(fieldKey)) == java.sql.Types.INTEGER) {
                                long tmp = 0;
                                try {
                                    tmp = Long.parseLong(recordSet.get(fieldKey).toString());
                                    String conversionKey = "conversion." + fieldKey;
                                    if (conversion.containsKey(conversionKey)) {
                                        tmp = tmp * Long.parseLong(conversion.get(conversionKey).toString());
                                    }
                                } catch (Exception e) {
                                    tmp = 0;
                                }
                                sqlValues.append(transformer.get(fieldKey));
                                sqlValues.append("=");
                                sqlValues.append(tmp);
                            } else {
                                double tmp = 0;
                                tmp = Double.parseDouble(recordSet.get(fieldKey).toString());
                                String conversionKey = "conversion." + fieldKey;
                                if (conversion.containsKey(conversionKey)) {
                                    tmp = tmp * Double.parseDouble(conversion.get(conversionKey).toString());
                                }
                                if (Double.isNaN(tmp)) {
                                    tmp = 0;
                                }
                                sqlValues.append(transformer.get(fieldKey));
                                sqlValues.append("=");
                                sqlValues.append(tmp);
                            }
                            firstValue = false;
                        } catch (NumberFormatException ex) {
                            String conversionKey = "conversion." + fieldKey;
                            if (conversion.containsKey(conversionKey)) {
                                sqlValues.append(transformer.get(fieldKey));
                                sqlValues.append("=");
                                sqlValues.append(recordSet.get(fieldKey));
                                sqlValues.append(conversion.get(conversionKey).toString());
                            } else {
                                sqlValues.append(transformer.get(fieldKey));
                                sqlValues.append("='");
                                sqlValues.append(escapeQuotes(recordSet.get(fieldKey)));
                                sqlValues.append("'");
                            }
                            firstValue = false;
                        } catch (NullPointerException ex) {
                            log.error("dbKey:" + dbKey + " fieldKey:" + fieldKey
                                    + " does not contain valid MDL structure.");
                        }
                    }
                }

                StringBuilder sql = new StringBuilder();
                if (sqlPriKeys.length() > 0) {
                    sql.append("INSERT INTO ");
                    sql.append(table);
                    sql.append(" SET ");
                    sql.append(sqlPriKeys.toString());
                    sql.append(",");
                    sql.append(sqlValues.toString());
                    sql.append(" ON DUPLICATE KEY UPDATE ");
                    sql.append(sqlPriKeys.toString());
                    sql.append(",");
                    sql.append(sqlValues.toString());
                    sql.append(";");
                } else {
                    if (sqlValues.length() > 0) {
                        sql.append("INSERT INTO ");
                        sql.append(table);
                        sql.append(" SET ");
                        sql.append(sqlValues.toString());
                        sql.append(" ON DUPLICATE KEY UPDATE ");
                        sql.append(sqlValues.toString());
                        sql.append(";");
                    }
                }
                if (sql.length() > 0) {
                    log.trace(sql);

                    if (batchMode) {
                        stmt.addBatch(sql.toString());
                        batch++;
                    } else {
                        stmt.execute(sql.toString());
                    }
                    if (batchMode && batch > 20000) {
                        int[] updateCounts = stmt.executeBatch();
                        log.info("Batch mode inserted=" + updateCounts.length + "records.");
                        batch = 0;
                    }
                }
            }

        }

        if (batchMode) {
            int[] updateCounts = stmt.executeBatch();
            log.info("Batch mode inserted=" + updateCounts.length + "records.");
        }
    } catch (SQLException ex) {
        // handle any errors
        isSuccessful = false;
        log.error(ex, ex);
        log.error("SQLException: " + ex.getMessage());
        log.error("SQLState: " + ex.getSQLState());
        log.error("VendorError: " + ex.getErrorCode());
    } catch (Exception e) {
        isSuccessful = false;
        log.error(ExceptionUtil.getStackTrace(e));
    } finally {
        if (batchMode && conn != null) {
            try {
                conn.commit();
                log.info("batchMode commit done");
            } catch (SQLException ex) {
                log.error(ex, ex);
                log.error("SQLException: " + ex.getMessage());
                log.error("SQLState: " + ex.getSQLState());
                log.error("VendorError: " + ex.getErrorCode());
            }
        }
        long latencyMillis = System.currentTimeMillis() - currentTimeMillis;
        int latencySeconds = ((int) (latencyMillis + 500)) / 1000;
        String logMsg = (isSuccessful ? "Saved" : "Error occurred in saving");
        log.info(logMsg + " (" + recordType + "," + cluster + ") " + latencySeconds + " sec. numOfRecords: "
                + numOfRecords);
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                log.error(ex, ex);
                log.error("SQLException: " + ex.getMessage());
                log.error("SQLState: " + ex.getSQLState());
                log.error("VendorError: " + ex.getErrorCode());
            }
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                log.error(ex, ex);
                log.error("SQLException: " + ex.getMessage());
                log.error("SQLState: " + ex.getSQLState());
                log.error("VendorError: " + ex.getErrorCode());
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                log.error(ex, ex);
                log.error("SQLException: " + ex.getMessage());
                log.error("SQLState: " + ex.getSQLState());
                log.error("VendorError: " + ex.getErrorCode());
            }
            conn = null;
        }

        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                log.warn("Could not close SequenceFile.Reader:", e);
            }
            reader = null;
        }
    }
    return true;
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

public SOAPEnvelope issue(RahasData data) throws TrustException {

    try {//from  w w w .  j a  v  a 2s  .  co  m
        MessageContext inMsgCtx = data.getInMessageContext();

        SAMLTokenIssuerConfig config = null;
        if (this.configElement != null) {
            config = new SAMLTokenIssuerConfig(
                    configElement.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
        }

        // Look for the file
        if (config == null && this.configFile != null) {
            config = new SAMLTokenIssuerConfig(this.configFile);
        }

        // Look for the param
        if (config == null && this.configParamName != null) {
            Parameter param = inMsgCtx.getParameter(this.configParamName);
            if (param != null && param.getParameterElement() != null) {
                config = new SAMLTokenIssuerConfig(param.getParameterElement()
                        .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
            } else {
                throw new TrustException("expectedParameterMissing", new String[] { this.configParamName });
            }
        }

        if (config == null) {
            throw new TrustException("configurationIsNull");
        }

        //initialize and set token persister and config in configuration context.
        if (TokenIssuerUtil.isPersisterConfigured(config)) {
            TokenIssuerUtil.manageTokenPersistenceSettings(config, inMsgCtx);
        }

        // Set the DOM impl to DOOM
        DocumentBuilderFactoryImpl.setDOOMRequired(true);

        SOAPEnvelope env = TrustUtil
                .createSOAPEnvelope(inMsgCtx.getEnvelope().getNamespace().getNamespaceURI());

        Crypto crypto;
        if (config.cryptoElement != null) { // crypto props
                                            // defined as
                                            // elements
            crypto = CryptoFactory.getInstance(TrustUtil.toProperties(config.cryptoElement),
                    inMsgCtx.getAxisService().getClassLoader());
        } else { // crypto props defined in a properties file
            crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
                    inMsgCtx.getAxisService().getClassLoader());
        }

        if (StringUtils.isBlank(data.getAppliesToAddress())) {
            audienceRestriction = "defaultAudienceRestriction";
        }

        audienceRestriction = data.getAppliesToAddress();

        // Creation and expiration times
        Date creationTime = new Date();
        Date expirationTime = new Date();
        expirationTime.setTime(creationTime.getTime() + config.ttl);

        // Get the document
        Document doc = ((Element) env).getOwnerDocument();

        // Get the key size and create a new byte array of that size
        int keySize = data.getKeysize();

        keySize = (keySize == -1) ? config.keySize : keySize;

        /*
         * Find the KeyType If the KeyType is SymmetricKey or PublicKey,
         * issue a SAML HoK assertion. - In the case of the PublicKey, in
         * coming security header MUST contain a certificate (maybe via
         * signature)
         * 
         * If the KeyType is Bearer then issue a Bearer assertion
         * 
         * If the key type is missing we will issue a HoK assertion
         */

        String keyType = data.getKeyType();
        SAMLAssertion assertion;
        if (StringUtils.isBlank(keyType)) {
            //According to ws-trust-1.3; <keytype> is an optional URI element.
            if (StringUtils.isNotBlank(data.getAppliesToAddress())) {
                keyType = data.getRstElement().getNamespace().getNamespaceURI()
                        + RahasConstants.KEY_TYPE_SYMM_KEY;

            } else {
                throw new TrustException(TrustException.INVALID_REQUEST,
                        new String[] { "Requested KeyType is missing" });
            }
        }

        if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
                || keyType.endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
            assertion = createHoKAssertion(config, doc, crypto, creationTime, expirationTime, data);
        } else if (keyType.endsWith(RahasConstants.KEY_TYPE_BEARER)) {
            assertion = createBearerAssertion(config, doc, crypto, creationTime, expirationTime, data);
        } else {
            assertion = createBearerAssertion(config, doc, crypto, creationTime, expirationTime, data);
        }

        OMElement rstrElem;
        int wstVersion = data.getVersion();
        if (RahasConstants.VERSION_05_02 == wstVersion) {
            rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, env.getBody());
        } else {
            OMElement rstrcElem = TrustUtil.createRequestSecurityTokenResponseCollectionElement(wstVersion,
                    env.getBody());
            rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, rstrcElem);
        }

        TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(RahasConstants.TOK_TYPE_SAML_10);

        if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
            TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
        }

        if (config.addRequestedAttachedRef) {
            createAttachedRef(rstrElem, assertion.getId(), wstVersion);
            /*
             * TrustUtil.createRequestedAttachedRef(wstVersion, rstrElem, "#" +
             * assertion.getId(), WSConstants.WSS_SAML_KI_VALUE_TYPE);
             */
        }

        if (config.addRequestedUnattachedRef) {
            createUnattachedRef(rstrElem, assertion.getId(), wstVersion);
            /*
             * TrustUtil.createRequestedUnattachedRef(wstVersion, rstrElem, assertion.getId(),
             * WSConstants.WSS_SAML_KI_VALUE_TYPE);
             */
        }

        if (data.getAppliesToAddress() != null) {
            TrustUtil.createAppliesToElement(rstrElem, data.getAppliesToAddress(), data.getAddressingNs());
        }

        // Use GMT time in milliseconds
        DateFormat zulu = new XmlSchemaDateFormat();

        // Add the Lifetime element
        TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu.format(creationTime),
                zulu.format(expirationTime));

        // Create the RequestedSecurityToken element and add the SAML token
        // to it
        OMElement reqSecTokenElem = TrustUtil.createRequestedSecurityTokenElement(wstVersion, rstrElem);
        Token assertionToken;
        try {
            Node tempNode = assertion.toDOM();
            reqSecTokenElem
                    .addChild((OMNode) ((Element) rstrElem).getOwnerDocument().importNode(tempNode, true));

            // Store the token
            assertionToken = new Token(assertion.getId(), (OMElement) assertion.toDOM(), creationTime,
                    expirationTime);

            // At this point we definitely have the secret
            // Otherwise it should fail with an exception earlier
            assertionToken.setSecret(data.getEphmeralKey());

        } catch (SAMLException e) {
            throw new TrustException("samlConverstionError", e);
        }

        if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
                && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {

            // Add the RequestedProofToken
            TokenIssuerUtil.handleRequestedProofToken(data, wstVersion, config, rstrElem, assertionToken, doc);
        }

        if (!config.isTokenStoreDisabled()) {
            assertionToken.setPersistenceEnabled(true);
            TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);
        }

        return env;
    } finally {
        // Unset the DOM impl to default
        DocumentBuilderFactoryImpl.setDOOMRequired(false);
    }

}

From source file:org.apache.rampart.builder.SymmetricBindingBuilder.java

/**
 * @param rmd//from ww  w .j a v a  2  s . co  m
 * @param sigToken
 * @return
 * @throws RampartException
 */
private String setupEncryptedKey(RampartMessageData rmd, Token sigToken) throws RampartException {
    try {
        WSSecEncryptedKey encrKey = this.getEncryptedKeyBuilder(rmd, sigToken);
        String id = encrKey.getId();
        byte[] secret = encrKey.getEphemeralKey();
        // Create a rahas token from this info and store it so we can use
        // it in the next steps

        Date created = new Date();
        Date expires = new Date();
        // TODO make this lifetime configurable ???
        expires.setTime(System.currentTimeMillis() + 300000);
        org.apache.rahas.EncryptedKeyToken tempTok = new org.apache.rahas.EncryptedKeyToken(id,
                (OMElement) encrKey.getEncryptedKeyElement(), created, expires);

        tempTok.setSecret(secret);

        // Set the SHA1 value of the encrypted key, this is used when the encrypted
        // key is referenced via a key identifier of type EncryptedKeySHA1
        tempTok.setSHA1(getSHA1(encrKey.getEncryptedEphemeralKey()));

        rmd.getTokenStorage().add(tempTok);

        String bstTokenId = encrKey.getBSTTokenId();
        // If direct ref is used to refer to the cert
        // then add the cert to the sec header now
        if (bstTokenId != null && bstTokenId.length() > 0) {
            RampartUtil.appendChildToSecHeader(rmd, encrKey.getBinarySecurityTokenElement());
        }

        return id;

    } catch (TrustException e) {
        throw new RampartException("errorInAddingTokenIntoStore");
    }
}

From source file:com.fluidops.iwb.widget.SemWiki.java

/**
 * Set the wiki version that is displayed
 * @param version the version as timestamp
 *//*  w  w  w  . ja  v a  2  s  .c  om*/
public void setVersion(String versionStr) {
    version = null;
    if (!StringUtil.isNullOrEmpty(versionStr)) {
        try {
            Date d = new Date();
            d.setTime(Long.valueOf(versionStr));
            version = d;
        } catch (Exception e) {
            logger.warn("Illegal version request: " + versionStr);
        }
    }
}

From source file:edu.harvard.iq.dvn.core.harvest.HarvesterServiceBean.java

private void createHarvestTimer(HarvestingDataverse dataverse) {
    if (dataverse.isScheduled()) {
        long intervalDuration = 0;
        Calendar initExpiration = Calendar.getInstance();
        initExpiration.set(Calendar.MINUTE, 0);
        initExpiration.set(Calendar.SECOND, 0);
        if (dataverse.getSchedulePeriod().equals(dataverse.SCHEDULE_PERIOD_DAILY)) {
            intervalDuration = 1000 * 60 * 60 * 24;
            initExpiration.set(Calendar.HOUR_OF_DAY, dataverse.getScheduleHourOfDay());

        } else if (dataverse.getSchedulePeriod().equals(dataverse.SCHEDULE_PERIOD_WEEKLY)) {
            intervalDuration = 1000 * 60 * 60 * 24 * 7;
            initExpiration.set(Calendar.HOUR_OF_DAY, dataverse.getScheduleHourOfDay());
            initExpiration.set(Calendar.DAY_OF_WEEK, dataverse.getScheduleDayOfWeek());

        } else {/*from   ww  w .j  a  v a2 s . c  o m*/
            logger.log(Level.WARNING, "Could not set timer for dataverse id, " + dataverse.getId()
                    + ", unknown schedule period: " + dataverse.getSchedulePeriod());
            return;
        }
        Date initExpirationDate = initExpiration.getTime();
        Date currTime = new Date();
        if (initExpirationDate.before(currTime)) {
            initExpirationDate.setTime(initExpiration.getTimeInMillis() + intervalDuration);
        }
        logger.log(Level.INFO, "Setting timer for dataverse " + dataverse.getVdc().getName()
                + ", initial expiration: " + initExpirationDate);
        //            timerService.createTimer(initExpirationDate, intervalDuration, new HarvestTimerInfo(dataverse.getId(), dataverse.getVdc().getName(), dataverse.getSchedulePeriod(), dataverse.getScheduleHourOfDay(), dataverse.getScheduleDayOfWeek()));
        dvnTimerService.createTimer(initExpirationDate, intervalDuration,
                new HarvestTimerInfo(dataverse.getId(), dataverse.getVdc().getName(),
                        dataverse.getSchedulePeriod(), dataverse.getScheduleHourOfDay(),
                        dataverse.getScheduleDayOfWeek()));
    }
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public List<ImagePosition> getImagePositions(int days) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        List<ImagePosition> positions = new LinkedList<ImagePosition>();
        TypedQuery<ImagePosition> query;
        if (days > -1) {
            Date time = new Date();
            long nowMs = time.getTime();
            time.setTime(nowMs - days * 24 * 60 * 60 * 1000);
            query = entityManager.createQuery(
                    "SELECT x FROM ImagePosition x WHERE x.time > :time ORDER BY x.time ASC",
                    ImagePosition.class);
            query.setParameter("time", time);
        } else {//from   w  w  w.  j  a  va  2s  .  c  o  m
            query = entityManager.createQuery("SELECT x FROM ImagePosition x ORDER BY x.time ASC",
                    ImagePosition.class);
        }
        positions.addAll(query.getResultList());
        return positions;
    }
}