Java Code Examples for java.text.MessageFormat

The following examples show how to use java.text.MessageFormat. These examples are extracted from open source projects.
Example 1
Project: Insights   File: TraceabilitySummaryUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String calTimeDiffrence(String operandName, List<JsonObject> toolRespPayload, String message)
		throws ParseException {
	int totalCount = toolRespPayload.size();
	if (totalCount >= 0 && toolRespPayload.get(0).has(operandName)) {
		int numOfUniqueAuthers = (int) toolRespPayload.stream()
				.filter(distinctByKey(payload -> payload.get("author").getAsString())).count();
		String firstCommitTime = toolRespPayload.get(0).get(operandName).getAsString();
		String lastCommitTime = toolRespPayload.get(totalCount - 1).get(operandName).getAsString();
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
		Date firstDate = sdf.parse(epochToHumanDate(firstCommitTime));
		Date secondDate = sdf.parse(epochToHumanDate(lastCommitTime));
		long diffInMillies = Math.abs(firstDate.getTime() - secondDate.getTime());
		String duration = InsightsUtils.getDateTimeFromEpoch(diffInMillies);
		MessageFormat mf = new MessageFormat(message);
		return mf.format(new Object[] { duration, numOfUniqueAuthers });
	}

	return "";

}
 
Example 2
Project: openjdk-jdk8u-backup   File: TextComponentPrintable.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs  {@code TextComponentPrintable} to print {@code JTextComponent}
 * {@code textComponent} with {@code headerFormat} and {@code footerFormat}.
 *
 * @param textComponent {@code JTextComponent} to print
 * @param headerFormat the page header or {@code null} for none
 * @param footerFormat the page footer or {@code null} for none
 */
private TextComponentPrintable(JTextComponent textComponent,
        MessageFormat headerFormat,
        MessageFormat footerFormat) {
    this.textComponentToPrint = textComponent;
    this.headerFormat = headerFormat;
    this.footerFormat = footerFormat;
    headerFont = textComponent.getFont().deriveFont(Font.BOLD,
        HEADER_FONT_SIZE);
    footerFont = textComponent.getFont().deriveFont(Font.PLAIN,
        FOOTER_FONT_SIZE);
    this.pagesMetrics =
        Collections.synchronizedList(new ArrayList<IntegerSegment>());
    this.rowsMetrics = new ArrayList<IntegerSegment>(LIST_SIZE);
    this.printShell = createPrintShell(textComponent);
}
 
Example 3
Project: maven-jaxb2-plugin   File: OptionsFactory.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Language createLanguage(String schemaLanguage)
		throws MojoExecutionException {
	if (StringUtils.isEmpty(schemaLanguage)) {
		return null;
	} else if ("AUTODETECT".equalsIgnoreCase(schemaLanguage))
		return null; // nothing, it is AUTDETECT by default.
	else if ("XMLSCHEMA".equalsIgnoreCase(schemaLanguage))
		return Language.XMLSCHEMA;
	else if ("DTD".equalsIgnoreCase(schemaLanguage))
		return Language.DTD;
	else if ("RELAXNG".equalsIgnoreCase(schemaLanguage))
		return Language.RELAXNG;
	else if ("RELAXNG_COMPACT".equalsIgnoreCase(schemaLanguage))
		return Language.RELAXNG_COMPACT;
	else if ("WSDL".equalsIgnoreCase(schemaLanguage))
		return Language.WSDL;
	else {
		throw new MojoExecutionException(MessageFormat.format(
				"Unknown schemaLanguage [{0}].", schemaLanguage));
	}
}
 
Example 4
Project: astor   File: ExceptionContext.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds a message string.
 *
 * @param locale Locale in which the message should be translated.
 * @param separator Message separator.
 * @return a localized message string.
 */
private String buildMessage(Locale locale,
                            String separator) {
    final StringBuilder sb = new StringBuilder();
    int count = 0;
    final int len = msgPatterns.size();
    for (int i = 0; i < len; i++) {
        final Localizable pat = msgPatterns.get(i);
        final Object[] args = msgArguments.get(i);
        final MessageFormat fmt = new MessageFormat(pat.getLocalizedString(locale),
                                                    locale);
        sb.append(fmt.format(args));
        if (++count < len) {
            // Add a separator if there are other messages.
            sb.append(separator);
        }
    }

    return sb.toString();
}
 
Example 5
Project: DataLink   File: MysqlJobConfigServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String reloadWriter(String json, MediaSourceInfo info) {
    try {
        checkType(info.getParameterObj());
        RdbMediaSrcParameter parameter = (RdbMediaSrcParameter)info.getParameterObj();
        String ip = parameter.getWriteConfig().getWriteHost();
        String port = parameter.getPort()+"";
        String schema = info.getParameterObj().getNamespace();
        String username = parameter.getWriteConfig().getUsername();
        String password = parameter.getWriteConfig().getDecryptPassword();
        String url = MessageFormat.format(FlinkerJobConfigConstant.MYSQL_URL, ip, port, schema);
        DLConfig connConf = DLConfig.parseFrom(json);
        connConf.remove("job.content[0].writer.parameter.connection[0].jdbcUrl");
        connConf.set("job.content[0].writer.parameter.connection[0].jdbcUrl", url);
        connConf.remove("job.content[0].writer.parameter.username");
        connConf.remove("job.content[0].writer.parameter.password");
        connConf.set("job.content[0].writer.parameter.username",username);
        connConf.set("job.content[0].writer.parameter.password",password);
        json = connConf.toJSON();
    } catch(Exception e) {
        LOGGER.error("reload writer json failure.",e);
    }
    return json;
}
 
Example 6
Project: cyberduck   File: HttpUploadFeature.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected void verify(final Path file, final MessageDigest digest, final Checksum checksum) throws ChecksumException {
    if(file.getType().contains(Path.Type.encrypted)) {
        log.warn(String.format("Skip checksum verification for %s with client side encryption enabled", file));
        return;
    }
    if(null == digest) {
        log.debug(String.format("Digest disabled for file %s", file));
        return;
    }
    // Obtain locally-calculated MD5 hash.
    final Checksum expected = Checksum.parse(Hex.encodeHexString(digest.digest()));
    if(ObjectUtils.notEqual(expected.algorithm, checksum.algorithm)) {
        log.warn(String.format("ETag %s returned by server is %s but expected %s", checksum.hash, checksum.algorithm, expected.algorithm));
    }
    else {
        // Compare our locally-calculated hash with the ETag returned by S3.
        if(!checksum.equals(expected)) {
            throw new ChecksumException(MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"), file.getName()),
                MessageFormat.format("Mismatch between MD5 hash {0} of uploaded data and ETag {1} returned by the server",
                    expected, checksum.hash));
        }
    }
}
 
Example 7
/**
 * Generated a public navigation link
 */
public void appendLink(StringBuffer buffer, String name, String view,
		String anchor)
{
	name = NameHelper.globaliseName(name, localSpace);
	String url;
	if (anchor != null && !"".equals(anchor)) {
		url = MessageFormat.format(anchorURLFormat, new Object[] { encode(name),
				encode(anchor), withBreadcrumbs?"":breadcrumbSwitch });			
	} else {
		url = MessageFormat.format(standardURLFormat,
				new Object[] { encode(name), withBreadcrumbs?"":breadcrumbSwitch });
	}

	buffer.append(MessageFormat.format(urlFormat, new Object[] {
			XmlEscaper.xmlEscape(url), XmlEscaper.xmlEscape(view) }));
}
 
Example 8
Project: tmxeditor8   File: ConversionWizardPage.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void validate() {
	IStatus result = Status.OK_STATUS;
	int line = 1;
	for (ConverterViewModel converterViewModel : converterViewModels) {
		result = converterViewModel.validate();
		if (!result.isOK()) {
			break;
		}
		line++;
	}
	if (!result.isOK()) {
		setPageComplete(false);
		setErrorMessage(MessageFormat.format(Messages.getString("ConversionWizardPage.13"), line)
				+ result.getMessage());
	} else {
		setErrorMessage(null);
		setPageComplete(true);
	}
}
 
Example 9
Project: multiapps-controller   File: UAAClientConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private URL readTokenEndpoint(URL targetURL) {
    try {
        Map<String, Object> infoMap = getControllerInfo(targetURL);
        Object endpoint = infoMap.get("token_endpoint");
        if (endpoint == null) {
            endpoint = infoMap.get("authorizationEndpoint");
        }
        if (endpoint == null) {
            throw new IllegalStateException(MessageFormat.format("Response from {0} does not contain a valid token endpoint",
                                                                 CONTROLLER_INFO_ENDPOINT));
        }
        return new URL(endpoint.toString());
    } catch (Exception e) {
        throw new IllegalStateException("Could not read token endpoint", e);
    }
}
 
Example 10
Project: jdk8u-jdk   File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String inputString(BufferedReader in, String prompt,
                           String defaultValue)
    throws IOException
{
    System.err.println(prompt);
    MessageFormat form = new MessageFormat
            (rb.getString(".defaultValue."));
    Object[] source = {defaultValue};
    System.err.print(form.format(source));
    System.err.flush();

    String value = in.readLine();
    if (value == null || collator.compare(value, "") == 0) {
        value = defaultValue;
    }
    return value;
}
 
Example 11
Project: hottub   File: SchemaWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void attributeUse( XSAttributeUse use ) {
    XSAttributeDecl decl = use.getDecl();

    String additionalAtts="";

    if(use.isRequired())
        additionalAtts += " use=\"required\"";
    if(use.getFixedValue()!=null && use.getDecl().getFixedValue()==null)
        additionalAtts += " fixed=\""+use.getFixedValue()+'\"';
    if(use.getDefaultValue()!=null && use.getDecl().getDefaultValue()==null)
        additionalAtts += " default=\""+use.getDefaultValue()+'\"';

    if(decl.isLocal()) {
        // this is anonymous attribute use
        dump(decl,additionalAtts);
    } else {
        // reference to a global one
        println(MessageFormat.format("<attribute ref=\"'{'{0}'}'{1}{2}\"/>",
            decl.getTargetNamespace(), decl.getName(), additionalAtts));
    }
}
 
Example 12
Project: APICloud-Studio   File: DiagnosticManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private synchronized IDiagnosticLog getWrapped()
{
	if (logClass == null)
	{
		logClass = new NullDiagnosticLog(); // default to null impl
		try
		{
			Object clazz = element.createExecutableExtension(ATTR_CLASS);
			if (clazz instanceof IDiagnosticLog)
			{
				logClass = (IDiagnosticLog) clazz;
			}
			else
			{
				IdeLog.logError(CorePlugin.getDefault(), MessageFormat.format(
						"The class {0} does not implement IDiagnosticLog.", element.getAttribute(ATTR_CLASS))); //$NON-NLS-1$
			}
		}
		catch (CoreException e)
		{
			IdeLog.logError(CorePlugin.getDefault(), e);
		}
	}
	return logClass;
}
 
Example 13
Project: ramus   File: BinaryAccessFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method writes string in UTF8 even if its length less then 254 bytes
 * in UTF8, string length can be up to Integer.MAX_VALUE. String can be
 * <code>null</code>.
 */

@Override
public void write254String(String string) throws IOException {
    if (string == null) {
        write(255);
    } else {
        byte[] bs = string.getBytes("UTF8");
        int length = bs.length;
        if (length > 254) {
            throw new IOException(
                    MessageFormat
                            .format(
                                    "String \"{0}\" can not be written, its length {1} bytes (more then 254 bytes)",
                                    string, length));
        }
        write(length);
        write(bs);
    }
}
 
Example 14
Project: DBus   File: JarManagerService.java    License: Apache License 2.0 6 votes vote down vote up
public int delete(Integer id) {
    TopologyJar topologyJar = topologyJarMapper.selectByPrimaryKey(id);
    try {
        Properties props = zkService.getProperties(Constants.COMMON_ROOT + "/" + Constants.GLOBAL_PROPERTIES);
        String user = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_CLUSTER_SERVER_SSH_USER);
        String stormNimbusHost = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_STORM_NIMBUS_HOST);
        String port = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_CLUSTER_SERVER_SSH_PORT);

        String path = topologyJar.getPath();
        String parentPath = path.substring(0, path.lastIndexOf("/"));
        String cmd = MessageFormat.format("ssh -p {0} {1}@{2} rm -rf {3}", port, user, stormNimbusHost, parentPath);
        logger.info("mdkir command: {}", cmd);
        int retVal = execCmd(cmd, null);
        if (retVal == 0) {
            logger.info("rm success.");
        }
        return topologyJarMapper.deleteByPrimaryKey(topologyJar.getId());
    } catch (Exception e) {
        return 0;
    }
}
 
Example 15
Project: konker-platform   File: DeviceConfigRestControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdateDeviceConfig() throws Exception {

    when(deviceConfigSetupService.update(tenant, application, deviceModel, location, json))
        .thenReturn(ServiceResponseBuilder.<DeviceConfig>ok()
                .withResult(deviceConfig)
                .withMessage(DeviceConfigSetupService.Messages.DEVICE_CONFIG_REGISTERED_SUCCESSFULLY.getCode()).build());

    getMockMvc().perform(MockMvcRequestBuilders
            .put(MessageFormat.format("/{0}/{1}/{2}/{3}/", application.getName(), BASEPATH, deviceModel.getName(), location.getName()))
    		.content(json)
    		.contentType(MediaType.APPLICATION_JSON)
    		.accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is2xxSuccessful())
            .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
            .andExpect(jsonPath("$.status", is("success")))
            .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
            .andExpect(jsonPath("$.result").doesNotExist());

}
 
Example 16
Project: netbeans   File: JavaSourceTest.java    License: Apache License 2.0 6 votes vote down vote up
private FileObject createTestFile (String className) {
    try {
        File workdir = this.getWorkDir();
        File root = new File (workdir, "src");
        root.mkdir();
        File data = new File (root, className+".java");

        PrintWriter out = new PrintWriter (new FileWriter (data));
        try {
            out.println(MessageFormat.format(TEST_FILE_CONTENT, new Object[] {className}));
        } finally {
            out.close ();
        }
        return FileUtil.toFileObject(data);
    } catch (IOException ioe) {
        return null;
    }
}
 
Example 17
Project: MyBox   File: FilesArchiveCompressController.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String handleDirectory(File dir) {
    try {
        if (archiver.equalsIgnoreCase(ArchiveStreamFactory.AR)) {
            return AppVariables.message("Skip");
        }
        dirFilesNumber = dirFilesHandled = 0;
        addEntry(dir, rootName);
        if (rootName == null || rootName.trim().isEmpty()) {
            handleDirectory(dir, dir.getName());
        } else {
            handleDirectory(dir, rootName + "/" + dir.getName());
        }
        return MessageFormat.format(AppVariables.message("DirHandledSummary"),
                dirFilesNumber, dirFilesHandled);
    } catch (Exception e) {
        logger.debug(e.toString());
        return AppVariables.message("Failed");
    }
}
 
Example 18
Project: APICloud-Studio   File: Index.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * deleteIndexFile
 */
void deleteIndexFile()
{
	if (isTraceEnabled())
	{
		logTrace(MessageFormat.format("Deleting index ''{0}''", this)); //$NON-NLS-1$
	}

	// TODO Enter write?

	File indexFile = this.getIndexFile();
	if (indexFile != null && indexFile.exists())
	{
		indexFile.delete();
	}
}
 
Example 19
Project: hottub   File: SchemaWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void wildcard( String tagName, XSWildcard wc, String extraAtts ) {
    final String proessContents;
    switch(wc.getMode()) {
    case XSWildcard.LAX:
        proessContents = " processContents='lax'";break;
    case XSWildcard.STRTICT:
        proessContents = "";break;
    case XSWildcard.SKIP:
        proessContents = " processContents='skip'";break;
    default:
        throw new AssertionError();
    }

    println(MessageFormat.format("<{0}{1}{2}{3}/>",tagName, proessContents, wc.apply(WILDCARD_NS), extraAtts));
}
 
Example 20
Project: rapidminer-studio   File: XMLTools.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This will parse the text contents of an child element of element parent with the given
 * tagName as integer. If no such child element can be found, the given default value is
 * returned. If more than one exists, the first is used. A {@link XMLException} is thrown if the
 * text content is not a valid integer.
 */
public static int getTagContentsAsInt(Element element, String tag, int dfltValue) throws XMLException {
	final String string = getTagContents(element, tag, false);
	if (string == null) {
		return dfltValue;
	}
	try {
		return Integer.parseInt(string);
	} catch (NumberFormatException e) {
		throw new XMLException(MessageFormat.format(CONTENTS_OF_TAG_0_MUST_BE_1_BUT_FOUND_2_LOG_MSG, tag, INTEGER_STRING, string));
	}
}
 
Example 21
Project: multiapps-controller   File: FileSystemFileStorageFactoryBean.java    License: Apache License 2.0 5 votes vote down vote up
private String getStoragePath(String serviceName) {
    if (StringUtils.isEmpty(serviceName)) {
        LOGGER.warn(Messages.FILE_SYSTEM_SERVICE_NAME_IS_NOT_SPECIFIED);
        return null;
    }
    try {
        CloudFactory cloudFactory = new CloudFactory();
        Cloud cloud = cloudFactory.getCloud();
        FileSystemServiceInfo serviceInfo = (FileSystemServiceInfo) cloud.getServiceInfo(serviceName);
        return serviceInfo.getStoragePath();
    } catch (CloudException e) {
        LOGGER.warn(MessageFormat.format(Messages.FAILED_TO_DETECT_FILE_SERVICE_STORAGE_PATH, serviceName), e);
    }
    return null;
}
 
Example 22
Project: openjdk-jdk8u-backup   File: PolicyTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {

        String URLString = ((JTextField)td.getComponent(
                ToolDialog.KSD_NAME_TEXTFIELD)).getText().trim();
        String type = ((JTextField)td.getComponent(
                ToolDialog.KSD_TYPE_TEXTFIELD)).getText().trim();
        String provider = ((JTextField)td.getComponent(
                ToolDialog.KSD_PROVIDER_TEXTFIELD)).getText().trim();
        String pwdURL = ((JTextField)td.getComponent(
                ToolDialog.KSD_PWD_URL_TEXTFIELD)).getText().trim();

        try {
            tool.openKeyStore
                        ((URLString.length() == 0 ? null : URLString),
                        (type.length() == 0 ? null : type),
                        (provider.length() == 0 ? null : provider),
                        (pwdURL.length() == 0 ? null : pwdURL));
            tool.modified = true;
        } catch (Exception ex) {
            MessageFormat form = new MessageFormat(PolicyTool.getMessage
                ("Unable.to.open.KeyStore.ex.toString."));
            Object[] source = {ex.toString()};
            tw.displayErrorDialog(td, form.format(source));
            return;
        }

        td.dispose();
    }
 
Example 23
Project: translationstudio8   File: NonTranslationQAPage.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 添加内置非译元素
 */
public void addInternalElement() {
	ISelection selection = comboViewer.getSelection();
	if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
		IStructuredSelection structuredSelection = (IStructuredSelection) selection;
		NontransElementBean interBean = (NontransElementBean) structuredSelection.getFirstElement();
		if (interBean.getId() == null) {
			return;
		}
		
		int eleSum = tableViewer.getTable().getItemCount();
		for (int i = 0; i < eleSum; i++) {
			NontransElementBean curBean = new NontransElementBean(); 
			if (tableViewer.getElementAt(i) instanceof NontransElementBean) {
				curBean = (NontransElementBean) tableViewer.getElementAt(i);
				
				if (curBean.getId().equals(interBean.getId())) {
					MessageDialog.openWarning(getShell(), Messages.getString("qa.all.dialog.warning"), MessageFormat
							.format(Messages.getString("qa.preference.NonTranslationQAPage.tip5"),
									interBean.getName()));
					return;
				}
			}
		}
		dataList.add(interBean);
		tableViewer.refresh();
	}
}
 
Example 24
Project: ModTheSpire   File: BundleUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Get a localized message from the bundle.
 *
 * @param bundleName the name of the resource bundle
 * @param locale     the locale
 * @param key        the key
 * @param params     parameters for the message
 *
 * @return the message, or the default
 */
public static String getMessage (String   bundleName,
                                 Locale   locale,
                                 String   key,
                                 Object[] params)
{
    ResourceBundle bundle;
    String         result = null;

    if (locale == null)
        locale = Locale.getDefault();

    bundle = ResourceBundle.getBundle (bundleName, locale);
    if (bundle != null)
    {
        try
        {
            String fmt = bundle.getString (key);
            if (fmt != null)
                result = MessageFormat.format (fmt, params);
        }

        catch (MissingResourceException ex)
        {
        }
    }

    return result;
}
 
Example 25
Project: ermasterr   File: TablespaceHtmlReportPageGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private String generateValueTable(final TablespaceProperties properties) throws IOException {
    final StringBuilder sb = new StringBuilder();

    final String template = ExportToHtmlManager.getTemplate("types/value_row_template.html");

    for (final Map.Entry<String, String> entry : properties.getPropertiesMap().entrySet()) {
        final Object[] args = {ResourceString.getResourceString(entry.getKey()), Format.null2blank(entry.getValue())};
        final String row = MessageFormat.format(template, args);

        sb.append(row);
    }

    return sb.toString();
}
 
Example 26
Project: ditto-examples   File: ConfigProperties.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private InputStream getPropertiesFileInputStream() {
    final ClassLoader classLoader = PropertiesSupplier.class.getClassLoader();
    final InputStream result = classLoader.getResourceAsStream(propertiesFileName);
    if (null == result) {
        final String messagePattern = "Resource with name <{0}> cannot be found!";
        throw new ConfigError(MessageFormat.format(messagePattern, propertiesFileName));
    }
    return result;
}
 
Example 27
Project: ctsms   File: CriteriaUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static org.hibernate.criterion.Criterion getRestrictionCriterion(RestrictionCriterionTypes restriction, String propertyName) {
	if (PROPERTY_NAME_REGEXP.matcher(propertyName).find()) {
		switch (restriction) {
			case IS_NULL:
				return Restrictions.isNull(propertyName);
			case IS_NOT_NULL:
				return Restrictions.isNotNull(propertyName);
			default:
				throw new IllegalArgumentException(MessageFormat.format(UNSUPPORTED_UNARY_RESTRICTION_CRITERION_TYPE, restriction.toString()));
		}
	} else {
		return Restrictions.sqlRestriction(MessageFormat.format(restriction.toString(), propertyName));
	}
}
 
Example 28
Project: gemfirexd-oss   File: AbstractRmiServiceExporter.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void run() {
  Assert.state(!isRunning(), "The remote object service ({0}) is already running!", getServiceNameForBinding());

  try {
    setSecurityManager();
    setRemoteObject(exportRemoteObject());
    getRegistry().rebind(getServiceNameForBinding(), getRemoteObject());
    this.remoteObjectIsBound = true;
    this.running = true;
  }
  catch (Exception e) {
    throw new RuntimeException(MessageFormat.format("Failed to run remote object service ({0})!", 
        getServiceNameForBinding()), e);
  }
}
 
Example 29
Project: allure1   File: AllureAspectUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getTitleWithoutParams() {
    String title = getTitle("{method}", METHOD_NAME, null, null);
    Object[] args = {METHOD_NAME};
    assertThat("Method without arguments is processed incorrectly", title,
            equalTo(MessageFormat.format("{0}", args)));
}
 
Example 30
Project: portecle   File: FPortecle.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the keystore entry's head certificate.
 *
 * @param sEntryAlias Entry alias
 * @return The keystore entry's head certificate
 * @throws CryptoException Problem getting head certificate
 */
private X509Certificate getHeadCert(String sEntryAlias)
    throws CryptoException
{
	try
	{
		// Get keystore
		KeyStore keyStore = m_keyStoreWrap.getKeyStore();

		// Get the entry's head certificate
		X509Certificate cert;
		if (keyStore.isKeyEntry(sEntryAlias))
		{
			cert = X509CertUtil.orderX509CertChain(
			    X509CertUtil.convertCertificates(keyStore.getCertificateChain(sEntryAlias)))[0];
		}
		else
		{
			cert = X509CertUtil.convertCertificate(keyStore.getCertificate(sEntryAlias));
		}

		return cert;
	}
	catch (KeyStoreException ex)
	{
		String sMessage = MessageFormat.format(RB.getString("FPortecle.NoAccessEntry.message"), sEntryAlias);
		throw new CryptoException(sMessage, ex);
	}
}
 
Example 31
Project: allure1   File: AllureAspectUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getTitleWithStringArray() {
    String[] firstArg = {"one string", "two string", "three string"};
    int secondArg = 2454575;
    String title = getTitle(NAME_PATTERN_WITH_TWO_ARGS, METHOD_NAME, null, new Object[]{firstArg, secondArg});
    Object[] args = {METHOD_NAME, Arrays.toString(firstArg), secondArg};
    assertThat("Method with String[] and int arguments is processed incorrectly", title,
            equalTo(MessageFormat.format(TITLE_STRING_WITH_TWO_ARGS, args)));
}
 
Example 32
Project: NBTEditor   File: KingsCrown.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPickup(EntityPickupItemEvent event) {
	Player player = ((Player) event.getEntity());
	PlayerInventory inv = player.getInventory();
	ItemStack lastHelmet = inv.getHelmet();
	if (lastHelmet == null || inv.addItem(lastHelmet).size() == 0) {
		inv.setHelmet(event.getItem().getItemStack());
		event.getItem().remove();
		event.setCancelled(true);
		if (shouldBroadcastMessage()) {
			UtilsMc.broadcastToWorld(player.getWorld(), MessageFormat.format("§6{0} §fhas been crown §6King§f!", player.getName(), getName()));
		}
	}
}
 
Example 33
Project: Partner-Center-Java   File: CartOperations.java    License: MIT License 5 votes vote down vote up
/**
 * Checkouts the cart.
 * 
 * @return The cart checkout result.
 */
@Override
public CartCheckoutResult checkout() 
{
	return this.getPartner().getServiceClient().post(
		this.getPartner(), 
		new TypeReference<CartCheckoutResult>(){},
		MessageFormat.format(
			PartnerService.getInstance().getConfiguration().getApis().get("PlaceOrder").getPath(),
			this.getContext().getItem1(),
			this.getContext().getItem2()),
		"success");
}
 
Example 34
Project: tmxeditor8   File: PathUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 构造SpreadsheetPackage对象
 * @param root
 *            资源根路径,在此路径下,包含了Spreadsheet解压后的所有文件和正确的目录结构
 * @throws Exception 
 */
public PathUtil(String superRoot) throws Exception {
	this.superRoot = superRoot;
	setRoot(superRoot); 
	wordRoot = superRoot + System.getProperty("file.separator") + PathConstant.WORD_FOLDER;
	interTagPath = superRoot + System.getProperty("file.separator") + PathConstant.interTag_FILE;
	if (!new File(wordRoot).exists() && !new File(wordRoot).isDirectory()) {
		throw new Exception(MessageFormat.format(Messages.getString("PathUtil.msg1"), PathConstant.WORD_FOLDER));
	}
}
 
Example 35
Project: sakai   File: InputRichTextRenderer.java    License: Educational Community License v2.0 5 votes vote down vote up
protected void writeFilesArray(ResponseWriter writer, String arrayVar,
                               Object attchedFiles, MessageFormat format,
                               boolean includeLabel) throws IOException {
   StringWriter buffer = new StringWriter();

   char startChar = '[';
   char endChar = ']';

   if (LIST_ITEM_FORMAT_HTML.equals(format)) {
      startChar = '{';
      endChar = '}';
   }

   buffer.write("  var " + arrayVar + " = "+startChar+"\n");

   if (includeLabel) {
      buffer.write("\"select a file url to insert\" : \"\"");
   }

   if (attchedFiles instanceof Map) {
      buffer.write(outputFiles((Map)attchedFiles, format, !includeLabel));
   }
   else {
      buffer.write(outputFiles((List)attchedFiles, format, !includeLabel));
   }

   buffer.write(endChar + ";\n");
   String result = buffer.toString();
   writer.write(result);
}
 
Example 36
Project: govpay   File: PendenzeDAO.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void patchAck(it.govpay.bd.model.Versamento versamentoLetto, PatchOp op) throws ValidationException {
	if(!op.getOp().equals(OpEnum.REPLACE)) {
		throw new ValidationException(MessageFormat.format(UtenzaPatchUtils.OP_XX_NON_VALIDO_PER_IL_PATH_YY, op.getOp(), op.getPath()));
	}

	Boolean ackVersamento = (Boolean) op.getValue();
	versamentoLetto.setAck(ackVersamento != null ? ackVersamento.booleanValue() : false);
}
 
Example 37
Project: google-cloud-eclipse   File: Messages.java    License: Apache License 2.0 5 votes vote down vote up
public static String getString(String key, Object... params) {
  try {
    return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params);
  } catch (MissingResourceException ex) {
    return '!' + key + '!';
  }
}
 
Example 38
Project: openjdk-8   File: PolicyParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ParsingException(int line, String msg) {
    super("line " + line + ": " + msg);
    MessageFormat form = new MessageFormat
        (ResourcesMgr.getString("line.number.msg"));
    Object[] source = {new Integer(line), msg};
    i18nMessage = form.format(source);
}
 
Example 39
Project: j2objc   File: MessageFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_format_Object() {
  // Regression for HARMONY-1875
  Locale.setDefault(Locale.CANADA);
  TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
  String pat="text here {0, date, yyyyyyyyy } and here";
  String etalon="text here  000002007  and here";
  MessageFormat obj = new MessageFormat(pat);
  assertEquals(etalon, obj.format(new Object[]{new Date(1198141737640L)}));

  assertEquals("{0}", MessageFormat.format("{0}", (Object[]) null));
  assertEquals("nullABC", MessageFormat.format("{0}{1}", (Object[]) new String[]{null, "ABC"}));
}
 
Example 40
Project: depan   File: NodeCompactor.java    License: Apache License 2.0 5 votes vote down vote up
private PlatformObject buildCollapseRoot() {

    CollapseTreeModel treeModel = getCollapseTreeModel();
    int rootCnt = treeModel.computeRoots().size();
    int nodeCnt = treeModel.computeNodes().size();

    String label = MessageFormat.format(
        "Collapse nodes [{0} roots, {1} nodes]", rootCnt, nodeCnt);
    return CollapseTreeRoot.build(
        label, treeModel, NodeTreeProviders.GRAPH_NODE_PROVIDER);
  }