List of usage examples for java.text DateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:com.nebkat.plugin.geoip.GeoIpPlugin.java
@EventHandler @CommandFilter("time") public void onTimeCommand(CommandEvent e) { if (e.getParams().length < 1) { return;/*from w w w . ja v a 2 s .com*/ } String target = e.getRawParams(); HttpGet get = new HttpGet(String.format(GEOCODE_API_URL, target.replaceAll(" ", "+"))); HttpResponse response; try { response = ConnectionManager.getHttpClient().execute(get); } catch (IOException ex) { get.abort(); Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching geocode data"); return; } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { get.abort(); Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching geocode data"); return; } GoogleGeocode geocode; try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { geocode = new Gson().fromJson(reader, GoogleGeocode.class); } catch (IOException ex) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching geocode data"); return; } catch (JsonParseException ex) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error parsing geocode data"); return; } if (!geocode.status.equals(GoogleGeocode.STATUS_OK)) { switch (geocode.status) { case GoogleGeocode.STATUS_NO_RESULTS: Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": No geocode data found for request"); break; case GoogleGeocode.STATUS_OVER_LIMIT: Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Geocode api over limit"); break; default: Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching geocode data"); break; } return; } get = new HttpGet(String.format(TIMEZONE_API_URL, geocode.results.get(0).geometry.location.lat, geocode.results.get(0).geometry.location.lng, System.currentTimeMillis() / 1000)); try { response = ConnectionManager.getHttpClient().execute(get); } catch (IOException ex) { get.abort(); Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching timezone data"); return; } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching timezone data"); return; } GoogleTimezone timezone; try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { timezone = new Gson().fromJson(reader, GoogleTimezone.class); } catch (IOException ex) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching timezone data"); return; } catch (JsonParseException ex) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error parsing timezone data"); return; } if (!geocode.status.equals(GoogleGeocode.STATUS_OK)) { switch (geocode.status) { case GoogleGeocode.STATUS_NO_RESULTS: Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": No timezone data found for location"); break; case GoogleGeocode.STATUS_OVER_LIMIT: Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Timezone api over limit"); break; default: Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching timezone data"); break; } return; } DateFormat date = new SimpleDateFormat("E d MMM HH:mm"); date.setTimeZone(TimeZone.getTimeZone(timezone.timeZoneId)); Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Time for " + geocode.results.get(0).formatted_address + " (" + timezone.timeZoneName + "): " + date.format(new Date())); }
From source file:org.n52.io.type.quantity.handler.img.ChartIoHandler.java
private void configureTimeAxis(XYPlot plot) { DateAxis timeAxis = (DateAxis) plot.getDomainAxis(); final Date start = getStartTime(getTimespan()); final Date end = getEndTime(getTimespan()); timeAxis.setRange(start, end);//from w w w . j a v a 2 s . c om final Locale locale = i18n.getLocale(); IoParameters parameters = getParameters(); String timeformat = parameters.getTimeFormat(); DateFormat requestTimeFormat = new SimpleDateFormat(timeformat, locale); final DateTimeZone timezone = getTimezone(); requestTimeFormat.setTimeZone(timezone.toTimeZone()); timeAxis.setDateFormatOverride(requestTimeFormat); timeAxis.setTimeZone(timezone.toTimeZone()); }
From source file:dk.dma.ais.utils.filter.AisFilter.java
public void printStats() { long elapsed = end - start; double elapsedSecs = elapsed / 1000.0; double msgPerMin = msgCount / (elapsedSecs / 60.0); long kbytes = bytes / 1000; DateFormat df = new SimpleDateFormat("HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("GMT+0")); System.err.println("\n"); System.err.println("Elapsed : " + df.format(new Date(elapsed))); System.err.println("Messages : " + msgCount); System.err.println("Msg/min : " + String.format(Locale.US, "%.2f", msgPerMin)); System.err.println("Msg/sec : " + String.format(Locale.US, "%.2f", msgPerMin / 60.0)); System.err.println("KBytes : " + kbytes); System.err.println("KB/s : " + String.format(Locale.US, "%.2f", kbytes / elapsedSecs)); System.err.println("Kbps : " + String.format(Locale.US, "%.2f", kbytes * 8.0 / elapsedSecs)); }
From source file:org.apache.nifi.reporting.SiteToSiteProvenanceReportingTask.java
@Override public void onTrigger(final ReportingContext context) { final boolean isClustered = context.isClustered(); final String nodeId = context.getClusterNodeIdentifier(); if (nodeId == null && isClustered) { getLogger().debug(/* ww w. java2 s. c o m*/ "This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. " + "Will wait for Node Identifier to be established."); return; } final ProcessGroupStatus procGroupStatus = context.getEventAccess().getControllerStatus(); final String rootGroupName = procGroupStatus == null ? null : procGroupStatus.getName(); final Map<String, String> componentMap = createComponentMap(procGroupStatus); final String nifiUrl = context.getProperty(INSTANCE_URL).evaluateAttributeExpressions().getValue(); URL url; try { url = new URL(nifiUrl); } catch (final MalformedURLException e1) { // already validated throw new AssertionError(); } final String hostname = url.getHost(); final String platform = context.getProperty(PLATFORM).evaluateAttributeExpressions().getValue(); final Map<String, ?> config = Collections.emptyMap(); final JsonBuilderFactory factory = Json.createBuilderFactory(config); final JsonObjectBuilder builder = factory.createObjectBuilder(); final DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT); df.setTimeZone(TimeZone.getTimeZone("Z")); consumer.consumeEvents(context.getEventAccess(), context.getStateManager(), events -> { final long start = System.nanoTime(); // Create a JSON array of all the events in the current batch final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder(); for (final ProvenanceEventRecord event : events) { final String componentName = componentMap.get(event.getComponentId()); arrayBuilder.add(serialize(factory, builder, event, df, componentName, hostname, url, rootGroupName, platform, nodeId)); } final JsonArray jsonArray = arrayBuilder.build(); // Send the JSON document for the current batch try { final Transaction transaction = getClient().createTransaction(TransferDirection.SEND); if (transaction == null) { getLogger().debug("All destination nodes are penalized; will attempt to send data later"); return; } final Map<String, String> attributes = new HashMap<>(); final String transactionId = UUID.randomUUID().toString(); attributes.put("reporting.task.transaction.id", transactionId); attributes.put("mime.type", "application/json"); final byte[] data = jsonArray.toString().getBytes(StandardCharsets.UTF_8); transaction.send(data, attributes); transaction.confirm(); transaction.complete(); final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); getLogger().info( "Successfully sent {} Provenance Events to destination in {} ms; Transaction ID = {}; First Event ID = {}", new Object[] { events.size(), transferMillis, transactionId, events.get(0).getEventId() }); } catch (final IOException e) { throw new ProcessException( "Failed to send Provenance Events to destination due to IOException:" + e.getMessage(), e); } }); }
From source file:org.apache.roller.weblogger.ui.struts2.editor.EntryBean.java
/** * Copy values from WeblogEntryData to this Form. *//* w w w . jav a 2s .c o m*/ public void copyFrom(WeblogEntry entry, Locale locale) { setId(entry.getId()); setTitle(entry.getTitle()); setLocale(entry.getLocale()); setStatus(entry.getStatus()); setSummary(entry.getSummary()); setText(entry.getText()); setCategoryId(entry.getCategory().getId()); setTagsAsString(entry.getTagsAsString()); // set comment count, ignoreSpam=false, approvedOnly=false setCommentCount(entry.getComments(false, false).size()); // init plugins values if (entry.getPlugins() != null) { setPlugins(StringUtils.split(entry.getPlugins(), ",")); } // init pubtime values if (entry.getPubTime() != null) { log.debug("entry pubtime is " + entry.getPubTime()); //Calendar cal = Calendar.getInstance(locale); Calendar cal = Calendar.getInstance(); cal.setTime(entry.getPubTime()); cal.setTimeZone(entry.getWebsite().getTimeZoneInstance()); setHours(cal.get(Calendar.HOUR_OF_DAY)); setMinutes(cal.get(Calendar.MINUTE)); setSeconds(cal.get(Calendar.SECOND)); // TODO: at some point this date conversion should be locale sensitive, // however at this point our calendar widget does not take into account // locales and only operates in the standard English US locale. DateFormat df = new SimpleDateFormat("MM/dd/yy"); df.setTimeZone(entry.getWebsite().getTimeZoneInstance()); setDateString(df.format(entry.getPubTime())); log.debug("pubtime vals are " + getDateString() + ", " + getHours() + ", " + getMinutes() + ", " + getSeconds()); } setAllowComments(entry.getAllowComments()); setCommentDays(entry.getCommentDays()); setRightToLeft(entry.getRightToLeft()); setPinnedToMain(entry.getPinnedToMain()); // enclosure url, if it exists Set<WeblogEntryAttribute> attrs = entry.getEntryAttributes(); if (attrs != null && attrs.size() > 0) { for (WeblogEntryAttribute attr : attrs) { if ("att_mediacast_url".equals(attr.getName())) { setEnclosureURL(attr.getValue()); } } } }
From source file:com.mobiquitynetworks.statsutilspig.JsonStructure.java
public Map<String, Object> createDateAndUnit(Tuple eventValues, int eventValuesSize) throws ExecException { // format for dates DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // timezone for dates df.setTimeZone(TimeZone.getTimeZone("UTC")); // Map to be returned Map<String, Object> mapToReturn = new HashMap<>(); Date b = new Date(); Date e = new Date(); String unit = ""; // case we only have the year so time unit would be '1y' if (eventValuesSize == 2) { String startDateStr = (Integer) eventValues.get(1) + "-01-01T00:00:00.000Z"; String endDateStr = (Integer) eventValues.get(1) + "-12-31T23:59:59.999Z"; try {//from ww w . j a v a 2s . c o m b = df.parse(startDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } try { e = df.parse(endDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } unit = "1y"; } // case we have the year and month so time unit would be '1M' else if (eventValuesSize == 3) { Calendar mycal = new GregorianCalendar((Integer) eventValues.get(1), (Integer) eventValues.get(1) - 1, 1); int days = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); String startDateStr = (Integer) eventValues.get(1) + "-" + (Integer) eventValues.get(2) + "-01T00:00:00.000Z"; String endDateStr = (Integer) eventValues.get(1) + "-" + (Integer) eventValues.get(2) + "-" + days + "T23:59:59.999Z"; try { b = df.parse(startDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } try { e = df.parse(endDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } unit = "1M"; } // case we have the year, month and day so time unit would be '1d' else if (eventValuesSize == 4) { String startDateStr = (Integer) eventValues.get(1) + "-" + (Integer) eventValues.get(2) + "-" + (Integer) eventValues.get(3) + "T00:00:00.000Z"; String endDateStr = (Integer) eventValues.get(1) + "-" + (Integer) eventValues.get(2) + "-" + (Integer) eventValues.get(3) + "T23:59:59.999Z"; try { b = df.parse(startDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } try { e = df.parse(endDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } unit = "1d"; } // case we have the year, month, day and hour so time unit would be '1h' else if (eventValuesSize == 5) { String startDateStr = (Integer) eventValues.get(1) + "-" + (Integer) eventValues.get(2) + "-" + (Integer) eventValues.get(3) + "T" + (Integer) eventValues.get(4) + ":00:00.000Z"; String endDateStr = (Integer) eventValues.get(1) + "-" + (Integer) eventValues.get(2) + "-" + (Integer) eventValues.get(3) + "T" + (Integer) eventValues.get(4) + ":59:59.999Z"; try { b = df.parse(startDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } try { e = df.parse(endDateStr); } catch (ParseException ex) { Logger.getLogger(JsonStructure.class.getName()).log(Level.SEVERE, null, ex); } unit = "1h"; } mapToReturn.put("b", b); mapToReturn.put("e", e); mapToReturn.put("u", unit); return mapToReturn; }
From source file:org.apache.archiva.stagerepository.merge.Maven2RepositoryMerger.java
private void createFolderStructure(String sourceRepoId, String targetRepoId, ArtifactMetadata artifactMetadata) throws IOException, RepositoryException { Configuration config = configuration.getConfiguration(); ManagedRepositoryConfiguration targetRepoConfig = config.findManagedRepositoryById(targetRepoId); ManagedRepositoryConfiguration sourceRepoConfig = config.findManagedRepositoryById(sourceRepoId); Date lastUpdatedTimestamp = Calendar.getInstance().getTime(); TimeZone timezone = TimeZone.getTimeZone("UTC"); DateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss"); fmt.setTimeZone(timezone); String timestamp = fmt.format(lastUpdatedTimestamp); String targetRepoPath = targetRepoConfig.getLocation(); String sourceRepoPath = sourceRepoConfig.getLocation(); String artifactPath = pathTranslator.toPath(artifactMetadata.getNamespace(), artifactMetadata.getProject(), artifactMetadata.getProjectVersion(), artifactMetadata.getId()); File sourceArtifactFile = new File(sourceRepoPath, artifactPath); File targetArtifactFile = new File(targetRepoPath, artifactPath); log.debug("artifactPath {}", artifactPath); int lastIndex = artifactPath.lastIndexOf(RepositoryPathTranslator.PATH_SEPARATOR); File targetFile = new File(targetRepoPath, artifactPath.substring(0, lastIndex)); if (!targetFile.exists()) { // create the folder structure when it does not exist targetFile.mkdirs();/*from w w w .jav a2s . co m*/ } // artifact copying copyFile(sourceArtifactFile, targetArtifactFile); // pom file copying // TODO need to use path translator to get the pom file path // String fileName = artifactMetadata.getProject() + "-" + artifactMetadata.getVersion() + ".pom"; // // File sourcePomFile = // pathTranslator.toFile( new File( sourceRepoPath ), artifactMetadata.getId(), artifactMetadata.getProject(), // artifactMetadata.getVersion(), fileName ); // // String relativePathToPomFile = sourcePomFile.getAbsolutePath().split( sourceRepoPath )[1]; // File targetPomFile = new File( targetRepoPath, relativePathToPomFile ); //pom file copying (file path is taken with out using path translator) String index = artifactPath.substring(lastIndex + 1); int last = index.lastIndexOf('.'); File sourcePomFile = new File(sourceRepoPath, artifactPath.substring(0, lastIndex) + "/" + artifactPath.substring(lastIndex + 1).substring(0, last) + ".pom"); File targetPomFile = new File(targetRepoPath, artifactPath.substring(0, lastIndex) + "/" + artifactPath.substring(lastIndex + 1).substring(0, last) + ".pom"); if (!targetPomFile.exists() && sourcePomFile.exists()) { copyFile(sourcePomFile, targetPomFile); } // explicitly update only if metadata-updater consumer is not enabled! if (!config.getRepositoryScanning().getKnownContentConsumers().contains("metadata-updater")) { // updating version metadata files File versionMetaDataFileInSourceRepo = pathTranslator.toFile(new File(sourceRepoPath), artifactMetadata.getNamespace(), artifactMetadata.getProject(), artifactMetadata.getVersion(), METADATA_FILENAME); if (versionMetaDataFileInSourceRepo.exists()) {//Pattern quote for windows path String relativePathToVersionMetadataFile = versionMetaDataFileInSourceRepo.getAbsolutePath() .split(Pattern.quote(sourceRepoPath))[1]; File versionMetaDataFileInTargetRepo = new File(targetRepoPath, relativePathToVersionMetadataFile); if (!versionMetaDataFileInTargetRepo.exists()) { copyFile(versionMetaDataFileInSourceRepo, versionMetaDataFileInTargetRepo); } else { updateVersionMetadata(versionMetaDataFileInTargetRepo, artifactMetadata, lastUpdatedTimestamp); } } // updating project meta data file String projectDirectoryInSourceRepo = new File(versionMetaDataFileInSourceRepo.getParent()).getParent(); File projectMetadataFileInSourceRepo = new File(projectDirectoryInSourceRepo, METADATA_FILENAME); if (projectMetadataFileInSourceRepo.exists()) { String relativePathToProjectMetadataFile = projectMetadataFileInSourceRepo.getAbsolutePath() .split(Pattern.quote(sourceRepoPath))[1]; File projectMetadataFileInTargetRepo = new File(targetRepoPath, relativePathToProjectMetadataFile); if (!projectMetadataFileInTargetRepo.exists()) { copyFile(projectMetadataFileInSourceRepo, projectMetadataFileInTargetRepo); } else { updateProjectMetadata(projectMetadataFileInTargetRepo, artifactMetadata, lastUpdatedTimestamp, timestamp); } } } }
From source file:com.appeligo.channelfeed.work.FileWriter.java
private synchronized void closeDoc() { if (body == null) { return;//from w w w . j ava2s . c o m } try { doc = new PrintStream(new GZIPOutputStream(new FileOutputStream(filenamePrefix + ".html.gz"))); writeHead(); } catch (IOException e) { log.error("Can't create .html.gz file.", e); return; } try { String programTitle = program.getProgramTitle(); doc.println("<!-- WARNING, XDS IS INFORMATIONAL ONLY AND CAN BE VERY UNRELIABLE -->"); if (xdsData.getCallLettersAndNativeChannel() != null) { doc.println( "<meta name=\"XDSCallLettersAndNativeChannel\" content=\"" + StringEscapeUtils.escapeHtml( xdsData.getCallLettersAndNativeChannel().replaceAll("[\\p{Cntrl}]", "")) + "\"/>"); } if (xdsData.getNetworkName() != null) { doc.println("<meta name=\"XDSNetworkName\" content=\"" + StringEscapeUtils.escapeHtml(xdsData.getNetworkName().replaceAll("[\\p{Cntrl}]", "")) + "\"/>"); } if (xdsData.getProgramName() != null) { doc.println("<meta name=\"XDSProgramName\" content=\"" + StringEscapeUtils.escapeHtml(xdsData.getProgramName().replaceAll("[\\p{Cntrl}]", "")) + "\"/>"); if (programTitle == null) { programTitle = xdsData.getProgramName(); } } try { if (xdsData.getProgramType() != null) { doc.println("<meta name=\"XDSProgramType\" content=\"" + XDSData.convertProgramType(xdsData.getProgramType()) + "\"/>"); } if (xdsData.getProgramStartTimeID() != null) { long startTimestamp = XDSData.convertProgramStartTimeID(xdsData.getProgramStartTimeID()); doc.println("<meta name=\"XDSProgramStartTimeID\" content=\"" + startTimestamp + "\"/>"); Date date = new Date(startTimestamp); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG); df.setTimeZone(TimeZone.getTimeZone("GMT")); doc.println("<meta name=\"XDSProgramStartTime\" content=\"" + df.format(date) + "\"/>"); if (XDSData.convertProgramTapeDelayed(xdsData.getProgramStartTimeID())) { doc.println("<meta name=\"XDSProgramTapeDelayed\" content=\"true\"/>"); } } if (xdsData.getProgramLength() != null) { doc.println("<meta name=\"XDSProgramLength\" content=\"" + XDSData.convertProgramLength(xdsData.getProgramLength()) + "\"/>"); } } catch (Exception e) { //ignore program type errors... probably bad data... such is XDS } if (program != null) { doc.println("<meta name=\"ProgramID\" content=\"" + program.getProgramId() + "\"/>"); doc.println("<meta name=\"ScheduleID\" content=\"" + program.getScheduleId() + "\"/>"); doc.println("<meta name=\"EpisodeTitle\" content=\"" + StringEscapeUtils.escapeHtml(program.getEpisodeTitle()) + "\"/>"); doc.println("<meta name=\"StartTime\" content=\"" + program.getStartTime().getTime() + "\"/>"); doc.println("<meta name=\"EndTime\" content=\"" + program.getEndTime().getTime() + "\"/>"); doc.println("<meta name=\"TVRating\" content=\"" + StringEscapeUtils.escapeHtml(program.getTvRating()) + "\"/>"); if (programTitle == null) { programTitle = Long.toString(program.getStartTime().getTime()); } } doc.println("<title>" + StringEscapeUtils.escapeHtml(programTitle) + "</title>"); doc.println("</head>"); doc.println("<body>"); doc.println("<h1>" + StringEscapeUtils.escapeHtml(programTitle) + "</h1>"); body.close(); body = null; InputStream readBody = new BufferedInputStream(new FileInputStream(filenamePrefix + ".body")); int b = readBody.read(); while (b >= 0) { doc.write(b); b = readBody.read(); } readBody.close(); File f = new File(filenamePrefix + ".body"); f.delete(); writeFoot(); doc.close(); doc = null; } catch (FileNotFoundException e) { log.error("Lost .body file!", e); } catch (IOException e) { log.error("Error copying .body to .html.gz", e); } doc = null; }
From source file:org.jolokia.jvmagent.handler.JolokiaHttpHandler.java
private String formatHeaderDate(Date date) { DateFormat rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); return rfc1123Format.format(date); }
From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java
private DateFormat getDateFormat(Calendar cal) { DateFormat dateFormat = (DateFormat) DEFAULT_DATE_FORMAT.clone(); if (cal != null) { TimeZone timeZone = cal.getTimeZone(); dateFormat.setTimeZone(timeZone); }/* w w w .j a v a 2 s.c om*/ return dateFormat; }