com.ibm.icu.text.MessageFormat Java Examples

The following examples show how to use com.ibm.icu.text.MessageFormat. 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: SlackClient.java    From mojito with Apache License 2.0 7 votes vote down vote up
Channel openIm(User user) throws SlackClientException {
    Preconditions.checkNotNull(user.getId());

    MultiValueMap<String, Object> payload = getBasePayloadMapWithAuthToken();
    payload.add("user", user.getId());
    payload.add("return_im", "true");

    HttpEntity<MultiValueMap<String, Object>> httpEntity = getHttpEntityForPayload(payload);

    ImOpenResponse imOpenResponse = restTemplate.postForObject(getUrl(API_IM_OPEN), httpEntity, ImOpenResponse.class);

    if (!imOpenResponse.getOk()) {
        String msg = MessageFormat.format("Cannot open instant message: {0}", imOpenResponse.getError());
        logger.debug(msg);
        throw new SlackClientException(msg);
    }

    return imOpenResponse.getChannel();
}
 
Example #2
Source File: LocalizedNumberEditorComposite.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private void handleFormatError( String value )
{
	MessageBox mbox = new MessageBox( getShell( ), SWT.ICON_WARNING
			| SWT.OK );
	mbox.setText( Messages.getString( "LocalizedNumberEditorComposite.error.Title" ) ); //$NON-NLS-1$
	mbox.setMessage( MessageFormat.format( Messages.getString( "LocalizedNumberEditorComposite.error.Message" ), //$NON-NLS-1$
			new Object[]{
				value
			} ) );
	mbox.open( );

	if ( bOriginalValueIsSet )
	{
		txtValue.setText( String.valueOf( (int) dValue ) );
	}
	else
	{
		txtValue.setText( "" ); //$NON-NLS-1$
	}
}
 
Example #3
Source File: TabbedPropertyRegistry.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Appends the given section to a tab from the list.
 */
protected void appendToTabDescriptor(ISectionDescriptor section,
		List aTabDescriptors) {
	for (Iterator i = aTabDescriptors.iterator(); i.hasNext();) {
		TabDescriptor tab = (TabDescriptor) i.next();
		if (tab.append(section)) {
			return;
		}
	}
	// could not append the section to any of the existing tabs - log error
	String message = MessageFormat.format(NO_TAB_ERROR, section.getId(), section.getTargetTab());
	Bundle bundle = FrameworkUtil.getBundle(TabbedPropertyRegistry.class);
	IStatus status = new Status(IStatus.ERROR, bundle.getSymbolicName(),
			TabbedPropertyViewStatusCodes.NO_TAB_ERROR, message, null);
	Platform.getLog(bundle).log(status);
}
 
Example #4
Source File: ValidationContextImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void add ( final Severity severity, Object[] data, final String message, final Object... arguments )
{
    if ( data == null )
    {
        data = new Object[] { this.target };
    }

    String formattedMessage;

    if ( arguments == null || arguments.length <= 0 )
    {
        formattedMessage = message;
    }
    else
    {
        formattedMessage = MessageFormat.format ( message, arguments );
    }

    final int severityCode = severity == null ? Diagnostic.OK : severity.getSeverityCode ();
    this.result.add ( new BasicDiagnostic ( severityCode, this.source, 0, formattedMessage, data ) );
}
 
Example #5
Source File: InjectionFragment2.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void generate() {
	List<BindingElement> elements;

	elements = getRuntimeBindings();
	if (!elements.isEmpty()) {
		LOG.info(MessageFormat.format("Generating the user-defined bindings for runtime module: {0}", //$NON-NLS-1$
				Strings.emptyIfNull(getComment())));
		bind(getLanguage().getRuntimeGenModule(), elements);
	}

	elements = getUiBindings();
	if (!elements.isEmpty()) {
		LOG.info(MessageFormat.format("Generating the user-defined bindings for ui module: {0}", //$NON-NLS-1$
				Strings.emptyIfNull(getComment())));
		bind(getLanguage().getEclipsePluginGenModule(), elements);
	}
}
 
Example #6
Source File: BindingFactory.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Add the binding.
 *
 * @param binding the binding to add.
 * @param override indicates if the binding could override an existing element.
 */
public void add(Binding binding, boolean override) {
	final Set<Binding> moduleBindings = this.module.get().getBindings();
	final Binding otherBinding = findBinding(moduleBindings, binding);
	if (!override) {
		if (otherBinding != null) {
			throw new IllegalArgumentException(MessageFormat.format(
					"Forbidden override of {0} by {1}.", //$NON-NLS-1$
					otherBinding, binding));
		}
	} else if (otherBinding != null) {
		this.removableBindings.add(otherBinding);
	}
	if (!this.bindings.add(binding)) {
		throw new IllegalArgumentException(
				MessageFormat.format("Duplicate binding for {0} in {1}", binding.getKey(), this.name)); //$NON-NLS-1$
	}
}
 
Example #7
Source File: SlackClient.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Sends an instant message
 *
 * @param message message to send
 * @throws SlackClientException
 */
public ChatPostMessageResponse sendInstantMessage(Message message) throws SlackClientException {
    logger.debug("sendInstantMessage to: {}", message.getChannel());

    HttpEntity<Message> httpEntity = getMessageHttpEntityForJsonPayload(message);

    ChatPostMessageResponse postForObject = restTemplate.postForObject(getUrl(API_CHAT_POST_MESSAGE), httpEntity, ChatPostMessageResponse.class);

    if (!postForObject.getOk()) {
        String msg = MessageFormat.format("Cannot post message in chat: {0}", postForObject.getError());
        logger.debug(msg);
        throw new SlackClientException(msg);
    }

    return postForObject;
}
 
Example #8
Source File: SlackClient.java    From mojito with Apache License 2.0 6 votes vote down vote up
User lookupUserByEmail(String email) throws SlackClientException {

        MultiValueMap<String, Object> payload = getBasePayloadMapWithAuthToken();
        payload.add("email", email);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = getHttpEntityForPayload(payload);
        UserResponse userResponse = restTemplate.postForObject(getUrl(API_USER_LOOKUP_BY_EMAIL), httpEntity, UserResponse.class);

        if (!userResponse.getOk()) {
            String msg = MessageFormat.format("Cannot lookup user by email: {0} ({1})", email, userResponse.getError());
            logger.debug(msg);
            throw new SlackClientException(msg);
        }

        return userResponse.getUser();
    }
 
Example #9
Source File: AssetExtractionService.java    From mojito with Apache License 2.0 6 votes vote down vote up
public PollableFuture<Void> processAssetAsync(
        Long assetContentId,
        FilterConfigIdOverride filterConfigIdOverride,
        List<String> filterOptions,
        Long parentTaskId) throws UnsupportedAssetFilterTypeException, InterruptedException, AssetExtractionConflictException {

    ProcessAssetJobInput processAssetJobInput = new ProcessAssetJobInput();
    processAssetJobInput.setAssetContentId(assetContentId);
    processAssetJobInput.setFilterConfigIdOverride(filterConfigIdOverride);
    processAssetJobInput.setFilterOptions(filterOptions);

    String pollableMessage = MessageFormat.format("Process asset content, id: {0}", assetContentId.toString());

    QuartzJobInfo quartzJobInfo = QuartzJobInfo.newBuilder(ProcessAssetJob.class)
            .withInput(processAssetJobInput)
            .withMessage(pollableMessage)
            .withParentId(parentTaskId)
            .withExpectedSubTaskNumber(2)
            .build();

    return quartzPollableTaskScheduler.scheduleJob(quartzJobInfo);
}
 
Example #10
Source File: PollableAspectParameters.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Init this instance with information contained in the {@link Pollable}
 * annotation.
 */
private void initFromAnnotation() {
    MethodSignature ms = (MethodSignature) pjp.getSignature();
    Method m = ms.getMethod();
    annotation = m.getAnnotation(Pollable.class);

    if (!annotation.name().isEmpty()) {
        name = annotation.name();
    } else {
        name = pjp.getSignature().getName();
    }

    if (!annotation.message().isEmpty()) {
        message = MessageFormat.format(annotation.message(), getMessageParams());
    }

    expectedSubTaskNumber = annotation.expectedSubTaskNumber();
    async = annotation.async();
    timeout = annotation.timeout();
}
 
Example #11
Source File: CTextCellEditor.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Processes a modify event that occurred in this text cell editor. This
 * framework method performs validation and sets the error message
 * accordingly, and then reports a change via
 * <code>fireEditorValueChanged</code>. Subclasses should call this method
 * at appropriate times. Subclasses may extend or reimplement.
 * 
 * @param e
 *            the SWT modify event
 */
protected void editOccured( ModifyEvent e )
{
	String value = text.getText( );
	if ( value.equals( "" ) )
	{
		value = null;//$NON-NLS-1$
	}
	Object typedValue = value;
	boolean oldValidState = isValueValid( );
	boolean newValidState = isCorrect( typedValue );

	if ( !newValidState )
	{
		// try to insert the current value into the error message.
		setErrorMessage( MessageFormat.format( getErrorMessage( ),
				new Object[]{
					value
				} ) );
	}
	valueChanged( oldValidState, newValidState );
}
 
Example #12
Source File: InjectionRecommender2.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Provide the recommendations.
 *
 * @param label the source of the recommendation.
 * @param source the source of recommendation.
 * @param current the current bindings.
 */
protected void recommendFrom(String label, Set<BindingElement> source, Set<Binding> current) {
	this.bindingFactory.setName(getName());
	boolean hasRecommend = false;
	for (final BindingElement sourceElement : source) {
		final Binding wrapElement = this.bindingFactory.toBinding(sourceElement);
		if (!current.contains(wrapElement)) {
			if (!hasRecommend) {
				LOG.info(MessageFormat.format("Begin recommendations for {0}", //$NON-NLS-1$
						label));
				hasRecommend = true;
			}
			LOG.warning(MessageFormat.format("\t{1}", //$NON-NLS-1$
					label, sourceElement.getKeyString()));
		}
	}
	if (hasRecommend) {
		LOG.info(MessageFormat.format("End recommendations for {0}", //$NON-NLS-1$
				label));
	} else {
		LOG.info(MessageFormat.format("No recommendation for {0}", //$NON-NLS-1$
				label));
	}
}
 
Example #13
Source File: BoxSDKAppUserService.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Box App User
 *
 * @return
 * @throws BoxSDKServiceException
 */
public BoxUser.Info createAppUser(String clientId, String clientSecret, String publicKeyId,
            String privateKey, String privateKeyPassword, String enterpriseId) throws BoxSDKServiceException {

    try {
        logger.debug("Creating Box App User: {}", MOJITO_APP_USER_NAME);
        JWTEncryptionPreferences jwtEncryptionPreferences = boxSDKJWTProvider.getJWTEncryptionPreferences(publicKeyId, privateKey, privateKeyPassword);
        BoxDeveloperEditionAPIConnection appEnterpriseConnection = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(
                enterpriseId,
                clientId,
                clientSecret,
                jwtEncryptionPreferences,
                new InMemoryLRUAccessTokenCache(5));

        CreateUserParams createUserParams = new CreateUserParams();
        createUserParams.setSpaceAmount(UNLIMITED_SPACE);

        return BoxUser.createAppUser(appEnterpriseConnection, MOJITO_APP_USER_NAME, createUserParams);
    } catch (BoxAPIException e) {
        String msg = MessageFormat.format("Couldn't create App User: {0}", e.getResponse());
        logger.error(msg);
        throw new BoxSDKServiceException(msg, e);
    }
}
 
Example #14
Source File: VirtualAssetService.java    From mojito with Apache License 2.0 6 votes vote down vote up
public TMTextUnitVariant addTextUnitVariant(long assetId, long localeId, String name, String content, String comment)
        throws VirtualAssetRequiredException, VirutalAssetMissingTextUnitException {
    logger.debug("Add text unit variant to virtual assetId: {}, with name: {}", assetId, name);

    TextUnitSearcherParameters textUnitSearcherParameters = new TextUnitSearcherParameters();
    textUnitSearcherParameters.setAssetId(assetId);
    textUnitSearcherParameters.setName(name);
    textUnitSearcherParameters.setSearchType(SearchType.EXACT);
    textUnitSearcherParameters.setUsedFilter(UsedFilter.USED);
    textUnitSearcherParameters.setLimit(1);

    List<TextUnitDTO> textUnitDTOs = textUnitSearcher.search(textUnitSearcherParameters);

    if (textUnitDTOs.isEmpty()) {
        textUnitSearcherParameters.setUsedFilter(UsedFilter.UNUSED);
        textUnitDTOs = textUnitSearcher.search(textUnitSearcherParameters);
    }

    if (textUnitDTOs.isEmpty()) {
        String msg = MessageFormat.format("Missing TmTextUnit for assetId: {0} and name: {1}", assetId, name);
        logger.debug(msg);
        throw new VirutalAssetMissingTextUnitException(msg);
    }

    return tmService.addCurrentTMTextUnitVariant(textUnitDTOs.get(0).getTmTextUnitId(), localeId, content);
}
 
Example #15
Source File: InjectionRecommender2.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Change the comment for the injection fragment.
 *
 * @param comment the comment for the fragment.
 */
public void setComment(String comment) {
	this.comment = comment;
	if (!Strings.isEmpty(comment)) {
		this.name = MessageFormat.format("{0} [{1}]", getClass().getName(), comment); //$NON-NLS-1$
	} else {
		this.name = getClass().getName();
	}
}
 
Example #16
Source File: InjectionRecommender2.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Provide the recommendations for the given module.
 *
 * @param superModule the super module to extract definitions from.
 * @param currentModuleAccess the accessor to the the current module's definition.
 */
protected void recommend(Class<?> superModule, GuiceModuleAccess currentModuleAccess) {
	LOG.info(MessageFormat.format("Building injection configuration from {0}", //$NON-NLS-1$
			superModule.getName()));
	final Set<BindingElement> superBindings = new LinkedHashSet<>();
	fillFrom(superBindings, superModule.getSuperclass());
	fillFrom(superBindings, superModule);

	final Set<Binding> currentBindings = currentModuleAccess.getBindings();

	recommendFrom(superModule.getName(), superBindings, currentBindings);
}
 
Example #17
Source File: InjectionFragment2.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Change the comment for the injection fragment.
 *
 * @param comment the comment for the fragment.
 */
public void setComment(String comment) {
	this.comment = comment;
	if (!Strings.isEmpty(comment)) {
		this.name = MessageFormat.format("{0} [{1}]", getClass().getName(), comment); //$NON-NLS-1$
	} else {
		this.name = getClass().getName();
	}
}
 
Example #18
Source File: I18n.java    From kyoko with MIT License 5 votes vote down vote up
/**
 * @param language Preferred language for messages.
 * @param key      Translation key.
 * @return MessageFormat object for specified translation key or null if it doesn't exist.
 */
@Nullable
public MessageFormat getICU(@NotNull Language language, @NotNull String key) {
    if (!languages.containsKey(Objects.requireNonNull(language))) {
        language = Language.ENGLISH;
    }

    var map = languages.get(language);
    var message = map.getICU(key);
    if (message == null) {
        message = languages.get(Language.ENGLISH).getICU(key);
    }

    return message;
}
 
Example #19
Source File: JndiDataSource.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Utility method to format externalized message, without using JDBCException.
 */
private String getMessage( String errorCode, String argument )
{
    if( sm_resourceHandle == null )
        sm_resourceHandle = new JdbcResourceHandle( ULocale.getDefault() );

    String msgText = sm_resourceHandle.getMessage( errorCode );
    if( argument == null )
        return msgText;
    return MessageFormat.format( msgText, new Object[]{ argument } );
}
 
Example #20
Source File: ReportContextImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String getMessage( String key, Object[] params )
{
	String msg = context.getDesign( ).getMessage( key );
	if ( msg == null )
		return "";
	return MessageFormat.format( msg, params );
}
 
Example #21
Source File: ReportContextImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String getMessage( String key, Locale locale, Object[] params )
{
	String msg = context.getDesign( ).getMessage( key, locale );
	if ( msg == null )
		return "";
	MessageFormat formatter = new MessageFormat( msg, locale );
	return formatter.format( params, new StringBuffer(), null ).toString();
}
 
Example #22
Source File: BirtException.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a localized message based on an error code. Overwrite this method
 * if you do not want to pass in the resource bundle
 * 
 * @param errorCode
 *            the error code
 * @return Localized display message.
 */
protected String getLocalizedMessage( String errorCode )
{
	String localizedMessage;
	Locale locale = null;
	if ( rb == null )
	{
		localizedMessage = errorCode; 
	}
	else
	{
		locale = rb.getLocale( );
		try
		{
			localizedMessage = rb.getString( errorCode );
		}
		catch ( Exception e )
		{
			localizedMessage = errorCode;
		}
	}

	try
	{
		MessageFormat form = new MessageFormat( localizedMessage,
				locale == null ? Locale.getDefault( ) : locale );
		return form.format( oaMessageArguments );
	}
	catch ( Throwable ex )
	{
		return localizedMessage;
	}
}
 
Example #23
Source File: TabDescriptor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the tab error when an issue is found loading from the
 * configuration element.
 *
 * @param configurationElement
 *            the configuration element
 * @param exception
 *            an optional CoreException
 */
private void handleTabError(IConfigurationElement configurationElement,
		CoreException exception) {
	String pluginId = configurationElement.getDeclaringExtension()
			.getContributor().getName();
	String message = MessageFormat.format(TAB_ERROR, pluginId);
	IStatus status = new Status(IStatus.ERROR, pluginId,
			TabbedPropertyViewStatusCodes.TAB_ERROR, message, exception);
	Bundle bundle = FrameworkUtil.getBundle(TabDescriptor.class);
	Platform.getLog(bundle).log(status);
}
 
Example #24
Source File: SectionDescriptor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the section error when an issue is found loading from the
 * configuration element.
 *
 * @param exception
 *            an optional CoreException
 */
private void handleSectionError(CoreException exception) {
	String pluginId = getConfigurationElement().getDeclaringExtension()
			.getContributor().getName();
	String message = TabbedPropertyMessages.SectionDescriptor_Section_error;
	if (exception == null) {
		message = MessageFormat.format(TabbedPropertyMessages.SectionDescriptor_Section_error, pluginId);
	} else {
		message = MessageFormat.format(TabbedPropertyMessages.SectionDescriptor_class_not_found_error, pluginId);
	}
	IStatus status = new Status(IStatus.ERROR, pluginId,
			TabbedPropertyViewStatusCodes.SECTION_ERROR, message, exception);
	Bundle bundle = FrameworkUtil.getBundle(SectionDescriptor.class);
	Platform.getLog(bundle).log(status);
}
 
Example #25
Source File: TabbedPropertyRegistry.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the tab error when an issue is found loading from the
 * configuration element.
 *
 * @param configurationElement
 *            the configuration element
 */
private void handleTabError(IConfigurationElement configurationElement,
		String category) {
	String pluginId = configurationElement.getDeclaringExtension()
			.getContributor().getName();
	String message = MessageFormat.format(TAB_ERROR, pluginId, category );
	IStatus status = new Status(IStatus.ERROR, pluginId,
			TabbedPropertyViewStatusCodes.TAB_ERROR, message, null);
	Bundle bundle = FrameworkUtil.getBundle(TabbedPropertyRegistry.class);
	Platform.getLog(bundle).log(status);
}
 
Example #26
Source File: MarkdownToHtmlController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public String handleFile(File srcFile, File targetPath) {
    try {
        countHandling(srcFile);
        File target = makeTargetFile(srcFile, targetPath);
        if (target == null) {
            return AppVariables.message("Skip");
        }
        Node document = parser.parse(FileTools.readTexts(srcFile));
        String html = renderer.render(document);
        String style;
        if (message("ConsoleStyle").equals(styleSelector.getValue())) {
            style = HtmlTools.ConsoleStyle;
        } else if (message("DefaultStyle").equals(styleSelector.getValue())) {
            style = HtmlTools.DefaultStyle;
        } else {
            style = null;
        }
        html = HtmlTools.html(titleInput.getText(), style, html);

        FileTools.writeFile(target, html);
        if (verboseCheck == null || verboseCheck.isSelected()) {
            updateLogs(MessageFormat.format(message("ConvertSuccessfully"),
                    srcFile.getAbsolutePath(), target.getAbsolutePath()));
        }
        targetFileGenerated(target);
        return AppVariables.message("Successful");
    } catch (Exception e) {
        logger.error(e.toString());
        return AppVariables.message("Failed");
    }
}
 
Example #27
Source File: Validations.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public static final void validateRange ( final ValidationContext context, final EStructuralFeature feature, final long value, final Long min, final Long max, final String label )
{
    if ( min != null && value < min )
    {
        context.add ( feature, MessageFormat.format ( "''{0}'' be greater or equal to {1,number,integer}", label, min ) );
    }
    if ( max != null && value > max )
    {
        context.add ( feature, MessageFormat.format ( "''{0}'' be less or equal to {1,number,integer}", label, min ) );
    }
}
 
Example #28
Source File: RelativeDateFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private MessageFormat initializeCombinedFormat(Calendar cal, ULocale locale) {
    String pattern;
    ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(
        ICUData.ICU_BASE_NAME, locale);
    String resourcePath = "calendar/" + cal.getType() + "/DateTimePatterns";
    ICUResourceBundle patternsRb= rb.findWithFallback(resourcePath);
    if (patternsRb == null && !cal.getType().equals("gregorian")) {
        // Try again with gregorian, if not already attempted.
        patternsRb = rb.findWithFallback("calendar/gregorian/DateTimePatterns");
    }

    if (patternsRb == null || patternsRb.getSize() < 9) {
        // Undefined or too few elements.
        pattern = "{1} {0}";
    } else {
        int glueIndex = 8;
        if (patternsRb.getSize() >= 13) {
          if (fDateStyle >= DateFormat.FULL && fDateStyle <= DateFormat.SHORT) {
              glueIndex += fDateStyle + 1;
          } else
              if (fDateStyle >= DateFormat.RELATIVE_FULL &&
                  fDateStyle <= DateFormat.RELATIVE_SHORT) {
                  glueIndex += fDateStyle + 1 - DateFormat.RELATIVE;
              }
        }
        int elementType = patternsRb.get(glueIndex).getType();
        if (elementType == UResourceBundle.ARRAY) {
            pattern = patternsRb.get(glueIndex).getString(0);
        } else {
            pattern = patternsRb.getString(glueIndex);
        }
    }
    combinedFormatHasDateAtStart = pattern.startsWith("{1}");
    fCombinedFormat = new MessageFormat(pattern, locale);
    return fCombinedFormat;
}
 
Example #29
Source File: ExtractionDiffService.java    From mojito with Apache License 2.0 5 votes vote down vote up
void checkExtractionDirectoryExists(String extractionName, ExtractionsPaths extractionsPaths) throws MissingExtractionDirectoryExcpetion {
    Path extractionPath = extractionsPaths.extractionPath(extractionName);

    if (!extractionPath.toFile().exists()) {
        String msg = MessageFormat.format("There is no directory for extraction: {0}, can't compare", extractionName);
        throw new MissingExtractionDirectoryExcpetion(msg);
    }
}
 
Example #30
Source File: TMService.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
 * locale other than the default locale.
 * <p/>
 * Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
 * references a {@link TMTextUnitVariant} that has same content, the
 * {@link TMTextUnitVariant} is returned and no entities are created.
 *
 * @param tmTextUnitId the text unit that will contains the translation
 * @param localeId locale id of the translation (default locale not
 * accepted)
 * @param content the translation content
 * @param comment the translation comment, can be {@code null}
 * @param status the translation status
 * @param includedInLocalizedFile indicate if the translation should be
 * included or not in the localized files
 * @param createdDate to specify a creation date (can be used to re-import
 * old TM), can be {@code null}
 * @return the result that contains the {@link TMTextUnitCurrentVariant} and
 * indicates if it was updated or not. The {@link TMTextUnitCurrentVariant}
 * holds the created {@link TMTextUnitVariant} or an existing one with same
 * content
 * @throws DataIntegrityViolationException If tmTextUnitId or localeId are
 * invalid
 */
public AddTMTextUnitCurrentVariantResult addTMTextUnitCurrentVariantWithResult(
        Long tmTextUnitId,
        Long localeId,
        String content,
        String comment,
        TMTextUnitVariant.Status status,
        boolean includedInLocalizedFile,
        DateTime createdDate) {

    logger.debug("Check if there is a current TMTextUnitVariant");
    TMTextUnitCurrentVariant currentTmTextUnitCurrentVariant = tmTextUnitCurrentVariantRepository.findByLocale_IdAndTmTextUnit_Id(localeId, tmTextUnitId);

    TMTextUnit tmTextUnit = tmTextUnitRepository.findOne(tmTextUnitId);

    if (tmTextUnit == null) {
        String msg = MessageFormat.format("Unable to find the TMTextUnit with ID: {0}. The TMTextUnitVariant and "
                + "TMTextUnitCurrentVariant will not be created.", tmTextUnitId);
        throw new RuntimeException(msg);
    }

    User createdBy = auditorAwareImpl.getCurrentAuditor();
    return addTMTextUnitCurrentVariantWithResult(currentTmTextUnitCurrentVariant,
            tmTextUnit.getTm().getId(),
            tmTextUnitId,
            localeId,
            content,
            comment,
            status,
            includedInLocalizedFile,
            createdDate,
            createdBy);
}