List of usage examples for java.time LocalDateTime now
public static LocalDateTime now()
From source file:org.ow2.proactive.workflow_catalog.rest.service.WorkflowRevisionServiceTest.java
private void getWorkflow(Optional<Long> revisionId, Optional<String> alt) throws IOException { Workflow mockedWf = mock(Workflow.class); when(mockedWf.getId()).thenReturn(DUMMY_ID); WorkflowRevision wfRev = new WorkflowRevision(DUMMY_ID, DUMMY_ID, "WR-TEST", "WR-PROJ-NAME", LocalDateTime.now(), null, Lists.newArrayList(), Lists.newArrayList(), getWorkflowAsByteArray("workflow.xml")); wfRev.setWorkflow(mockedWf);/* w w w . j av a 2s. c om*/ when(bucketRepository.findOne(anyLong())).thenReturn(mock(Bucket.class)); when(workflowRepository.findOne(anyLong())).thenReturn(mock(Workflow.class)); if (revisionId.isPresent()) { when(workflowRevisionRepository.getWorkflowRevision(anyLong(), anyLong(), anyLong())).thenReturn(wfRev); } else { when(workflowRepository.getMostRecentWorkflowRevision(anyLong(), anyLong())).thenReturn(wfRev); } workflowRevisionService.getWorkflow(DUMMY_ID, DUMMY_ID, revisionId, alt); verify(bucketRepository, times(1)).findOne(DUMMY_ID); verify(workflowRepository, times(1)).findOne(DUMMY_ID); }
From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java
private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize, ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth, Integer intradayHeight) { Preconditions.checkNotNull(stock, "stock must not be null!"); Preconditions.checkNotNull(type, "ChartType must not be null!"); String guid = AuthenticationUtil.getPrincipal().getUsername(); String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken(); ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid); Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class); if (connection != null) { byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm"); LocalDateTime dateTime = LocalDateTime.now(); String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230" String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_" + formattedDateTime + ".png"; String pathToYahooPicture = env.getProperty("pictures.yahoo.path").concat(File.separator + imageName); try {//from ww w .j a va 2s . c o m Path newPath = Paths.get(pathToYahooPicture); Files.write(newPath, yahooChart, StandardOpenOption.CREATE); } catch (IOException e) { throw new Error("Storage of " + pathToYahooPicture + " failed", e); } ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, pathToYahooPicture); chartStockRepository.save(chartStock); } }
From source file:com.bekwam.resignator.model.ConfigurationDataSourceImpl.java
private void initFileSystem() throws IOException { if (logger.isDebugEnabled()) { logger.debug("[INIT FS]"); }/*from ww w . j av a2 s.c o m*/ String userHome = System.getProperty("user.home"); Preconditions.checkNotNull(userHome); Preconditions.checkNotNull(configDir); Preconditions.checkNotNull(jsonConfigFile); // // Create the .resignator / resignator.properties if not present in ${user.home} // File fullConfigDir = new File(userHome, configDir); if (fullConfigDir.exists() && !fullConfigDir.isDirectory()) { String msg = fullConfigDir.getAbsolutePath() + " is a file and must be a directory; delete the file and restart the app"; logger.error(msg); throw new IllegalStateException(msg); } if (!fullConfigDir.exists()) { if (logger.isDebugEnabled()) { logger.debug("[INIT FS] configDir {} does not exist; creating", fullConfigDir.getAbsolutePath()); } fullConfigDir.mkdir(); } File cf = new File(fullConfigDir, jsonConfigFile); boolean retval = cf.createNewFile(); // verifies that user can create a file here configFile = Optional.of(cf); if (logger.isDebugEnabled()) { logger.debug("[INIT FS] configFile newly created?={}", retval); } if (retval) { // write out empty json if (logger.isDebugEnabled()) { logger.debug("[INIT FS] serializing empty config object to file for first time"); } activeConf.setLastUpdatedDateTime(LocalDateTime.now()); saveConfiguration(); // empty config } }
From source file:com.ccserver.digital.controller.CreditCardApplicationDocumentControllerTest.java
private CreditCardApplicationDTO getCreditCardApplicationDTO() { CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO(); // ----- cardType // ----- DoB/* w ww . j a va 2 s . com*/ creditCardApplicationDTO.setDob(LocalDateTime.now()); // ----- Name creditCardApplicationDTO.setFirstName("LE"); creditCardApplicationDTO.setMiddleName("Hong"); creditCardApplicationDTO.setLastName("Thanh"); // ----- gender creditCardApplicationDTO.setGender(Gender.Male); // ----- Moblie PhoneDTO moblie = new PhoneDTO(); moblie.setCountryCode("084"); moblie.setPhoneNumber("0985481179"); creditCardApplicationDTO.setMobile(moblie); // ----- phoneBusiness PhoneDTO phoneBusiness = new PhoneDTO(); phoneBusiness.setCountryCode("084"); phoneBusiness.setPhoneNumber("0985481179"); creditCardApplicationDTO.setBusinessPhone(phoneBusiness); // ----- email creditCardApplicationDTO.setEmail("letuanthuongtin@gmail.com"); // ----- passportNumber creditCardApplicationDTO.setPassportNumber("123456789"); // ----- dateOfIssue creditCardApplicationDTO.setDateOfIssue(LocalDateTime.now()); // ----- placeOfIssue SelectionList selectionListDTO = new SelectionList(); selectionListDTO.setCategory("plauceOfise"); selectionListDTO.setCode("11"); creditCardApplicationDTO.setPlaceOfIssue(selectionListDTO); // ----- citizenship CountryDTO citizenship = new CountryDTO(); citizenship.setId(1L); citizenship.setCode("VN"); citizenship.setVi("Viet Nam"); citizenship.setEn("VietNam"); creditCardApplicationDTO.setCitizenship(citizenship); // ----- haveGreenCard creditCardApplicationDTO.setHaveGreenCard(true); // ----- isUSResident creditCardApplicationDTO.setUSResident(true); // ----- education // creditCardApplicationDTO.setEducation(EducationQualification.HighShool); // ----- maritalStatus // creditCardApplicationDTO.setMaritalStatus(MaritalStatus.Single); // ----- numberOfChildren creditCardApplicationDTO.setNumberOfChildren(4); // ----- permanent address--- // TODO: create province and district for integration test AddressDTO permanentAddress = new AddressDTO(); BaseProvinceDTO province = new BaseProvinceDTO(); province.setName("Ha Noi"); province.setId(1L); DistrictDTO districtDTO1 = new DistrictDTO(); districtDTO1.setName("Hai Ba Trung"); districtDTO1.setId(1L); permanentAddress.setDistrict(districtDTO1); permanentAddress.setProvince(province); permanentAddress.setStreet("LE Thanh NGhi"); permanentAddress.setAddressDetails("So Nha 18"); creditCardApplicationDTO.setPermanentAddress(permanentAddress); // ----- currentIsPermanent creditCardApplicationDTO.setCurrentIsPermanent(true); // ----- currentAddress creditCardApplicationDTO.setCurrentAddress(permanentAddress); // ----- typeOfEmployement creditCardApplicationDTO.setTypeOfEmployement(TypeOfEmployment.Business); // ----- licenseNumber creditCardApplicationDTO.setLicenseNumber("12345"); // ----- businessStartDate creditCardApplicationDTO.setBusinessStartDate(LocalDateTime.now()); // ----- businessTelephone PhoneDTO businessTelephone = new PhoneDTO(); businessTelephone.setCountryCode("084"); businessTelephone.setPhoneNumber("0985481179"); businessTelephone.setExt("01"); creditCardApplicationDTO.setBusinessTelephone(businessTelephone); // ----- businessAddress creditCardApplicationDTO.setBusinessAddress(permanentAddress); // ----- nameOfEmployer CompanyDTO companyDTO = new CompanyDTO(); companyDTO.setCode("111"); creditCardApplicationDTO.setNameOfEmployer(companyDTO); // ----- occupation //creditCardApplicationDTO.setOccupation("Engineer"); // ----- industry // creditCardApplicationDTO.setIndustry("finance"); // ----- yearsOfWorking creditCardApplicationDTO.setYearsOfWorking(1); // ----- monthsOfWorking creditCardApplicationDTO.setMonthsOfWorking(8); // ----- employerAddress creditCardApplicationDTO.setEmployerAddress(permanentAddress); // ----- monthlyIncome creditCardApplicationDTO.setMonthlyIncome(new BigDecimal("10")); // ----- monthlyExpenses creditCardApplicationDTO.setMonthlyExpenses(new BigDecimal("5")); // ----- securityQuestion SelectionListDTO securityQuestion = new SelectionListDTO(); securityQuestion.setId(3L); creditCardApplicationDTO.setSecurityQuestion(securityQuestion); // ----- securityAnswer creditCardApplicationDTO.setSecurityAnswer("Thanh"); // ----- referenceName creditCardApplicationDTO.setReferenceName("LE Tuan"); // ----- relationshipReference SelectionListDTO relationship = new SelectionListDTO(); relationship.setId(3L); creditCardApplicationDTO.setRelationshipReference(relationship); // ----- phoneOfReference creditCardApplicationDTO.setPhoneOfReference(moblie); // ----- branchDelivery // creditCardApplicationDTO.setDeliveryCard("Branch 1"); // ----- isSecondaryCard creditCardApplicationDTO.setSecondaryCard(true); // ----- isAccurateCommit creditCardApplicationDTO.setAccurateCommit(true); // ----- agreeTermsConditions creditCardApplicationDTO.setAgreeTermsConditions(true); return creditCardApplicationDTO; }
From source file:io.mandrel.spider.SpiderService.java
public long fork(long id) throws BindException { Spider spider = get(id);//from w w w . jav a 2 s . c om spider.setId(0); spider.setName(generator.next()); cleanDates(spider); BindingResult errors = Validators.validate(spider); if (errors.hasErrors()) { errors.getAllErrors().stream().forEach(oe -> log.info(oe.toString())); throw new BindException(errors); } spider.setStatus(SpiderStatuses.INITIATED); spider.setCreated(LocalDateTime.now()); spider = spiderRepository.add(spider); return spider.getId(); }
From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java
/** Attempts to parse a (typically recurring) time * @param human_readable_duration - Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#) * @param base_date - for relative date, locks the date to this origin (mainly for testing in this case?) * @return the machine readable duration, or an error *//* www . j av a 2 s. co m*/ public static Validation<String, Duration> getDuration(final String human_readable_duration, Optional<Date> base_date) { // There's a few different cases: // - the validation from getTimePeriod // - a slightly more complicated version <N><p> where <p> == period from the above // - use Natty for more complex expressions final Validation<String, ChronoUnit> first_attempt = getTimePeriod(human_readable_duration); if (first_attempt.isSuccess()) { return Validation .success(Duration.of(first_attempt.success().getDuration().getSeconds(), ChronoUnit.SECONDS)); } else { // Slightly more complex version final Matcher m = date_parser.matcher(human_readable_duration); if (m.matches()) { final Validation<String, Duration> candidate_ret = getTimePeriod(m.group(2)).map(cu -> { final LocalDateTime now = LocalDateTime.now(); return Duration.between(now, now.plus(Integer.parseInt(m.group(1)), cu)); }); if (candidate_ret.isSuccess()) return candidate_ret; } } // If we're here then try Natty final Date now = base_date.orElse(new Date()); return getSchedule(human_readable_duration, Optional.of(now)).map(d -> { final long duration = d.getTime() - now.getTime(); return Duration.of(duration, ChronoUnit.MILLIS); }); }
From source file:org.openthinclient.pkgmgr.UpdateDatabase.java
@Override public PackageListUpdateReport execute(ProgressReceiver progressReceiver) { final PackageListDownloader packageListDownloader = new PackageListDownloader(configuration, downloadManager);/* w w w . j ava 2 s .c o m*/ final PackageListUpdateReport report = new PackageListUpdateReport(); for (Source source : sourcesList.getSources()) { if (!source.isEnabled()) { LOG.info("Disabled source {} skipped.", source); continue; } updateProgress(progressReceiver, source); final LocalPackageList localPackageList = packageListDownloader.download(source, progressReceiver); List<Package> parsePackagesList = parsePackagesList(localPackageList).collect(Collectors.toList()); parsePackagesList.forEach((pkg) -> processPackage(source, pkg, report)); List<Package> outdatedPackages = collectOutdatedPackages(source, parsePackagesList); outdatedPackages.forEach(existingPkg -> { if (existingPkg.isInstalled()) { LOG.warn("Keep existing {} installed, but {} doesn't provide it anymore.", existingPkg.toStringWithNameAndVersion(), source); } else { LOG.info("Deleting existing {}, because {} doesn't provide it anymore.", existingPkg.toStringWithNameAndVersion(), source); db.getPackageRepository().delete(existingPkg); report.incRemoved(); } }); // update the timestamp source.setLastUpdated(LocalDateTime.now()); db.getSourceRepository().save(source); } return report; }
From source file:org.apdplat.superword.system.AntiRobotFilter.java
public void init(FilterConfig config) throws ServletException { int initialDelay = 24 - LocalDateTime.now().getHour(); scheduledExecutorService.scheduleAtFixedRate(() -> { try {/* w w w.j av a 2 s . c o m*/ LOG.info("clear last day anti-robot counter"); LocalDateTime timePoint = LocalDateTime.now().minusDays(1); String date = SIMPLE_DATE_FORMAT .format(Date.from(timePoint.atZone(ZoneId.systemDefault()).toInstant())); Map<String, Integer> archive = new HashMap<String, Integer>(); Enumeration<String> keys = servletContext.getAttributeNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (key.startsWith("anti-robot-") && key.endsWith(date)) { archive.put(key, ((AtomicInteger) servletContext.getAttribute(key)).intValue()); } } archive.keySet().forEach(servletContext::removeAttribute); File path = new File(servletContext.getRealPath("/WEB-INF/data/anti-robot-archive/")); if (!path.exists()) { path.mkdirs(); } String file = path.getPath() + "/" + date + "__user_agent_invalid_count_" + invalidCount + ".txt"; Files.write(Paths.get(file), archive.entrySet().stream() .map(e -> e.getKey().replace("anti-robot-", "").replace("-", "\t") + "\t" + e.getValue()) .map(line -> { String[] attrs = line.split("\\s+"); String location = ""; if (attrs != null && attrs.length > 1) { String ip = attrs[1]; location = IPUtils.getIPLocation(ip).toString(); } return line + "\t" + location; }).collect(Collectors.toList())); invalidCount = 0; LOG.info("clear last day anti-robot counter finished: " + file); } catch (Exception e) { LOG.error("save anti-robot-archive failed", e); } }, initialDelay, 24, TimeUnit.HOURS); }
From source file:com.inqool.dcap.office.indexer.indexer.SolrBulkIndexer.java
private SolrInputDocument recursivelyIndex(final ModelTreeNode data) throws IOException { ZdoModel model;//from w ww. j ava2 s. c o m model = data.getModel(); if (model == null) { return null; } // if (!model.isIndexable()) { // logger.debug("Resource: {} retrieved without indexable type.", uri); // return null; // } logger.debug("Resource: {} retrieved with indexable type.", store.removeTransactionFromUrl(model.getUrl())); if (!allowableTypes.contains(model.get(ZdoTerms.zdoType))) { return null; } if (!ZdoGroup.ZDO.name().equals(model.get(ZdoTerms.group))) { logger.info("Not indexing this document as it is not published."); return null; } final SolrInputDocument inputDoc = modelToSolrInputDoc(model); // inputDoc.addField("datePublished", OffsetDateTime.now().withOffsetSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME)); String datePublished = model.get(ZdoTerms.datePublished); if (datePublished != null) { //If reindexing, we just read data about when it was originally published from Fedora inputDoc.addField("datePublished", datePublished); } else { datePublished = LocalDateTime.now().atZone(ZoneOffset.systemDefault()) .withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); inputDoc.addField("datePublished", datePublished); //solr needs UTC time ZdoModel patchmodel = new ZdoModel(); patchmodel.setUrl(model.getUrl()); patchmodel.add(ZdoTerms.datePublished, datePublished); store.patchMetadata(patchmodel); } //Get all children's uris, parse them recursively, and add them to result //If we are an almost-leaf node, also search for children bound on the original object String originalObjectUrl = model.get(ZdoTerms.kdrObject); if (!ZdoType.isBranchEndCategory(model.get(ZdoTerms.zdoType))) { for (ModelTreeNode child : data.getChildren()) { SolrInputDocument childDoc = recursivelyIndex(child); if (childDoc != null) { inputDoc.addChildDocument(childDoc); } } } else { //we are end branch category //Treat born digital documents differently as they don't have pages but whole PDF if (ZdoType.bornDigital.name().equals(model.get(ZdoTerms.zdoType))) { //Retrieve the usercopy - PDF String queryString = "SELECT ?userCopy ?thumb WHERE {\n" + "?userCopy <http://purl.org/dc/terms/isPartOf> <" + originalObjectUrl + ">.\n" + "?userCopy <" + ZdoTerms.zdoType.getURI() + "> \"" + ZdoType.binary.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?userCopy <" + ZdoTerms.fileType.getURI() + "> \"" + ZdoFileType.userCopy.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "}"; QueryExecution queryExecution = QueryExecutionFactory.sparqlService(SPARQL_ENDPOINT, queryString); ResultSet resultSet = queryExecution.execSelect(); if (resultSet.hasNext()) { QuerySolution querySolution = resultSet.next(); String userCopyUrl = querySolution.getResource("userCopy").getURI(); inputDoc.addField("pdfId", store.getOnlyIdFromUrl(userCopyUrl)); } else { throw new RuntimeException("Damn this pdf has no pdf or thumbnail."); } } else { //Other than born-digital branch end node //These are to sort pages based on their index SortedMap<Integer, String> imageMap = new TreeMap<>(); SortedMap<Integer, String> thumbMap = new TreeMap<>(); SortedMap<Integer, String> txtMap = new TreeMap<>(); SortedMap<Integer, String> altoMap = new TreeMap<>(); String videoUrl = null; //Retrieve image, thumbnail and ocr text info String queryString = "SELECT ?pageIndex ?userCopy ?ucMime ?thumb ?txt ?alto WHERE {\n" + //first find pages - children of the node "?page <" + ZdoTerms.zdoType.getURI() + "> \"" + ZdoType.page.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?page <http://purl.org/dc/terms/isPartOf> <" + originalObjectUrl + ">.\n" + "?page <" + ZdoTerms.pageIndex.getURI() + "> ?pageIndex.\n" + "OPTIONAL {\n" + //then children of those pages that are binary usercopy images "?userCopy <http://purl.org/dc/terms/isPartOf> ?page.\n" + "?userCopy <" + ZdoTerms.zdoType.getURI() + "> \"" + ZdoType.binary.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?userCopy <" + ZdoTerms.fileType.getURI() + "> \"" + ZdoFileType.userCopy.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?userCopy <" + ZdoTerms.mimeType.getURI() + "> ?ucMime.\n" + "}\nOPTIONAL {\n" + //and their thumbnails "?thumb <http://purl.org/dc/terms/isPartOf> ?page.\n" + "?thumb <" + ZdoTerms.zdoType.getURI() + "> \"" + ZdoType.binary.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?thumb <" + ZdoTerms.fileType.getURI() + "> \"" + ZdoFileType.thumb.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "}\nOPTIONAL {\n" + //and also children of those pages that are binary text "?txt <http://purl.org/dc/terms/isPartOf> ?page.\n" + "?txt <" + ZdoTerms.zdoType.getURI() + "> \"" + ZdoType.binary.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?txt <" + ZdoTerms.fileType.getURI() + "> \"" + ZdoFileType.txt.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "}\nOPTIONAL {\n" + //and also alto children with ocr text "?alto <http://purl.org/dc/terms/isPartOf> ?page.\n" + "?alto <" + ZdoTerms.zdoType.getURI() + "> \"" + ZdoType.binary.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "?alto <" + ZdoTerms.fileType.getURI() + "> \"" + ZdoFileType.alto.name() + "\"^^<http://www.w3.org/2001/XMLSchema#string>.\n" + "}\n}"; QueryExecution queryExecution = QueryExecutionFactory.sparqlService(SPARQL_ENDPOINT, queryString); ResultSet resultSet = queryExecution.execSelect(); while (resultSet.hasNext()) { QuerySolution querySolution = resultSet.next(); Integer pageIndex = Integer.valueOf(querySolution.getLiteral("pageIndex").getString()); Resource userCopyResource = querySolution.getResource("userCopy"); if (userCopyResource != null) { String userCopyUrl = userCopyResource.getURI(); if (userCopyUrl != null) { if ("video/mp4".equals(querySolution.getLiteral("ucMime").getString())) { if (videoUrl != null) { logger.error( "More than one video per document encountered. There can only be one."); } videoUrl = userCopyUrl; } else { imageMap.put(pageIndex, userCopyUrl); } } } Resource thumbnailResource = querySolution.getResource("thumb"); if (thumbnailResource != null) { String thumbUrl = thumbnailResource.getURI(); if (thumbUrl != null) { thumbMap.put(pageIndex, thumbUrl); } } Resource txtResource = querySolution.getResource("txt"); if (txtResource != null) { String txtUrl = txtResource.getURI(); if (txtUrl != null) { txtMap.put(pageIndex, txtUrl); } } Resource altoResource = querySolution.getResource("alto"); if (altoResource != null) { String altoUrl = altoResource.getURI(); if (altoUrl != null) { altoMap.put(pageIndex, altoUrl); } } } if (videoUrl != null) { inputDoc.addField("videoId", store.getOnlyIdFromUrl(videoUrl)); } List<String> imageIds = new ArrayList<>(); if (!imageMap.isEmpty()) { for (String userCopyUrl : imageMap.values()) { imageIds.add(store.getOnlyIdFromUrl(userCopyUrl)); } inputDoc.addField("imageIds", imageIds); } if (!thumbMap.isEmpty()) { List<String> thumbIds = new ArrayList<>(); for (String thumbUrl : thumbMap.values()) { thumbIds.add(store.getOnlyIdFromUrl(thumbUrl)); } inputDoc.addField("thumbIds", thumbIds); } List<String> txtIds = new ArrayList<>(); if (!txtMap.isEmpty()) { String fulltext = ""; for (String txtUrl : txtMap.values()) { txtIds.add(store.getOnlyIdFromUrl(txtUrl)); InputStream in = new URL(txtUrl).openStream(); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "utf-8"); String text = writer.toString(); fulltext += text + " "; } inputDoc.addField("fullText", fulltext.trim()); } List<String> altoIds = new ArrayList<>(); if (!altoMap.isEmpty()) { for (String altoUrl : altoMap.values()) { altoIds.add(store.getOnlyIdFromUrl(altoUrl)); } } ZdoModel kdrObject = store.get(model.get(ZdoTerms.kdrObject)); String origPdfUrl = kdrObject.get(ZdoTerms.pdfUrl); String origEpubUrl = kdrObject.get(ZdoTerms.epubUrl); ZdoModel patchModel = new ZdoModel(); //Used to add new pdf and epub data to Fedora patchModel.setUrl(model.get(ZdoTerms.kdrObject)); if ("true".equals(model.get(ZdoTerms.allowPdfExport)) && !imageIds.isEmpty()) { if (origPdfUrl == null) { String pdfId = UUID.randomUUID().toString(); patchModel.add(ZdoTerms.pdfUrl, store.createUrl(pdfId)); String orgId = model.get(ZdoTerms.organization); String watermarkId = null; if ("true".equals(model.get(ZdoTerms.watermark))) { watermarkId = organizationSettingsAccess.fetchOrgWatermark(orgId); if (watermarkId == null) { watermarkId = portalSettingsAccess.fetchPortalSettings().getWatermarkId(); } } PdfCreatorDto pdfCreatorDto = new PdfCreatorDto(pdfId, imageIds, altoIds, watermarkId, model.get(ZdoTerms.watermarkPosition)); Response response = ClientBuilder.newClient().target(IP_ENDPOINT + "pdf").request() .post(Entity.json(pdfCreatorDto)); if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new RuntimeException("Failed to call pdf creator in image processing war."); } inputDoc.addField("pdfId", pdfId); } else { //When reindexing, pdf already exists inputDoc.addField("pdfId", store.getOnlyIdFromUrl(origPdfUrl)); } } if ("true".equals(model.get(ZdoTerms.allowEpubExport)) && !txtIds.isEmpty()) { if (origEpubUrl == null) { String epubId = UUID.randomUUID().toString(); patchModel.add(ZdoTerms.epubUrl, store.createUrl(epubId)); epubCreator.createBook(epubId, model.get(DCTerms.title), model.get(DCTerms.creator), txtIds); inputDoc.addField("epubId", epubId); } else { inputDoc.addField("epubId", store.getOnlyIdFromUrl(origEpubUrl)); } } store.patchMetadata(patchModel); //warning, this does not go to triplestore } } logger.debug("Executing update of: {}...", store.removeTransactionFromUrl(model.getUrl())); return inputDoc; }
From source file:de.steilerdev.myVerein.server.model.Settings.java
/** * This function stores the currently loaded settings file, if it did not change. If the database details changed, the method is restarting the context, unfortunately this is not sufficient. * @param currentUser The currently logged in user, used to log the person who changed the settings. * @return Returns true if successfully saved settings, false otherwise. *///from ww w . ja v a 2 s . com public boolean saveSettings(User currentUser, SettingsRepository settingsRepository) { if (databaseChanged) { try { logger.debug("Saving settings to " + settingsResource.getFile().getAbsolutePath()); loadSettingsFromFile().store(new FileOutputStream(settingsResource.getFile()), "Settings last changed " + (currentUser != null ? ("by " + currentUser.getEmail() + " (" + LocalDateTime.now().toString() + ")") : LocalDateTime.now().toString())); logger.info("You need to restart the application context, because database configuration changed"); // try // { // //Getting servlet context to be able to re initiate it. // ServletContext servletContext = ((XmlWebApplicationContext) applicationContext).getServletContext(); // // //Closing application context, mongoDB and servlet context. // mongoDbFactory.destroy(); // ContextLoader contextLoader = new ContextLoader(); // contextLoader.closeWebApplicationContext(servletContext); // // //Restarting servlet context // contextLoader.initWebApplicationContext(servletContext); // } catch (BeansException | IllegalStateException e) // { // throw e; // } catch (Exception e) // { // throw new MongoException(e.getMessage()); // } this.settings = null; } catch (IOException e) { logger.error("Unable to save settings: " + e.getMessage()); return false; } } else { logger.debug("No need to save the settings to file"); } if (settingsRepository != null) { logger.debug("Saving settings to database"); settingsRepository.save(this); } else { logger.warn("Not saving settings to database, because there is no repository available"); } return true; }