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. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Insights   Source 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
/**
 * 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
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
Source Project: astor   Source 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
Source Project: DataLink   Source 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
Source Project: cyberduck   Source 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
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
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
Source Project: jdk8u-jdk   Source 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
Source Project: hottub   Source 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
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
Source Project: ramus   Source 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
Source Project: DBus   Source 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
@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
Source Project: netbeans   Source 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
Source Project: MyBox   Source 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
Source Project: APICloud-Studio   Source 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
Source Project: hottub   Source 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
/**
 * 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
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
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
/**
 * 添加内置非译元素
 */
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
Source Project: ModTheSpire   Source 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
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
Source Project: ditto-examples   Source 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
Source Project: ctsms   Source 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
Source Project: gemfirexd-oss   Source 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
Source Project: allure1   Source 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
Source Project: portecle   Source 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);
	}
}