List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:net.bpelunit.framework.control.deploy.ode.ODERequestEntityFactory.java
private void prepareDeploySOAP(File file) throws IOException, SOAPException { MessageFactory mFactory = MessageFactory.newInstance(); SOAPMessage message = mFactory.createMessage(); SOAPBody body = message.getSOAPBody(); SOAPElement xmlDeploy = body.addChildElement(ODE_ELEMENT_DEPLOY); SOAPElement xmlZipFilename = xmlDeploy.addChildElement(ODE_ELEMENT_ZIPNAME); xmlZipFilename.setTextContent(FilenameUtils.getName(file.toString()).split("\\.")[0]); SOAPElement xmlZipContent = xmlDeploy.addChildElement(ODE_ELEMENT_PACKAGE); SOAPElement xmlBase64ZipFile = xmlZipContent.addChildElement(ODE_ELEMENT_ZIP, "dep", NS_DEPLOY_SERVICE); xmlBase64ZipFile.addAttribute(new QName(NS_XML_MIME, CONTENT_TYPE_STRING), ZIP_CONTENT_TYPE); StringBuilder content = new StringBuilder(); byte[] arr = FileUtils.readFileToByteArray(file); byte[] encoded = Base64.encodeBase64Chunked(arr); for (int i = 0; i < encoded.length; i++) { content.append((char) encoded[i]); }/*w ww .j a v a2s .c om*/ xmlBase64ZipFile.setTextContent(content.toString()); ByteArrayOutputStream b = new ByteArrayOutputStream(); message.writeTo(b); fContent = b.toString(); }
From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java
/** * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection , * FileUploadSelector, String, UploadProgress) *///from w w w . j a va 2 s. c o m @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex, final UploadProgress progress) throws Exception { final ApplicationInstance app = conn.getUserInstance().getApplicationInstance(); final DiskFileItemFactory itemFactory = new DiskFileItemFactory(); itemFactory.setRepository(getDiskCacheLocation()); itemFactory.setSizeThreshold(getMemoryCacheThreshold()); String encoding = conn.getRequest().getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } final ServletFileUpload upload = new ServletFileUpload(itemFactory); upload.setHeaderEncoding(encoding); upload.setProgressListener(new UploadProgressListener(progress)); long sizeLimit = uploadSelect.getUploadSizeLimit(); if (sizeLimit == 0) sizeLimit = getFileUploadSizeLimit(); if (sizeLimit != NO_SIZE_LIMIT) { upload.setSizeMax(sizeLimit); } String fileName = null; String contentType = null; try { final FileItemIterator iter = upload.getItemIterator(conn.getRequest()); if (iter.hasNext()) { final FileItemStream stream = iter.next(); if (!stream.isFormField()) { fileName = FilenameUtils.getName(stream.getName()); contentType = stream.getContentType(); final Set<String> types = uploadSelect.getContentTypeFilter(); if (!types.isEmpty()) { if (!types.contains(contentType)) { app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable( uploadSelect, uploadIndex, fileName, contentType, progress)); return; } } progress.setStatus(Status.inprogress); final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName()); item.getOutputStream(); // initialise DiskFileItem internals uploadSelect.notifyCallback( new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize())); IOUtils.copy(stream.openStream(), item.getOutputStream()); app.enqueueTask(uploadSelect.getTaskQueue(), new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress)); return; } } app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new RuntimeException("No multi-part content!"), progress)); } catch (final FileUploadBase.SizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final FileUploadBase.FileSizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final MultipartStream.MalformedStreamException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress)); } }
From source file:com.kamike.misc.FsNameUtils.java
public static String getName(String disk, String filename, String fid, String uid) { String name = FilenameUtils.getName(filename); String prefix = FilenameUtils.getPrefix(filename); Date date = new Date(System.currentTimeMillis()); String extension = FilenameUtils.getExtension(filename); return getName(prefix, disk, getShortDate(date), name, fid, uid, extension); }
From source file:net.bpelunit.framework.control.deploy.ode.ODEDeployer.java
public void deploy(String pathToTest, ProcessUnderTest put) throws DeploymentException { LOGGER.info("ODE deployer got request to deploy " + put); check(fArchive, "Archive Location"); check(fDeploymentAdminServiceURL, "deployment admin server URL"); String archivePath = getArchiveLocation(pathToTest); if (!new File(archivePath).exists()) { throw new DeploymentException(String.format("The archive location '%s' does not exist", archivePath)); }//w w w . j a v a 2 s .c om boolean archiveIsTemporary = false; if (!FilenameUtils.getName(archivePath).endsWith(".zip")) { // if the deployment is a directory and not a zip file if (new File(archivePath).isDirectory()) { archivePath = zipDirectory(new File(archivePath)); // Separate zip file was created and should be later cleaned up archiveIsTemporary = true; } else { throw new DeploymentException("Unknown archive format for the archive " + fArchive); } } java.io.File uploadingFile = new java.io.File(archivePath); // process the bundle for replacing wsdl eprs here. requires base url // string from specification loader. // should be done via the ODEDeploymentArchiveHandler. hard coded ode // process deployment string will be used // to construct the epr of the process wsdl. this requires the location // of put wsdl in order to obtain the // service name of the process in process wsdl. alternatively can use // inputs from deploymentsoptions. // test coverage logic. Moved to ProcessUnderTest deploy() method. HttpClient client = new HttpClient(new NoPersistenceConnectionManager()); PostMethod method = new PostMethod(fDeploymentAdminServiceURL); RequestEntity re = fFactory.getDeployRequestEntity(uploadingFile); method.setRequestEntity(re); LOGGER.info("ODE deployer about to send SOAP request to deploy " + put); // Provide custom retry handler if necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); method.addRequestHeader("SOAPAction", ""); String responseBody; int statusCode = 0; try { statusCode = client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (Exception e) { throw new DeploymentException("Problem contacting the ODE Server: " + e.getMessage(), e); } finally { method.releaseConnection(); if (uploadingFile.exists() && archiveIsTemporary) { uploadingFile.delete(); } } if (isHttpErrorCode(statusCode)) { throw new DeploymentException("ODE Server reported a Deployment Error: " + responseBody); } try { fProcessId = extractProcessId(responseBody); } catch (IOException e) { throw new DeploymentException("Problem extracting deployment information: " + e.getMessage(), e); } }
From source file:com.exilant.exility.core.TestProcessor.java
@Override public void process(String FileInput) throws ExilityException { String stamp = ResourceManager.getTimeStamp(); String qualifiedFileName = null; String testFileOutput = null; String testFile = null;// w w w . j a va 2 s. c o m List<String[]> list = new ArrayList<String[]>(); DataCollection dc = new DataCollection(); File file = new File(FileInput); File dir = new File(FileInput); testFileOutput = FileInput + "/" + FilenameUtils.getName(file.toString()) + Constants.OUT_SUFFIX; String summaryFile = FileInput + "/" + Constants.SUMMARY + "/" + Constants.SUMMARY + stamp + ".xml"; try { if (file.isFile() && (file.getCanonicalPath()).endsWith(".xml")) { qualifiedFileName = FilenameUtils.getName(file.toString()); testFile = testFileOutput + "/" + qualifiedFileName + "_out" + stamp + ".xml"; dc = this.test(file.toString(), testFile, list); generate(dc, testFile, list); } else { for (File testFileInput : dir.listFiles()) { try { if (testFileInput.isFile() && (testFileInput.getCanonicalPath()).endsWith(".xml")) { qualifiedFileName = FilenameUtils.getName(dir.toString()); testFile = testFileOutput + "/" + qualifiedFileName + "_out" + stamp + ".xml"; dc = this.test(testFileInput.toString(), testFile, list); generate(dc, testFile, list); } } catch (IOException e) { Spit.out("Output file could not be created for " + qualifiedFileName); e.printStackTrace(); } } } generateSummary(dc, summaryFile, list); } catch (IOException e) { Spit.out("Output file could not be created for " + FileInput); e.printStackTrace(); } }
From source file:edu.umn.msi.tropix.galaxy.service.GalaxyJobProcessorImpl.java
@Override protected void doPreprocessing() { final Iterator<String> fileNameIterator = fileNames.iterator(); final Iterator<InputContext> inputContextsIterator = inputContexts.iterator(); while (fileNameIterator.hasNext()) { Preconditions.checkState(inputContextsIterator.hasNext()); final String fileName = fileNameIterator.next(); LOG.debug(String.format("In preprocessing with filename %s", fileName)); // Verify this write attempt isn't trying to write outside the specified staging directory. // Later this should be modified to let subdirectories be written. Preconditions.checkState(FilenameUtils.getName(fileName).equals(fileName)); final OutputContext outputContext = getStagingDirectory().getOutputContext(fileName); inputContextsIterator.next().get(outputContext); }// w ww . jav a 2 s.c o m if (LOG.isDebugEnabled()) { LOG.debug("Pre Expanded Galaxy Tool"); LOG.debug(GalaxyXmlUtils.serialize(tool)); LOG.debug("RootInput"); LOG.debug(GalaxyXmlUtils.serialize(rootInput)); } final Context context = Contexts.expandPathsAndBuildContext(tool, rootInput, getStagingDirectory()); toolEvaluator.resolve(tool, context); if (LOG.isDebugEnabled()) { LOG.debug("Expanded Galaxy Tool"); LOG.debug(new XMLUtility<Tool>(Tool.class).toString(tool)); } if (tool.getConfigfiles() != null) { for (final ConfigFile configFile : tool.getConfigfiles().getConfigfile()) { final String configFileName = configFile.getName(); Preconditions.checkState(FilenameUtils.getName(configFileName).equals(configFileName)); getStagingDirectory().getOutputContext(configFileName).put(configFile.getValue().getBytes()); } } final JobDescriptionType jobDescription = getJobDescription().getJobDescriptionType(); jobDescription.setDirectory(getStagingDirectory().getAbsolutePath()); galaxyConverter.populateJobDescription(jobDescription, tool); }
From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileDownloadServiceImpl.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER); String operationId = req.getParameter("operationid"); if (user != null && operationId != null && !operationId.isEmpty()) { try {/* ww w . j a v a2 s . c o m*/ GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient(); Operation operation = client.getOperationById(operationId); File file = new File(operation.getDest()); if (file.isDirectory()) { file = new File(operation.getDest() + "/" + FilenameUtils.getName(operation.getSource())); } int length = 0; ServletOutputStream op = resp.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(file.getName()); logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'."); resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); resp.setContentLength((int) file.length()); resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); byte[] bbuf = new byte[4096]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } in.close(); op.flush(); op.close(); } catch (GRIDAClientException ex) { logger.error(ex); } } }
From source file:de.monticore.io.paths.ModelCoordinateImpl.java
@Override public String getName() { if (hasLocation()) { return FilenameUtils.getName(location.toString()); } else {/*from w w w .j av a2 s . c o m*/ return FilenameUtils.getName(qualifiedPath.toString()); } }
From source file:com.mindquarry.desktop.client.dialog.conflict.ReplaceConflictDialog.java
@Override protected void createLowerDialogArea(Composite composite) { Composite subComposite = new Composite(composite, SWT.NONE); subComposite.setLayout(new GridLayout(2, false)); Button button1 = makeRadioButton(subComposite, I18N.getString("Rename file and upload it using a new name:"), //$NON-NLS-1$ ReplaceConflict.Action.RENAME); button1.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { newNameField.setEnabled(true); }// ww w. ja va 2s.c om }); newNameField = createNewNameField(subComposite, FilenameUtils.getName(conflict.getStatus().getPath())); newNameField.setFocus(); // no replace available because it is a dangerous, unrecoverable action /* * Button button2 = makeRadioButton(subComposite, * //M.getString("Overwrite the file on the server with your * local version"), //$NON-NLS-1$ //Action.REPLACE); * M.getString("Overwrite your local file with the one from the * server"), //$NON-NLS-1$ Action.REPLACE); * button2.addListener(SWT.Selection, new Listener() { public void * handleEvent(Event event) { newNameField.setEnabled(false); * okButton.setEnabled(true); } }); */ }
From source file:de.uzk.hki.da.format.PublishXSLTConversionStrategy.java
/** * Convert file./*from w ww . j a v a2 s . co m*/ * * @param ci the ci * @return the list * @throws FileNotFoundException the file not found exception * @throws IllegalStateException the illegal state exception * @author Daniel M. de Oliveira * @author Sebastian Cuy */ @Override public List<Event> convertFile(ConversionInstruction ci) throws FileNotFoundException, IllegalStateException { if (object == null) throw new IllegalStateException("Object not set"); if (object.getIdentifier() == null || object.getIdentifier().equals("")) throw new IllegalStateException("object.getIdentifier() - returns no valid value"); String objectId = object.getIdentifier().substring(object.getIdentifier().indexOf("-") + 1); logger.debug("objectId: " + objectId); Source xmlSource = createXMLSource(ci.getSource_file().toRegularFile()); String targetFileName = FilenameUtils .removeExtension(FilenameUtils.getName(ci.getSource_file().toRegularFile().getAbsolutePath())); if (!ci.getConversion_routine().getName().endsWith("_paths-for-presenter")) targetFileName += "_" + ci.getConversion_routine().getName(); List<Event> results = new ArrayList<Event>(); DAFile publFile = new DAFile(object.getLatestPackage(), "dip/public", ci.getTarget_folder() + "/" + targetFileName + ".xml"); DAFile instFile = new DAFile(object.getLatestPackage(), "dip/institution", ci.getTarget_folder() + "/" + targetFileName + ".xml"); new File(object.getDataPath() + "/dip/public/" + ci.getTarget_folder()).mkdirs(); new File(object.getDataPath() + "/dip/institution/" + ci.getTarget_folder()).mkdirs(); logger.debug("Will transform {} to {}", ci.getSource_file(), publFile); logger.debug("Will transform {} to {}", ci.getSource_file(), instFile); try { if (objectId != null) transformer.setParameter("object-id", objectId); transformer.transform(xmlSource, new StreamResult(publFile.toRegularFile().getAbsolutePath())); transformer.transform(xmlSource, new StreamResult(instFile.toRegularFile().getAbsolutePath())); } catch (TransformerException e) { throw new RuntimeException("Error while transforming xml.", e); } Event e1 = new Event(); e1.setType("CONVERT"); e1.setDetail(stylesheet); e1.setSource_file(ci.getSource_file()); e1.setTarget_file(publFile); e1.setDate(new Date()); Event e2 = new Event(); e2.setType("CONVERT"); e2.setDetail(stylesheet); e2.setSource_file(ci.getSource_file()); e2.setTarget_file(instFile); e2.setDate(new Date()); results.add(e1); results.add(e2); return results; }