List of usage examples for java.util Date setMinutes
@Deprecated public void setMinutes(int minutes)
From source file:com.framework.demo.web.controller.calendar.CalendarController.java
@RequestMapping("/load") @ResponseBody//w ww . ja va2s.c o m public Collection<Map> ajaxLoad(Searchable searchable, @CurrentUser SysUser loginUser) { searchable.addSearchParam("userId_eq", loginUser.getId()); List<PersonalCalendar> calendarList = calendarService.findAllWithNoPageNoSort(searchable); return Lists.<PersonalCalendar, Map>transform(calendarList, new Function<PersonalCalendar, Map>() { public Map apply(PersonalCalendar c) { Map<String, Object> m = Maps.newHashMap(); Date startDate = new Date(c.getStartDate().getTime()); Date endDate = DateUtils.addDays(startDate, c.getLength() - 1); boolean allDays = c.getStartTime() == null && c.getEndTime() == null; if (!allDays) { startDate.setHours(c.getStartTime().getHours()); startDate.setMinutes(c.getStartTime().getMinutes()); startDate.setSeconds(c.getStartTime().getSeconds()); endDate.setHours(c.getEndTime().getHours()); endDate.setMinutes(c.getEndTime().getMinutes()); endDate.setSeconds(c.getEndTime().getSeconds()); } m.put("id", c.getId()); m.put("start", DateFormatUtils.format(startDate, "yyyy-MM-dd HH:mm:ss")); m.put("end", DateFormatUtils.format(endDate, "yyyy-MM-dd HH:mm:ss")); m.put("allDay", allDays); m.put("title", c.getTitle()); m.put("details", c.getDetails()); if (StringUtils.isNotEmpty(c.getBackgroundColor())) { m.put("backgroundColor", c.getBackgroundColor()); m.put("borderColor", c.getBackgroundColor()); } if (StringUtils.isNotEmpty(c.getTextColor())) { m.put("textColor", c.getTextColor()); } return m; } }); }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorTest.java
public void testGoodTransform() throws Exception { IPentahoSession session = new StandaloneSession("test"); KettleSystemListener.environmentInit(session); ModelInfo info = createModel();/* ww w. j a va 2 s.co m*/ CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta()); gen.preview(session); DataRow rows[] = info.getData(); assertNotNull(rows); assertEquals(235, rows.length); Date testDate = new Date(); testDate.setDate(1); testDate.setHours(0); testDate.setMinutes(0); testDate.setMonth(0); testDate.setSeconds(0); testDate.setYear(110); // test the first row // test the data types DataRow row = rows[0]; assertNotNull(row); Object cells[] = row.getCells(); assertNotNull(cells); // assertEquals( 8, cells.length ); assertTrue(cells[0] instanceof Long); assertTrue(cells[1] instanceof Double); assertTrue(cells[2] instanceof Long); assertTrue(cells[3] instanceof Date); assertTrue(cells[4] instanceof String); assertTrue(cells[5] instanceof Long); assertTrue(cells[6] instanceof Double); assertTrue(cells[7] instanceof Boolean); // test the values assertEquals((long) 3, cells[0]); assertEquals(25677.96525, cells[1]); assertEquals((long) 1231, cells[2]); assertEquals(testDate.getYear(), ((Date) cells[3]).getYear()); assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth()); assertEquals(testDate.getDate(), ((Date) cells[3]).getDate()); assertEquals(testDate.getHours(), ((Date) cells[3]).getHours()); // assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing? assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds()); // assertEquals( testDate, cells[3] ); assertEquals("Afghanistan", cells[4]); assertEquals((long) 11, cells[5]); assertEquals(111.9090909, cells[6]); assertEquals(false, cells[7]); // test the second row testDate.setDate(2); // test the data types row = rows[1]; assertNotNull(row); cells = row.getCells(); assertNotNull(cells); assertTrue(cells[0] instanceof Long); assertTrue(cells[1] instanceof Double); assertTrue(cells[2] instanceof Long); assertTrue(cells[3] instanceof Date); assertTrue(cells[4] == null); assertTrue(cells[5] instanceof Long); assertTrue(cells[6] instanceof Double); assertTrue(cells[7] instanceof Boolean); // test the values assertEquals((long) 4, cells[0]); assertEquals(24261.81026, cells[1]); assertEquals((long) 1663, cells[2]); assertEquals(testDate.getYear(), ((Date) cells[3]).getYear()); assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth()); assertEquals(testDate.getDate(), ((Date) cells[3]).getDate()); assertEquals(testDate.getHours(), ((Date) cells[3]).getHours()); // assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing? assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds()); // assertEquals( testDate, cells[3] ); assertEquals(null, cells[4]); // IfNull value does not seem to work assertEquals((long) 7, cells[5]); assertEquals(237.5714286, cells[6]); assertEquals(true, cells[7]); }
From source file:at.general.solutions.android.ical.parser.ICalParserThread.java
private Date parseIcalDate(String dateLine) { try {//from ww w . ja v a 2 s . c o m dateLine = StringUtils.replace(dateLine, ";", ""); Date date = null; if (dateLine.contains(ICalTag.DATE_TIMEZONE)) { String[] parts = StringUtils.split(dateLine, ":"); ICAL_DATETIME_FORMAT.setTimeZone(TimeZone .getTimeZone(parts[0].substring(ICalTag.DATE_TIMEZONE.length(), parts[0].length()))); date = ICAL_DATETIME_FORMAT.parse(parts[1]); ICAL_DATETIME_FORMAT.setTimeZone(icalDefaultTimeZone); } else if (dateLine.contains(ICalTag.DATE_VALUE)) { String[] parts = StringUtils.split(dateLine, ":"); date = ICAL_DATE_FORMAT.parse(parts[1]); date.setHours(0); date.setMinutes(0); date.setSeconds(0); } else { dateLine = StringUtils.replace(dateLine, ":", ""); date = ICAL_DATETIME_FORMAT.parse(dateLine); } return date; } catch (ParseException e) { Log.e(LOG_TAG, "Cant't parse date!", e); return null; } }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java
public void testLoadTable1() throws Exception { IPentahoSession session = new StandaloneSession("test"); KettleSystemListener.environmentInit(session); ModelInfo info = createModel();//from w ww. j a v a 2 s.c om CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta()); // create the model String tableName = info.getStageTableName(); try { gen.execSqlStatement(getDropTableStatement(tableName), getDatabaseMeta(), null); } catch (CsvTransformGeneratorException e) { // table might not be there yet, it is OK } // generate the database table gen.createOrModifyTable(session); // load the table loadTable(gen, info, true, session); // check the results long rowCount = this.getRowCount(tableName); assertEquals((long) 235, rowCount); DatabaseMeta databaseMeta = getDatabaseMeta(); assertNotNull(databaseMeta); Database database = new Database(databaseMeta); assertNotNull(database); database.connect(); Connection connection = null; Statement stmt = null; ResultSet sqlResult = null; try { connection = database.getConnection(); assertNotNull(connection); stmt = database.getConnection().createStatement(); // check the first row Date testDate = new Date(); testDate.setDate(1); testDate.setHours(0); testDate.setMinutes(0); testDate.setMonth(0); testDate.setSeconds(0); testDate.setYear(110); boolean ok = stmt.execute("select * from " + tableName); assertTrue(ok); sqlResult = stmt.getResultSet(); assertNotNull(sqlResult); ok = sqlResult.next(); assertTrue(ok); // test the values assertEquals((long) 3, sqlResult.getLong(1)); assertEquals(25677.96525, sqlResult.getDouble(2)); assertEquals((long) 1231, sqlResult.getLong(3)); assertEquals(testDate.getYear(), sqlResult.getDate(4).getYear()); assertEquals(testDate.getMonth(), sqlResult.getDate(4).getMonth()); assertEquals(testDate.getDate(), sqlResult.getDate(4).getDate()); assertEquals(testDate.getHours(), sqlResult.getTime(4).getHours()); // assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing? assertEquals(testDate.getSeconds(), sqlResult.getTime(4).getSeconds()); // assertEquals( testDate, cells[3] ); assertEquals("Afghanistan", sqlResult.getString(5)); assertEquals((long) 11, sqlResult.getLong(6)); assertEquals(111.9090909, sqlResult.getDouble(7)); assertEquals(false, sqlResult.getBoolean(8)); } finally { sqlResult.close(); stmt.close(); connection.close(); } }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java
public void testGoodTransform() throws Exception { IPentahoSession session = new StandaloneSession("test"); KettleSystemListener.environmentInit(session); String KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL = System.getProperty("KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL", "N"); ModelInfo info = createModel();/*from www. j av a 2s.c o m*/ CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta()); gen.preview(session); DataRow rows[] = info.getData(); assertNotNull(rows); assertEquals(235, rows.length); Date testDate = new Date(); testDate.setDate(1); testDate.setHours(0); testDate.setMinutes(0); testDate.setMonth(0); testDate.setSeconds(0); testDate.setYear(110); // test the first row // test the data types DataRow row = rows[0]; assertNotNull(row); Object cells[] = row.getCells(); assertNotNull(cells); // assertEquals( 8, cells.length ); assertTrue(cells[0] instanceof Long); assertTrue(cells[1] instanceof Double); assertTrue(cells[2] instanceof Long); assertTrue(cells[3] instanceof Date); assertTrue(cells[4] instanceof String); assertTrue(cells[5] instanceof Long); assertTrue(cells[6] instanceof Double); assertTrue(cells[7] instanceof Boolean); // test the values assertEquals((long) 3, cells[0]); assertEquals(25677.96525, cells[1]); assertEquals((long) 1231, cells[2]); assertEquals(testDate.getYear(), ((Date) cells[3]).getYear()); assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth()); assertEquals(testDate.getDate(), ((Date) cells[3]).getDate()); assertEquals(testDate.getHours(), ((Date) cells[3]).getHours()); // assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing? assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds()); // assertEquals( testDate, cells[3] ); assertEquals("Afghanistan", cells[4]); assertEquals((long) 11, cells[5]); assertEquals(111.9090909, cells[6]); assertEquals(false, cells[7]); // test the second row testDate.setDate(2); // test the data types row = rows[1]; assertNotNull(row); cells = row.getCells(); assertNotNull(cells); assertTrue(cells[0] instanceof Long); assertTrue(cells[1] instanceof Double); assertTrue(cells[2] instanceof Long); assertTrue(cells[3] instanceof Date); if ("Y".equals(KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL)) { assertTrue("".equals(cells[4])); } else { assertTrue(cells[4] == null); } assertTrue(cells[5] instanceof Long); assertTrue(cells[6] instanceof Double); assertTrue(cells[7] instanceof Boolean); // test the values assertEquals((long) 4, cells[0]); assertEquals(24261.81026, cells[1]); assertEquals((long) 1663, cells[2]); assertEquals(testDate.getYear(), ((Date) cells[3]).getYear()); assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth()); assertEquals(testDate.getDate(), ((Date) cells[3]).getDate()); assertEquals(testDate.getHours(), ((Date) cells[3]).getHours()); // assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing? assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds()); // assertEquals( testDate, cells[3] ); if ("Y".equals(KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL)) { assertEquals("", cells[4]); assertEquals(cells[4], ""); } else { assertEquals(null, cells[4]); // IfNull value does not seem to work } assertEquals((long) 7, cells[5]); assertEquals(237.5714286, cells[6]); assertEquals(true, cells[7]); }
From source file:org.wso2.carbon.connector.integration.test.tsheets.TSheetsConnectorIntegrationTest.java
/** * Set up the environment.// ww w. j av a 2 s . c o m */ @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { init("tsheets-connector-1.0.2-SNAPSHOT"); esbRequestHeadersMap.put("Accept-Charset", "UTF-8"); esbRequestHeadersMap.put("Content-Type", "application/json"); apiRequestHeadersMap.putAll(esbRequestHeadersMap); apiRequestHeadersMap.put("Authorization", "Bearer " + connectorProperties.getProperty("accessToken")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date = new Date(); SimpleDateFormat sdf01 = new SimpleDateFormat("yyyy-MM-dd"); date.setDate(date.getDate() - 1); String timeSheetTwoEnd = sdf.format(date) + "-07:00"; date.setMinutes(date.getMinutes() - 1); String timeSheetTwoStart = sdf.format(date) + "-07:00"; date.setDate(date.getDate() - 1); String timeSheetOneEnd = sdf.format(date) + "-07:00"; String listTimeSheetOneEnd = sdf01.format(date); date.setMinutes(date.getMinutes() - 1); String timeSheetOneStart = sdf.format(date) + "-07:00"; String listTimeSheetOneStart = sdf01.format(date); connectorProperties.setProperty("timeSheetOneStart", timeSheetOneStart); connectorProperties.setProperty("timeSheetOneEnd", timeSheetOneEnd); connectorProperties.setProperty("timeSheetTwoStart", timeSheetTwoStart); connectorProperties.setProperty("timeSheetTwoEnd", timeSheetTwoEnd); connectorProperties.setProperty("listTimeSheetOneStart", listTimeSheetOneStart); connectorProperties.setProperty("listTimeSheetOneEnd", listTimeSheetOneEnd); }
From source file:module.signature.util.XAdESValidator.java
/** * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)} * @param streamWithSignature//from w w w. j ava2s . co m * the {@link InputStream} that has the signature content * @return true if it's valid, false otherwise */ public boolean validateXMLSignature(InputStream streamWithSignature) { try { // get the xsd schema Validator validator = schemaXSD.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); ErrorHandler eh = new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } }; // parse the document parser.setErrorHandler(eh); Document document = parser.parse(streamWithSignature); // XAdES extension NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object"); // XMLDSIG NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (checkSchema) { if (nlObject.getLength() < 1) { return false; } if (nlSignature.getLength() < 1) { return false; } // parse the XML DOM tree againts the XSD schema validator.validate(new DOMSource(nlSignature.item(0))); } if (checkSignature) { // Validate Every Signature Element (including CounterSignatures) for (int i = 0; i < nlSignature.getLength(); i++) { Element signature = (Element) nlSignature.item(i); // String baseURI = fileToValidate.toURL().toString(); XMLSignature xmlSig = new XMLSignature(signature, null); KeyInfo ki = xmlSig.getKeyInfo(); // If signature contains X509Data if (ki.containsX509Data()) { NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime"); Date signingDate = null; if (nlSigningTime.item(0) != null) { StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent()) .deleteCharAt(22); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); signingDate = simpleDateFormat.parse(xmlDate.toString()); } //verificao OCSP //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente. if (checkRevocation) { //keystore certs cc, raiz estado Security.setProperty("ocsp.enable", "true"); //System.setProperty("com.sun.security.enableCRLDP", "true"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf .generateCertPath(Collections.singletonList(ki.getX509Certificate())); // TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null); // Set trustAnchors = Collections.singleton(trustA); PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore); params.setRevocationEnabled(true); // validar o estado na data da assinatura if (nlSigningTime.item(0) != null) { params.setDate(signingDate); } try { CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX"); CertPathValidatorResult result = cpValidator.validate(certPath, params); //TODO FENIX-196 probably one would want to send a notification here } catch (CertPathValidatorException ex) { return false; } catch (InvalidAlgorithmParameterException ex) { return false; } } // verifica a validade do certificado no momento da assinatura if (checkValidity) { if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES try { ki.getX509Certificate().checkValidity(signingDate); } catch (CertificateExpiredException ex) { return false; } catch (CertificateNotYetValidException ex) { return false; } } } // validate against Certificate Public Key boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey()); if (!validSignature) { return false; } } // if signature includes KeyInfo KeyValue, also check against it if (ki.containsKeyValue()) { boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey()); if (!validSignature) { return false; } } //let's check the SignatureTimeStamp(s) joantune NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp"); Element signatureValue = null; if (signatureTimeStamps.getLength() > 0) { signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0); } for (int j = 0; j < signatureTimeStamps.getLength(); j++) { logger.debug("Found a SignatureTimeStamp"); Element signatureTimeStamp = (Element) signatureTimeStamps.item(j); //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*", "EncapsulatedTimeStamp"); for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) { logger.debug("Found an EncapsulatedTimeStamp"); Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k); //let's check it // note, we have the timestamptoken, not the whole response, that is, we don't have the status field ASN1Sequence signedTimeStampToken = ASN1Sequence .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent())); CMSSignedData cmsSignedData = new CMSSignedData( Base64.decode(encapsulatedTimeStamp.getTextContent())); TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData); //let's construct the Request to make sure this is a valid response //let's generate the digest MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8")); //let's make sure the digests are the same if (!Arrays.equals(digest, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering //FENIX-196 logger.debug("Found a different digest in the timestamp!"); return false; } try { //TODO for now we won't use the provided certificates that came with the TST // X509Store certificateStore = (X509Store) timeStampToken.getCertificates(); // JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder(); // timeStampToken.validate(tsaCert, "BC"); // timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder() // .build(tsaCert), builder.build())); timeStampToken.validate(new SignerInformationVerifier( new JcaContentVerifierProviderBuilder().build(tsaCert), new BcDigestCalculatorProvider())); //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :) Date currentDatePlus5Minutes = new Date(); //let's make it go 5 minutes ahead currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5); if (!timeStampToken.getTimeStampInfo().getGenTime() .before(currentDatePlus5Minutes)) { //FENIX-196 probably we want to log this! //what the heck, timestamp is done in the future!! (clocks might be out of sync) logger.warn("Found a timestamp in the future!"); return false; } logger.debug("Found a valid TimeStamp!"); //as we have no other timestamp elements in this signature, this means all is ok! :) //(point 5) of g.2.2.16.1.3 on the specs } catch (TSPException exception) { logger.debug("TimeStamp response did not validate", exception); return false; } } } } } } catch (IOException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (ParserConfigurationException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (SAXException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Exception ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; }
From source file:com.pearson.dashboard.util.Util.java
public static void retrieveTestResults(DashboardForm dashboardForm, Configuration configuration, String cutoffDateStr, List<String> testSets) throws IOException, URISyntaxException, ParseException { RallyRestApi restApi = loginRally(configuration); QueryRequest testCaseResultsRequest = new QueryRequest("TestCaseResult"); testCaseResultsRequest.setFetch(//from w w w . ja v a2s .c om new Fetch("Build", "TestCase", "TestSet", "Verdict", "FormattedID", "Date", "TestCaseCount")); if (testSets == null || testSets.isEmpty()) { testSets = new ArrayList<String>(); testSets.add("TS0"); } QueryFilter queryFilter = new QueryFilter("TestSet.FormattedID", "=", testSets.get(0)); int q = 1; while (testSets.size() > q) { queryFilter = queryFilter.or(new QueryFilter("TestSet.FormattedID", "=", testSets.get(q))); q++; } testCaseResultsRequest.setLimit(4000); testCaseResultsRequest.setQueryFilter(queryFilter); boolean dataNotReceived = true; while (dataNotReceived) { try { QueryResponse testCaseResultResponse = restApi.query(testCaseResultsRequest); JsonArray array = testCaseResultResponse.getResults(); int numberTestCaseResults = array.size(); dataNotReceived = false; List<Priority> priorities = new ArrayList<Priority>(); Priority priority0 = new Priority(); priority0.setPriorityName("Pass"); Priority priority1 = new Priority(); priority1.setPriorityName("Blocked"); Priority priority2 = new Priority(); priority2.setPriorityName("Error"); Priority priority3 = new Priority(); priority3.setPriorityName("Fail"); Priority priority4 = new Priority(); priority4.setPriorityName("Inconclusive"); Priority priority5 = new Priority(); priority5.setPriorityName("NotAttempted"); List<TestCase> testCases = new ArrayList<TestCase>(); List<TestResult> testResults = new ArrayList<TestResult>(); if (numberTestCaseResults > 0) { for (int i = 0; i < numberTestCaseResults; i++) { TestResult testResult = new TestResult(); TestCase testCase = new TestCase(); String build = array.get(i).getAsJsonObject().get("Build").getAsString(); String verdict = array.get(i).getAsJsonObject().get("Verdict").getAsString(); DateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd"); String strDate = array.get(i).getAsJsonObject().get("Date").getAsString().substring(0, 10); int hour = Integer.parseInt( array.get(i).getAsJsonObject().get("Date").getAsString().substring(11, 13)); int min = Integer.parseInt( array.get(i).getAsJsonObject().get("Date").getAsString().substring(14, 16)); Date date = (Date) formatter1.parse(strDate); date.setHours(hour); date.setMinutes(min); JsonObject testSetJsonObj = array.get(i).getAsJsonObject().get("TestSet").getAsJsonObject(); JsonObject testCaseJsonObj = array.get(i).getAsJsonObject().get("TestCase") .getAsJsonObject(); String testSet = testSetJsonObj.get("FormattedID").getAsString(); String testCaseId = testCaseJsonObj.get("FormattedID").getAsString(); int resultExists = testResultExists(testSet, testCaseId, date, testResults, testCases); if (resultExists != 0) { testResult.setDate(date); testResult.setStatus(verdict); testResult.setTestCase(testCaseId); testResult.setTestSet(testSet); testResults.add(testResult); testCase.setTestCaseId(testCaseId); testCase.setLastVerdict(verdict); testCase.setName(testSet); testCase.setDescription(""); testCase.setLastRun(strDate); testCase.setLastBuild(build); testCase.setPriority(""); testCases.add(testCase); } } } for (TestResult result : testResults) { String verdict = result.getStatus(); if (verdict.equalsIgnoreCase("error")) { priority2.setPriorityCount(priority2.getPriorityCount() + 1); } else if (verdict.equalsIgnoreCase("pass")) { priority0.setPriorityCount(priority0.getPriorityCount() + 1); } else if (verdict.equalsIgnoreCase("fail")) { priority3.setPriorityCount(priority3.getPriorityCount() + 1); } else if (verdict.equalsIgnoreCase("inconclusive")) { priority4.setPriorityCount(priority4.getPriorityCount() + 1); } else if (verdict.equalsIgnoreCase("blocked")) { priority1.setPriorityCount(priority1.getPriorityCount() + 1); } } dashboardForm.setTestCases(testCases); QueryRequest testCaseCountReq = new QueryRequest("TestSet"); testCaseCountReq.setFetch(new Fetch("FormattedID", "Name", "TestCaseCount")); queryFilter = new QueryFilter("FormattedID", "=", testSets.get(0)); q = 1; while (testSets.size() > q) { queryFilter = queryFilter.or(new QueryFilter("FormattedID", "=", testSets.get(q))); q++; } testCaseCountReq.setQueryFilter(queryFilter); QueryResponse testCaseResponse = restApi.query(testCaseCountReq); int testCaseCount = 0; for (int i = 0; i < testCaseResponse.getResults().size(); i++) { testCaseCount = testCaseCount + testCaseResponse.getResults().get(i).getAsJsonObject() .get("TestCaseCount").getAsInt(); } int unAttempted = testCaseCount - priority0.getPriorityCount() - priority1.getPriorityCount() - priority2.getPriorityCount() - priority3.getPriorityCount() - priority4.getPriorityCount(); priority5.setPriorityCount(unAttempted); List<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(priority0.getPriorityCount()); arrayList.add(priority1.getPriorityCount()); arrayList.add(priority2.getPriorityCount()); arrayList.add(priority3.getPriorityCount()); arrayList.add(priority4.getPriorityCount()); arrayList.add(priority5.getPriorityCount()); Integer maximumCount = Collections.max(arrayList); if (maximumCount <= 0) { priority0.setPxSize("0"); priority1.setPxSize("0"); priority2.setPxSize("0"); priority3.setPxSize("0"); priority4.setPxSize("0"); priority5.setPxSize("0"); } else { priority0.setPxSize(Math.round((100 * priority0.getPriorityCount()) / maximumCount) + ""); priority1.setPxSize(Math.round((100 * priority1.getPriorityCount()) / maximumCount) + ""); priority2.setPxSize(Math.round((100 * priority2.getPriorityCount()) / maximumCount) + ""); priority3.setPxSize(Math.round((100 * priority3.getPriorityCount()) / maximumCount) + ""); priority4.setPxSize(Math.round((100 * priority4.getPriorityCount()) / maximumCount) + ""); priority5.setPxSize(Math.round((100 * priority5.getPriorityCount()) / maximumCount) + ""); } priorities.add(priority0); priorities.add(priority1); priorities.add(priority2); priorities.add(priority3); priorities.add(priority4); priorities.add(priority5); dashboardForm.setTestCasesCount(testCaseCount); dashboardForm.setTestCasesPriorities(priorities); } catch (HttpHostConnectException connectException) { if (restApi != null) { restApi.close(); } try { restApi = loginRally(configuration); } catch (URISyntaxException e) { e.printStackTrace(); } } } }
From source file:org.mythdroid.activities.Guide.java
/** * Round the given Date to the nearest column time * @param time/* ww w .j av a2s .co m*/ */ private void roundTime(Date time) { final int mins = time.getMinutes(); final int off = mins % colMins; if (off == 0) return; int half = colMins / 2; if (half * 2 < colMins) half++; if (off < half) time.setMinutes(mins - off); else time.setMinutes(mins + (colMins - off)); }
From source file:org.sakaiproject.evaluation.beans.EvalBeanUtils.java
/** * Sets all the system defaults for this evaluation object * and ensures all required fields are correctly set, * use this whenever you create a new evaluation <br/> * This is guaranteed to be non-destructive (i.e. it will not replace existing values * but it will fixup any required fields which are nulls to default values), * will force null due date to be non-null but will respect the {@link EvalEvaluation#useDueDate} flag * /* w ww.j a va2s .c om*/ * @param eval an {@link EvalEvaluation} object (can be persisted or new) * @param evaluationType a type constant of EvalConstants#EVALUATION_TYPE_*, * if left null then {@link EvalConstants#EVALUATION_TYPE_EVALUATION} is used */ public void setEvaluationDefaults(EvalEvaluation eval, String evaluationType) { // set the type to the default to ensure not null if (eval.getType() == null) { eval.setType(EvalConstants.EVALUATION_TYPE_EVALUATION); } // set to the supplied type if supplied and do any special settings if needed based on the type if (evaluationType != null) { eval.setType(evaluationType); } // only do these for new evals if (eval.getId() == null) { if (eval.getState() == null) { eval.setState(EvalConstants.EVALUATION_STATE_PARTIAL); } } // make sure the dates are set Calendar calendar = new GregorianCalendar(); Date now = new Date(); // if default start hour is set, use it for start time (must be tomorrow as eval cannot start in the past). Integer hour = (Integer) settings.get(EvalSettings.EVAL_DEFAULT_START_HOUR); if (hour != null) { // add 1 day to make it tomorrow now.setTime(now.getTime() + 86400000L); // set desired hour now.setHours(hour); now.setMinutes(0); now.setSeconds(0); } calendar.setTime(now); if (eval.getStartDate() == null) { eval.setStartDate(now); LOG.debug("Setting start date to default of: " + eval.getStartDate()); } else { calendar.setTime(eval.getStartDate()); } if (eval.useDueDate != null && !eval.useDueDate) { // allow evals which are open forever eval.setDueDate(null); eval.setStopDate(null); eval.setViewDate(null); } else { // using the due date calendar.add(Calendar.DATE, 1); // +1 day if (eval.getDueDate() == null) { // default the due date to the end of the start date + 1 day Date endOfDay = EvalUtils.getEndOfDayDate(calendar.getTime()); eval.setDueDate(endOfDay); LOG.debug("Setting due date to default of: " + eval.getDueDate()); } else { calendar.setTime(eval.getDueDate()); } boolean useStopDate; if (eval.useStopDate != null && !eval.useStopDate) { useStopDate = false; } else { useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE); } if (useStopDate) { // assign stop date to equal due date for now if (eval.getStopDate() == null) { eval.setStopDate(eval.getDueDate()); LOG.debug("Setting stop date to default of: " + eval.getStopDate()); } } else { eval.setStopDate(null); } boolean useViewDate; if (eval.useViewDate != null && !eval.useViewDate) { useViewDate = false; } else { useViewDate = (Boolean) settings.get(EvalSettings.EVAL_USE_VIEW_DATE); } if (useViewDate) { // assign default view date calendar.add(Calendar.DATE, 1); if (eval.getViewDate() == null) { // default the view date to the today + 2 eval.setViewDate(calendar.getTime()); LOG.debug("Setting view date to default of: " + eval.getViewDate()); } } else { eval.setViewDate(null); } } // handle the view dates default Boolean useSameViewDates = (Boolean) settings.get(EvalSettings.EVAL_USE_SAME_VIEW_DATES); Date sharedDate = eval.getViewDate() == null ? eval.getDueDate() : eval.getViewDate(); if (eval.getStudentsDate() == null || useSameViewDates) { eval.setStudentsDate(sharedDate); } if (eval.getInstructorsDate() == null || useSameViewDates) { eval.setInstructorsDate(sharedDate); } // results viewable settings Date studentsDate; Boolean studentsView = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_VIEW_RESULTS); if (studentsView != null) { eval.setStudentViewResults(studentsView); } Date instructorsDate; Boolean instructorsView = (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); if (instructorsView != null) { eval.setInstructorViewResults(instructorsView); } // Added by EVALSYS-1063. Modified by EVALSYS-1176. // Will modify the value of EvalEvaluation.instructorViewAllResults property iff current value is null. // Will use value of EvalSettings.INSTRUCTOR_ALLOWED_VIEW_ALL_RESULTS setting if available, false otherwise. Boolean instructorsAllView = eval.getInstructorViewAllResults(); if (instructorsAllView == null) { Boolean instructorsAllViewSetting = (Boolean) settings .get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_ALL_RESULTS); if (instructorsAllViewSetting == null) { eval.setInstructorViewAllResults(Boolean.FALSE); } else { eval.setInstructorViewAllResults(instructorsAllViewSetting); } } // Section awareness default controlled by sakai.property if (eval.getSectionAwareness() == null || !eval.getSectionAwareness()) { eval.setSectionAwareness(EVALSYS_SECTION_AWARE_DEFAULT); } // Results sharing default controlled by sakai.property if (eval.getResultsSharing() == null) { if (!EvalConstants.SHARING_VISIBLE.equals(EVALSYS_RESULTS_SHARING_DEFAULT) && !EvalConstants.SHARING_PRIVATE.equals(EVALSYS_RESULTS_SHARING_DEFAULT) && !EvalConstants.SHARING_PUBLIC.equals(EVALSYS_RESULTS_SHARING_DEFAULT)) { eval.setResultsSharing(EvalConstants.SHARING_VISIBLE); } else { eval.setResultsSharing(EVALSYS_RESULTS_SHARING_DEFAULT); } } // Instructors view results default controlled by sakai.property if ((Boolean) eval.getInstructorViewResults() == null) { eval.setInstructorViewResults(EVALSYS_INSTRUCTOR_VIEW_RESPONSES_DEFAULT); } if (eval.getInstructorViewAllResults() == null) { eval.setInstructorViewAllResults(EVALSYS_INSTRUCTOR_VIEW_RESPONSES_DEFAULT); } if (EvalConstants.SHARING_PRIVATE.equals(eval.getResultsSharing())) { eval.setStudentViewResults(false); eval.setInstructorViewResults(false); eval.setInstructorViewAllResults(false); } else if (EvalConstants.SHARING_PUBLIC.equals(eval.getResultsSharing())) { eval.setStudentViewResults(true); eval.setInstructorViewResults(true); eval.setInstructorViewAllResults(true); studentsDate = eval.getViewDate(); eval.setStudentsDate(studentsDate); instructorsDate = eval.getViewDate(); eval.setInstructorsDate(instructorsDate); } // student completion settings if (eval.getBlankResponsesAllowed() == null) { Boolean blankAllowed = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED); if (blankAllowed == null) { blankAllowed = false; } eval.setBlankResponsesAllowed(blankAllowed); } if (eval.getModifyResponsesAllowed() == null) { Boolean modifyAllowed = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES); if (modifyAllowed == null) { modifyAllowed = false; } eval.setModifyResponsesAllowed(modifyAllowed); } if (eval.getUnregisteredAllowed() == null) { eval.setUnregisteredAllowed(Boolean.FALSE); } if (eval.getAllRolesParticipate() == null) { Boolean allRolesParticipate = (Boolean) settings.get(EvalSettings.ALLOW_ALL_SITE_ROLES_TO_RESPOND); if (allRolesParticipate == null) { allRolesParticipate = false; } eval.setAllRolesParticipate(allRolesParticipate); } // fix up the reminder days to the default if (eval.getReminderDays() == null) { Integer reminderDays = 1; Integer defaultReminderDays = (Integer) settings.get(EvalSettings.DEFAULT_EMAIL_REMINDER_FREQUENCY); if (defaultReminderDays != null) { reminderDays = defaultReminderDays; } eval.setReminderDays(reminderDays); } // set the reminder email address to the default if (eval.getReminderFromEmail() == null) { // email from address control String from = (String) settings.get(EvalSettings.FROM_EMAIL_ADDRESS); // https://bugs.caret.cam.ac.uk/browse/CTL-1525 - default to admin address if option set Boolean useAdminEmail = (Boolean) settings.get(EvalSettings.USE_ADMIN_AS_FROM_EMAIL); if (useAdminEmail) { // try to get the email address for the owner (eval admin) EvalUser owner = commonLogic.getEvalUserById(commonLogic.getCurrentUserId()); if (owner != null && owner.email != null && !"".equals(owner.email)) { from = owner.email; } } eval.setReminderFromEmail(from); } // admin settings if (eval.getInstructorOpt() == null) { String instOpt = (String) settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE); if (instOpt == null) { instOpt = EvalConstants.INSTRUCTOR_REQUIRED; } eval.setInstructorOpt(instOpt); } }