org.springframework.extensions.surf.util.I18NUtil Java Examples

The following examples show how to use org.springframework.extensions.surf.util.I18NUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileFolderServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testShallowFilesAndFoldersListWithLocale() throws Exception
{
    Locale savedLocale = I18NUtil.getContentLocaleOrNull();
    try
    {
        I18NUtil.setContentLocale(Locale.CANADA);
        List<FileInfo> files = fileFolderService.list(workingRootNodeRef);
        // check
        String[] expectedNames = new String[]
        { NAME_L0_FILE_A, NAME_L0_FILE_B, NAME_L0_FOLDER_A, NAME_L0_FOLDER_B, NAME_L0_FOLDER_C };
        checkFileList(files, 2, 3, expectedNames);
    }
    finally
    {
        I18NUtil.setContentLocale(savedLocale);
    }
}
 
Example #2
Source File: MailActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Attempt to localize the subject, using the subject parameter as the message key.
 * 
 * @param subject Message key for subject lookup
 * @param params Parameters for the message
 * @param locale Locale to use
 * @return The localized message, or subject if the message format could not be found
 */
private String getLocalizedSubject(String subject, Object[] params, Locale locale)
{
    String localizedSubject = null;
    if (locale == null)
    {
        localizedSubject = I18NUtil.getMessage(subject, params);
    }
    else 
    {
        localizedSubject = I18NUtil.getMessage(subject, locale, params);
    }
    
    if (localizedSubject == null)
    {
        return subject;
    }
    else
    {
        return localizedSubject;
    }
    
}
 
Example #3
Source File: CopyServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Builds name by appending copy label.
 */
String buildNewName(final String name)
{
    String baseName = FilenameUtils.getBaseName(name);
    String extension = FilenameUtils.getExtension(name);

    String newName = I18NUtil.getMessage(COPY_OF_LABEL, baseName);

    // append extension, if any, to filename
    if (extension != null && !extension.isEmpty())
    {
        newName = newName + FilenameUtils.EXTENSION_SEPARATOR_STR + extension;
    }

    return newName;
}
 
Example #4
Source File: GenericDeleteAspectForTypePatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    // We don't need to catch the potential InvalidQNameException here as it will be caught
    // in AbstractPatch and correctly handled there
    QName qnameType = QName.createQName(this.qnameStringType);
    QName qnameAspect = QName.createQName(this.qnameStringAspect);

    Long maxNodeId = patchDAO.getMaxAdmNodeID();
    
    Pair<Long, QName> type = qnameDAO.getQName(qnameType);
    Pair<Long, QName> aspect = qnameDAO.getQName(qnameAspect);
    
    if (type != null && aspect != null)
    {
        for (Long i = 0L; i < maxNodeId; i+=BATCH_SIZE)
        {
            Work work = new Work(type, aspect, i);
            retryingTransactionHelper.doInTransaction(work, false, true);
        }
    }

    return I18NUtil.getMessage(MSG_SUCCESS, qnameAspect, qnameType);
}
 
Example #5
Source File: TaskFormProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getMessageValue(WorkflowTask task)
{
    String message = I18NUtil.getMessage(MessageFieldProcessor.MSG_VALUE_NONE);
    
    String description = (String)task.getProperties().get(WorkflowModel.PROP_DESCRIPTION);
    if (description != null)
    {
        String taskTitle = task.getTitle();
        if (taskTitle == null || !taskTitle.equals(description))
        {
            message = description;
        }
    }
    
    return message;
}
 
Example #6
Source File: GlobalLocalizationFilter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Apply Client and Repository language locale based on the 'Accept-Language' request header
 *
 * @param req HttpServletRequest
 */
public void setLanguageFromRequestHeader(HttpServletRequest req)
{
    Locale locale = null;

    String acceptLang = req.getHeader("Accept-Language");
    if (acceptLang != null && acceptLang.length() > 0)
    {
        StringTokenizer tokenizer = new StringTokenizer(acceptLang, ",; ");
        // get language and convert to java locale format
        String language = tokenizer.nextToken().replace('-', '_');
        locale = I18NUtil.parseLocale(language);
        I18NUtil.setLocale(locale);
    }
    else
    {
        I18NUtil.setLocale(Locale.getDefault());
    }
}
 
Example #7
Source File: SearchDateConversion.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param dateAndResolution
 * @return String date
 */
public static String getDateStart(Pair<Date, Integer> dateAndResolution)
{
    Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
    cal.setTime(dateAndResolution.getFirst());
    switch (dateAndResolution.getSecond())
    {
        case Calendar.YEAR:
            cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
        case Calendar.MONTH:
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        case Calendar.DAY_OF_MONTH:
            cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
        case Calendar.HOUR_OF_DAY:
            cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
        case Calendar.MINUTE:
            cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
        case Calendar.SECOND:
            cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
        case Calendar.MILLISECOND:
        default:
    }
    SimpleDateFormat formatter = CachingDateFormat.getSolrDatetimeFormat();
    formatter.setTimeZone(UTC_TIMEZONE);
    return formatter.format(cal.getTime());
}
 
Example #8
Source File: PatchServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean validatePatchImpl(List<Patch> patches)
{
    boolean success = true;
    int serverSchemaVersion = descriptorService.getServerDescriptor().getSchema();
    for (Patch patch : patches)
    {
        if (patch.getFixesToSchema() > serverSchemaVersion)
        {
            logger.error(I18NUtil.getMessage(MSG_VALIDATION_FAILED, patch.getId(), serverSchemaVersion, patch
                    .getFixesToSchema(), patch.getTargetSchema()));
            success = false;
        }
    }
    if (!success)
    {
        this.transactionService.setAllowWrite(false, vetoName);
    }
    return success;
}
 
Example #9
Source File: ContentData.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Create a compound set of data representing a single instance of <i>content</i>.
 * <p>
 * In order to ensure data integrity, the {@link #getMimetype() mimetype}
 * must be set if the {@link #getContentUrl() content URL} is set.
 * 
 * @param contentUrl the content URL.  If this value is non-null, then the
 *      <b>mimetype</b> must be supplied.
 * @param mimetype the content mimetype.  This is mandatory if the <b>contentUrl</b> is specified.
 * @param size the content size.
 * @param encoding the content encoding.  This is mandatory if the <b>contentUrl</b> is specified.
 * @param locale the locale of the content (may be <tt>null</tt>).  If <tt>null</tt>, the
 *      {@link I18NUtil#getLocale() default locale} will be used.
 */
public ContentData(String contentUrl, String mimetype, long size, String encoding, Locale locale)
{
    if (contentUrl != null && (mimetype == null || mimetype.length() == 0))
    {
        mimetype = MimetypeMap.MIMETYPE_BINARY;
    }
    checkContentUrl(contentUrl, mimetype, encoding);
    this.contentUrl = contentUrl;
    this.mimetype = mimetype;
    this.size = size;
    this.encoding = encoding;
    if (locale == null)
    {
        locale = I18NUtil.getLocale();
    }
    this.locale = locale;
}
 
Example #10
Source File: ContentFilterLanguagesMap.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String getLabelByCode(String code)
{
    // get the translated language label
    String label;

    label = I18NUtil.getMessage(MESSAGE_PREFIX + code);

    // if not found, get the default name (found in content-filter-lang.xml)
    if(label == null || label.length() == 0)
    {
        label = languagesByCode.get(code);
    }

    // if not found, return the language code
    if(label == null || label.length() == 0)
    {
        label = code + " (label not found)";
    }

    return label;
}
 
Example #11
Source File: SearchDateConversion.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param dateAndResolution
 * @return String date
 */
public static String getDateEnd(Pair<Date, Integer> dateAndResolution)
{
    Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
    cal.setTime(dateAndResolution.getFirst());
    switch (dateAndResolution.getSecond())
    {
        case Calendar.YEAR:
            cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
        case Calendar.MONTH:
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        case Calendar.DAY_OF_MONTH:
            cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
        case Calendar.HOUR_OF_DAY:
            cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
        case Calendar.MINUTE:
            cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
        case Calendar.SECOND:
            cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
        case Calendar.MILLISECOND:
        default:
    }
    SimpleDateFormat formatter = CachingDateFormat.getSolrDatetimeFormat();
    formatter.setTimeZone(UTC_TIMEZONE);
    return formatter.format(cal.getTime());
}
 
Example #12
Source File: AbstractLocaleDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Pair<Long, Locale> getLocalePair(Long id)
{
    if (id == null)
    {
        throw new IllegalArgumentException("Cannot look up entity by null ID.");
    }
    
    Pair<Long, String> entityPair = localeEntityCache.getByKey(id);
    if (entityPair == null)
    {
        throw new DataIntegrityViolationException("No locale exists for ID " + id);
    }
    String localeStr = entityPair.getSecond();
    // Convert the locale string to a locale
    Locale locale = null;
    if (LocaleEntity.DEFAULT_LOCALE_SUBSTITUTE.equals(localeStr))
    {
        locale = I18NUtil.getLocale();
    }
    else
    {
        locale = DefaultTypeConverter.INSTANCE.convert(Locale.class, entityPair.getSecond());
    }
    
    return new Pair<Long, Locale>(id, locale);
}
 
Example #13
Source File: TaskOwnerFieldProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected FieldDefinition makeTransientFieldDefinition()
{
    PropertyFieldDefinition fieldDef = new PropertyFieldDefinition(KEY, DATA_TYPE);
    fieldDef.setRepeating(false);
    fieldDef.setProtectedField(true);
    
    fieldDef.setLabel(I18NUtil.getMessage(MSG_LABEL));
    fieldDef.setDescription(I18NUtil.getMessage(MSG_DESCRIPTION));
    fieldDef.setDataKeyName(PROP_DATA_PREFIX + KEY);
    return fieldDef;
}
 
Example #14
Source File: RepoAdminServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getLocalisedMessage(String msgId, Object... params)
{
    String localisedMsg = I18NUtil.getMessage(msgId, params);
    if (localisedMsg == null)
    {
        localisedMsg = msgId;
    }
    return localisedMsg;
}
 
Example #15
Source File: UpdateFollowingEmailTemplatesPatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected NodeRef getBaseTemplate()
{
    List<NodeRef> refs = searchService.selectNodes(
            repository.getRootHome(), 
            XPATH, 
            null, 
            namespaceService, 
            false);
    if (refs.size() != 1)
    {
        throw new AlfrescoRuntimeException(I18NUtil.getMessage("patch.updateFollowingEmailTemplatesPatch.error"));
    }
    return refs.get(0);
}
 
Example #16
Source File: ParameterizedItemDefinitionImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set the parameter definitions for the rule item
 * 
 * @param parameterDefinitions  the parameter definitions
 */
public void setParameterDefinitions(List<ParameterDefinition> parameterDefinitions)
{
    Locale currentLocale = I18NUtil.getLocale();
    new HashMap<Locale, Map<String, ParameterDefinition>>();
    if (hasDuplicateNames(parameterDefinitions) == true)
    {
        throw new RuleServiceException(ERR_NAME_DUPLICATION);
    }
    this.parameterDefinitions.put(currentLocale, parameterDefinitions);
    createParamDefinitionsByName();
}
 
Example #17
Source File: FixPersonSizeCurrentTypePatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    StringBuilder result = new StringBuilder(I18NUtil.getMessage(MSG_START));
    int updateCount = patchDAO.updatePersonSizeCurrentType();
    result.append(I18NUtil.getMessage(MSG_DONE, updateCount));
    return result.toString();
}
 
Example #18
Source File: UpdateWorkflowNotificationTemplatesPatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.repo.admin.patch.AbstractPatch#applyInternal()
 */
@Override
protected String applyInternal() throws Exception
{   
    updateTemplates();        
    return I18NUtil.getMessage("patch.updateWorkflowNotificationTemplates.result");
}
 
Example #19
Source File: UsageDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NodeRef createNode(long parentNodeId)
{
    ChildAssocEntity assoc = nodeDAO.newNode(
            parentNodeId,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            storeRef,
            null,
            ContentModel.TYPE_CONTENT,
            I18NUtil.getLocale(),
            null,
            null);
    
    return assoc.getChildNode().getNodeRef();
}
 
Example #20
Source File: TypedPropertyValueGetter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Serializable processLocaleValue(Object value)
{
    if (value instanceof String) 
    {
        return I18NUtil.parseLocale((String) value);
    }
    else
    {
        throw new FormException("Locale property values must be represented as a String! Value is of type: "
                + value.getClass());
    }
}
 
Example #21
Source File: SizeFieldProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected FieldDefinition makeTransientFieldDefinition() 
{
    String dataKeyName = PROP_DATA_PREFIX + KEY;
    PropertyFieldDefinition sizeField = new PropertyFieldDefinition(KEY, 
                DataTypeDefinition.LONG.getLocalName());
    sizeField.setLabel(I18NUtil.getMessage(MSG_SIZE_LABEL));
    sizeField.setDescription(I18NUtil.getMessage(MSG_SIZE_DESC));
    sizeField.setDataKeyName(dataKeyName);
    sizeField.setProtectedField(true);
    return sizeField;
}
 
Example #22
Source File: EncodingFieldProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected FieldDefinition makeTransientFieldDefinition() 
{
    String dataKeyName = PROP_DATA_PREFIX + KEY;
    PropertyFieldDefinition encodingField = new PropertyFieldDefinition(KEY, 
                DataTypeDefinition.TEXT.getLocalName());
    encodingField.setLabel(I18NUtil.getMessage(MSG_ENCODING_LABEL));
    encodingField.setDescription(I18NUtil.getMessage(MSG_ENCODING_DESC));
    encodingField.setDataKeyName(dataKeyName);
    return encodingField;
}
 
Example #23
Source File: ModuleComponentHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public synchronized void shutdownModules()
{
    // Check properties
    PropertyCheck.mandatory(this, "serviceRegistry", serviceRegistry);
    PropertyCheck.mandatory(this, "registryService", registryService);
    PropertyCheck.mandatory(this, "moduleService", moduleService);
    PropertyCheck.mandatory(this, "tenantAdminService", tenantAdminService);
    
    /*
     * Ensure correct authentication
     */
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            // Get all the modules
            List<ModuleDetails> modules = moduleService.getAllModules();
            loggerService.info(I18NUtil.getMessage(MSG_FOUND_MODULES, modules.size()));

            for (ModuleDetails module : modules)
            {
                Map<String, ModuleComponent> components = getComponents(module.getId());
                for (ModuleComponent component : components.values())
                {
                    component.shutdown();
                }
            }
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example #24
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Performs a locale-sensitive sort by name of a node array
 * @param nodes the node array
 */
private static void sort(Object[] nodes)
{
    final Collator col = Collator.getInstance(I18NUtil.getLocale());
    Arrays.sort(nodes, new Comparator<Object>(){
        @Override
        public int compare(Object o1, Object o2)
        {
            return col.compare(((ScriptNode)o1).getName(), ((ScriptNode)o2).getName());
        }});        
}
 
Example #25
Source File: ModuleComponentHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks to see if there are any modules registered as installed that aren't in the
 * list of modules taken from the WAR.
 * <p>
 * Currently, the behaviour specified is that a warning is generated only.
 */
private void checkForMissingModules()
{
    // Get the IDs of all modules from the registry
    Collection<String> moduleIds = getRegistryModuleIDs();
    
    // Check that each module is present in the distribution
    for (String moduleId : moduleIds)
    {
        ModuleDetails moduleDetails = moduleService.getModule(moduleId);
        if (moduleDetails != null)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Installed module found in distribution: " + moduleId);
            }
        }
        else
        {
            // Get the specifics of the missing module
            
            ModuleVersionNumber versionCurrent = getVersion(moduleId);
            // The module is missing, so warn
            loggerService.warn(I18NUtil.getMessage(MSG_MISSING, moduleId, versionCurrent));
        }
    }
}
 
Example #26
Source File: AbstractModuleComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void init()
{
    // Ensure that the description gets I18N'ized
    description = I18NUtil.getMessage(description);
    // Register the component with the service
    if (moduleService != null)                  // Allows optional registration of the component
    {
        moduleService.registerComponent(this);
    }
}
 
Example #27
Source File: VirtualCheckOutCheckInServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    super.setUp();
    PROP_WORKING_COPY_NAME = CheckOutCheckInServiceImpl
            .createWorkingCopyName(PROP_FILE_NAME,
                                   I18NUtil.getMessage("coci_service.working_copy_label"));
    
    checkOutCheckInService = ctx.getBean("checkOutCheckInService",
                                                                                    CheckOutCheckInService.class);
    versionService = ctx.getBean("versionService",
                                                                            VersionService.class);

    node = nodeService.getChildByName(virtualFolder1NodeRef,
                                      ContentModel.ASSOC_CONTAINS,
                                      "Node1");
    originalContentNodeRef = createContent(node,
                                           PROP_FILE_NAME,
                                           TEST_CONTENT_1,
                                           MimetypeMap.MIMETYPE_TEXT_PLAIN,
                                           "UTF-8").getChildRef();
    nodeService.addAspect(originalContentNodeRef,
                          ContentModel.ASPECT_VERSIONABLE,
                          null);
    physicalFileNodeRef = nodeService.getChildByName(virtualFolder1NodeRef,
                                                     ContentModel.ASSOC_CONTAINS,
                                                     PROP_FILE_NAME);
}
 
Example #28
Source File: ResponseWriter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Renders a JSON error response
 *
 * @param errorResponse The error
 * @param res           web script response
 * @throws IOException
 */
default void renderErrorResponse(final ErrorResponse errorResponse, final WebScriptResponse res, final JacksonHelper jsonHelper)
            throws IOException
{

    String logId = "";

    if (Status.STATUS_INTERNAL_SERVER_ERROR == errorResponse.getStatusCode() || resWriterLogger().isDebugEnabled())
    {
        logId = org.alfresco.util.GUID.generate();
        resWriterLogger().error(logId + " : " + errorResponse.getStackTrace());
    }

    String stackMessage = I18NUtil.getMessage(DefaultExceptionResolver.STACK_MESSAGE_ID);

    final ErrorResponse errorToWrite = new ErrorResponse(errorResponse.getErrorKey(), errorResponse.getStatusCode(),
                errorResponse.getBriefSummary(), stackMessage, logId, errorResponse.getAdditionalState(), DefaultExceptionResolver.ERROR_URL);

    setContentInfoOnResponse(res, DEFAULT_JSON_CONTENT);

    // Status must be set before the response is written by Jackson (which will by default close and commit the response).
    // In a r/w txn, web script buffered responses ensure that it doesn't really matter but for r/o txns this is important.
    res.setStatus(errorToWrite.getStatusCode());

    jsonHelper.withWriter(res.getOutputStream(), new JacksonHelper.Writer()
    {
        @SuppressWarnings("unchecked")
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            JSONObject obj = new JSONObject();
            obj.put("error", errorToWrite);
            objectMapper.writeValue(generator, obj);
        }
    });
}
 
Example #29
Source File: InvitationServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates a description for the workflow
 * 
 * @param siteInfo The site to generate a description for
 * @param messageId The resource bundle key to use for the description 
 * @return The workflow description
 */
protected String generateWorkflowDescription(SiteInfo siteInfo, String messageId)
{
    String siteTitle = siteInfo.getTitle();
    if (siteTitle == null || siteTitle.length() == 0)
    {
        siteTitle = siteInfo.getShortName();
    }
    
    Locale locale = (Locale) this.nodeService.getProperty(siteInfo.getNodeRef(), ContentModel.PROP_LOCALE);
    
    return I18NUtil.getMessage(messageId, locale == null ? I18NUtil.getLocale() : locale, siteTitle);
}
 
Example #30
Source File: RepositoryExporterComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public RepositoryExportHandle[] export(NodeRef repositoryDestination, String packageName)
{
    ParameterCheck.mandatory("repositoryDestination", repositoryDestination);
    FileInfo destInfo = fileFolderService.getFileInfo(repositoryDestination);
    if (destInfo == null || !destInfo.isFolder())
    {
        throw new ExporterException("Repository destination " + repositoryDestination + " is not a folder.");
    }

    List<FileExportHandle> exportHandles = exportStores(exportStores, packageName, new TempFileExporter());
    Map<String, String> mimetypeExtensions = mimetypeService.getExtensionsByMimetype();
    List<RepositoryExportHandle> repoExportHandles = new ArrayList<RepositoryExportHandle>(exportHandles.size());
    for (FileExportHandle exportHandle : exportHandles)
    {
        String name = exportHandle.packageName + "." + mimetypeExtensions.get(exportHandle.mimeType);
        String title = exportHandle.packageName;
        String description;
        if (exportHandle.storeRef != null)
        {
            description = I18NUtil.getMessage("export.store.package.description", new Object[] { exportHandle.storeRef.toString() });
        }
        else
        {
            description = I18NUtil.getMessage("export.generic.package.description");
        }
        
        NodeRef repoExportFile = addExportFile(repositoryDestination, name, title, description, exportHandle.mimeType, exportHandle.exportFile);
        RepositoryExportHandle handle = new RepositoryExportHandle();
        handle.storeRef = exportHandle.storeRef;
        handle.packageName = exportHandle.packageName;
        handle.mimeType = exportHandle.mimeType;
        handle.exportFile = repoExportFile;
        repoExportHandles.add(handle);
        
        // delete temporary export file
        exportHandle.exportFile.delete();
    }
    
    return repoExportHandles.toArray(new RepositoryExportHandle[repoExportHandles.size()]);
}