List of usage examples for java.sql Date Date
public Date(long date)
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void insert(final Nummeraanduiding nummeraanduiding) throws DAOException { try {/*w ww . j a v a 2 s . c o m*/ jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection .prepareStatement("insert into bag_nummeraanduiding (" + "bag_nummeraanduiding_id," + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "huisnummer," + "officieel," + "huisletter," + "huisnummertoevoeging," + "postcode," + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "type_adresseerbaar_object," + "bron_documentdatum," + "bron_documentnummer," + "nummeraanduiding_status," + "bag_woonplaats_id," + "bag_openbare_ruimte_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setLong(1, nummeraanduiding.getIdentificatie()); ps.setInt(2, nummeraanduiding.getAanduidingRecordInactief().ordinal()); ps.setLong(3, nummeraanduiding.getAanduidingRecordCorrectie()); ps.setInt(4, nummeraanduiding.getHuisnummer()); ps.setInt(5, nummeraanduiding.getOfficieel().ordinal()); if (nummeraanduiding.getHuisletter() == null) ps.setNull(6, Types.VARCHAR); else ps.setString(6, nummeraanduiding.getHuisletter()); if (nummeraanduiding.getHuisnummertoevoeging() == null) ps.setNull(7, Types.VARCHAR); else ps.setString(7, nummeraanduiding.getHuisnummertoevoeging()); if (nummeraanduiding.getPostcode() == null) ps.setNull(8, Types.VARCHAR); else ps.setString(8, nummeraanduiding.getPostcode()); ps.setTimestamp(9, new Timestamp(nummeraanduiding.getBegindatumTijdvakGeldigheid().getTime())); if (nummeraanduiding.getEinddatumTijdvakGeldigheid() == null) ps.setNull(10, Types.TIMESTAMP); else ps.setTimestamp(10, new Timestamp(nummeraanduiding.getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(11, nummeraanduiding.getInOnderzoek().ordinal()); ps.setInt(12, nummeraanduiding.getTypeAdresseerbaarObject().ordinal()); ps.setDate(13, new Date(nummeraanduiding.getDocumentdatum().getTime())); ps.setString(14, nummeraanduiding.getDocumentnummer()); ps.setInt(15, nummeraanduiding.getNummeraanduidingStatus().ordinal()); if (nummeraanduiding.getGerelateerdeWoonplaats() == null) ps.setNull(16, Types.INTEGER); else ps.setLong(16, nummeraanduiding.getGerelateerdeWoonplaats()); ps.setLong(17, nummeraanduiding.getGerelateerdeOpenbareRuimte()); return ps; } }); } catch (DataAccessException e) { throw new DAOException("Error inserting nummeraanduiding: " + nummeraanduiding.getIdentificatie(), e); } }
From source file:adalid.commons.util.TimeUtils.java
public static Date newDate(int year, int monthOfYear, int dayOfMonth) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year);//from w ww.j a va 2 s.c om c.set(Calendar.MONTH, monthOfYear - 1); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return new Date(c.getTimeInMillis()); }
From source file:de.fhg.fokus.openride.services.driver.offer.OfferService.java
@POST @Produces("text/json") @Consumes("*/*")//from w ww . j a v a 2 s . co m public Response postOffer(@Context HttpServletRequest con, @PathParam("username") String username, String json) { System.out.println("postOffer start"); // get the parameter containing the request-information. Enumeration ee = con.getParameterNames(); System.out.println("Elements"); while (ee.hasMoreElements()) { System.out.println("Element: " + ee.nextElement()); } //String json = (String)con.getParameter("json"); System.out.println("json: " + json); if (json != null) { // to use this method client must send json content! // build a List of Objects that shall be available in the JSON context. ArrayList startlist = new ArrayList(); startlist.add(new Offer()); startlist.add(new PostOfferResponse()); XStream x = Utils.getJasonXStreamer(startlist); Offer r = (Offer) x.fromXML(json); // do something with tht information // Add the new ride to DB! CustomerEntity e = customerControllerBean.getCustomerByNickname(username); //RoutePoint[] routepoints = routerBean.getEquiDistantRoutePoints(new Coordinate[]{new Coordinate(r.getRidestartPtLat(), r.getRidestartPtLon()), new Coordinate(r.getRideendPtLat(), r.getRideendPtLon())}, new Timestamp(r.getRidestartTime()), Constants.ROUTE_FASTEST_PATH_DEFAULT, Constants.ROUTER_NEAREST_NEIGHBOR_THRESHOLD, Constants.MATCHING_MAX_ROUTE_POINT_DISTANCE); // FIXME: What shall these parameters contain? Extend the Object! //System.out.println("routpoints: " + routepoints); int rideId = -1; System.out.println("startaddr: " + r.getStartptAddress() + " endptAddr: " + r.getEndptAddress()); if ((rideId = driverUndertakesRideControllerBean.addRide(e.getCustId(), new Point(r.getRidestartPtLon(), r.getRidestartPtLat()), new Point(r.getRideendPtLon(), r.getRideendPtLat()), r.getIntermediatePoints(), //Point[] intermediate route points new Date(r.getRidestartTime()), StringEscapeUtils.unescapeHtml(r.getRideComment()), r.getAcceptableDetourInMin(), r.getAcceptableDetourInKm(), r.getAcceptableDetourInPercent(), r.getOfferedSeatsNo(), StringEscapeUtils.unescapeHtml(r.getOfferedCurrency()), StringEscapeUtils.unescapeHtml(r.getStartptAddress()), StringEscapeUtils.unescapeHtml(r.getEndptAddress()))) == -1) { return Response.status(Response.Status.BAD_REQUEST).build(); } else { Response response = Response.ok(x.toXML(new PostOfferResponse(rideId))).build(); return response; } // in this case no special response-information is needed. } else { return Response.status(Response.Status.NOT_FOUND).build(); } }
From source file:com.huison.DriverAssistant_Web.util.LoginHelper.java
public static void changePassword(final BaseActivity activity, final String username, final String phone, final String oldPassword, final String newPassword) { UmengEventSender.sendEvent(activity, UmengEventTypes.changePW); final ProgressDialog pd = new ProgressDialog(activity); pd.setMessage(""); pd.show();//w ww. ja va 2 s . c o m AsyncHttpClient client = activity.getAsyncHttpClient(); RequestParams params = new RequestParams(); /* * Map<String, String> map = new HashMap<String, String>(); * map.put("sessionkey", BaseActivity.getSESSIONKEY()); * map.put("userid", username); map.put("mob", phone); * map.put("oldpasswork", oldPassword); map.put("passwork", * newPassword); map.put("version", activity.getVersionName()); * params.put("action", CHANGE_PASSWORD_ACTION); params.put("xml", * BaseActivity.getXML(map)); */ try { JSONObject p = new JSONObject(); p.put("mobile", phone); p.put("password", oldPassword); p.put("method", "editpassword"); p.put("version", activity.getVersionName()); p.put("devicetype", "android"); p.put("newpassword", newPassword); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis());// String time = formatter.format(curDate); p.put("time", time); Log.v("", p.toString()); String data = Util.DesJiaMi(p.toString(), "czxms520"); // Log.v("",data); params.put("data", data); } catch (Exception e) { e.printStackTrace(); } client.post(BaseActivity.REQUESTURL, params, new JsonHttpResponseHandler() { @Override public void onDispatchSuccess(int statusCode, Header[] headers, String result) { try { result = Util.decrypt(result, "czxms520"); Log.v(TAG, "JSON" + result); JSONObject jo = new JSONObject(result); String code = jo.getString("code"); String msg = getJSONValueAsString(jo, "message"); if (code.equals("0")) { // jo = jo.getJSONObject("data"); activity.showMessageBoxAndFinish(msg); activity.setPassword(newPassword); } else { activity.showMessageBox(msg); } } catch (JSONException e) { activity.showMessageBox(activity.getText(R.string.server404)); Log.e("change password error", Log.getStackTraceString(e)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailureAnyway(int statusCode, Header[] headers, Throwable throwable, BaseBinaryResponse jsonResponse) { pd.dismiss(); activity.showMessageBox(activity.getText(R.string.server404)); } @Override public void onSuccessAnyway(int statusCode, Header[] headers, BaseBinaryResponse jsonResponse) { pd.dismiss(); // ChangePasswordActivity.instance.finish(); } }); TimeCounter.countTime(activity, pd); }
From source file:gov.nih.nci.integration.caaers.CaAERSParticipantStrategyTest.java
/** * Tests rollback() of Update Participant Registration using the ServiceInvocationStrategy class for failure case * /* www .j av a 2 s . com*/ * @throws IntegrationException - IntegrationException * @throws JAXBException - JAXBException * @throws MalformedURLException - MalformedURLException * @throws SOAPFaultException - SOAPFaultException * * */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void rollbackUpdateRegisterParticipantFailure() throws IntegrationException, SOAPFaultException, MalformedURLException, JAXBException { final Date stTime = new Date(new java.util.Date().getTime()); xsltTransformer.transform(null, null, null); EasyMock.expectLastCall().andAnswer(new IAnswer() { public Object answer() { return getParticipantXMLString(); } }).anyTimes(); final CaaersServiceResponse caaersServiceResponse = getUpdateParticipantResponse(FAILURE); EasyMock.expect(wsClient.updateParticipant((String) EasyMock.anyObject())).andReturn(caaersServiceResponse); EasyMock.replay(wsClient); final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID, getParticipantInterimMessage(), stTime, caAERSUpdateRegistrationServiceInvocationStrategy.getStrategyIdentifier()); final ServiceInvocationResult result = caAERSUpdateRegistrationServiceInvocationStrategy .rollback(serviceInvocationMessage); Assert.assertNotNull(result); }
From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java
/** * This is used for updating a replicafileinfo instance based on the * results of a checksumjob./*from w w w . j a v a2s .c o m*/ * Updates the following fields for the entry in the replicafileinfo: * <br/>- checksum = checksum argument. * <br/>- upload_status = completed. * <br/>- filelist_status = ok. * <br/>- checksum_status = UNKNOWN. * <br/>- checksum_checkdatetime = now. * <br/>- filelist_checkdatetime = now. * * @param replicafileinfoId The unique id for the replicafileinfo. * @param checksum The new checksum for the entry. * @param con An open connection to the archive database */ protected static void updateReplicaFileInfoChecksum(long replicafileinfoId, String checksum, Connection con) { PreparedStatement statement = null; try { // The SQL statement final String sql = "UPDATE replicafileinfo SET checksum = ?, " + "upload_status = ?, filelist_status = ?, checksum_status " + "= ?, checksum_checkdatetime = ?, filelist_checkdatetime = ?" + " WHERE replicafileinfo_guid = ?"; Date now = new Date(Calendar.getInstance().getTimeInMillis()); // complete the SQL statement. statement = DBUtils.prepareStatement(con, sql, checksum, ReplicaStoreState.UPLOAD_COMPLETED.ordinal(), FileListStatus.OK.ordinal(), ChecksumStatus.UNKNOWN.ordinal(), now, now, replicafileinfoId); // execute the SQL statement statement.executeUpdate(); con.commit(); } catch (Exception e) { String msg = "Problems updating the replicafileinfo."; log.warn(msg); throw new IOFailure(msg, e); } finally { DBUtils.closeStatementIfOpen(statement); } }
From source file:org.ednovo.gooru.domain.service.classplan.LearnguideServiceImpl.java
@Override public Learnguide createNewCollection(String lesson, String grade, String[] taxonomyCode, User user, String type, Map<String, String> customFieldAndValueMap, String lessonObjectives) { Learnguide collection = new Learnguide(); ContentType contentType = (ContentType) this.getBaseRepository().get(ContentType.class, ContentType.RESOURCE);//w ww .jav a2s . c o m License license = (License) this.getBaseRepository().get(License.class, License.OTHER); ResourceType resourceType = null; if (type.equalsIgnoreCase(CLASS_PLAN)) { resourceType = (ResourceType) this.getBaseRepository().get(ResourceType.class, ResourceType.Type.CLASSPLAN.getType()); } else if (type.equalsIgnoreCase(CLASS_BOOK)) { resourceType = (ResourceType) this.getBaseRepository().get(ResourceType.class, ResourceType.Type.CLASSBOOK.getType()); } collection.setType(type); collection.setLesson(lesson); collection.setTitle(lesson); collection.setResourceSegments(Learnguide.getSegmentsSkeleton()); collection.setGrade(grade); collection.setContentType(contentType); collection.setGooruOid(UUID.randomUUID().toString()); collection.setLastModified(new Date(System.currentTimeMillis())); collection.setCreatedOn(new Date(System.currentTimeMillis())); collection.setSharing(Sharing.PRIVATE.getSharing()); collection.setUser(user); collection.setOrganization(user.getPrimaryOrganization()); collection.setCreator(user); collection.setLicense(license); collection.setResourceType(resourceType); collection.setUrl(""); collection.setDistinguish(Short.valueOf("0")); collection.setIsFeatured(0); collection.setNarration(""); collection.setRequestPending(0); collection.setGoals(lessonObjectives); // Add taxonomy data List<Code> codeList = new ArrayList<Code>(); if (taxonomyCode != null) { for (String codeId : taxonomyCode) { if (!codeId.equals("-")) { codeList.add((Code) this.getTaxonomyRepository().findCodeByTaxCode(codeId)); } } if (codeList.size() != 0) { Set<Code> taxonomySet = new HashSet<Code>(codeList); collection.setTaxonomySet(taxonomySet); } } this.getLearnguideRepository().save(collection); // Save Resource Folder this.getLearnguideRepository().save(collection); this.getResourceImageUtil().setDefaultThumbnailImageIfFileNotExist((Resource) collection); /* * Commenting this line of code. Organization already saved in resource * level in base class(saveOrUpdate) */ // s3ResourceApiHandler.updateOrganization(collection); UserContentRelationshipUtil.updateUserContentRelationship(collection, user, RELATIONSHIP.CREATE); if (logger.isInfoEnabled()) { logger.info(LogUtil.getApplicationLogStream(LEARN_GUIDE, "Indexing new learnguide with content id as " + collection.getGooruOid())); } final String cacheKey = "e.col.i-" + collection.getContentId().toString(); getRedisService().putValue(cacheKey, JsonSerializer.serializeToJson(collection, true), RedisService.DEFAULT_PROFILE_EXP); indexProcessor.index(collection.getGooruOid(), IndexProcessor.INDEX, COLLECTION); try { revisionHistoryService.createVersion(collection, NEW_COLLECTION); } catch (Exception ex) { ex.printStackTrace(); } return collection; }
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 after purge * * @throws Exception/*from w w w. j a va2 s. c om*/ */ @Test @Rollback public void testIfNewConceptAddedAfterPurge() 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, true, 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 = new ArrayList<VocabularyConcept>(); concepts.add(vc11); // get updated values of concepts with attributes List<VocabularyConcept> updatedConcepts = getVocabularyConceptsWithAttributes(vocabularyFolder); Assert.assertEquals("Updated Concepts does not include 1 vocabulary concept", 1, updatedConcepts.size()); // last object should be the inserted one, so use it is id to set (all other fields are updated manually) vc11.setId(updatedConcepts.get(0).getId()); // compare manually updated objects with queried ones (after import operation) ReflectionAssert.assertReflectionEquals(concepts, updatedConcepts, ReflectionComparatorMode.LENIENT_DATES, ReflectionComparatorMode.LENIENT_ORDER); }
From source file:eu.planets_project.pp.plato.action.project.LoadPlanAction.java
public String startFastTrackEvaluation() { unlockProject();//from w w w . j av a 2 s . c om selectedPlan = new Plan(); selectedPlan.getPlanProperties().setAuthor(user.getFullName()); selectedPlan.getPlanProperties().setPrivateProject(true); selectedPlan.getPlanProperties().setOwner(user.getUsername()); // set Fast Track properties selectedPlan.getState().setValue(PlanState.FTE_INITIALISED); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-kkmmss"); String timestamp = format.format(new Date(System.currentTimeMillis())); String identificationCode = Plan.fastTrackEvaluationPrefix + timestamp; selectedPlan.getProjectBasis().setIdentificationCode(identificationCode); // We have to prevent the user from navigating to the step 'Load plan' // because the user wouldn't be able to leave this step: Going to 'Define // Basis' is not possible as the project hasn't been saved so far. // // We 'activate' the changed flag so that the user is asked to either // save the project or discard changes. TreeNode root = new Node(); root.setName("Root"); selectedPlan.getTree().setRoot(root); // ok - the selected project is free - unlock the old project unlockProject(); // load the selected project (and keep the id!) setPlanPropertiesID(selectedPlan.getPlanProperties().getId()); // Strangely enough the outjection doesnt work here, so to be sure we set the member explicitly Contexts.getSessionContext().set("selectedPlan", selectedPlan); this.initializeProject(selectedPlan); FTrequirements.enter(); return "success"; }
From source file:gemlite.core.internal.db.AsyncEventHelper.java
/** * Set column value at given index in a prepared statement. The implementation * tries using the matching underlying type to minimize any data type * conversions, and avoid creating wrapper Java objects (e.g. {@link Integer} * for primitive int).//from ww w .j a va2 s.c om * * @param type * the SQL type of the column as specified by JDBC {@link Types} * class * @param ps * the prepared statement where the column value has to be set * @param row * the source row as a {@link ResultSet} from where the value has to * be extracted * @param rowPosition * the 1-based position of the column in the provided * <code>row</code> * @param paramIndex * the 1-based position of the column in the target prepared * statement (provided <code>ps</code> argument) * @param sync * the {@link DBSynchronizer} object, if any; it is used to store * whether the current driver is JDBC4 compliant to enable performing * BLOB/CLOB operations {@link PreparedStatement#setBinaryStream}, * {@link PreparedStatement#setCharacterStream} * * @throws SQLException * in case of an exception in setting parameters */ public final void setColumnInPrepStatement(String type, Object val, PreparedStatement ps, final DBSynchronizer sync, int paramIndex) throws SQLException { switch (type) { case JavaTypes.STRING: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.VARCHAR); else { final String realVal = (String) val; ps.setString(paramIndex, realVal); } break; case JavaTypes.INT1: case JavaTypes.INT2: case JavaTypes.INT3: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.INTEGER); else { final int realVal = (int) val; ps.setInt(paramIndex, realVal); } break; case JavaTypes.DOUBLE1: case JavaTypes.DOUBLE2: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DOUBLE); else { final double realVal = (double) val; ps.setDouble(paramIndex, realVal); } break; case JavaTypes.FLOAT1: case JavaTypes.FLOAT2: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.FLOAT); else { final float realVal = (float) val; ps.setDouble(paramIndex, realVal); } break; case JavaTypes.BOOLEAN1: case JavaTypes.BOOLEAN2: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.BOOLEAN); else { final boolean realVal = (boolean) val; ps.setBoolean(paramIndex, realVal); } break; case JavaTypes.DATE_SQL: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DATE); else { final Date realVal = (Date) val; ps.setDate(paramIndex, realVal); } break; case JavaTypes.DATE_UTIL: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DATE); else { final java.util.Date realVal = (java.util.Date) val; ps.setDate(paramIndex, new Date(realVal.getTime())); } break; case JavaTypes.BIGDECIMAL: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DECIMAL); else { final BigDecimal realVal = (BigDecimal) val; ps.setBigDecimal(paramIndex, realVal); } break; case JavaTypes.TIME: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.TIME); else { final Time realVal = (Time) val; ps.setTime(paramIndex, realVal); } break; case JavaTypes.TIMESTAMP: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.TIMESTAMP); else { final Timestamp realVal = (Timestamp) val; ps.setTimestamp(paramIndex, realVal); } break; case JavaTypes.OBJECT: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.JAVA_OBJECT); else { final Object realVal = (Object) val; ps.setObject(paramIndex, realVal); } break; default: throw new UnsupportedOperationException("java.sql.Type = " + type + " not supported"); } }