List of usage examples for java.util Date toString
public String toString()
where:dow mon dd hh:mm:ss zzz yyyy
From source file:org.metawatch.manager.MetaWatchService.java
private void readFromDevice() { if (MetaWatchService.fakeWatch) { try {/*from ww w. j av a2 s . c o m*/ Thread.sleep(10000); } catch (InterruptedException e) { } return; } try { byte[] bytes = new byte[256]; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "before blocking read"); // Do a proper read loop int haveread = 0; int lengthtoread = 4; while ((lengthtoread - haveread) != 0) { haveread += inputStream.read(bytes, haveread, lengthtoread - haveread); if (haveread > 1) { lengthtoread = bytes[1]; } } // print received String str = "received: "; int len = (bytes[1] & 0xFF); if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "packet length: " + len); for (int i = 0; i < len; i++) { // str+= Byte.toString(bytes[i]) + ", "; str += "0x" + Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1) + ", "; } if (Preferences.logging) Log.d(MetaWatchStatus.TAG, str); /* * switch (bytes[2]) { case eMessageType.GetDeviceTypeResponse.msg: if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "received: device type response"); break; case eMessageType.NvalOperationResponseMsg.msg: if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "received: nval response"); break; case eMessageType.StatusChangeEvent.msg: if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "received: status change event"); break; } */ /* * if (bytes[2] == 0x31) { // nval response if (bytes[3] == 0x00) // success if (bytes[4] == 0x00) // set to 12 hour format Protocol.setNvalTime(true); } */ if (bytes[2] == eMessageType.NvalOperationResponseMsg.msg) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): NvalOperationResponseMsg"); // Do something here? } else if (bytes[2] == eMessageType.StatusChangeEvent.msg) { // status // change // event if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): status change"); if (bytes[4] == 0x01) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): mode changed"); synchronized (Notification.getInstance().modeChanged) { Notification.getInstance().modeChanged.notify(); } } else if (bytes[4] == 0x11) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): scroll request notification"); synchronized (Notification.getInstance().scrollRequest) { Notification.getInstance().scrollRequest.notify(); } } else if (bytes[4] == 0x10) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): scroll complete."); } else if (bytes[4] == 0x02) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): mode timeout."); // The watch switches back to idle mode (showing the initial // page) after 10 minutes // Activate the last used idle page in this case Idle.getInstance().toPage(MetaWatchService.this, 0); Idle.getInstance().toIdle(MetaWatchService.this); Idle.getInstance().updateIdle(MetaWatchService.this, true); } } else if (bytes[2] == eMessageType.ButtonEventMsg.msg) { // button // press if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): button event"); pressedButton(bytes[3] & 0xFF); // } else if (bytes[2] == eMessageType.GetDeviceTypeResponse.msg) { // device // type if (bytes[4] == 1 || bytes[4] == 4) { watchType = WatchType.ANALOG; watchGen = WatchGen.GEN1; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): device type response; analog watch (gen1)"); NavigationManagement.processWatchConnection(this); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean displaySplash = sharedPreferences.getBoolean("DisplaySplashScreen", false); if (displaySplash) { Protocol.getInstance(MetaWatchService.this).sendOledBitmap( Utils.getBitmap(this, "splash_16_0.bmp"), WatchBuffers.NOTIFICATION, 0); Protocol.getInstance(MetaWatchService.this).sendOledBitmap( Utils.getBitmap(this, "splash_16_1.bmp"), WatchBuffers.NOTIFICATION, 1); } } else { watchType = WatchType.DIGITAL; if (bytes[4] == 5 || bytes[4] == 6) { watchGen = WatchGen.GEN2; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): device type response; Strata/Frame (gen2)"); } else { watchGen = WatchGen.GEN1; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): device type response; digital watch (gen1)"); } Protocol.getInstance(MetaWatchService.this).configureMode(); Protocol.getInstance(MetaWatchService.this).setNvalLcdInvert(Preferences.invertLCD); Protocol.getInstance(MetaWatchService.this).configureIdleBufferSize(true); // Disable built in action for Right top immediate Protocol.getInstance(MetaWatchService.this).disableButton(0, 0, WatchBuffers.IDLE); Protocol.getInstance(MetaWatchService.this).disableButton(0, 0, WatchBuffers.APPLICATION); Protocol.getInstance(MetaWatchService.this).disableButton(0, 0, WatchBuffers.NOTIFICATION); NavigationManagement.processWatchConnection(this); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean displaySplash = sharedPreferences.getBoolean("DisplaySplashScreen", false); if (displaySplash) { Notification.getInstance().addBitmapNotification(this, Utils.getBitmap(this, "splash.png"), new VibratePattern(false, 0, 0, 0), 10000, "Splash"); } // In 10 seconds update the date and time format // Well after the entire connection process, and Idle update on the watch new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { Protocol.getInstance(MetaWatchService.this).setTimeDateFormat(MetaWatchService.this); } }, 10000); } Protocol.getInstance(MetaWatchService.this).getRealTimeClock(); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(MetaWatchService.this); /* Notify watch on connection if requested. */ boolean notifyOnConnect = sharedPreferences.getBoolean("NotifyWatchOnConnect", false); if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.connect(): notifyOnConnect=" + notifyOnConnect); if (notifyOnConnect) { NotificationBuilder.createOtherNotification(MetaWatchService.this, null, "MetaWatch", getResources().getString(R.string.connection_connected), 1); } Idle.getInstance().activateButtons(this); } else if (bytes[2] == eMessageType.ReadBatteryVoltageResponse.msg) { boolean powerGood = bytes[4] > 0; boolean batteryCharging = bytes[5] > 0; float batterySense = (((int) bytes[7] << 8) + (int) bytes[6]) / 1000.0f; float batteryAverage = (((int) bytes[9] << 8) + (int) bytes[8]) / 1000.0f; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): received battery voltage response." + " power_good=" + powerGood + " battery_charging=" + batteryCharging + " battery_sense=" + batterySense + " battery_average=" + batteryAverage); String voltageFrequencyString = PreferenceManager.getDefaultSharedPreferences(this) .getString("collectWatchVoltage", "0"); final int voltageFrequency = Integer.parseInt(voltageFrequencyString); if (voltageFrequency > 0) { File sdcard = Environment.getExternalStorageDirectory(); File csv = new File(sdcard, "metawatch_voltage.csv"); boolean fileExists = csv.exists(); FileWriter fw = new FileWriter(csv, true); if (fileExists == false) { fw.write("Date,Sense,Average\n"); } Date date = new Date(); fw.write("\"" + date.toString() + "\"," + batterySense + "," + batteryAverage + "\n"); fw.flush(); fw.close(); } } else if (bytes[2] == eMessageType.ReadLightSensorResponse.msg) { float lightSense = (((int) bytes[1] << 8) + (int) bytes[0]) / 1000.0f; float lightAverage = (((int) bytes[3] << 8) + (int) bytes[2]) / 1000.0f; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): received light sensor response." + " light_sense=" + lightSense + " light_average=" + lightAverage); } else if (bytes[2] == eMessageType.GetRealTimeClockResponse.msg) { long timeNow = System.currentTimeMillis(); long roundTrip = timeNow - Monitors.getInstance().getRTCTimestamp; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): received rtc response." + " round trip= " + roundTrip); Monitors.getInstance().rtcOffset = (int) (roundTrip / 2000); Protocol.getInstance(MetaWatchService.this).setRealTimeClock(MetaWatchService.this); } else { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): Unknown message : 0x" + Integer.toString((bytes[2] & 0xff) + 0x100, 16).substring(1) + ", "); } } catch (IOException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); resetConnection(); } catch (Exception e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); resetConnection(); } }
From source file:uk.ac.soton.itinnovation.sad.service.services.SchedulingService.java
/** * Executes SAD Plugin using Quartz.//from w w w. java 2s. c om * * @param pluginName name of the plugin. * @param arguments JSON arguments. * @param inputs JSON inputs. * @param outputs JSON outputs. * @param schedule JSON schedule. * @return metadata of the new SAD job. */ public JSONObject runPlugin(String pluginName, JSONArray arguments, JSONArray inputs, JSONArray outputs, JSONObject schedule) { logger.debug("Running plugin by name: " + pluginName + ", with arguments: " + arguments.toString() + ", schedule: " + schedule.toString()); JSONObject pluginInfo = pluginsService.getPluginByName(pluginName); if (pluginInfo.isEmpty()) { throw new RuntimeException("Plugin not found: " + pluginName); } if (!pluginInfo.containsKey("paths")) { throw new RuntimeException( "Plugin configuration must contain \'paths\'. Misconfigured plugin: " + pluginName); } if (!pluginInfo.containsKey("pluginFolder")) { throw new RuntimeException( "Plugin configuration must be loaded with pluginsService that fills in the \'pluginFolder\' field. Misconfigured plugin: " + pluginName); } JSONObject pluginPaths = pluginInfo.getJSONObject("paths"); if (!pluginPaths.containsKey("jar")) { throw new RuntimeException( "Plugin configuration must contain \'paths/jar\'. Misconfigured plugin: " + pluginName); } if (!pluginPaths.containsKey("dependenciesFolder")) { throw new RuntimeException( "Plugin configuration must contain \'paths/dependenciesFolder\'. Misconfigured plugin: " + pluginName); } String jarPath = pluginPaths.getString("jar"); String dependenciesFolderPath = pluginPaths.getString("dependenciesFolder"); String inputsAsString = inputs.toString(); String outputsAsString = outputs.toString(); logger.debug("Plugin jar path from configuration: " + jarPath + ", dependenciesFolderPath: " + dependenciesFolderPath); String pathToPlugins = pluginsService.getAbsolutePluginsPath(); logger.debug("Plugin folder configuration: " + pathToPlugins); // Create database record of the new job String jobId = addJob(null, pluginName, pluginInfo.toString(), "Job for plugin " + pluginName, arguments.toString(), inputsAsString, outputsAsString, schedule.toString()); // Report number of plugins and the name to ECC if (emClient.isEmClientOK()) { if (emClient.isMetricModelSetup()) { int jobsNum = getJobs().size(); logger.debug("Reporting new jobs run number [" + jobsNum + "] and plugin name: '" + pluginName + "' to ECC"); emClient.pushNumPluginsRunMeasurementToEcc(jobsNum); emClient.pushPluginNameMeasurementToEcc(pluginName); } else { logger.error("NOT reporting new jobs run number and plugin name: '" + pluginName + "' to ECC because metric model is not set up yet" + " (start discovery phase in ECC or connect to a running experiment)"); } } JobBuilder jobBuilder = JobBuilder.newJob(PluginRunner.class).withIdentity(pluginName, jobId) .usingJobData("pluginName", pluginName).usingJobData("jar", jarPath) .usingJobData("dependenciesFolderPath", dependenciesFolderPath) .usingJobData("pathToPlugins", pathToPlugins) .usingJobData("pluginFolder", pluginInfo.getString("pluginFolder")) .usingJobData("pathToCoordinator", configurationService.getConfiguration().getCoordinatorPath()) .usingJobData("eccPort", eccIntegrationService.getPortForPluginName(pluginName)) .usingJobData("jobId", jobId); if (emClient.isEmClientOK()) { if (emClient.isMetricModelSetup()) { jobBuilder = jobBuilder // .usingJobData("basepath", configurationService.getConfiguration().getBasepath() + "/report") .usingJobData("basepath", "http://127.0.0.1:" + localPort + contextPath + "/report") .usingJobData("emClientOK", emClient.isEmClientOK()) .usingJobData("isMetricModelSetup", emClient.isMetricModelSetup()); } } JobDetail job = jobBuilder.build(); Trigger trigger = jsonScheduleToTrigger(schedule, pluginName, jobId); // Need to deal with times: 0 or negative logger.debug("Submitting job with start time: " + trigger.getStartTime() + ", final fire time: " + trigger.getFinalFireTime()); logger.debug("First 20 scheduled executions:"); List<Date> scheduledExecutions_20 = TriggerUtils.computeFireTimes((OperableTrigger) trigger, new BaseCalendar(), 20); // JSONArray scheduledExecutions_20AsJson = new JSONArray(); for (Date d : scheduledExecutions_20) { logger.debug("\t" + d.toString()); // scheduledExecutions_20AsJson.add(d.toString()); } try { scheduler.scheduleJob(job, trigger); } catch (SchedulerException ex) { throw new RuntimeException("Failed to schedule Quartz job", ex); } long startTime = System.currentTimeMillis(); SADJob sadJob = getJob(jobId); sadJob.setStatus(ExecStatus.SCHEDULED); getCoordinator(false).saveObject(sadJob); pushDatabaseQueryDuration(Long.toString(System.currentTimeMillis() - startTime)); SADJob theJob = getJob(jobId); JSONObject result = jobAsJson(theJob); return result; }
From source file:org.openbravo.client.application.ViewComponent.java
/** * This function returns the last grid configuration change made into a window at any level (at * whole system level or just a for particuar tab or field). * // www . j a v a2 s .co m * This value is needed for the eTag calculation, so, if there has been any grid configuration * change, the eTag should change in order to load again the view definition. * * @param window * the window to obtain its last grid configuration change * @return a String with the last grid configuration change */ private String getLastGridConfigurationChange(Window window) { Date lastModification = new Date(0); List<GCSystem> sysConfs = OBDal.getInstance().createQuery(GCSystem.class, "").list(); if (!sysConfs.isEmpty()) { if (lastModification.compareTo(sysConfs.get(0).getUpdated()) < 0) { lastModification = sysConfs.get(0).getUpdated(); } } String tabHql = "select max(updated) from OBUIAPP_GC_Tab where tab.window.id = :windowId"; Query qryTabData = OBDal.getInstance().getSession().createQuery(tabHql); qryTabData.setParameter("windowId", window.getId()); Date tabUpdated = (Date) qryTabData.uniqueResult(); if (tabUpdated != null && lastModification.compareTo(tabUpdated) < 0) { lastModification = tabUpdated; } String fieldHql = "select max(updated) from OBUIAPP_GC_Field where obuiappGcTab.tab.window.id = :windowId"; Query qryFieldData = OBDal.getInstance().getSession().createQuery(fieldHql); qryFieldData.setParameter("windowId", window.getId()); Date fieldUpdated = (Date) qryFieldData.uniqueResult(); if (fieldUpdated != null && lastModification.compareTo(fieldUpdated) < 0) { lastModification = fieldUpdated; } return lastModification.toString(); }
From source file:org.ejbca.ui.web.pub.CertDistServlet.java
/** * handles http get/*from w ww .j a va 2 s. c o m*/ * * @param req servlet request * @param res servlet response * * @throws IOException input/output error * @throws ServletException error */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException, ServletException { log.trace(">doGet()"); String command; // Keep this for logging. String remoteAddr = req.getRemoteAddr(); final AuthenticationToken administrator = new AlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("PublicWeb: " + remoteAddr)); //Admin administrator = new Admin(Admin.TYPE_PUBLIC_WEB_USER, remoteAddr); RequestHelper.setDefaultCharacterEncoding(req); String issuerdn = null; if (req.getParameter(ISSUER_PROPERTY) != null) { // HttpServetRequets.getParameter URLDecodes the value for you // No need to do it manually, that will cause problems with + characters issuerdn = req.getParameter(ISSUER_PROPERTY); issuerdn = CertTools.stringToBCDNString(issuerdn); } int caid = 0; if (req.getParameter(CAID_PROPERTY) != null) { caid = Integer.parseInt(req.getParameter(CAID_PROPERTY)); } // See if the client wants the response cert or CRL in PEM format (default is DER) String format = req.getParameter(FORMAT_PROPERTY); command = req.getParameter(COMMAND_PROPERTY_NAME); if (command == null) { command = ""; } if ((command.equalsIgnoreCase(COMMAND_CRL) || command.equalsIgnoreCase(COMMAND_DELTACRL)) && issuerdn != null) { try { byte[] crl = null; if (command.equalsIgnoreCase(COMMAND_CRL)) { crl = crlSession.getLastCRL(issuerdn, false); // CRL } else { crl = crlSession.getLastCRL(issuerdn, true); // deltaCRL } X509CRL x509crl = CertTools.getCRLfromByteArray(crl); String dn = CertTools.getIssuerDN(x509crl); // We must remove cache headers for IE ServletUtils.removeCacheHeaders(res); // moz is only kept for backwards compatibility, can be removed in EJBCA 6.4 or 6.5 String moz = req.getParameter(MOZILLA_PROPERTY); String filename = CertTools.getPartFromDN(dn, "CN") + ".crl"; if (command.equalsIgnoreCase(COMMAND_DELTACRL)) { filename = "delta_" + filename; } if ((moz == null) || !moz.equalsIgnoreCase("y")) { res.setHeader("Content-disposition", "attachment; filename=\"" + StringTools.stripFilename(filename) + "\""); } res.setContentType("application/x-x509-crl"); if (StringUtils.equals(format, "PEM")) { RequestHelper.sendNewB64File(Base64.encode(crl, true), res, filename, RequestHelper.BEGIN_CRL_WITH_NL, RequestHelper.END_CRL_WITH_NL); } else { res.setContentLength(crl.length); res.getOutputStream().write(crl); } log.debug("Sent latest CRL to client at " + remoteAddr); } catch (Exception e) { log.debug("Error sending latest CRL to " + remoteAddr + ": ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting latest CRL."); return; } } else if (command.equalsIgnoreCase(COMMAND_EECERT)) { // HttpServetRequets.getParameter URLDecodes the value for you // No need to do it manually, that will cause problems with + characters String dn = req.getParameter(ISSUER_PROPERTY); if (dn == null) { log.debug("Bad request, no 'issuer' arg to 'eecert'."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Usage command=eecert?issuer=<issuerdn>&serno=<serialnumber in hex>."); return; } String serno = req.getParameter(SERNO_PROPERTY); if (serno == null) { log.debug("Bad request, no 'serno' arg to 'eeceert'."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Usage command=eecert?issuer=<issuerdn>&serno=<serialnumber in hex>."); return; } log.debug("Looking for certificate with issuer/serno '" + dn + "', '" + serno + "'."); try { // Serial number in hex Certificate cert = storesession.findCertificateByIssuerAndSerno(dn, new BigInteger(serno, 16)); sendEndEntityCert(administrator, req, res, format, cert); } catch (NumberFormatException e) { log.debug("Error getting End Entity certificate, invalid serial number (hex): ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting End Entity certificate, invalid serial number (hex)."); return; } catch (CertificateEncodingException e) { log.info("Error getting End Entity certificate, invalid certificate?: ", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error getting End Entity certificate, invalid certificate."); return; } catch (NoSuchFieldException e) { log.info("Error getting End Entity certificate, can not get field to generate filename?: ", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error getting End Entity certificate, invalid certificate."); return; } catch (AuthorizationDeniedException e) { log.error("Error getting End Entity certificate, not authorized to create PKCS7: ", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error getting End Entity certificate, not authorized to create PKCS7."); return; } catch (CesecoreException e) { log.info( "Error getting End Entity certificate, CA to create PKCS7 does not exist, or can not create PKCS7: ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting End Entity certificate, CA to create PKCS7 does not exist, or can not create PKCS7."); return; } } else if (command.equalsIgnoreCase(COMMAND_CERT) || command.equalsIgnoreCase(COMMAND_LISTCERT)) { // HttpServetRequets.getParameter URLDecodes the value for you // No need to do it manually, that will cause problems with + characters String dn = req.getParameter(SUBJECT_PROPERTY); if (dn == null) { log.debug("Bad request, no 'subject' arg to 'lastcert' or 'listcert' command."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Usage command=lastcert/listcert?subject=<subjectdn>."); return; } try { log.debug("Looking for certificates for '" + dn + "'."); Collection<Certificate> certcoll = storesession.findCertificatesBySubject(dn); Object[] certs = certcoll.toArray(); if (command.equalsIgnoreCase(COMMAND_CERT)) { long maxdate = 0; int latestcertno = -1; for (int i = 0; i < certs.length; i++) { if (i == 0) { maxdate = CertTools.getNotBefore((Certificate) certs[i]).getTime(); latestcertno = 0; } else if (CertTools.getNotBefore((Certificate) certs[i]).getTime() > maxdate) { maxdate = CertTools.getNotBefore(((Certificate) certs[i])).getTime(); latestcertno = i; } } Certificate certcert = null; if (latestcertno > -1) { certcert = (Certificate) certs[latestcertno]; } if (certcert == null) { log.debug("No certificate found for requested subject DN. '" + dn + "'."); res.sendError(HttpServletResponse.SC_NOT_FOUND, "No certificate found for requested subject DN."); } else { sendEndEntityCert(administrator, req, res, format, certcert); log.debug("Sent latest certificate for '" + dn + "' to client at " + remoteAddr); } } if (command.equalsIgnoreCase(COMMAND_LISTCERT)) { res.setContentType("text/html"); PrintWriter pout = new PrintWriter(res.getOutputStream()); printHtmlHeader("Certificates for " + HTMLTools.htmlescape(dn), pout); for (int i = 0; i < certs.length; i++) { Date notBefore = CertTools.getNotBefore((Certificate) certs[i]); Date notAfter = CertTools.getNotAfter((Certificate) certs[i]); String subject = CertTools.getSubjectDN((Certificate) certs[i]); String issuer = CertTools.getIssuerDN((Certificate) certs[i]); BigInteger serno = CertTools.getSerialNumber((Certificate) certs[i]); pout.println("<pre>Subject:" + subject); pout.println("Issuer:" + issuer); pout.println("NotBefore:" + notBefore.toString()); pout.println("NotAfter:" + notAfter.toString()); pout.println("Serial number:" + serno.toString()); pout.println("</pre>"); pout.println("<a href=\"certdist?cmd=revoked&issuer=" + URLEncoder.encode(issuer, "UTF-8") + "&serno=" + serno.toString() + "\">Check if certificate is revoked</a>"); pout.println("<hr>"); } if (certs.length == 0) { pout.println("No certificates exists for '" + HTMLTools.htmlescape(dn) + "'."); } printHtmlFooter(pout); pout.close(); } } catch (Exception e) { log.debug("Error getting certificates for '" + dn + "' for " + remoteAddr + ": ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting certificates."); return; } } else if ((command.equalsIgnoreCase(COMMAND_NSCACERT) || command.equalsIgnoreCase(COMMAND_IECACERT) || command.equalsIgnoreCase(COMMAND_CACERT)) && (issuerdn != null || caid != 0)) { String lev = req.getParameter(LEVEL_PROPERTY); int level = 0; boolean pkcs7 = false; if (lev != null) { level = Integer.parseInt(lev); } else { pkcs7 = true; } // CA is level 0, next over root level 1 etc etc, -1 returns chain as PKCS7 try { Certificate[] chain = null; chain = getCertificateChain(administrator, caid, issuerdn); // chain.length-1 is last cert in chain (root CA) if (chain.length < level) { PrintStream ps = new PrintStream(res.getOutputStream()); ps.println("No CA certificate of level " + level + " exist."); log.debug("No CA certificate of level " + level + " exist."); return; } Certificate cacert = (Certificate) chain[level]; String filename = RequestHelper.getFileNameFromCertNoEnding(cacert, "ca"); byte[] enccert = null; if (pkcs7) { enccert = signSession.createPKCS7(administrator, cacert, true); } else { enccert = cacert.getEncoded(); } if (command.equalsIgnoreCase(COMMAND_NSCACERT)) { res.setContentType("application/x-x509-ca-cert"); res.setContentLength(enccert.length); res.getOutputStream().write(enccert); log.debug("Sent CA cert to NS client, len=" + enccert.length + "."); } else if (command.equalsIgnoreCase(COMMAND_IECACERT)) { // We must remove cache headers for IE ServletUtils.removeCacheHeaders(res); if (pkcs7) { res.setHeader("Content-disposition", "attachment; filename=\"" + StringTools.stripFilename(filename) + ".p7c\""); } else { String ending = ".crt"; if (cacert instanceof CardVerifiableCertificate) { ending = ".cvcert"; } res.setHeader("Content-disposition", "attachment; filename=\"" + StringTools.stripFilename(filename + ending) + "\""); } res.setContentType("application/octet-stream"); res.setContentLength(enccert.length); res.getOutputStream().write(enccert); log.debug("Sent CA cert to IE client, len=" + enccert.length + "."); } else if (command.equalsIgnoreCase(COMMAND_CACERT)) { byte[] b64cert = Base64.encode(enccert); String out; if (pkcs7) { out = "-----BEGIN PKCS7-----\n"; } else { out = "-----BEGIN CERTIFICATE-----\n"; } out += new String(b64cert); if (pkcs7) { out += "\n-----END PKCS7-----\n"; } else { out += "\n-----END CERTIFICATE-----\n"; } // We must remove cache headers for IE ServletUtils.removeCacheHeaders(res); res.setHeader("Content-disposition", "attachment; filename=\"" + StringTools.stripFilename(filename) + ".pem\""); res.setContentType("application/octet-stream"); res.setContentLength(out.length()); res.getOutputStream().write(out.getBytes()); log.debug("Sent CA cert to client, len=" + out.length() + "."); } else { res.setContentType("text/plain"); res.getOutputStream().println( "Commands=" + COMMAND_NSCACERT + " || " + COMMAND_IECACERT + " || " + COMMAND_CACERT); return; } } catch (Exception e) { log.debug("Error getting CA certificates: ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificates."); return; } } else if (command.equalsIgnoreCase(COMMAND_CACHAIN) && (issuerdn != null || caid != 0)) { // Full certificate chain for CA was requested. try { handleCaChainCommands(administrator, issuerdn, caid, format, res); } catch (NoSuchFieldException e) { log.debug("Error getting certificates for '" + caid + "' for " + remoteAddr + ": ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting certificates."); return; } } else if (command.equalsIgnoreCase(COMMAND_REVOKED)) { String dn = req.getParameter(ISSUER_PROPERTY); if (dn == null) { log.debug("Bad request, no 'issuer' arg to 'revoked' command."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Usage command=revoked?issuer=<issuerdn>&serno=<serialnumber>."); return; } String serno = req.getParameter(SERNO_PROPERTY); if (serno == null) { log.debug("Bad request, no 'serno' arg to 'revoked' command."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Usage command=revoked?issuer=<issuerdn>&serno=<serialnumber>."); return; } log.debug("Looking for certificate for '" + dn + "' and serno='" + serno + "'."); try { CertificateStatus revinfo = storesession.getStatus(dn, new BigInteger(serno)); PrintWriter pout = new PrintWriter(res.getOutputStream()); res.setContentType("text/html"); printHtmlHeader("Check revocation", pout); if (revinfo != null) { if (revinfo.revocationReason == RevokedCertInfo.NOT_REVOKED) { pout.println("<h1>NOT REVOKED</h1>"); pout.println("Certificate with issuer '" + HTMLTools.htmlescape(dn) + "' and serial number '" + HTMLTools.htmlescape(serno) + "' is NOT revoked."); } else { pout.println("<h1>REVOKED</h1>"); pout.println("Certificate with issuer '" + HTMLTools.htmlescape(dn) + "' and serial number '" + HTMLTools.htmlescape(serno) + "' is revoked."); pout.println("RevocationDate is '" + revinfo.revocationDate + "' and reason '" + revinfo.revocationReason + "'."); } } else { pout.println("<h1>CERTIFICATE DOES NOT EXIST</h1>"); pout.println("Certificate with issuer '" + HTMLTools.htmlescape(dn) + "' and serial number '" + HTMLTools.htmlescape(serno) + "' does not exist."); } printHtmlFooter(pout); pout.close(); } catch (Exception e) { log.debug("Error checking revocation for '" + dn + "' with serno '" + serno + "': ", e); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error checking revocation."); return; } } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Commands=cacert | lastcert | listcerts | crl | deltacrl | revoked && issuer=<issuerdn>"); return; } }
From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoDocuments.java
@SuppressWarnings("deprecation") private void setup(Document curDoc) { try {//from ww w.j av a 2s.c o m // LOGGER.info(getCallingMethod()+":"+"Start setup..."); @SuppressWarnings("rawtypes") Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", curDoc); // LOGGER.info(getCallingMethod()+":"+"All Embedded computed"); int numOfAttachments = allEmbedded.isEmpty() ? 0 : (allEmbedded.get(0).equals("") ? 0 : allEmbedded.size()); String docID = curDoc.getUniversalID(); this.setDocumentUniqueID(docID); // LOGGER.info("Num of attachments="+new // Integer(numOfAttachments).toString()); boolean readOnly = this.checkReadOnlyAccess(curDoc); this.setReadOnly(readOnly); LOGGER.info("Creation date for " + curDoc.getUniversalID() + " =" + curDoc.getCreated().toString() + "; Time zone=" + curDoc.getCreated().getZoneTime() + "; Local time=" + curDoc.getCreated().getLocalTime()); Date curCreationDate = curDoc.getCreated().toJavaDate(); LOGGER.info("Current date in Java is " + curCreationDate.toString() + "Time zone=" + new Integer(curCreationDate.getTimezoneOffset()).toString() + "; Locale time is:" + curCreationDate.toLocaleString()); if (curDoc.hasItem("DAVCreated")) { // Item davCreated=curDoc.getFirstItem("DAVCreated"); @SuppressWarnings("rawtypes") Vector times = curDoc.getItemValueDateTimeArray("DAVCreated"); if (times != null) { if (times.size() > 0) { Object time = times.elementAt(0); if (time != null) { if (time.getClass().getName().endsWith("DateTime")) { curCreationDate = ((DateTime) time).toJavaDate(); if (curCreationDate == null) { curCreationDate = curDoc.getCreated().toJavaDate(); } } } } } } Date curChangeDate = curDoc.getLastModified().toJavaDate(); if (curDoc.hasItem("DAVModified")) { @SuppressWarnings("rawtypes") Vector times = curDoc.getItemValueDateTimeArray("DAVModified"); if (times != null) { if (times.size() > 0) { Object time = times.elementAt(0); if (time != null) { if (time.getClass().getName().endsWith("DateTime")) { curChangeDate = ((DateTime) time).toJavaDate(); if (curChangeDate == null) { curChangeDate = curDoc.getLastModified().toJavaDate(); } } } } } } this.setCreationDate(curCreationDate); this.setLastModified(curChangeDate); LOGGER.info("Creation date is set to " + this.getCreationDate().toString()); LOGGER.info("Last modified date is set to " + this.getLastModified().toString()); String pubHRef = ((IDAVAddressInformation) this.getRepository()).getPublicHref(); // LOGGER.info("THIS getpublichref="+this.getPublicHref()); String curAttName = null; if (numOfAttachments == 0) { // LOGGER.info(getCallingMethod()+":"+"Start setting resource"); this.setName(docID); String name = curDoc.getItemValueString( ((DAVRepositoryDominoDocuments) (this.getRepository())).getDirectoryField()); this.setName(name); if (this.getPublicHref().equals("")) { // try{ this.setPublicHref(pubHRef + "/" + name); // URLEncoder.encode(name, "UTF-8")); // }catch(UnsupportedEncodingException e){ // LOGGER.error(e); // } } this.setCollection(true); this.setInternalAddress( ((IDAVAddressInformation) this.getRepository()).getInternalAddress() + "/" + docID); this.setResourceType("NotesDocument"); this.setMember(false); this.setContentLength(0L); // this.fetchChildren(); } else { curAttName = allEmbedded.get(0).toString(); // LOGGER.info("Attachment name is "+curAttName); this.setMember(true); this.setResourceType("NotesAttachment"); if (this.getPublicHref().equals("")) { try { this.setPublicHref(pubHRef + "/" + URLEncoder.encode(curAttName, "UTF-8")); } catch (UnsupportedEncodingException e) { LOGGER.error(e); } // this.setPublicHref( pubHRef+"/"+curAttName); } this.setInternalAddress(((IDAVAddressInformation) this.getRepository()).getInternalAddress() + "/" + docID + "/$File/" + curAttName); this.setCollection(false); this.setName(curAttName); EmbeddedObject curAtt = curDoc.getAttachment(curAttName); if (curAtt == null) { // LOGGER.info("Error! Current Embedded is null"); return; } else { // LOGGER.info("Embedded is not null. OK! "); } Long curSize = new Long(curAtt.getFileSize()); this.setContentLength(curSize); } // LOGGER.info("Current res realized! pubHREF="+this.getPublicHref()+"; Internal Address="+this.getInternalAddress()+"; "); } catch (NotesException ne) { LOGGER.error("ERROR! Can not set; " + ne.getMessage()); } }
From source file:edu.hawaii.soest.pacioos.text.SimpleTextSource.java
/** * For the given Data Turbine channel, request the last sample timestamp * for comparison against samples about to be flushed * @return lastSampleTimeAsSecondsSinceEpoch the last sample time as seconds since the epoch * @throws SAPIException// w w w. j a va2 s. c om */ public long getLastSampleTime() throws SAPIException { // query the DT to find the timestamp of the last sample inserted Sink sink = new Sink(); Date initialDate = new Date(); long lastSampleTimeAsSecondsSinceEpoch = initialDate.getTime() / 1000L; try { ChannelMap requestMap = new ChannelMap(); int entryIndex = requestMap.Add(getRBNBClientName() + "/" + getChannelName()); log.debug("Request Map: " + requestMap.toString()); sink.OpenRBNBConnection(getServer(), "lastEntrySink"); sink.Request(requestMap, 0., 1., "newest"); ChannelMap responseMap = sink.Fetch(5000); // get data within 5 seconds // initialize the last sample date log.debug("Initialized the last sample date to: " + initialDate.toString()); log.debug("The last sample date as a long is: " + lastSampleTimeAsSecondsSinceEpoch); if (responseMap.NumberOfChannels() == 0) { // set the last sample time to 0 since there are no channels yet lastSampleTimeAsSecondsSinceEpoch = 0L; log.debug("Resetting the last sample date to the epoch: " + (new Date(lastSampleTimeAsSecondsSinceEpoch * 1000L)).toString()); } else if (responseMap.NumberOfChannels() > 0) { lastSampleTimeAsSecondsSinceEpoch = new Double(responseMap.GetTimeStart(entryIndex)).longValue(); log.debug("There are existing channels. Last sample time: " + (new Date(lastSampleTimeAsSecondsSinceEpoch * 1000L)).toString()); } } catch (SAPIException sapie) { throw sapie; } finally { sink.CloseRBNBConnection(); } return lastSampleTimeAsSecondsSinceEpoch; }
From source file:org.biopax.ols.impl.BaseOBO2AbstractLoader.java
/** * inetrnal helper method to initialize and reset shared objects *//*from w w w. j a va 2s . c o m*/ protected void initializeCommonObjects() { //no need to check if parser is not null because //of previous sanity check at the start of process() //this is not true in the cast of the NEWT loader!!! String version; if (parser != null) { version = parser.getSession().getCurrentHistory().getVersion(); //if version is not set, set it to file date if (version == null) { Date tmp = parser.getSession().getCurrentHistory().getDate(); //if date is not set, set it to current date if (tmp != null) version = tmp.toString(); else version = (new Date()).toString(); } } else { version = (new Date()).toString(); } //create ontology ontBean = new OntologyBean(); if (ONTOLOGY_DEFINITION != null && ONTOLOGY_DEFINITION.length() > 2000) { logger.warn("ontology definition longer than allowed database column length - truncating"); ONTOLOGY_DEFINITION = ONTOLOGY_DEFINITION.substring(0, 2000); } ontBean.setDefinition(ONTOLOGY_DEFINITION); if (FULL_NAME != null && FULL_NAME.length() > 128) { logger.warn("ontology full name longer than allowed database column length - truncating"); FULL_NAME = FULL_NAME.substring(0, 128); } ontBean.setFullOntologyName(FULL_NAME); ontBean.setLoadDate(new java.sql.Date(GregorianCalendar.getInstance().getTime().getTime())); if (SHORT_NAME != null && SHORT_NAME.length() > 32) { logger.warn("ontology short name longer than allowed database column length - truncating"); SHORT_NAME = SHORT_NAME.substring(0, 32); } ontBean.setShortOntologyName(SHORT_NAME); if (version != null && version.length() > 128) { logger.warn("ontology version longer than allowed database column length - truncating"); version = version.substring(0, 128); } ontBean.setVersion(version); ontBean.setFullyLoaded(false); if (QUERY_URL != null && QUERY_URL.length() > 255) { logger.warn("ontology query url longer than allowed database column length - truncating"); QUERY_URL = QUERY_URL.substring(0, 255); } ontBean.setQueryURL(QUERY_URL); if (SOURCE_URL != null && SOURCE_URL.length() > 255) { logger.warn("ontology source url longer than allowed database column length - truncating"); SOURCE_URL = SOURCE_URL.substring(0, 255); } ontBean.setSourceURL(SOURCE_URL); //make certain there's no dirty data (esp if we're using it to load multiple ontologies) ontologyTerms.clear(); //create mapping sets IS_A_SET.clear(); IS_A_SET.add(Constants.IS_A_RELATION_TYPE); IS_A_SET.add(Constants.IS_A_RELATION_TYPE.toUpperCase()); //other mappings seen IS_A_SET.add("isa"); IS_A_SET.add("ISA"); IS_A_SET.add("OBO_REL:is_a"); PART_OF_SET.clear(); PART_OF_SET.add(Constants.PART_OF_RELATION_TYPE); PART_OF_SET.add(Constants.PART_OF_RELATION_TYPE.toUpperCase()); //other mappings seen PART_OF_SET.add("partof"); PART_OF_SET.add("PARTOF"); PART_OF_SET.add("OBO_REL:part_of"); PART_OF_SET.add("is_part_of"); DEV_FROM_SET.clear(); DEV_FROM_SET.add(Constants.DEVELOPS_FROM_RELATION_TYPE); DEV_FROM_SET.add(Constants.DEVELOPS_FROM_RELATION_TYPE.toUpperCase()); //other mappings seen DEV_FROM_SET.add("DERIVED/DEVELOPS_FROM"); //set PSI-MOD specific xrefs that will be converted to annotations MOD_NUMERIC_ANNOTATIONS = new HashSet<String>(); MOD_NUMERIC_ANNOTATIONS.add("DiffAvg"); MOD_NUMERIC_ANNOTATIONS.add("DiffMono"); MOD_NUMERIC_ANNOTATIONS.add("MassAvg"); MOD_NUMERIC_ANNOTATIONS.add("MassMono"); MOD_STRING_ANNOTATIONS = new HashSet<String>(); MOD_STRING_ANNOTATIONS.add("DiffFormula"); MOD_STRING_ANNOTATIONS.add("Formula"); MOD_STRING_ANNOTATIONS.add("Source"); MOD_STRING_ANNOTATIONS.add("Origin"); MOD_STRING_ANNOTATIONS.add("TermSpec"); //create relations IS_A = initializeTermBean(Constants.IS_A_RELATION_TYPE, Loader.RELATION_TYPE); ontologyTerms.put(IS_A.getIdentifier(), IS_A); PART_OF = initializeTermBean(Constants.PART_OF_RELATION_TYPE, Loader.RELATION_TYPE); ontologyTerms.put(PART_OF.getIdentifier(), PART_OF); DEVELOPS_FROM = initializeTermBean(Constants.DEVELOPS_FROM_RELATION_TYPE, Loader.RELATION_TYPE); ontologyTerms.put(DEVELOPS_FROM.getIdentifier(), DEVELOPS_FROM); //create synonyms ALT_ID = initializeTermBean(Constants.ALT_ID_SYNONYM_TYPE, Loader.SYNONYM_TYPE); ontologyTerms.put(ALT_ID.getIdentifier(), ALT_ID); EXACT = initializeTermBean(Constants.EXACT_SYNONYM_TYPE, Loader.SYNONYM_TYPE); ontologyTerms.put(EXACT.getIdentifier(), EXACT); NARROW = initializeTermBean(Constants.NARROW_SYNONYM_TYPE, Loader.SYNONYM_TYPE); ontologyTerms.put(NARROW.getIdentifier(), NARROW); BROAD = initializeTermBean(Constants.BROAD_SYNONYM_TYPE, Loader.SYNONYM_TYPE); ontologyTerms.put(BROAD.getIdentifier(), BROAD); RELATED = initializeTermBean(Constants.RELATED_SYNONYM_TYPE, Loader.SYNONYM_TYPE); ontologyTerms.put(RELATED.getIdentifier(), RELATED); SYNONYM = initializeTermBean(Constants.DEFAULT_SYNONYM_TYPE, Loader.SYNONYM_TYPE); ontologyTerms.put(SYNONYM.getIdentifier(), SYNONYM); //initialize synonymTypeDefs if (parser != null) { Collection<SynonymType> synonymTypes = parser.getSession().getSynonymTypes(); if (synonymTypes != null && !synonymTypes.isEmpty()) { for (SynonymType st : synonymTypes) { ontologyTerms.put(st.getID(), initializeTermBean(st.getName(), SHORT_NAME + ":" + st.getID(), getSynonymTypeDef(st.getScope()))); } } } // //get rid of stale data // instances.clear(); //get rid of stale data and get root terms rootTerms.clear(); if (parser != null) { rootTerms.addAll(getRootTerms()); } }
From source file:org.alfresco.dataprep.SitePagesService.java
/** * Remove an event/* w ww.ja v a 2 s .c om*/ * @param userName String user name * @param password String user password * @param siteName String site name * @param what String what * @param where String event location * @param from Date event start date * @param to Date event end date * @param timeStart String event start time * @param timeEnd String event time finish * @param allDay boolean all day event * @return boolean true if event is removed * @throws RuntimeException if site is not found */ public boolean removeEvent(final String userName, final String password, final String siteName, final String what, final String where, Date from, Date to, String timeStart, String timeEnd, final boolean allDay) { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(siteName) || StringUtils.isEmpty(what) || StringUtils.isEmpty(from.toString()) || StringUtils.isEmpty(to.toString())) { throw new IllegalArgumentException("Parameter missing"); } String eventName = getEventName(userName, password, siteName, what, where, from, to, timeStart, timeEnd, allDay); if (StringUtils.isEmpty(eventName)) { throw new RuntimeException("Event not found"); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String reqURL = client.getAlfrescoUrl() + "alfresco/s/calendar/event/" + siteName + "/" + eventName; HttpDelete request = new HttpDelete(reqURL); HttpResponse response = client.executeRequest(userName, password, request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_NO_CONTENT: return true; case HttpStatus.SC_NOT_FOUND: throw new RuntimeException("Invalid site " + siteName); default: logger.error("Unable to delete event: " + response.toString()); break; } return false; }
From source file:org.kuali.student.enrollment.registration.search.service.impl.CourseRegistrationSearchServiceImpl.java
/** * Returns list of Registration Info for the person: CO, AO, Schedules, etc. * * @throws OperationFailedException// w ww.j a va 2s .c o m */ private SearchResultInfo searchForCourseRegistrationByPersonAndTerm(SearchRequestInfo searchRequestInfo) throws OperationFailedException { SearchResultInfo resultInfo = new SearchResultInfo(); SearchRequestHelper requestHelper = new SearchRequestHelper(searchRequestInfo); String atpId = requestHelper.getParamAsString(SearchParameters.ATP_ID); String personId = requestHelper.getParamAsString(SearchParameters.PERSON_ID); List<String> lprTypes = requestHelper.getParamAsList(SearchParameters.LPR_TYPE); StringBuilder queryBuilder = new StringBuilder(""); queryBuilder.append("SELECT atp.ID, atp.ATP_CD, atp.NAME as atp_name, " + "lpr.LUI_ID, lpr.MASTER_LPR_ID, lpr.LPR_TYPE, lpr.LPR_STATE, lpr.CREDITS, lpr.GRADING_OPT_ID, lpr.CROSSLIST, lpr.CREATETIME, " + "luiId.LUI_CD, lui.NAME as lui_name, lui.DESCR_FORMATTED, lui.LUI_TYPE, luiId.LNG_NAME, " + "luiRes.RESULT_VAL_GRP_ID, schedCmp.TBA_IND, " + "room.ROOM_CD, rBldg.BUILDING_CD, " + "schedTmslt.WEEKDAYS, schedTmslt.START_TIME_MS, schedTmslt.END_TIME_MS " + "FROM KSEN_ATP atp, " + " KSEN_LPR lpr, " + " KSEN_LUI lui, " + " KSEN_LUI_IDENT luiId " + "LEFT OUTER JOIN KSEN_LUI_RESULT_VAL_GRP luiRes " + "ON luiRes.LUI_ID = luiId.LUI_ID " + "LEFT OUTER JOIN KSEN_LUI_SCHEDULE aoSched " + "ON aoSched.LUI_ID = luiId.LUI_ID " + "LEFT OUTER JOIN KSEN_SCHED_CMP schedCmp " + "ON schedCmp.SCHED_ID = aoSched.SCHED_ID " + "LEFT OUTER JOIN KSEN_ROOM room " + "ON room.ID = schedCmp.ROOM_ID " + "LEFT OUTER JOIN KSEN_ROOM_BUILDING rBldg " + "ON rBldg.ID = room.BUILDING_ID " + "LEFT OUTER JOIN KSEN_SCHED_CMP_TMSLOT schedCmpTmslt " + "ON schedCmpTmslt.SCHED_CMP_ID = schedCmp.ID " + "LEFT OUTER JOIN KSEN_SCHED_TMSLOT schedTmslt " + "ON schedTmslt.ID = schedCmpTmslt.TM_SLOT_ID " + "WHERE lpr.PERS_ID = :personId " + " AND atp.ID = lpr.ATP_ID " + " AND lui.ID = lpr.LUI_ID " + " AND luiId.LUI_ID = lui.ID " + " AND lpr.LPR_STATE = '" + LprServiceConstants.ACTIVE_STATE_KEY + "' "); if (!StringUtils.isEmpty(atpId)) { queryBuilder.append(" AND lpr.ATP_ID = :atpId "); } if (!CollectionUtils.isEmpty(lprTypes)) { queryBuilder.append(" AND lpr.LPR_TYPE in (:lprType) "); } Query query = entityManager.createNativeQuery(queryBuilder.toString()); query.setParameter(SearchParameters.PERSON_ID, personId); if (!StringUtils.isEmpty(atpId)) { query.setParameter(SearchParameters.ATP_ID, atpId); } if (!CollectionUtils.isEmpty(lprTypes)) { query.setParameter(SearchParameters.LPR_TYPE, lprTypes); } @SuppressWarnings("unchecked") List<Object[]> results = query.getResultList(); for (Object[] resultRow : results) { int i = 0; SearchResultRowInfo row = new SearchResultRowInfo(); row.addCell(SearchResultColumns.ATP_ID, (String) resultRow[i++]); row.addCell(SearchResultColumns.ATP_CD, (String) resultRow[i++]); row.addCell(SearchResultColumns.ATP_NAME, (String) resultRow[i++]); row.addCell(SearchResultColumns.LUI_ID, (String) resultRow[i++]); row.addCell(SearchResultColumns.MASTER_LPR_ID, (String) resultRow[i++]); row.addCell(SearchResultColumns.PERSON_LUI_TYPE, (String) resultRow[i++]); row.addCell(SearchResultColumns.LPR_STATE, (String) resultRow[i++]); row.addCell(SearchResultColumns.CREDITS, (String) resultRow[i++]); row.addCell(SearchResultColumns.GRADING_OPTION_ID, (String) resultRow[i++]); row.addCell(SearchResultColumns.CROSSLIST, (String) resultRow[i++]); Date lprCreateTime = (Date) resultRow[i++]; row.addCell(SearchResultColumns.LPR_CREATETIME, lprCreateTime.toString()); row.addCell(SearchResultColumns.LUI_CODE, (String) resultRow[i++]); row.addCell(SearchResultColumns.LUI_NAME, (String) resultRow[i++]); row.addCell(SearchResultColumns.LUI_DESC, (String) resultRow[i++]); row.addCell(SearchResultColumns.LUI_TYPE, (String) resultRow[i++]); row.addCell(SearchResultColumns.LUI_LONG_NAME, (String) resultRow[i++]); row.addCell(SearchResultColumns.RES_VAL_GROUP_KEY, (String) resultRow[i++]); BigDecimal tbaInd = (BigDecimal) resultRow[i++]; row.addCell(SearchResultColumns.TBA_IND, (tbaInd == null) ? "" : tbaInd.toString()); row.addCell(SearchResultColumns.ROOM_CODE, (String) resultRow[i++]); row.addCell(SearchResultColumns.BUILDING_CODE, (String) resultRow[i++]); row.addCell(SearchResultColumns.WEEKDAYS, (String) resultRow[i++]); BigDecimal startTimeMs = (BigDecimal) resultRow[i++]; row.addCell(SearchResultColumns.START_TIME_MS, (startTimeMs == null) ? "" : startTimeMs.toString()); BigDecimal endTimeMs = (BigDecimal) resultRow[i]; row.addCell(SearchResultColumns.END_TIME_MS, (endTimeMs == null) ? "" : endTimeMs.toString()); resultInfo.getRows().add(row); } return resultInfo; }
From source file:fr.gouv.culture.vitam.eml.PstExtract.java
private Element extractInfoActivity(PSTActivity activity) { Element root = XmlDom.factory.createElement("activity"); String value = null;// ww w .ja v a 2 s. co m value = activity.getLogType(); if (value != null && !value.isEmpty()) { root.add(XmlDom.factory.createElement("LogType").addText(value)); } Date date = activity.getLogStart(); if (date != null) { root.add(XmlDom.factory.createElement("LogStart").addText(date.toString())); } Integer ival = activity.getLogDuration(); root.add(XmlDom.factory.createElement("LogDuration").addText(ival.toString())); date = activity.getLogEnd(); if (date != null) { root.add(XmlDom.factory.createElement("LogEnd").addText(date.toString())); } ival = activity.getLogFlags(); root.add(XmlDom.factory.createElement("LogFlags").addText(ival.toString())); Boolean bval = activity.isDocumentPrinted(); root.add(XmlDom.factory.createElement("isDocumentPrinted").addText(bval.toString())); bval = activity.isDocumentSaved(); root.add(XmlDom.factory.createElement("isDocumentSaved").addText(bval.toString())); bval = activity.isDocumentRouted(); root.add(XmlDom.factory.createElement("isDocumentRouted").addText(bval.toString())); bval = activity.isDocumentPosted(); root.add(XmlDom.factory.createElement("isDocumentPosted").addText(bval.toString())); value = activity.getLogTypeDesc(); if (value != null && !value.isEmpty()) { root.add(XmlDom.factory.createElement("LogTypeDesc").addText(value)); } return root; }