Example usage for org.springframework.util StringUtils getFilenameExtension

List of usage examples for org.springframework.util StringUtils getFilenameExtension

Introduction

In this page you can find the example usage for org.springframework.util StringUtils getFilenameExtension.

Prototype

@Nullable
public static String getFilenameExtension(@Nullable String path) 

Source Link

Document

Extract the filename extension from the given Java resource path, e.g.

Usage

From source file:se.alingsas.alfresco.repo.workflow.CompleteDocumentServiceTaskDelegate.java

/**
 * CompleteDocumentServiceTaskDelegate will handle completion of document in
 * workflow// w w w.ja  v  a 2  s  .  c  om
 */
@Override
public void execute(final DelegateExecution execution) throws Exception {
    LOG.debug("Entering CompleteDocumentServiceTaskDelegate");

    final ServiceRegistry serviceRegistry = WorkflowUtil.getServiceRegistry();
    final LockService lockService = serviceRegistry.getLockService();

    final NodeService nodeService = serviceRegistry.getNodeService();
    final FileFolderService fileFolderService = serviceRegistry.getFileFolderService();

    final CheckOutCheckInService checkOutCheckInService = serviceRegistry.getCheckOutCheckInService();
    final PermissionService permissionService = serviceRegistry.getPermissionService();

    ActivitiScriptNode akwfTargetFolder = (ActivitiScriptNode) execution
            .getVariable(CommonWorkflowModel.TARGET_FOLDER);
    final NodeRef targetFolderNodeRef = akwfTargetFolder.getNodeRef();
    final OwnableService ownableService = serviceRegistry.getOwnableService();
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {
        public Object doWork() throws Exception {

            List<ChildAssociationRef> childAssocs = WorkflowUtil.getBpmPackageFiles(execution, nodeService);
            if (childAssocs != null && childAssocs.size() > 0) {
                for (ChildAssociationRef childAssoc : childAssocs) {
                    NodeRef fileNodeRef = childAssoc.getChildRef();
                    String akwfApprover = (String) execution.getVariable("akwf_approver");

                    LOG.debug("Unlocking document");
                    lockService.unlock(fileNodeRef);

                    String readPermSiteRoleGroup = (String) execution
                            .getVariable(CommonWorkflowModel.SITE_GROUP);
                    LOG.debug("Removing temporary read permission on file for " + readPermSiteRoleGroup);
                    permissionService.deletePermission(fileNodeRef, readPermSiteRoleGroup,
                            PermissionService.READ);
                    execution.setVariable(CommonWorkflowModel.REMOVE_PERMISSIONS_DONE, "true");
                    if (!nodeService.getPrimaryParent(fileNodeRef).getParentRef().equals(targetFolderNodeRef)) {
                        LOG.debug("Moving document");
                        String name = (String) nodeService.getProperty(fileNodeRef, ContentModel.PROP_NAME);
                        NodeRef childByName = nodeService.getChildByName(targetFolderNodeRef,
                                ContentModel.ASSOC_CONTAINS, name);
                        if (childByName != null) {
                            String strippedFileName = StringUtils.stripFilenameExtension(name);
                            String filenameExtension = StringUtils.getFilenameExtension(name);
                            name = strippedFileName + "_" + System.currentTimeMillis() + "."
                                    + filenameExtension;
                            LOG.info("File exists, renaming to " + name);
                        }
                        fileFolderService.move(fileNodeRef, targetFolderNodeRef, name);
                    }
                    /*
                     * try { fileFolderService.move(fileNodeRef, targetFolderNodeRef,
                     * null); } catch (FileExistsException e) {
                     * 
                     * 
                     * 
                     * }
                     */
                    ownableService.setOwner(fileNodeRef, akwfApprover);
                    LOG.debug("Checking in document");
                    NodeRef workingCopy = checkOutCheckInService.checkout(fileNodeRef);
                    nodeService.setProperty(workingCopy, AkDmModel.PROP_AKDM_DOC_STATUS,
                            CommonWorkflowModel.DOC_STATUS_DONE);
                    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
                    versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);

                    versionProperties.put(VersionModel.PROP_DESCRIPTION,
                            "Dokumentet frdigstlldes av " + akwfApprover);
                    checkOutCheckInService.checkin(workingCopy, versionProperties);

                }
            }
            return "";
        }
    }, AuthenticationUtil.getSystemUserName());
}

From source file:se.alingsas.alfresco.repo.workflow.RevertDocumentServiceTaskDelegate.java

@Override
public void execute(final DelegateExecution execution) throws Exception {
    LOG.debug("Entering RevertDocumentServiceTaskDelegate");

    final ServiceRegistry serviceRegistry = WorkflowUtil.getServiceRegistry();
    final LockService lockService = serviceRegistry.getLockService();

    final NodeService nodeService = serviceRegistry.getNodeService();
    final FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    final PermissionService permissionService = serviceRegistry.getPermissionService();
    final CheckOutCheckInService checkOutCheckInService = serviceRegistry.getCheckOutCheckInService();

    ActivitiScriptNode akwfTargetFolder = (ActivitiScriptNode) execution
            .getVariable(CommonWorkflowModel.TARGET_FOLDER);
    final NodeRef targetFolderNodeRef = akwfTargetFolder.getNodeRef();
    final OwnableService ownableService = serviceRegistry.getOwnableService();
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {
        public Object doWork() throws Exception {

            List<ChildAssociationRef> childAssocs = WorkflowUtil.getBpmPackageFiles(execution, nodeService);
            if (childAssocs != null && childAssocs.size() > 0) {
                for (ChildAssociationRef childAssoc : childAssocs) {
                    NodeRef fileNodeRef = childAssoc.getChildRef();
                    String akwfApprover = (String) execution.getVariable("akwf_approver");

                    LOG.debug("Unlocking document.");
                    lockService.unlock(fileNodeRef);

                    String readPermSiteRoleGroup = (String) execution
                            .getVariable(CommonWorkflowModel.SITE_GROUP);
                    if (readPermSiteRoleGroup != null) {
                        LOG.debug("Removing temporary read permission on file for " + readPermSiteRoleGroup);
                        permissionService.deletePermission(fileNodeRef, readPermSiteRoleGroup,
                                PermissionService.READ);
                        execution.setVariable(CommonWorkflowModel.REMOVE_PERMISSIONS_DONE, "true");
                    }/* w  w  w .j  a  v  a  2  s  . co m*/
                    ChildAssociationRef primaryParent = nodeService.getPrimaryParent(fileNodeRef);

                    if (!targetFolderNodeRef.equals(primaryParent.getParentRef())) {
                        LOG.debug("Moving document.");
                        try {
                            fileFolderService.move(fileNodeRef, targetFolderNodeRef, null);
                        } catch (FileExistsException e) {
                            LOG.info("File exists, renaming...");
                            String name = (String) nodeService.getProperty(fileNodeRef, ContentModel.PROP_NAME);
                            String strippedFileName = StringUtils.stripFilenameExtension(name);
                            String filenameExtension = StringUtils.getFilenameExtension(name);
                            name = strippedFileName + "_" + System.currentTimeMillis() + "."
                                    + filenameExtension;
                            fileFolderService.move(fileNodeRef, targetFolderNodeRef, name);
                        }
                    } else {
                        LOG.debug("Target folder is the same as source folder. Will not move the file.");
                    }
                    ownableService.setOwner(fileNodeRef, akwfApprover);
                    LOG.debug("Checking in document");
                    NodeRef workingCopy = checkOutCheckInService.checkout(fileNodeRef);
                    nodeService.setProperty(workingCopy, AkDmModel.PROP_AKDM_DOC_STATUS,
                            CommonWorkflowModel.DOC_STATUS_WORKING);
                    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
                    versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);

                    versionProperties.put(VersionModel.PROP_DESCRIPTION,
                            "Dokumentets status ndrades till arbetsdokument av " + akwfApprover);
                    checkOutCheckInService.checkin(workingCopy, versionProperties);

                }
            }
            return "";
        }
    }, AuthenticationUtil.getSystemUserName());
}

From source file:net.sourceforge.subsonic.domain.MusicFile.java

/**
 * Returns the file suffix, e.g., "mp3".
 *
 * @return The file suffix.
 */
public String getSuffix() {
    return StringUtils.getFilenameExtension(getName());
}

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

private void resizeImage(Resource resource, File file, int width, int height, Media.ResizeMode mode)
        throws IOException {
    long startTime = System.currentTimeMillis();

    if (width <= 0) {
        width = Integer.MAX_VALUE;
    }//  ww  w .  j  a  v  a2  s .co  m
    if (height <= 0) {
        height = Integer.MAX_VALUE;
    }

    BufferedImage image = ImageIO.read(resource.getInputStream());

    ResampleOp resampleOp;
    BufferedImage resized;

    switch (mode) {
    case RESIZE:
        resampleOp = new ResampleOp(DimensionConstrain.createMaxDimension(width, height, true));
        resampleOp.setFilter(ResampleFilters.getLanczos3Filter());
        resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal);
        resized = resampleOp.filter(image, null);
        ImageIO.write(resized, StringUtils.getFilenameExtension(file.getName()), file);
        break;
    case CROP:
        float wr = (float) width / (float) image.getWidth();
        float hr = (float) height / (float) image.getHeight();
        float fraction = (wr > hr) ? wr : hr;

        if (fraction < 1) {
            resampleOp = new ResampleOp(DimensionConstrain.createRelativeDimension(fraction));
            resampleOp.setFilter(ResampleFilters.getLanczos3Filter());
            resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal);
            resized = resampleOp.filter(image, null);
        } else {
            resized = image;
        }

        if (resized.getWidth() > width) {
            resized = resized.getSubimage((resized.getWidth() - width) / 2, 0, width, resized.getHeight());
        } else if (resized.getHeight() > height) {
            resized = resized.getSubimage(0, (resized.getHeight() - height) / 2, resized.getWidth(), height);
        }

        ImageIO.write(resized, StringUtils.getFilenameExtension(file.getName()), file);
        break;
    default:
        throw new IllegalStateException();
    }

    long stopTime = System.currentTimeMillis();
    logger.debug("Resized image: time [{}ms]", stopTime - startTime);
}

From source file:com.example.securelogin.domain.service.account.AccountSharedServiceImpl.java

@Override
public String create(Account account, String imageId) {
    if (exists(account.getUsername())) {
        throw new BusinessException(ResultMessages.error().add(MessageKeys.E_SL_AC_5001));
    }/*from w ww. j a v  a  2 s .c  o m*/
    String rawPassword = passwordGenerator.generatePassword(10, passwordGenerationRules);
    account.setPassword(passwordEncoder.encode(rawPassword));
    accountRepository.create(account);
    accountRepository.createRoles(account);
    TempFile tempFile = fileUploadSharedService.findTempFile(imageId);
    InputStream image = tempFile.getBody();
    AccountImage accountImage = new AccountImage();
    accountImage.setUsername(account.getUsername());
    accountImage.setBody(image);
    accountImage.setExtension(StringUtils.getFilenameExtension(tempFile.getOriginalName()));
    accountRepository.createImage(accountImage);
    fileUploadSharedService.deleteTempFile(imageId);
    return rawPassword;
}

From source file:your.microservice.core.util.YourServletUriComponentsBuilder.java

/**
 * Removes any path extension from the {@link HttpServletRequest#getRequestURI()
 * requestURI}. This method must be invoked before any calls to {@link #path(String)}
 * or {@link #pathSegment(String...)}./*from  ww  w.ja va 2 s.  c  o  m*/
 * <pre>
 *  // GET http://foo.com/rest/books/6.json
 *
 *  YourServletUriComponentsBuilder builder = YourServletUriComponentsBuilder.fromRequestUri(this.request);
 *  String ext = builder.removePathExtension();
 *  String uri = builder.path("/pages/1.{ext}").buildAndExpand(ext).toUriString();
 *
 *  assertEquals("http://foo.com/rest/books/6/pages/1.json", result);
 * </pre>
 * @return the removed path extension for possible re-use, or {@code null}
 * @since 4.0
 */
public String removePathExtension() {
    String extension = null;
    if (this.servletRequestURI != null) {
        String filename = WebUtils.extractFullFilenameFromUrlPath(this.servletRequestURI);
        extension = StringUtils.getFilenameExtension(filename);
        if (!StringUtils.isEmpty(extension)) {
            int end = this.servletRequestURI.length() - extension.length() + 1;
            replacePath(this.servletRequestURI.substring(0, end));
        }
        this.servletRequestURI = null;
    }
    return extension;
}

From source file:org.cloudfoundry.tools.io.compiler.ResourceJavaFileManager.java

private String getNameWithoutExtension(String name) {
    String extension = StringUtils.getFilenameExtension(name);
    if (name == null || extension == null) {
        return name;
    }//  w ww .  j  ava 2  s.c  o  m
    return name.substring(0, name.length() - extension.length() - 1);
}

From source file:se.alingsas.alfresco.repo.utils.byggreda.ByggRedaUtil.java

/**
 * Checks for file existance trying different cases on extension.
 * @param path/*from w  w  w.jav a 2 s.co  m*/
 * @return the correct path or null if file does not exist
 */
private String checkFileExistsIgnoreExtensionCase(String path) {
    File f = new File(path);
    if (!f.exists()) {
        String ext = StringUtils.getFilenameExtension(path);
        String fileWithNoExt = path.substring(0, path.indexOf(ext));
        LOG.debug("Extracted filename without extension: " + fileWithNoExt + " Extension: " + ext);
        //Try all lowercase
        path = fileWithNoExt + ext.toLowerCase();
        LOG.debug("Trying " + path);
        f = new File(path);
        if (!f.exists()) {
            //Try with all uppercase
            path = fileWithNoExt + ext.toUpperCase();
            LOG.debug("Trying " + path);
            f = new File(path);
            if (!f.exists()) {
                //Try with capitalized extension
                String tmp = ext.substring(0, 1).toUpperCase() + ext.substring(1).toLowerCase();
                path = fileWithNoExt + tmp;
                LOG.debug("Trying " + path);
                f = new File(path);
                if (!f.exists()) {
                    path = null;
                }
            }
        }

        if (path != null) {
            LOG.debug("Found actual filename to be: " + path);
        }
    }
    return path;
}

From source file:architecture.ee.web.community.spring.controller.SocialConnectController.java

private String getPathExtension(HttpServletRequest request) {
    String fileName = WebUtils.extractFullFilenameFromUrlPath(request.getRequestURI());
    String extension = StringUtils.getFilenameExtension(fileName);
    return extension != null ? "." + extension : "";
}

From source file:com.thoughtworks.go.http.mocks.MockServletContext.java

@Override
public String getMimeType(String filePath) {
    String extension = StringUtils.getFilenameExtension(filePath);
    if (this.mimeTypes.containsKey(extension)) {
        return this.mimeTypes.get(extension).toString();
    } else {//from   www  . j av a  2s . c  om
        try {
            return Optional.of(Files.probeContentType(Paths.get(filePath))).orElse("application/octet-stream");
        } catch (IOException e) {
            return "application/octet-stream";
        }
    }
}