List of usage examples for java.sql Date Date
public Date(long date)
From source file:com.error.hunter.ListenService.java
@SuppressLint("SimpleDateFormat") public static String formatData(long data) { Date d = new Date(data); DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = format2.format(d); return str;/*from w w w . j a v a 2s .c o m*/ }
From source file:javasnack.h2.DbUnitCsvUsageTest.java
@BeforeTest public void prepareDb() throws Exception { tmpDir = FileDirHelper.createTmpDir(); Class.forName("org.h2.Driver"); conn = DriverManager.getConnection("jdbc:h2:mem:test2", "sa", ""); new T1().setup(conn); Calendar c = Calendar.getInstance(); c.clear();/*from w w w. j ava 2 s .c o m*/ c.set(2000, 11, 31, 23, 59, 59); long insertTIM = c.getTimeInMillis(); new T1(true, 10, new BigDecimal(20), 30.0, new Time(insertTIM), new Date(insertTIM), new Timestamp(insertTIM), "'Hello', \"World\"!").insertMe(conn); c.clear(); c.set(2001, 0, 1, 12, 30, 15); insertTIM = c.getTimeInMillis(); new T1(false, 20, new BigDecimal(30), 40.0, new Time(insertTIM), new Date(insertTIM), new Timestamp(insertTIM), "'Hello', \n\"World\"!").insertMe(conn); new T2().setup(conn); new T2(10, "abc").insertMe(conn); new T2(20, "def").insertMe(conn); new T3().setup(conn); new T3("label100").insertMe(conn); new T3("label200").insertMe(conn); new T4().setup(conn); new T4(UnsignedByte.create0x00to0xFFString(), UnsignedByte.create0x00to0xFF(), UnsignedByte.create0x00to0xFF()).insertMe(conn); }
From source file:org.apache.phoenix.end2end.DateTimeIT.java
private String initAtable() throws SQLException { String tableName = generateUniqueName(); ensureTableCreated(getUrl(), tableName, ATABLE_NAME, (byte[][]) null, null); PreparedStatement stmt = conn.prepareStatement("upsert into " + tableName + "(" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_STRING, " + " B_STRING, " + " A_INTEGER, " + " A_DATE, " + " X_DECIMAL, " + " X_LONG, " + " X_INTEGER," + " Y_INTEGER," + " A_BYTE," + " A_SHORT," + " A_FLOAT," + " A_DOUBLE," + " A_UNSIGNED_FLOAT," + " A_UNSIGNED_DOUBLE)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, tenantId);/* www . j a va2 s . c o m*/ stmt.setString(2, ROW1); stmt.setString(3, A_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 1); stmt.setDate(6, date); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 1); stmt.setShort(12, (short) 128); stmt.setFloat(13, 0.01f); stmt.setDouble(14, 0.0001); stmt.setFloat(15, 0.01f); stmt.setDouble(16, 0.0001); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW2); stmt.setString(3, A_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 2); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 2); stmt.setShort(12, (short) 129); stmt.setFloat(13, 0.02f); stmt.setDouble(14, 0.0002); stmt.setFloat(15, 0.02f); stmt.setDouble(16, 0.0002); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW3); stmt.setString(3, A_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 3); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 3); stmt.setShort(12, (short) 130); stmt.setFloat(13, 0.03f); stmt.setDouble(14, 0.0003); stmt.setFloat(15, 0.03f); stmt.setDouble(16, 0.0003); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW4); stmt.setString(3, A_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 4); stmt.setDate(6, date == null ? null : date); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 4); stmt.setShort(12, (short) 131); stmt.setFloat(13, 0.04f); stmt.setDouble(14, 0.0004); stmt.setFloat(15, 0.04f); stmt.setDouble(16, 0.0004); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW5); stmt.setString(3, B_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 5); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 5); stmt.setShort(12, (short) 132); stmt.setFloat(13, 0.05f); stmt.setDouble(14, 0.0005); stmt.setFloat(15, 0.05f); stmt.setDouble(16, 0.0005); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW6); stmt.setString(3, B_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 6); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 6); stmt.setShort(12, (short) 133); stmt.setFloat(13, 0.06f); stmt.setDouble(14, 0.0006); stmt.setFloat(15, 0.06f); stmt.setDouble(16, 0.0006); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW7); stmt.setString(3, B_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 7); stmt.setDate(6, date == null ? null : date); stmt.setBigDecimal(7, BigDecimal.valueOf(0.1)); stmt.setLong(8, 5L); stmt.setInt(9, 5); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 7); stmt.setShort(12, (short) 134); stmt.setFloat(13, 0.07f); stmt.setDouble(14, 0.0007); stmt.setFloat(15, 0.07f); stmt.setDouble(16, 0.0007); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW8); stmt.setString(3, B_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 8); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, BigDecimal.valueOf(3.9)); long l = Integer.MIN_VALUE - 1L; assert (l < Integer.MIN_VALUE); stmt.setLong(8, l); stmt.setInt(9, 4); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 8); stmt.setShort(12, (short) 135); stmt.setFloat(13, 0.08f); stmt.setDouble(14, 0.0008); stmt.setFloat(15, 0.08f); stmt.setDouble(16, 0.0008); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW9); stmt.setString(3, C_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 9); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, BigDecimal.valueOf(3.3)); l = Integer.MAX_VALUE + 1L; assert (l > Integer.MAX_VALUE); stmt.setLong(8, l); stmt.setInt(9, 3); stmt.setInt(10, 300); stmt.setByte(11, (byte) 9); stmt.setShort(12, (short) 0); stmt.setFloat(13, 0.09f); stmt.setDouble(14, 0.0009); stmt.setFloat(15, 0.09f); stmt.setDouble(16, 0.0009); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW10); stmt.setString(3, B_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 7); // Intentionally null stmt.setDate(6, null); stmt.setBigDecimal(7, BigDecimal.valueOf(0.1)); stmt.setLong(8, 5L); stmt.setInt(9, 5); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 7); stmt.setShort(12, (short) 134); stmt.setFloat(13, 0.07f); stmt.setDouble(14, 0.0007); stmt.setFloat(15, 0.07f); stmt.setDouble(16, 0.0007); stmt.execute(); conn.commit(); return tableName; }
From source file:org.geoserver.wms.dimension.RasterTimeDimensionDefaultValueTest.java
private void prepareFutureCoverageData(QName coverageName) throws IOException { SimpleDateFormat tsFormatter = new SimpleDateFormat("yyyyMMdd"); // Prepare the target dates for the dummy coverages to be created Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); long justPast = cal.getTimeInMillis(); cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); long oneMonthInFuture = cal.getTimeInMillis(); cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1); long oneYearInFuture = cal.getTimeInMillis(); // Copy watertemp.zip test coverage resource in the data dir under a different name: GeoServerResourceLoader loader = getCatalog().getResourceLoader(); File targetDir = loader.createDirectory(getDataDirectory().root(), coverageName.getPrefix() + File.separator + coverageName.getLocalPart()); File target = new File(targetDir, coverageName.getLocalPart() + ".zip"); loader.copyFromClassPath("org/geoserver/wms/dimension/watertemp.zip", target); // unpack the archive IOUtils.decompress(target, targetDir); // delete archive target.delete();// w w w . j a v a 2 s . com // Make three new dummy coverage files with the needed timestamps: File input = null; File output = null; FilenameFilter tiffFilter = new DefaultFileFilter("*.tiff"); String[] tiffnames = targetDir.list(tiffFilter); if (tiffnames != null) { if (tiffnames.length > 0) { input = new File(targetDir, tiffnames[0]); output = new File(targetDir, "DUMMY_watertemp_000_" + tsFormatter.format(new Date(justPast)) + "T0000000_12.tiff"); FileUtils.copyFile(input, output); output = new File(targetDir, "DUMMY_watertemp_000_" + tsFormatter.format(new Date(oneMonthInFuture)) + "T0000000_12.tiff"); FileUtils.copyFile(input, output); output = new File(targetDir, "DUMMY_watertemp_000_" + tsFormatter.format(new Date(oneYearInFuture)) + "T0000000_12.tiff"); FileUtils.copyFile(input, output); } } addRasterLayerFromDataDir(WATTEMP_FUTURE, getCatalog()); }
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void insert(final Woonplaats woonplaats) throws DAOException { try {/* w w w . j av a 2s. co m*/ jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("insert into bag_woonplaats (" + "bag_woonplaats_id," + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "woonplaats_naam," + "woonplaats_geometrie," + "officieel," + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer," + "woonplaats_status" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setLong(1, woonplaats.getIdentificatie()); ps.setInt(2, woonplaats.getAanduidingRecordInactief().ordinal()); ps.setLong(3, woonplaats.getAanduidingRecordCorrectie()); ps.setString(4, woonplaats.getWoonplaatsNaam()); ps.setString(5, woonplaats.getWoonplaatsGeometrie()); ps.setInt(6, woonplaats.getOfficieel().ordinal()); ps.setTimestamp(7, new Timestamp(woonplaats.getBegindatumTijdvakGeldigheid().getTime())); if (woonplaats.getEinddatumTijdvakGeldigheid() == null) ps.setNull(8, Types.TIMESTAMP); else ps.setTimestamp(8, new Timestamp(woonplaats.getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(9, woonplaats.getInOnderzoek().ordinal()); ps.setDate(10, new Date(woonplaats.getDocumentdatum().getTime())); ps.setString(11, woonplaats.getDocumentnummer()); ps.setInt(12, woonplaats.getWoonplaatsStatus().ordinal()); return ps; } }); } catch (DataAccessException e) { throw new DAOException("Error inserting woonplaats: " + woonplaats.getIdentificatie(), e); } }
From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java
private Object convertStringTypes(Object val, String javaColType) { String valStr = val.toString(); if (javaColType.equals(BIG_DECIMAL_TYPE)) { return new BigDecimal(valStr); } else if (javaColType.equals(DATE_TYPE) || javaColType.equals(TIME_TYPE) || javaColType.equals(TIMESTAMP_TYPE)) { // Oracle expects timestamps for Date also by default based on version // Just allow all date types to be assignment compatible if (valStr.length() == 10 && valStr.matches("^\\d{4}-\\d{2}-\\d{2}$")) { // Date in yyyy-mm-dd format Date d = Date.valueOf(valStr); if (javaColType.equals(DATE_TYPE)) { return d; } else if (javaColType.equals(TIME_TYPE)) { return new Time(d.getTime()); } else if (javaColType.equals(TIMESTAMP_TYPE)) { return new Timestamp(d.getTime()); }/*from ww w . j a va2s. co m*/ } else if (valStr.length() == 8 && valStr.matches("^\\d{2}:\\d{2}:\\d{2}$")) { // time in hh:mm:ss Time t = Time.valueOf(valStr); if (javaColType.equals(DATE_TYPE)) { return new Date(t.getTime()); } else if (javaColType.equals(TIME_TYPE)) { return t; } else if (javaColType.equals(TIMESTAMP_TYPE)) { return new Timestamp(t.getTime()); } } else if (valStr.length() >= 19 && valStr.length() <= 26 && valStr.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(.\\d+)?$")) { // timestamp in yyyy-mm-dd hh:mm:ss Timestamp ts = Timestamp.valueOf(valStr); if (javaColType.equals(DATE_TYPE)) { return new Date(ts.getTime()); } else if (javaColType.equals(TIME_TYPE)) { return new Time(ts.getTime()); } else if (javaColType.equals(TIMESTAMP_TYPE)) { return ts; } } else { return null; } } else if (javaColType.equals(STRING_TYPE)) { return valStr; } else if (javaColType.equals(BOOLEAN_TYPE)) { return Boolean.valueOf(valStr); } else if (javaColType.equals(BYTE_TYPE)) { return Byte.parseByte(valStr); } else if (javaColType.equals(SHORT_TYPE)) { return Short.parseShort(valStr); } else if (javaColType.equals(INTEGER_TYPE)) { return Integer.parseInt(valStr); } else if (javaColType.equals(LONG_TYPE)) { return Long.parseLong(valStr); } else if (javaColType.equals(FLOAT_TYPE)) { return Float.parseFloat(valStr); } else if (javaColType.equals(DOUBLE_TYPE)) { return Double.parseDouble(valStr); } return null; }
From source file:eionet.meta.service.CSVVocabularyImportServiceTest.java
/** * In this test, one line CSV is imported. Row 1 includes a non existing concept to be imported with data elements * * @throws Exception// w w w .j av a2 s .c o m */ @Test @Rollback public void testIfNewConceptAdded() throws Exception { // get vocabulary folder VocabularyFolder vocabularyFolder = vocabularyService.getVocabularyFolder(TEST_VALID_VOCABULARY_ID); // get initial values of concepts with attributes List<VocabularyConcept> concepts = getVocabularyConceptsWithAttributes(vocabularyFolder); // get reader for CSV file Reader reader = getReaderFromResource("csv_import/csv_import_test_3.csv"); // import CSV into database vocabularyImportService.importCsvIntoVocabulary(reader, vocabularyFolder, false, false); Assert.assertFalse("Transaction rolled back (unexpected)", transactionManager.getTransaction(null).isRollbackOnly()); // manually create values of new concept for comparison VocabularyConcept vc11 = new VocabularyConcept(); // vc11.setId(11); //this field will be updated after re-querying vc11.setIdentifier("csv_test_concept_4"); vc11.setLabel("csv_test_concept_label_4"); vc11.setDefinition("csv_test_concept_def_4"); vc11.setStatus(StandardGenericStatus.VALID); vc11.setAcceptedDate(new Date(System.currentTimeMillis())); vc11.setStatusModified(new Date(System.currentTimeMillis())); // create element attributes (there is only one concept) List<List<DataElement>> elementAttributes = new ArrayList<List<DataElement>>(); DataElement elem = null; String identifier = null; int dataElemId = -1; // skos:prefLabel identifier = "skos:prefLabel"; dataElemId = 8; List<DataElement> elements = new ArrayList<DataElement>(); elem = new DataElement(); elem.setId(dataElemId); elem.setIdentifier(identifier); elem.setAttributeValue("bg_csv_test_concept_4"); elem.setAttributeLanguage("bg"); elements.add(elem); elem = new DataElement(); elem.setId(dataElemId); elem.setIdentifier(identifier); elem.setAttributeValue("bg2_csv_test_concept_4"); elem.setAttributeLanguage("bg"); elements.add(elem); elementAttributes.add(elements); // skos:definition identifier = "skos:definition"; dataElemId = 9; elements = new ArrayList<DataElement>(); elem = new DataElement(); elem.setId(dataElemId); elem.setIdentifier(identifier); elem.setAttributeValue("de_csv_test_concept_4"); elem.setAttributeLanguage("de"); elements.add(elem); elementAttributes.add(elements); vc11.setElementAttributes(elementAttributes); concepts.add(vc11); // get updated values of concepts with attributes List<VocabularyConcept> updatedConcepts = getVocabularyConceptsWithAttributes(vocabularyFolder); Assert.assertEquals("Updated Concepts does not include 4 vocabulary concepts", updatedConcepts.size(), 4); // last object should be the inserted one, so use it is id to set (all other fields are updated manually) vc11.setId(updatedConcepts.get(3).getId()); // compare manually updated objects with queried ones (after import operation) ReflectionAssert.assertReflectionEquals(concepts, updatedConcepts, ReflectionComparatorMode.LENIENT_DATES, ReflectionComparatorMode.LENIENT_ORDER); }
From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java
private void massUpdateTaskGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) { if (CollectionUtils.isNotEmpty(taskGanttItems)) { Lock lock = DistributionLockUtil.getLock("gantt-task-service" + sAccountId); try {//from w w w . ja v a 2 s. c o m final long now = new GregorianCalendar().getTimeInMillis(); if (lock.tryLock(30, TimeUnit.SECONDS)) { try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); PreparedStatement batchTasksStatement = connection.prepareStatement( "UPDATE `m_prj_task` SET " + "taskname = ?, `startdate` = ?, `enddate` = ?, " + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignUser`=?, `ganttindex`=?, " + "`milestoneId`=?, `parentTaskId`=? WHERE `id` = ?"); for (int i = 0; i < taskGanttItems.size(); i++) { TaskGanttItem ganttItem = taskGanttItems.get(i); if (ProjectTypeConstants.TASK.equals(ganttItem.getType())) { batchTasksStatement.setString(1, ganttItem.getName()); batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate())); batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate())); batchTasksStatement.setDate(4, new Date(now)); batchTasksStatement.setDouble(5, ganttItem.getProgress()); batchTasksStatement.setString(6, ganttItem.getAssignUser()); batchTasksStatement.setInt(7, ganttItem.getGanttIndex()); batchTasksStatement.setObject(8, ganttItem.getMilestoneId()); batchTasksStatement.setObject(9, ganttItem.getParentTaskId()); batchTasksStatement.setInt(10, ganttItem.getId()); batchTasksStatement.addBatch(); } } batchTasksStatement.executeBatch(); connection.commit(); } } } catch (Exception e) { throw new MyCollabException(e); } finally { DistributionLockUtil.removeLock("gantt-task-service" + sAccountId); lock.unlock(); } } }
From source file:com.seniordesign.autoresponder.Services.DrivingDetectionService.java
@Override public void onLocationChanged(Location location) { //check and make sure service has not been disabled (safety check) //prevents "rouge" service if (db != null && !db.getDrivingDetectionToggle()) { this.stopSelf(); return;/*from w w w. j a v a 2 s. com*/ } float threshHold = DrivingDetectionInfo.threshHold; ArrayList<LocationRecord> buffer = info.getLocationHistory(); if (DrivingDetectionInfo.isTesting) threshHold = DrivingDetectionInfo.testingThreshHold; //add the location to the buffer info.addToHistory(new LocationRecord(location, new Date(System.currentTimeMillis()))); //notify Location output of an update Intent intent = new Intent(DrivingDetectionService.ACTION_DEBUG_UPDATE); intent.putExtra("Status", this.status); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent); switch (this.status) { case DrivingDetectionService.IDLE: Log.d(TAG, "IDLE reached"); //if threshold exceed, perform a more intensive driving status check if (buffer.size() > 1) { Log.d(TAG, DrivingDetectionInfo.getSpeed(buffer.get(1), buffer.get(0)) + " : " + threshHold); } if (buffer.size() > 1 && DrivingDetectionInfo.getSpeed(buffer.get(1), buffer.get(0)) >= threshHold) { Log.d(TAG, "IDLE threshHold exceeded"); checkDrivingStatus(); } break; case DrivingDetectionService.LOADING_BUFFER: Log.d(TAG, "LOADING_BUFFER reached"); //once the buffer has been filled, remove that buffer and pass it to worker thread if (info.getLocationHistory().size() >= checkPeriod) { //stop location updates so that interval can be increased //LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, me); googleApiClient.disconnect(); //update the service status status = DrivingDetectionService.DETERMINING_STATUS; //segregate the buffer so that its not modified while worker thread is using it loadResults = info.getLocationHistory(); info = new DrivingDetectionInfo(2); //pass the bufferResult to the worker and start the thread //once the worker has made a determination it will send a broadcast with the DRIVING/IDLE status worker = new Thread(new DrivingDetectionWorker(getApplicationContext(), loadResults)); worker.setDaemon(true); worker.start(); // restart the location detection if (checkPlayServices()) { buildGoogleApiClient(); } else { Log.e(TAG, "could not find Google Play Services"); } } break; case DrivingDetectionService.DETERMINING_STATUS: Log.d(TAG, "DETERMINING_STATUS reached"); //do nothing break; case DrivingDetectionService.DRIVING: Log.d(TAG, "DRIVING reached"); //if threshold no longer exceeded, perform a more intensive driving status check if (buffer.size() > 1 && DrivingDetectionInfo.getSpeed(buffer.get(1), buffer.get(0)) < threshHold) { checkDrivingStatus(); } break; default: Log.e(TAG, "unknown status encountered: " + status); break; } //Log.d(TAG, " lat = " + location.getLatitude() + " long = " + location.getLongitude() + " speed = " + location.getSpeed()); //start the worker thread /*worker = new Thread(new DrivingDetectionWorker(getApplicationContext(), info)); worker.setDaemon(true); worker.start();*/ }
From source file:org.kuali.mobility.sakai.service.SakaiForumServiceImpl.java
@Override public ForumThread findThread(String topicId, String threadId, String userId) { ForumThread thread = new ForumThread(); thread.setId(threadId);/* w ww . java 2 s .co m*/ thread.setTopicId(topicId); try { String url = configParamService.findValueByName("Sakai.Url.Base") + "forum_message/topic/" + topicId + ".json"; ResponseEntity<InputStream> is = oncourseOAuthService.oAuthGetRequest(userId, url, "text/html"); String json = IOUtils.toString(is.getBody(), "UTF-8"); JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(json); JSONArray itemArray = jsonObj.getJSONArray("forum_message_collection"); Map<String, Message> messages = new HashMap<String, Message>(); for (int i = 0; i < itemArray.size(); i++) { JSONObject message = itemArray.getJSONObject(i); String messageId = message.getString("messageId"); Message m = messages.get(messageId); if (m == null) { m = new Message(); } m.setId(message.getString("messageId")); m.setTopicId(message.getString("topicId")); m.setCreatedBy(message.getString("authoredBy")); m.setTitle(message.getString("title")); m.setBody(message.getString("body")); m.setIsRead((message.getBoolean("read"))); m.setIndentIndex(message.getInt("indentIndex")); if (m.getBody().equals("null")) { m.setBody("(No message)"); } JSONArray attachmentArray = message.getJSONArray("attachments"); if (attachmentArray != null && !attachmentArray.isEmpty()) { List<Attachment> attachments = new ArrayList<Attachment>(); for (int j = 0; j < attachmentArray.size(); j++) { JSONObject attach = attachmentArray.getJSONObject(j); Attachment attachment = new Attachment(); attachment.setUrl(attach.getString("id")); attachment.setTitle(attach.getString("name")); attachment.setMimeType(attach.getString("type")); attachment.setFileType( determineAttachmentFileType(attachment.getUrl(), attachment.getMimeType())); attachments.add(attachment); } m.setAttachments(attachments); } long time = message.getLong("createdOn"); m.setCreatedTime(time); Date cDate = new Date(time); DateFormat df = new SimpleDateFormat("MM/dd/yyyy h:mm a"); m.setCreatedDate(df.format(cDate)); if (m.getIndentIndex() > 0) { String replyToId = message.getString("replyTo"); m.setIndentIndex(message.getInt("indentIndex")); m.setInReplyTo(replyToId); Message parent = messages.get(replyToId); if (parent == null) { parent = new Message(); messages.put(replyToId, parent); } parent.getReplies().add(m); } messages.put(messageId, m); } Message m = messages.get(threadId); thread.setTitle(m.getTitle()); getThreadMessages(m, thread.getMessages()); } catch (Exception e) { LOG.error(e.getMessage(), e); } return thread; }