List of usage examples for org.apache.commons.io FilenameUtils concat
public static String concat(String basePath, String fullFilenameToAdd)
From source file:edu.kit.dama.staging.services.impl.StagingService.java
/** * This method finalizes the download for the provided download entity. This * method is intended to be used internally only. * * @param pDownloadInfo The download information. * * @return TRUE if the download could be finalized. *///w w w .j a v a 2s . co m private boolean finalizeDownload(DownloadInformation pDownloadInfo) { if (!pDownloadInfo.getStatusEnum().isFinalizationPossible()) { LOGGER.error( "Finalization of download impossible. Status of download #{} is {}, but has to be DOWNLOAD_STATUS.SCHEDULED", pDownloadInfo.getTransferId(), pDownloadInfo.getStatusEnum()); return false; } LOGGER.debug("Setting download status to PREPARING"); pDownloadInfo.setStatusEnum(DOWNLOAD_STATUS.PREPARING); if (!updateTransferStatus(pDownloadInfo)) { LOGGER.error("Failed to update download status to {}. Finalizing impossible.", DOWNLOAD_STATUS.PREPARING); return false; } LOGGER.debug("Performing download finalization for download with id {}", pDownloadInfo.getTransferId()); boolean result = true; try { URL stagingUrl = new URL(pDownloadInfo.getStagingUrl()); LOGGER.debug("Obtaining AccessPoint with id '{}'", pDownloadInfo.getAccessPointId()); AbstractStagingAccessPoint accessPoint = StagingConfigurationManager.getSingleton() .getAccessPointById(pDownloadInfo.getAccessPointId()); LOGGER.debug("Obtaining user paths for staging URL '{}'", stagingUrl.toString()); File localStagingPath = accessPoint.getLocalPathForUrl(stagingUrl, getContext(pDownloadInfo)); //obtain settings path as the file tree to download is stored there File localSettingsPath = new File(localStagingPath, Constants.STAGING_SETTINGS_FOLDER_NAME); //try to perform staging StagingFile destinationForStaging = new StagingFile(new AbstractFile(localStagingPath)); LOGGER.debug("Perform staging into folder '{}'", destinationForStaging); String treeFile = FilenameUtils.concat(localSettingsPath.getPath(), DownloadPreparationHandler.DATA_FILENAME); LOGGER.debug(" - Loading file tree from {}", treeFile); IFileTree downloadTree = DataOrganizationUtils.readTreeFromFile(new File(treeFile)); //get filetree and restore LOGGER.debug("Restoring data organization tree using storage virtualization"); if (!StagingConfigurationManager.getSingleton().getStorageVirtualizationAdapter().restore(pDownloadInfo, downloadTree, destinationForStaging)) { LOGGER.error("Failed to restore data organization tree from file {}", treeFile); pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId()); pDownloadInfo.setErrorMessage("Failed to reconstruct file tree."); result = false; } else { LOGGER.debug("Creating file tree and transfer container."); IFileTree tree = DataOrganizationUtils.createTreeFromFile(pDownloadInfo.getDigitalObjectId(), destinationForStaging.getAbstractFile(), destinationForStaging.getAbstractFile().getUrl(), false); TransferTaskContainer container = TransferTaskContainer.factoryDownloadContainer(pDownloadInfo, tree, StagingConfigurationManager.getSingleton().getRestServiceUrl()); container.setDestination(localStagingPath.toURI().toURL()); LOGGER.debug("Transfer container successfully created."); boolean postProcessingSucceeded = true; StagingProcessor[] processors = pDownloadInfo.getStagingProcessors() .toArray(new StagingProcessor[] {}); Arrays.sort(processors, StagingProcessor.DEFAULT_PRIORITY_COMPARATOR); LOGGER.debug("Executing {} staging processors", processors.length); for (StagingProcessor processor : processors) { if (processor.isDisabled()) { LOGGER.info("StagingProcessor with id {} is disabled. Skipping execution.", processor.getUniqueIdentifier()); continue; } try { LOGGER.debug(" - Try to execute processor {} ({})", new Object[] { processor.getName(), processor.getUniqueIdentifier() }); AbstractStagingProcessor sProcessor = processor.createInstance(); LOGGER.debug(" - Executing processor"); sProcessor.performPostTransferProcessing(container); LOGGER.debug(" - Finishing processor execution"); sProcessor.finalizePostTransferProcessing(container); LOGGER.debug(" - Processor successfully executed"); } catch (ConfigurationException ex) { LOGGER.error("Failed to configure StagingProcessor " + processor.getName() + " (" + processor.getUniqueIdentifier() + ")", ex); pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId()); pDownloadInfo.setErrorMessage("Internal error. Failed to configure StagingProcessor '" + processor.getName() + "'."); postProcessingSucceeded = false; result = false; } catch (StagingProcessorException ex) { LOGGER.error("Failed to perform StagingProcessor " + processor.getName() + " (" + processor.getUniqueIdentifier() + ")", ex); pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId()); pDownloadInfo.setErrorMessage("Internal error. Failed to execute StagingProcessor '" + processor.getName() + "'."); postProcessingSucceeded = false; result = false; } } if (postProcessingSucceeded) { //preparation successfully...transfer can be performed LOGGER.debug("Download preparation finished. Download #{} for object {} is now ready.", pDownloadInfo.getTransferId(), pDownloadInfo.getDigitalObjectId()); pDownloadInfo.setStatus(DOWNLOAD_STATUS.DOWNLOAD_READY.getId()); pDownloadInfo.setErrorMessage(null); //handle notification Properties notificationProperties = MailNotificationHelper.restoreProperties(localSettingsPath); if (!notificationProperties.isEmpty()) { if (result) { LOGGER.debug("Try to notify user about finalized download"); MailNotificationHelper.sendDownloadNotification(notificationProperties, pDownloadInfo); } else { LOGGER.warn("Download not finalized successfully. Notification skipped."); } } } else { LOGGER.error("Postprocessing failed, skipping user notification."); //status to download should be already set } } } catch (MalformedURLException mue) { LOGGER.error("Failed to convert staging URL '" + pDownloadInfo.getStagingUrl() + "' of transfer '" + pDownloadInfo.getTransferId() + "' to local path", mue); pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId()); pDownloadInfo .setErrorMessage("Staging URL '" + pDownloadInfo.getStagingUrl() + "' seems to be invalid."); result = false; } catch (AdalapiException ex) { //failed to handle file tree stuff LOGGER.error("Failed finalize download for object ID " + pDownloadInfo.getId(), ex); pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId()); pDownloadInfo.setErrorMessage("Failed to finalize download. Cause: " + ex.getMessage()); result = false; } catch (RuntimeException t) { //failed to handle file tree stuff LOGGER.error("An unexpected error occured while downloading object " + pDownloadInfo.getTransferId() + ". Download cannot be continued.", t); pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId()); pDownloadInfo.setErrorMessage("Unhandled error during download. Cause: " + t.getMessage()); result = false; } LOGGER.debug("Updating download information to status {}", pDownloadInfo.getStatusEnum()); if (updateTransferStatus(pDownloadInfo)) { LOGGER.debug("Download status successfully updated."); } else { LOGGER.error("Failed to update status or download #{} for digital object {} to {}", pDownloadInfo.getTransferId(), pDownloadInfo.getDigitalObjectId(), pDownloadInfo.getStatusEnum()); result = false; } return result; }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java
private void loadConnectorJsp(Service service, HttpServletResponse response) { FileInputStream fileinputstream = null; String jspProvidedByService = connectorConfigurationManager.getJspPath(service); try {//from ww w .ja v a2 s . c o m if (StringUtils.isNotBlank(jspProvidedByService)) { String cssdkFilesDirectory = FilenameUtils.concat( config.getValue(Names.com_citrix_cpbm_portal_settings_services_datapath), service.getServiceName() + "_" + service.getVendorVersion()); String jspPath = cssdkFilesDirectory + "/" + CssdkConstants.JSP_DIRECTORY + "/" + jspProvidedByService; fileinputstream = new FileInputStream(jspPath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("text/html"); OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } catch (FileNotFoundException e) { logger.error("FileNot Found...", e); } catch (IOException e) { logger.error("IOException Found...", e); } response.setStatus(HttpServletResponse.SC_NOT_FOUND); }
From source file:net.sf.jvifm.ui.FileLister.java
public void doUnCompress(boolean extractToPwd) { String[] selectionFiles = getSelectionFiles(); if (selectionFiles == null || selectionFiles.length <= 0) return;/*from w w w.jav a 2 s .co m*/ String archFileName = selectionFiles[0]; String baseName = ""; if (archFileName.endsWith(".tar.gz")) { baseName = archFileName.substring(0, archFileName.length() - 7); } else if (archFileName.endsWith(".tar.bz2")) { baseName = archFileName.substring(0, archFileName.length() - 8); } else { baseName = FilenameUtils.getBaseName(archFileName); } Command command = null; if (extractToPwd) { command = new UnCompressCommand(archFileName, pwd); } else { command = new UnCompressCommand(archFileName, FilenameUtils.concat(pwd, baseName)); } command.setFileLister(this); commandRunner.run(command); }
From source file:net.sf.jvifm.ui.FileLister.java
public void doCompress() { String[] selectionFiles = getSelectionFiles(); ZipUtil zipUtil = new ZipUtil(); if (selectionFiles == null || selectionFiles.length <= 0) return;/* ww w .j a va 2s. c o m*/ // String baseName=FilenameUtils.getBaseName(selectionFiles[0]); try { zipUtil.zip(FilenameUtils.concat(pwd, new File(pwd).getName()), selectionFiles); } catch (Exception e) { Util.openMessageWindow(e.getMessage()); e.printStackTrace(); } }
From source file:net.sf.jvifm.ui.FileLister.java
public void enterPath(int count) { int i = 0;/* w ww.j av a 2 s .c om*/ String[] selection = getSelectionFiles(); if (selection.length > 1) { Util.editFile(getPwd(), selection); if (getOperateMode() != Mode.ORIG) switchToNormalMode(); return; } String nextEntry = getItemFullPath(currentRow); if (nextEntry == null) return; String historyDir = (String) historyManager.getSelectedItem(nextEntry); while (i < count - 1 && historyDir != null && new File(nextEntry).isDirectory()) { nextEntry = FilenameUtils.concat(nextEntry, historyDir); historyDir = (String) historyManager.getSelectedItem(nextEntry); i++; } File file = new File(nextEntry); if (file.isFile() && count == 1) { Util.editFile(getPwd(), nextEntry); } else if (file.isFile() && count != 1) { file = file.getParentFile(); visit(file.getPath()); } else { visit(file.getPath()); } }
From source file:com.cloudant.sync.datastore.BasicDatastore.java
@Override public String extensionDataFolder(String extensionName) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(extensionName), "extension name can not be null or empty"); return FilenameUtils.concat(this.extensionsDir, extensionName); }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractChannelController.java
@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST) @ResponseBody//w ww . j a v a 2s .c om public String editChannelLogo(@ModelAttribute("channelLogoForm") ChannelLogoForm form, BindingResult result, HttpServletRequest request, ModelMap map) { logger.debug("### editChannelLogo method starting...(POST)"); String fileSize = checkFileUploadMaxSizeException(request); if (fileSize != null) { result.rejectValue("logo", "error.image.max.upload.size.exceeded"); JsonObject error = new JsonObject(); error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(), new Object[] { fileSize }, request.getLocale())); return error.toString(); } String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (rootImageDir != null && !rootImageDir.trim().equals("")) { Channel channel = channelService.getChannelById(form.getChannel().getId().toString()); ChannelLogoFormValidator validator = new ChannelLogoFormValidator(); validator.validate(form, result); if (result.hasErrors()) { JsonObject error = new JsonObject(); setPage(map, Page.CHANNELS); error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale())); return error.toString(); } else { String channelsDir = "channels"; File file = new File(FilenameUtils.concat(rootImageDir, channelsDir)); if (!file.exists()) { file.mkdir(); } String channelsAbsoluteDir = FilenameUtils.concat(rootImageDir, channelsDir); String relativeImageDir = FilenameUtils.concat(channelsDir, channel.getId().toString()); File file1 = new File(FilenameUtils.concat(channelsAbsoluteDir, channel.getId().toString())); if (!file1.exists()) { file1.mkdir(); } MultipartFile logoFile = form.getLogo(); try { if (!logoFile.getOriginalFilename().trim().equals("")) { String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir, logoFile); channel.setImagePath(logoFileRelativePath); } channelService.updateChannel(channel); } catch (IOException e) { logger.debug("###IO Exception in writing custom image file"); } } String response = null; try { response = JSONUtils .toJSONString(channelService.getChannelById(form.getChannel().getId().toString())); } catch (JsonGenerationException e) { logger.debug("###IO Exception in writing custom image file"); } catch (JsonMappingException e) { logger.debug("###IO Exception in writing custom image file"); } catch (IOException e) { logger.debug("###IO Exception in writing custom image file"); } logger.debug("### editChannelLogo method ending (Success)...(POST)"); return response; } else { result.rejectValue("logo", "error.custom.image.upload.dir"); setPage(map, Page.CHANNELS); JsonObject error = new JsonObject(); error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale())); logger.debug("### editChannelLogo method ending (No Image Logo Dir Defined)...(POST)"); return error.toString(); } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductBundlesController.java
/** * This method is used to edit the Product Bundle logo * //www . ja va2s .co m * @param form * @param result * @param request * @param map * @return */ @RequestMapping(value = ("/editlogo"), method = RequestMethod.POST) @ResponseBody public String editBundleLogo(@ModelAttribute("bundleLogoForm") ProductBundleLogoForm form, BindingResult result, HttpServletRequest request, ModelMap map) { logger.debug("### editBundleLogo method starting...(POST)"); String fileSize = checkFileUploadMaxSizeException(request); if (fileSize != null) { result.rejectValue("logo", "error.image.max.upload.size.exceeded"); JsonObject error = new JsonObject(); error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(), new Object[] { fileSize }, request.getLocale())); return error.toString(); } String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (rootImageDir != null && !rootImageDir.trim().equals("")) { ProductBundle bundle = form.getBundle(); ProductBundleLogoFormValidator validator = new ProductBundleLogoFormValidator(); validator.validate(form, result); if (result.hasErrors()) { return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()); } else { String bundlesDir = "productbundles"; File file = new File(FilenameUtils.concat(rootImageDir, bundlesDir)); if (!file.exists()) { file.mkdir(); } String bundlesAbsoluteDir = FilenameUtils.concat(rootImageDir, bundlesDir); String relativeImageDir = FilenameUtils.concat(bundlesDir, bundle.getId().toString()); File file1 = new File(FilenameUtils.concat(bundlesAbsoluteDir, bundle.getId().toString())); if (!file1.exists()) { file1.mkdir(); } MultipartFile logoFile = form.getLogo(); try { if (!logoFile.getOriginalFilename().trim().equals("")) { String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir, logoFile); bundle.setImagePath(logoFileRelativePath); } bundle = productBundleService.updateProductBundle(bundle, false); } catch (IOException e) { logger.debug("###IO Exception in writing custom image file"); result.rejectValue("logo", "error.uploading.file"); JsonObject error = new JsonObject(); error.addProperty("errormessage", messageSource .getMessage(result.getFieldError("logo").getCode(), null, request.getLocale())); return error.toString(); } } String response = null; try { response = JSONUtils.toJSONString(bundle); } catch (JsonGenerationException e) { logger.debug("###IO Exception in writing custom image file"); } catch (JsonMappingException e) { logger.debug("###IO Exception in writing custom image file"); } catch (IOException e) { logger.debug("###IO Exception in writing custom image file"); } return response; } else { result.rejectValue("logo", "error.custom.image.upload.dir"); JsonObject error = new JsonObject(); error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale())); return error.toString(); } }
From source file:de.sub.goobi.forms.ProzesskopieForm.java
@SuppressWarnings("unchecked") private void initializePossibleDigitalCollections() { this.possibleDigitalCollection = new ArrayList<>(); ArrayList<String> defaultCollections = new ArrayList<>(); String filename = FilenameUtils.concat(ConfigCore.getKitodoConfigDirectory(), FileNames.DIGITAL_COLLECTIONS_FILE); if (!(new File(filename).exists())) { Helper.setFehlerMeldung("File not found: ", filename); return;//from w w w . j a v a 2 s. co m } this.digitalCollections = new ArrayList<>(); try { /* Datei einlesen und Root ermitteln */ SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(new File(filename)); Element root = doc.getRootElement(); /* alle Projekte durchlaufen */ List<Element> projekte = root.getChildren(); for (Element project : projekte) { // collect default collections if (project.getName().equals("default")) { List<Element> myCols = project.getChildren("DigitalCollection"); for (Element digitalCollection : myCols) { if (digitalCollection.getAttribute("default") != null && digitalCollection.getAttributeValue("default").equalsIgnoreCase("true")) { digitalCollections.add(digitalCollection.getText()); } defaultCollections.add(digitalCollection.getText()); } } else { // run through the projects List<Element> projektnamen = project.getChildren("name"); for (Element projectName : projektnamen) { // all all collections to list if (projectName.getText().equalsIgnoreCase(this.prozessKopie.getProject().getTitle())) { List<Element> myCols = project.getChildren("DigitalCollection"); for (Element digitalCollection : myCols) { if (digitalCollection.getAttribute("default") != null && digitalCollection .getAttributeValue("default").equalsIgnoreCase("true")) { digitalCollections.add(digitalCollection.getText()); } this.possibleDigitalCollection.add(digitalCollection.getText()); } } } } } } catch (JDOMException | IOException e1) { logger.error("error while parsing digital collections", e1); Helper.setFehlerMeldung("Error while parsing digital collections", e1); } if (this.possibleDigitalCollection.size() == 0) { this.possibleDigitalCollection = defaultCollections; } // if only one collection is possible take it directly if (isSingleChoiceCollection()) { this.digitalCollections.add(getDigitalCollectionIfSingleChoice()); } }
From source file:com.cloudant.sync.datastore.DatastoreImpl.java
public String extensionDataFolder(String extensionName) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(extensionName), "extension name cannot be null or empty"); return FilenameUtils.concat(this.extensionsDir, extensionName); }