List of usage examples for org.joda.time DateTime plusDays
public DateTime plusDays(int days)
From source file:at.gv.egovernment.moa.id.configuration.auth.pvp2.servlets.BuildMetadata.java
License:EUPL
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)/* www . j av a 2 s .c om*/ */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ConfigurationProvider config = ConfigurationProvider.getInstance(); //config.initializePVP2Login(); SecureRandomIdentifierGenerator idGen = new SecureRandomIdentifierGenerator(); EntitiesDescriptor spEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class); DateTime date = new DateTime(); spEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS)); String name = config.getPVP2MetadataEntitiesName(); if (MiscUtil.isEmpty(name)) { log.info("NO Metadata EntitiesName configurated"); throw new ConfigurationException("NO Metadata EntitiesName configurated"); } spEntitiesDescriptor.setName(name); spEntitiesDescriptor.setID(idGen.generateIdentifier()); EntityDescriptor spEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class); spEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS)); spEntitiesDescriptor.getEntityDescriptors().add(spEntityDescriptor); String serviceURL = config.getPublicUrlPreFix(request); if (!serviceURL.endsWith("/")) serviceURL = serviceURL + "/"; log.debug("Set OnlineApplicationURL to " + serviceURL); spEntityDescriptor.setEntityID(serviceURL); SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); spSSODescriptor.setAuthnRequestsSigned(true); spSSODescriptor.setWantAssertionsSigned(true); X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory(); keyInfoFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); KeyStore keyStore = config.getPVP2KeyStore(); X509Credential signingcredential = new KeyStoreX509CredentialAdapter(keyStore, config.getPVP2KeystoreMetadataKeyAlias(), config.getPVP2KeystoreMetadataKeyPassword().toCharArray()); log.debug("Set Metadata key information"); //Set MetaData Signing key KeyDescriptor entitiesSignKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class); entitiesSignKeyDescriptor.setUse(UsageType.SIGNING); entitiesSignKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingcredential)); Signature entitiesSignature = getSignature(signingcredential); spEntitiesDescriptor.setSignature(entitiesSignature); //Set AuthRequest Signing certificate X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore, config.getPVP2KeystoreAuthRequestKeyAlias(), config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray()); KeyDescriptor signKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class); signKeyDescriptor.setUse(UsageType.SIGNING); signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); //set AuthRequest encryption certificate if (MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyAlias())) { X509Credential authEncCredential = new KeyStoreX509CredentialAdapter(keyStore, config.getPVP2KeystoreAuthRequestEncryptionKeyAlias(), config.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray()); KeyDescriptor encryKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class); encryKeyDescriptor.setUse(UsageType.ENCRYPTION); encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); } else { log.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); } NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); persistentnameIDFormat.setFormat(NameIDType.PERSISTENT); spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat); NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); transientnameIDFormat.setFormat(NameIDType.TRANSIENT); spSSODescriptor.getNameIDFormats().add(transientnameIDFormat); NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED); spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat); AssertionConsumerService postassertionConsumerService = SAML2Utils .createSAMLObject(AssertionConsumerService.class); postassertionConsumerService.setIndex(0); postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); postassertionConsumerService.setLocation(serviceURL + Constants.SERVLET_PVP2ASSERTION); spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); //add SLO services SingleLogoutService postBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class); postBindingService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); postBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_FRONT); spSSODescriptor.getSingleLogoutServices().add(postBindingService); SingleLogoutService redirectBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class); redirectBindingService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); redirectBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_FRONT); spSSODescriptor.getSingleLogoutServices().add(redirectBindingService); SingleLogoutService soapBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class); soapBindingService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); soapBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_BACK); spSSODescriptor.getSingleLogoutServices().add(soapBindingService); spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor); spSSODescriptor.setWantAssertionsSigned(true); spSSODescriptor.setAuthnRequestsSigned(true); AttributeConsumingService attributeService = SAML2Utils .createSAMLObject(AttributeConsumingService.class); attributeService.setIndex(0); attributeService.setIsDefault(true); ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); serviceName.setName(new LocalizedString("Default Service", "de")); attributeService.getNames().add(serviceName); attributeService.getRequestAttributes().addAll(AttributeListBuilder.getRequestedAttributes()); spSSODescriptor.getAttributeConsumingServices().add(attributeService); DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Marshaller out = Configuration.getMarshallerFactory().getMarshaller(spEntitiesDescriptor); out.marshall(spEntitiesDescriptor, document); Signer.signObject(entitiesSignature); Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); DOMSource source = new DOMSource(document); transformer.transform(source, sr); sw.close(); String metadataXML = sw.toString(); response.setContentType("text/xml"); response.getOutputStream().write(metadataXML.getBytes()); response.getOutputStream().close(); } catch (ConfigurationException e) { log.warn("Configuration can not be loaded.", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (NoSuchAlgorithmException e) { log.warn("Requested Algorithm could not found.", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (KeyStoreException e) { log.warn("Requested KeyStoreType is not implemented.", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (CertificateException e) { log.warn("KeyStore can not be opend or userd.", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (SecurityException e) { log.warn("KeyStore can not be opend or used", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (ParserConfigurationException e) { log.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (MarshallingException e) { log.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (SignatureException e) { log.warn("PVP2 Metadata can not be signed", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (TransformerConfigurationException e) { log.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (TransformerFactoryConfigurationError e) { log.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (TransformerException e) { log.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (Exception e) { log.warn("Unspecific PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } }
From source file:at.gv.egovernment.moa.id.demoOA.servlet.pvp2.BuildMetadata.java
License:EUPL
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)/*from ww w .j a v a 2 s . c o m*/ */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Configuration config = Configuration.getInstance(); SecureRandomIdentifierGenerator idGen = new SecureRandomIdentifierGenerator(); EntitiesDescriptor spEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class); DateTime date = new DateTime(); spEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS)); String name = config.getPVP2MetadataEntitiesName(); if (MiscUtil.isEmpty(name)) { Logger.info("NO Metadata EntitiesName configurated"); throw new ConfigurationException("NO Metadata EntitiesName configurated"); } spEntitiesDescriptor.setName(name); spEntitiesDescriptor.setID(idGen.generateIdentifier()); //set period of validity for metadata information DateTime validUntil = new DateTime(); spEntitiesDescriptor.setValidUntil(validUntil.plusDays(7)); EntityDescriptor spEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class); spEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS)); spEntitiesDescriptor.getEntityDescriptors().add(spEntityDescriptor); //set OA-ID (PublicURL Prefix) as identifier String serviceURL = config.getPublicUrlPreFix(request); if (!serviceURL.endsWith("/")) serviceURL = serviceURL + "/"; Logger.debug("Set OnlineApplicationURL to " + serviceURL); spEntityDescriptor.setEntityID(serviceURL); SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); spSSODescriptor.setAuthnRequestsSigned(true); spSSODescriptor.setWantAssertionsSigned(true); X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory(); keyInfoFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); KeyStore keyStore = config.getPVP2KeyStore(); X509Credential signingcredential = new KeyStoreX509CredentialAdapter(keyStore, config.getPVP2KeystoreMetadataKeyAlias(), config.getPVP2KeystoreMetadataKeyPassword().toCharArray()); Logger.debug("Set Metadata key information"); //Set MetaData Signing key KeyDescriptor entitiesSignKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class); entitiesSignKeyDescriptor.setUse(UsageType.SIGNING); entitiesSignKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingcredential)); Signature entitiesSignature = getSignature(signingcredential); spEntitiesDescriptor.setSignature(entitiesSignature); //Set AuthRequest Signing certificate X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore, config.getPVP2KeystoreAuthRequestKeyAlias(), config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray()); KeyDescriptor signKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class); signKeyDescriptor.setUse(UsageType.SIGNING); signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); //set AuthRequest encryption certificate if (MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyAlias()) || MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyPassword())) { X509Credential authEncCredential = new KeyStoreX509CredentialAdapter(keyStore, config.getPVP2KeystoreAuthRequestEncryptionKeyAlias(), config.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray()); KeyDescriptor encryKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class); encryKeyDescriptor.setUse(UsageType.ENCRYPTION); encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); //set encryption methode // EncryptionMethod encMethode = SAML2Utils.createSAMLObject(EncryptionMethod.class); // encMethode.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM); // encryKeyDescriptor.getEncryptionMethods().add(encMethode); // // EncryptionMethod keyencMethode = SAML2Utils.createSAMLObject(EncryptionMethod.class); // keyencMethode.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP); // encryKeyDescriptor.getEncryptionMethods().add(keyencMethode); spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); } else { Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); } NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); persistentnameIDFormat.setFormat(NameIDType.PERSISTENT); spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat); NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); transientnameIDFormat.setFormat(NameIDType.TRANSIENT); spSSODescriptor.getNameIDFormats().add(transientnameIDFormat); NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED); spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat); //set HTTP-POST Binding assertion consumer service AssertionConsumerService postassertionConsumerService = SAML2Utils .createSAMLObject(AssertionConsumerService.class); postassertionConsumerService.setIndex(0); postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); postassertionConsumerService.setLocation(serviceURL + Constants.SERVLET_PVP2ASSERTION); spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); //set Single Log-Out service SingleLogoutService sloService = SAML2Utils.createSAMLObject(SingleLogoutService.class); sloService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); sloService.setLocation(serviceURL + Constants.SERVLET_PVPSINGLELOGOUT); spSSODescriptor.getSingleLogoutServices().add(sloService); spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor); AttributeConsumingService attributeService = SAML2Utils .createSAMLObject(AttributeConsumingService.class); attributeService.setIndex(0); attributeService.setIsDefault(true); ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); serviceName.setName(new LocalizedString("Default Service", "de")); attributeService.getNames().add(serviceName); //set attributes which are requested attributeService.getRequestAttributes().addAll(AttributeListBuilder.getRequestedAttributes()); spSSODescriptor.getAttributeConsumingServices().add(attributeService); //build metadata DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Marshaller out = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(spEntitiesDescriptor); out.marshall(spEntitiesDescriptor, document); Signer.signObject(entitiesSignature); Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); DOMSource source = new DOMSource(document); transformer.transform(source, sr); sw.close(); String metadataXML = sw.toString(); response.setContentType("text/xml"); response.getOutputStream().write(metadataXML.getBytes()); response.getOutputStream().close(); } catch (ConfigurationException e) { Logger.warn("Configuration can not be loaded.", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (NoSuchAlgorithmException e) { Logger.warn("Requested Algorithm could not found.", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (ParserConfigurationException e) { Logger.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (TransformerConfigurationException e) { Logger.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (TransformerFactoryConfigurationError e) { Logger.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (TransformerException e) { Logger.warn("PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } catch (Exception e) { Logger.warn("Unspecific PVP2 Metadata createn error", e); throw new ServletException("MetaData can not be created. Look into LogFiles for more details."); } }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.MetadataAction.java
License:EUPL
public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { try {/*from w w w . j a v a2 s. c om*/ EntitiesDescriptor idpEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class); idpEntitiesDescriptor.setName(PVPConfiguration.getInstance().getIDPIssuerName()); idpEntitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); DateTime date = new DateTime(); idpEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS)); EntityDescriptor idpEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class); idpEntitiesDescriptor.getEntityDescriptors().add(idpEntityDescriptor); //TODO: maybe change EntityID to Metadata URL //idpEntityDescriptor // .setEntityID(PVPConfiguration.getInstance().getIDPSSOMetadataService()); idpEntityDescriptor.setEntityID(PVPConfiguration.getInstance().getIDPPublicPath()); idpEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS)); List<ContactPerson> persons = PVPConfiguration.getInstance().getIDPContacts(); idpEntityDescriptor.getContactPersons().addAll(persons); idpEntityDescriptor.setOrganization(PVPConfiguration.getInstance().getIDPOrganisation()); X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory(); //keyInfoFactory.setEmitPublicKeyValue(true); keyInfoFactory.setEmitEntityIDAsKeyName(true); keyInfoFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); Credential metadataSigningCredential = CredentialProvider.getIDPMetaDataSigningCredential(); Signature signature = CredentialProvider.getIDPSignature(metadataSigningCredential); //set KeyInfo Element SecurityHelper.prepareSignatureParams(signature, metadataSigningCredential, null, null); idpEntitiesDescriptor.setSignature(signature); //set IDP metadata idpEntityDescriptor.getRoleDescriptors().add(generateIDPMetadata(keyInfoGenerator)); //set SP metadata for interfederation idpEntityDescriptor.getRoleDescriptors().add(generateSPMetadata(keyInfoGenerator)); DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Marshaller out = Configuration.getMarshallerFactory().getMarshaller(idpEntitiesDescriptor); out.marshall(idpEntitiesDescriptor, document); Signer.signObject(signature); Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); DOMSource source = new DOMSource(document); transformer.transform(source, sr); sw.close(); String metadataXML = sw.toString(); Logger.debug("METADATA: " + metadataXML); httpResp.setContentType("text/xml"); httpResp.getOutputStream().write(metadataXML.getBytes("UTF-8")); httpResp.getOutputStream().close(); return null; } catch (Exception e) { Logger.error("Failed to generate metadata", e); throw new MOAIDException("pvp2.13", null); } }
From source file:au.com.scds.chats.dom.activity.RecurringActivity.java
License:Apache License
@Action //@ActionLayout(named = "Add Next") //@MemberOrder(name = "futureActivities", sequence = "1") public RecurringActivity addNextScheduledActivity() { if (getChildActivities().size() == 0) { if (getStartDateTime() == null) { container.warnUser(//from w w w . j a va2s . c o m "Please set 'Start date time' for this Recurring Activity (as starting time from which to schedule more activity events)"); } else { ActivityEvent obj = container.newTransientInstance(ActivityEvent.class); obj.setParentActivity(this); obj.setName(getName()); obj.setAbbreviatedName(getAbbreviatedName()); //set time one second ahead for comparison inequality obj.setStartDateTime(getStartDateTime().plusSeconds(1)); getChildActivities().add(obj); container.persistIfNotAlready(obj); container.flush(); } } else { // find last event from which to schedule next // first should be last in chronological order DateTime origin = getChildActivities().first().getStartDateTime(); ActivityEvent obj = container.newTransientInstance(ActivityEvent.class); obj.setParentActivity(this); obj.setName(getName()); obj.setAbbreviatedName(getAbbreviatedName()); switch (getPeriodicity()) { case DAILY: obj.setStartDateTime(origin.plusDays(1)); break; case WEEKLY: obj.setStartDateTime(origin.plusDays(7)); break; case FORTNIGHTLY: obj.setStartDateTime(origin.plusDays(14)); break; case MONTHLY: obj.setStartDateTime(origin.plusDays(28)); break; case BIMONTHLY: obj.setStartDateTime(origin.plusDays(56)); break; } getChildActivities().add(obj); container.persistIfNotAlready(obj); container.flush(); } return this; }
From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java
License:Apache License
private void addListing(ChannelListings channelListings, Config config, ChannelConfig channelConfig, String channelTag, DateTime from, DateTime to) { StopWatch watch = new StopWatch(); watch.start();// w w w . java 2 s . c om List<Event> events = getEvents(config, channelTag, from, to); LOGGER.debug("Found {} events between {} and {}", events.size(), from, to); for (Event event : events) { ProgrammeDetail programmeDetails; LOGGER.debug("Processing event id {}", event.getEventId()); DateTime scheduleDate = new DateTime(event.getScheduledDate()); if (scheduleDate.plusMinutes(event.getDuration()).isAfterNow() && scheduleDate.isBefore(from.plusDays(config.getSynopsis()))) { LOGGER.debug("Fetching detailed synopsis for {}", event.getEventId()); try { EventDetails eventDetails = getForObject(DETAILS_URI, EventDetails.class, event.getEventId(), config.getRegionId()); programmeDetails = createProgrammeDetails(eventDetails.getEvent()); } catch (Exception e) { LOGGER.debug("Failed to get detailed synopsis. Using basic details instead."); programmeDetails = createProgrammeDetails(event); } } else { programmeDetails = createProgrammeDetails(event); } channelListings.addProgram(channelConfig.getId(), programmeDetails); } watch.stop(); String numberOfPrograms = String.valueOf(channelListings.getNumberOfPrograms(channelConfig.getId())); LOGGER.info("{} {} events [took {}]", rightPad(channelConfig.getId() + " - " + channelConfig.getName(), 40), leftPad(numberOfPrograms, 4), formatDurationWords(watch.getTime())); }
From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java
License:Apache License
private List<Event> getEvents(Config config, String channelTag, DateTime from, DateTime to) { List<Event> events = new ArrayList<>(); DateTime subFrom = from; while (subFrom.isBefore(to)) { DateTime subTo = subFrom.plusDays(1); if (subTo.isAfter(to)) { subTo = to;//w w w . j ava 2s . co m } LOGGER.debug("Fetching events between {} and {}", subFrom, subTo); try { Events subEvents = getForObject(EVENTS_URI, Events.class, channelTag, subFrom.getMillis(), subTo.getMillis(), config.getRegionId()); LOGGER.debug("Found {} events between {} and {}", subEvents.getEvents().size(), subFrom, subTo); events.addAll(subEvents.getEvents()); } catch (Exception e) { LOGGER.debug("Failed to get events between {} and {}"); } subFrom = subTo; } return events; }
From source file:au.id.hazelwood.xmltvguidebuilder.runner.App.java
License:Apache License
public void run(File configFile, File outFile) throws InvalidConfigException, JAXBException, IOException { LOGGER.info("Running XMLTV Guide Builder"); StopWatch watch = new StopWatch(); watch.start();//w w w . ja va 2 s .c o m LOGGER.info("Reading config file '{}'", configFile.getCanonicalPath()); Config config = configFactory.create(configFile); DateTime today = new DateTime().withTimeAtStartOfDay(); DateTime from = today.plusDays(config.getOffset()); DateTime to = from.plusDays(config.getDays()); LOGGER.info("Getting listing from foxtel grabber between {} and {}", toISODateTime(from), toISODateTime(to)); ChannelListings channelListings = grabber.getListing(config, from, to, config.getChannelConfigs()); LOGGER.info("Verifying listings for all channels between {} and {}", new Object[] { toISODateTime(from), toISODateTime(to) }); DateTime subsetTo = from.plusDays(7).isBefore(to) ? from.plusDays(7) : to; listingVerifier.verifyListing(channelListings, from, to, subsetTo); LOGGER.info("Backup old output files"); backupOldOutputFiles(outFile); LOGGER.info("Writing result to {}", outFile.getCanonicalPath()); Writer writer = new BufferedWriter(new FileWriterWithEncoding(outFile, "UTF-8")); bindingService.marshal(xmltvMapper.toXmltv(channelListings), writer); IOUtils.closeQuietly(writer); watch.stop(); LOGGER.info("XMLTV Guide Builder successful in {}", formatDurationWords(watch.getTime())); }
From source file:azkaban.app.jmx.JobScheduler.java
License:Apache License
public String scheduleWorkflow(String jobName, boolean ignoreDeps, int hour, int minutes, int seconds, String scheduledDate, boolean isRecurring, int period, String periodUnits) { String errorMsg = null;//from w ww . j a va2 s . com if (jobName == null || jobName.trim().length() == 0) { errorMsg = "You must select at least one job to run."; logger.error(errorMsg); return errorMsg; } JobDescriptor descriptor = jobManager.getJobDescriptor(jobName); if (descriptor == null) { errorMsg = "Job: '" + jobName + "' doesn't exist."; logger.error(errorMsg); return errorMsg; } DateTime day = null; DateTime time = null; try { if (scheduledDate == null || scheduledDate.trim().length() == 0) { day = new LocalDateTime().toDateTime(); time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds); if (day.isAfter(time)) { time = time.plusDays(1); } } else { try { day = DateTimeFormat.forPattern("MM-dd-yyyy").parseDateTime(scheduledDate); } catch (IllegalArgumentException e) { logger.error(e); return "Invalid date: '" + scheduledDate + "', \"MM-dd-yyyy\" format is expected."; } time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds); } } catch (IllegalFieldValueException e) { logger.error(e); return "Invalid schedule time (see logs): " + e.getMessage(); } ReadablePeriod thePeriod = null; if (isRecurring) { if ("d".equals(periodUnits)) { thePeriod = Days.days(period); } else if ("h".equals(periodUnits)) { thePeriod = Hours.hours(period); } else if ("m".equals(periodUnits)) { thePeriod = Minutes.minutes(period); } else if ("s".equals(periodUnits)) { thePeriod = Seconds.seconds(period); } else { errorMsg = "Unknown period unit: " + periodUnits; logger.error(errorMsg); return errorMsg; } } try { if (thePeriod == null) { scheduler.schedule(jobName, time, ignoreDeps); } else { scheduler.schedule(jobName, time, thePeriod, ignoreDeps); } return "Schedule Successful!"; } catch (Exception e) { logger.error(e); return "Schedule Failed (see logs): " + e.getMessage(); } }
From source file:azkaban.app.Scheduler.java
License:Apache License
/** * Schedule the given job to run at the next occurance of the partially * specified date, and repeating on the given period. For example if the * partial date is 12:00pm then the job will kick of the next time it is * 12:00pm/* w w w .ja v a2s . co m*/ * * @param jobId An id for the job * @param partial A description of the date to run on * @param period The period on which the job should repeat */ public ScheduledFuture<?> schedule(String jobId, ReadablePartial partial, ReadablePeriod period, boolean ignoreDep) { // compute the next occurrence of this date DateTime now = new DateTime(); DateTime date = now.withFields(partial); if (period != null) { date = updatedTime(date, period); } else if (now.isAfter(date)) { // Will try to schedule non recurring for tomorrow date = date.plusDays(1); } if (now.isAfter(date)) { // Schedule is non recurring. logger.info("Scheduled Job " + jobId + " was originally scheduled for " + _dateFormat.print(date)); return null; } logger.info("Scheduling job '" + jobId + "' for " + _dateFormat.print(date) + (period != null ? " with a period of " + PeriodFormat.getDefault().print(period) : "")); return schedule(new ScheduledJob(jobId, date, period, ignoreDep), true); }
From source file:backend.expr.NTDExpr.java
@Override public Object eval(ExprContext ctx) { DateTime stDay = toDate(this.startDay.eval(ctx)); int incDay = ((Number) this.expr.eval(ctx)).intValue(); return StdRecord.DT_FMT.print(stDay.plusDays(incDay + 1)); }