Java Code Examples for java.text.MessageFormat

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Debug/.

Source file: LogFormatter.java

  33 
vote

/** 
 */
public LogFormatter(){
  super();
  final String propName=getClass().getName() + ".format";
  String format=LogManager.getLogManager().getProperty(propName);
  if (format == null || format.trim().length() == 0) {
    format=DEFAULT_FORMAT;
  }
  if (format.contains("{") || format.contains("}")) {
    throw new IllegalArgumentException("curly braces not allowed");
  }
  format=format.replace("%L","{0}").replace("%m","{1}").replace("%M","{2}").replace("%t","{3}").replace("%c","{4}").replace("%T","{5}").replace("%n","{6}").replace("%C","{7}").replace("%S","{8}") + "\n";
  messageFormat=new MessageFormat(format);
}
 

Example 2

From project andtweet, under directory /src/com/xorcode/andtweet/.

Source file: PreferencesActivity.java

  32 
vote

protected void showHistorySize(){
  String[] k=getResources().getStringArray(R.array.history_size_keys);
  String[] d=getResources().getStringArray(R.array.history_size_display);
  String displayHistorySize=d[0];
  String historySize=mHistorySizePreference.getValue();
  for (int i=0; i < k.length; i++) {
    if (historySize.equals(k[i])) {
      displayHistorySize=d[i];
      break;
    }
  }
  MessageFormat sf=new MessageFormat(getText(R.string.summary_preference_history_size).toString());
  mHistorySizePreference.setSummary(sf.format(new Object[]{displayHistorySize}));
}
 

Example 3

From project BukkitUtilities, under directory /src/main/java/name/richardson/james/bukkit/utilities/formatters/.

Source file: ChoiceFormatter.java

  32 
vote

public String getMessage(){
  final MessageFormat formatter=new MessageFormat(this.message);
  final ChoiceFormat cFormatter=new ChoiceFormat(this.limits,this.formats);
  formatter.setFormatByArgumentIndex(0,cFormatter);
  return formatter.format(this.arguments);
}
 

Example 4

From project codjo-control, under directory /codjo-control-server/src/main/java/net/codjo/control/server/plugin/.

Source file: PostControlAudit.java

  32 
vote

public void fill(JobAudit jobAudit){
  Arguments arguments=new Arguments();
  arguments.put(VALID_LINE_COUNT,Integer.toString(validLineCount));
  arguments.put(BAD_LINE_COUNT,Integer.toString(badLineCount));
  jobAudit.setArguments(arguments);
  if (getBadLineCount() > 0) {
    MessageFormat messageFormat=new MessageFormat(translate("PostControlAudit.message"),Locale.FRENCH);
    Object[] param={getBadLineCount()};
    jobAudit.setWarningMessage(messageFormat.format(param));
  }
}
 

Example 5

From project commons-io, under directory /src/test/java/org/apache/commons/io/input/.

Source file: XmlStreamReaderTest.java

  32 
vote

/** 
 * Create the XML.
 */
private String getXML(String bomType,String xmlType,String streamEnc,String prologEnc){
  MessageFormat xml=XMLs.get(xmlType);
  String info=INFO.format(new Object[]{bomType,xmlType,prologEnc});
  String xmlDoc=xml.format(new Object[]{streamEnc,prologEnc,info});
  return xmlDoc;
}
 

Example 6

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.

Source file: Messages.java

  31 
vote

private static String getMessage(String key,Locale locale,Object... params){
  MessageFormat mf=new MessageFormat("");
  try {
    if (locale == null) {
      mf.applyPattern(ResourceBundle.getBundle(BUNDLE).getString(key));
    }
 else {
      mf.applyPattern(ResourceBundle.getBundle(BUNDLE,locale).getString(key));
    }
  }
 catch (  Exception e) {
    mf.applyPattern(key);
  }
  return mf.format(params);
}
 

Example 7

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: UriParser.java

  31 
vote

/** 
 * TODO: use  {@link Matcher#replaceAll(String)}
 * @param inputString
 * @param replaceFormat
 * @return the replaced string
 */
public CharSequence replaceMessageFormatString(CharSequence inputString,String replaceFormat){
  Pattern pattern=this.uriWithin;
  Matcher matcher=pattern.matcher(inputString);
  if (matcher.find()) {
    int start=0;
    ApplicationNullPointerException.notNull(replaceFormat,"cannot do a replace because there is no format");
    MessageFormat messageFormat=new MessageFormat(replaceFormat);
    StringBuilder stringBuilder=new StringBuilder();
    int groupCount=matcher.groupCount();
    do {
      int end=matcher.start();
      stringBuilder.append(inputString.subSequence(start,end));
      String[] result=new String[groupCount];
      for (int i=0; i < result.length; i++) {
        result[i]=matcher.group(i);
      }
      String formatted=messageFormat.format(result);
      stringBuilder.append(formatted);
      start=matcher.end();
    }
 while (matcher.find());
    return stringBuilder;
  }
 else {
    return inputString;
  }
}
 

Example 8

From project andstatus, under directory /src/org/andstatus/app/data/.

Source file: MyPreferences.java

  31 
vote

/** 
 * @param pa Preference Activity
 * @param keyPreference android:key - Name of the preference key
 * @param entryValuesR android:entryValues
 * @param displayR Almost like android:entries but to show in the summary (may be the same as android:entries) 
 * @param summaryR
 */
public static void showListPreference(PreferenceActivity pa,String keyPreference,int entryValuesR,int displayR,int summaryR){
  String displayParm="";
  ListPreference lP=(ListPreference)pa.findPreference(keyPreference);
  if (lP != null) {
    String[] k=pa.getResources().getStringArray(entryValuesR);
    String[] d=pa.getResources().getStringArray(displayR);
    displayParm=d[0];
    String listValue=lP.getValue();
    for (int i=0; i < k.length; i++) {
      if (listValue.equals(k[i])) {
        displayParm=d[i];
        break;
      }
    }
  }
 else {
    displayParm=keyPreference + " was not found";
  }
  MessageFormat sf=new MessageFormat(pa.getText(summaryR).toString());
  lP.setSummary(sf.format(new Object[]{displayParm}));
}
 

Example 9

From project arquillian-core, under directory /testenrichers/ejb/src/main/java/org/jboss/arquillian/testenricher/ejb/.

Source file: EJBInjectionEnricher.java

  31 
vote

/** 
 * Resolves the JNDI name of the given field. If <tt>mappedName</tt> or <tt>beanName</tt> are specified, they're used to resolve JNDI name. Otherwise, default policy applies. If both, the <tt>mappedName</tt> and <tt>beanName</tt>, are specified at the same time, an  {@link IllegalStateException}will be thrown.
 * @param fieldType annotated field which JNDI name should be resolved.
 * @param mappedName Value of {@link EJB}'s <tt>mappedName</tt> attribute.
 * @param beanName Value of {@link EJB}'s <tt>beanName</tt> attribute.
 * @return possible JNDI names which should be looked up to access the proper object.
 */
protected String[] resolveJNDINames(Class<?> fieldType,String mappedName,String beanName){
  MessageFormat msg=new MessageFormat("Trying to resolve JNDI name for field \"{0}\" with mappedName=\"{1}\" and beanName=\"{2}\"");
  log.finer(msg.format(new Object[]{fieldType,mappedName,beanName}));
  Validate.notNull(fieldType,"EJB enriched field cannot to be null.");
  boolean isMappedNameSet=hasValue(mappedName);
  boolean isBeanNameSet=hasValue(beanName);
  if (isMappedNameSet && isBeanNameSet) {
    throw new IllegalStateException("@EJB annotation attributes 'mappedName' and 'beanName' cannot be specified at the same time.");
  }
  String[] jndiNames;
  if (isMappedNameSet) {
    jndiNames=new String[]{mappedName};
  }
 else   if (isBeanNameSet) {
    jndiNames=new String[]{"java:module/" + beanName + "!"+ fieldType.getName()};
  }
 else {
    jndiNames=new String[]{"java:global/test.ear/test/" + fieldType.getSimpleName() + "Bean","java:global/test.ear/test/" + fieldType.getSimpleName(),"java:global/test/" + fieldType.getSimpleName(),"java:global/test/" + fieldType.getSimpleName() + "Bean","java:global/test/" + fieldType.getSimpleName() + "/no-interface","test/" + fieldType.getSimpleName() + "Bean/local","test/" + fieldType.getSimpleName() + "Bean/remote","test/" + fieldType.getSimpleName() + "/no-interface",fieldType.getSimpleName() + "Bean/local",fieldType.getSimpleName() + "Bean/remote",fieldType.getSimpleName() + "/no-interface","ejblocal:" + fieldType.getCanonicalName(),fieldType.getCanonicalName()};
  }
  return jndiNames;
}
 

Example 10

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/logging/.

Source file: LatkeFormatter.java

  31 
vote

/** 
 * Public default constructor.
 */
public LatkeFormatter(){
  final String propName=getClass().getName() + ".format";
  String format=LogManager.getLogManager().getProperty(propName);
  if (format == null || format.trim().length() == 0) {
    format=DEFAULT_FORMAT;
  }
  if (format.contains("{") || format.contains("}")) {
    throw new IllegalArgumentException("curly braces not allowed");
  }
  format=format.replace("%L","{0}").replace("%m","{1}").replace("%M","{2}").replace("%t","{3}").replace("%c","{4}").replace("%T","{5}").replace("%n","{6}").replace("%C","{7}").replace("%ln","{8}") + System.getProperty("line.separator");
  messageFormat=new MessageFormat(format);
}
 

Example 11

From project CircDesigNA, under directory /src/org/apache/commons/math/exception/util/.

Source file: MessageFactory.java

  31 
vote

/** 
 * Builds a message string by from two patterns (specific and general) and an argument list.
 * @param locale Locale in which the message should be translated.
 * @param specific Format specifier (may be null).
 * @param general Format specifier (may be null).
 * @param arguments Format arguments. They will be substituted in<em>both</em> the  {@code general} and {@code specific} format specifiers.
 * @return a localized message string.
 */
public static String buildMessage(Locale locale,Localizable specific,Localizable general,Object... arguments){
  final StringBuilder sb=new StringBuilder();
  if (general != null) {
    final MessageFormat fmt=new MessageFormat(general.getLocalizedString(locale),locale);
    sb.append(fmt.format(arguments));
  }
  if (specific != null) {
    if (general != null) {
      sb.append(": ");
    }
    final MessageFormat fmt=new MessageFormat(specific.getLocalizedString(locale),locale);
    sb.append(fmt.format(arguments));
  }
  return sb.toString();
}
 

Example 12

From project clutter, under directory /src/clutter/hypertoolkit/security/.

Source file: CookieJar.java

  31 
vote

public long currentPrincipal() throws SecurityException {
  final Maybe<String> contents=getString(SESSION_KEY_NAME);
  if (!contents.hasValue()) {
    throw new SecurityException();
  }
  try {
    Object[] objects=new MessageFormat(SESSION_COOKIE_FORMAT).parse(contents.getValue());
    return Long.parseLong((String)objects[1]);
  }
 catch (  Throwable t) {
    throw new SecurityException();
  }
}
 

Example 13

From project cogroo4, under directory /cogroo-nlp/src/main/java/org/cogroo/exceptions/.

Source file: InternationalizedException.java

  31 
vote

public String getLocalizedMessage(Locale aLocale){
  if (getMessageKey() == null)   return null;
  try {
    ResourceBundle bundle=ResourceBundle.getBundle(getResourceBundleName(),aLocale,this.getClass().getClassLoader());
    String message=bundle.getString(getMessageKey());
    if (getArguments().length > 0) {
      MessageFormat fmt=new MessageFormat(message);
      fmt.setLocale(aLocale);
      return fmt.format(getArguments());
    }
 else     return message;
  }
 catch (  Exception e) {
    return "EXCEPTION MESSAGE LOCALIZATION FAILED: " + e.toString();
  }
}
 

Example 14

From project conf4j, under directory /conf4j-base/src/main/java/org/conf4j/util/.

Source file: MacroProcessor.java

  31 
vote

/** 
 * Parses a string containing <code>${xxx}</code> style property references into two lists. The first list is a collection of text fragments, while the other is a set of string property names. <code>null</code> entries in the first list indicate a property reference from the second list. It can be overridden with a more efficient or customized version.
 * @param textToParse Text to parse. Must not be <code>null</code>.
 * @param fragments List to add text fragments to. Must not be <code>null</code>.
 * @param propertyRefs List to add property names to. Must not be <code>null</code>.
 * @exception MacroParsingException if the string contains an opening <code>${</code> without a closing<code>}</code>
 */
private static final void parsePropertyString(String textToParse,List<String> fragments,List<String> propertyRefs) throws MacroParsingException {
  final MessageFormat SYNTAX_ERROR_IN_0=new MessageFormat(STR_SYNTAX_ERROR_IN_0);
  int prev=0;
  int pos;
  while ((pos=textToParse.indexOf('$',prev)) >= 0) {
    if (pos > 0)     fragments.add(textToParse.substring(prev,pos));
    if (pos == (textToParse.length() - 1)) {
      fragments.add("$");
      prev=pos + 1;
    }
 else     if (textToParse.charAt(pos + 1) != '{') {
      if (textToParse.charAt(pos + 1) == '$') {
        fragments.add("$");
        prev=pos + 2;
      }
 else {
        fragments.add(textToParse.substring(pos,pos + 2));
        prev=pos + 2;
      }
    }
 else {
      final int endName=textToParse.indexOf('}',pos);
      if (endName < 0)       throw new MacroParsingException(SYNTAX_ERROR_IN_0.format(new String[]{textToParse}));
      String propertyName=textToParse.substring(pos + 2,endName);
      fragments.add(null);
      propertyRefs.add(propertyName);
      prev=endName + 1;
    }
  }
  if (prev < textToParse.length())   fragments.add(textToParse.substring(prev));
}
 

Example 15

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  30 
vote

public ServeConnection(Socket s,Webserver ser){
  socket=s;
  serve=ser;
  expdatefmt.setTimeZone(tz);
  headerdateformat.setTimeZone(tz);
  rfc850DateFmt.setTimeZone(tz);
  asciiDateFmt.setTimeZone(tz);
  if (serve.isAccessLogged()) {
    accessFmt=new MessageFormat((String)serve.arguments.get(ARG_ACCESS_LOG_FMT));
    logPlaceholders=new Object[12];
  }
  initSSLAttrs();
  try {
    in=new ServeInputStream(socket.getInputStream(),this);
    out=new ServeOutputStream(socket.getOutputStream(),this);
  }
 catch (  IOException ioe) {
    close();
    return;
  }
  serve.threadPool.executeThread(this);
}
 

Example 16

From project Android, under directory /app/src/main/java/com/github/mobile/persistence/.

Source file: AccountDataManager.java

  30 
vote

/** 
 * Read data from file
 * @param file
 * @return data
 */
@SuppressWarnings("unchecked") private <V>V read(final File file){
  long start=System.currentTimeMillis();
  long length=file.length();
  Object data=new RequestReader(file,FORMAT_VERSION).read();
  if (data != null)   Log.d(TAG,MessageFormat.format("Cache hit to {0}, {1} ms to load {2} bytes",file.getName(),(System.currentTimeMillis() - start),length));
  return (V)data;
}
 

Example 17

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/casemodule/.

Source file: NewCaseWizardAction.java

  30 
vote

/** 
 * The method to perform new case creation
 */
private void newCaseAction(){
  WizardDescriptor wizardDescriptor=new WizardDescriptor(getPanels());
  wizardDescriptor.setTitleFormat(new MessageFormat("{0}"));
  wizardDescriptor.setTitle("New Case Information");
  Dialog dialog=DialogDisplayer.getDefault().createDialog(wizardDescriptor);
  dialog.setVisible(true);
  dialog.toFront();
  boolean finished=wizardDescriptor.getValue() == WizardDescriptor.FINISH_OPTION;
  boolean isCancelled=wizardDescriptor.getValue() == WizardDescriptor.CANCEL_OPTION;
  if (finished) {
  }
  if (isCancelled) {
    String createdDirectory=(String)wizardDescriptor.getProperty("createdDirectory");
    if (createdDirectory != null) {
      logger.log(Level.INFO,"Deleting a created case directory due to isCancelled set, dir: " + createdDirectory);
      Case.deleteCaseDirectory(new File(createdDirectory));
    }
    if (Case.existsCurrentCase()) {
      CaseCloseAction closeCase=SystemAction.get(CaseCloseAction.class);
      closeCase.actionPerformed(null);
    }
  }
  panels=null;
}
 

Example 18

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/.

Source file: I18nManager.java

  29 
vote

public String getMessage(String key,Object... arguments){
  if (messages == null) {
    createResourceBundle();
  }
  return MessageFormat.format(messages.getString(key),arguments);
}
 

Example 19

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  29 
vote

protected void generateTaskAndFormConfigForUserTask(KickstartUserTask userTask,StringBuilder taskModelsString,StringBuilder formConfigString,String baseName,HashMap<String,String> formPropertyMapping){
  if (userTask.getForm() != null) {
    String uniqueTaskName=baseName + "_" + userTask.getName().toLowerCase().replace(" ","_");
    String prefixedUniqueTaskName=KICKSTART_PREFIX + uniqueTaskName;
    userTask.getForm().setFormKey(prefixedUniqueTaskName);
    StringBuilder typeString=new StringBuilder();
    StringBuilder formAppearanceString=new StringBuilder();
    StringBuilder formVisibilityString=new StringBuilder();
    String descriptionPropertyName=KICKSTART_PREFIX + "description_" + uniqueTaskName;
    if (userTask.getDescription() != null) {
      formVisibilityString.append(MessageFormat.format(getFormConfigFieldVisibilityTemplate(),descriptionPropertyName));
      formAppearanceString.append(MessageFormat.format(getFormConfigInfoTemplate(),descriptionPropertyName,"Description"));
    }
    if (userTask.getForm().getFormProperties() != null && userTask.getForm().getFormProperties().size() > 0) {
      for (      KickstartFormProperty formProperty : userTask.getForm().getFormProperties()) {
        String uniquePropertyName=KICKSTART_PREFIX + baseName + "_"+ createFriendlyName(formProperty.getProperty());
        formPropertyMapping.put(formProperty.getProperty(),uniquePropertyName);
        if (formProperty.getType().equals("documents")) {
          formVisibilityString.append(MessageFormat.format(getFormConfigFieldVisibilityTemplate(),"packageItems"));
          formAppearanceString.append(MessageFormat.format(getFormConfigFieldTemplate(),"packageItems",formProperty.getProperty()));
        }
 else {
          typeString.append(MessageFormat.format(getTaskModelPropertyTemplate(),uniquePropertyName,getAlfrescoModelType(formProperty.getType()),formProperty.isRequired()));
          formVisibilityString.append(MessageFormat.format(getFormConfigFieldVisibilityTemplate(),uniquePropertyName));
          formAppearanceString.append(MessageFormat.format(getFormConfigFieldTemplate(),uniquePropertyName,formProperty.getProperty()));
        }
      }
    }
    if (userTask.getDescription() != null) {
      for (      String formProperty : formPropertyMapping.keySet()) {
        String formPropertyExpression="${" + formProperty + "}";
        if (userTask.getDescription().contains(formPropertyExpression)) {
          userTask.setDescription(userTask.getDescription().replace(formPropertyExpression,"${" + formPropertyMapping.get(formProperty) + "}"));
        }
      }
    }
    taskModelsString.append(MessageFormat.format(getTaskModelTypeTemplate(),prefixedUniqueTaskName,descriptionPropertyName,userTask.getDescription(),typeString.toString()));
    formConfigString.append(MessageFormat.format(getFormConfigEvaluatorConfigTemplate(),prefixedUniqueTaskName,formVisibilityString.toString(),formAppearanceString.toString()));
  }
}
 

Example 20

From project AdServing, under directory /modules/utilities/utils/src/main/java/net/mad/ads/base/utils/utils/logging/.

Source file: LogWrapper.java

  29 
vote

public void init(Class clazz,File logPropertiesFile){
  try {
    Properties prop=Properties2.loadProperties(logPropertiesFile);
    if (logger == null) {
      logger=Logger.getLogger(prop.getProperty(LOGGER_NAME));
      String fileName=prop.getProperty(LOG_FILE_NAME);
      RollingFileHandler rfh=new RollingFileHandler(fileName,".log");
      rfh.setFormatter(new CustomMessageFormatter(new MessageFormat(prop.getProperty(MESSAGE_FORMAT))));
      logger.setLevel(AdLevel.parse(prop.getProperty(LOG_LEVEL)));
      logger.addHandler(rfh);
    }
    this.className=clazz.getName();
  }
 catch (  FileNotFoundException fnfe) {
    fnfe.printStackTrace();
  }
catch (  IOException ioe) {
    ioe.printStackTrace();
  }
}
 

Example 21

From project agile, under directory /agile-framework/src/main/java/org/apache/naming/.

Source file: StringManager.java

  29 
vote

/** 
 * Get a string from the underlying resource bundle and format it with the given set of arguments.
 * @param key
 * @param args
 */
public String getString(String key,Object[] args){
  String iString=null;
  String value=getString(key);
  try {
    Object nonNullArgs[]=args;
    for (int i=0; i < args.length; i++) {
      if (args[i] == null) {
        if (nonNullArgs == args)         nonNullArgs=(Object[])args.clone();
        nonNullArgs[i]="null";
      }
    }
    iString=MessageFormat.format(value,nonNullArgs);
  }
 catch (  IllegalArgumentException iae) {
    StringBuffer buf=new StringBuffer();
    buf.append(value);
    for (int i=0; i < args.length; i++) {
      buf.append(" arg[" + i + "]="+ args[i]);
    }
    iString=buf.toString();
  }
  return iString;
}
 

Example 22

From project agit, under directory /agit/src/main/java/com/madgag/agit/operations/.

Source file: Pull.java

  29 
vote

private AnyObjectId commitToMergeFor(FetchResult fetchRes,String remoteBranchName,boolean remote){
  AnyObjectId commitToMerge;
  if (remote) {
    Ref r=null;
    if (fetchRes != null) {
      r=fetchRes.getAdvertisedRef(remoteBranchName);
      if (r == null)       r=fetchRes.getAdvertisedRef(R_HEADS + remoteBranchName);
    }
    if (r == null)     throw new JGitInternalException(MessageFormat.format(JGitText.get().couldNotGetAdvertisedRef,remoteBranchName));
 else     commitToMerge=r.getObjectId();
  }
 else {
    try {
      commitToMerge=repo.resolve(remoteBranchName);
      if (commitToMerge == null)       throw exceptionMessage(R.string.ref_not_resolved,remoteBranchName);
    }
 catch (    IOException e) {
      throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,e);
    }
  }
  return commitToMerge;
}
 

Example 23

From project agorava-core, under directory /agorava-core-api/src/main/java/org/agorava/core/api/exception/.

Source file: AgoravaRestException.java

  29 
vote

public AgoravaRestException(int code,String url,String msg){
  super(MessageFormat.format("Remote service returned the error code {0} for the following URL : {1}\nThe following data was returned :\n{2}\n",code,url,msg));
  this.code=code;
  this.url=url;
  this.msg=msg;
}
 

Example 24

From project alfredo, under directory /examples/src/main/java/com/cloudera/alfredo/examples/.

Source file: WhoServlet.java

  29 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/plain");
  resp.setStatus(HttpServletResponse.SC_OK);
  String user=req.getRemoteUser();
  String principal=(req.getUserPrincipal() != null) ? req.getUserPrincipal().getName() : null;
  Writer writer=resp.getWriter();
  writer.write(MessageFormat.format("You are: user[{0}] principal[{1}]\n",user,principal));
}
 

Example 25

From project androidTileMapEditor_1, under directory /src/it/sineo/android/tileMapEditor/.

Source file: TiledMapActivity.java

  29 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.tilemap);
  ActionBar bar=getSupportActionBar();
  bar.setHomeButtonEnabled(true);
  bar.setDisplayHomeAsUpEnabled(true);
  view=(TiledMapView)findViewById(R.id.tiledmap);
  view.setOnShortPressListener(shortPressListener);
  view.setOnLongPressListener(longPressListener);
  Intent i=getIntent();
  if (i.hasExtra(C.EXTRA_MAP_ID)) {
    mapId=i.getLongExtra(C.EXTRA_MAP_ID,-1);
    view.restoreFromJSON(i.getStringExtra(C.EXTRA_MAP_JSON));
    getSupportActionBar().setTitle(view.getMapName());
  }
 else {
    int rows=i.getIntExtra(C.EXTRA_MAP_ROWS,-1);
    int columns=i.getIntExtra(C.EXTRA_MAP_COLUMNS,-1);
    if (rows != -1 && columns != -1) {
      view.initMap(rows,columns);
    }
 else {
      Log.e(TAG,MessageFormat.format("missing dimensions (rows={0}, columns={1}",rows,columns));
    }
    showDialog(C.DIALOG_RENAME_MAP);
  }
  adapter=new ImageAdapter(TiledMapActivity.this);
  try {
    String[] tileSets=getAssets().list("gfx");
    for (    String tileSet : tileSets) {
      adapter.addFromAssets("gfx/" + tileSet);
    }
  }
 catch (  IOException ioex) {
    ioex.printStackTrace();
  }
  registerForContextMenu(view);
}
 

Example 26

From project apb, under directory /modules/apb-installer/src/apb/installer/.

Source file: Installer.java

  29 
vote

private void generateScript() throws FileNotFoundException {
  final File scriptFile=new File(binDir,"apb");
  println("Generating apb shell script: " + scriptFile);
  PrintWriter writer=new PrintWriter(scriptFile);
  File l=Utils.makeRelative(binDir,libDir);
  String dir;
  if (l == null) {
    dir=libDir.getAbsolutePath();
  }
 else   if (isWindows()) {
    dir="$(cygpath --windows $(dirname $(type -p $0))/)" + l;
  }
 else {
    dir="$(dirname $(type -p $0))/" + l;
  }
  dir+=File.separator;
  String[] props={APB_MEMORY,dir};
  for (int i=0; i < script.length; i++) {
    writer.println(MessageFormat.format(script[i],props));
  }
  writer.close();
  if (scriptFile.setExecutable(true))   println("Making script executable.");
}
 

Example 27

From project arquillian-extension-android, under directory /android-impl/src/main/java/org/jboss/arquillian/android/impl/.

Source file: CountDownWatch.java

  29 
vote

/** 
 * Creates a countdown watch and starts it
 * @param timeout timeout
 * @param unit timeout unit
 */
public CountDownWatch(long timeout,TimeUnit unit){
  if (EnumSet.of(TimeUnit.MICROSECONDS,TimeUnit.MILLISECONDS).contains(unit)) {
    throw new IllegalArgumentException(MessageFormat.format("Time Unit {0} is not supported",unit));
  }
  this.timeStart=System.currentTimeMillis();
  this.timeout=timeout;
  this.unit=unit;
}
 

Example 28

From project arquillian-showcase, under directory /spring/spring-hibernate/src/main/java/com/acme/spring/hibernate/repository/impl/.

Source file: HibernateStockRepository.java

  29 
vote

/** 
 * <p>Validates that the passed parameter is not null or empty string, in case it isn't than  {@link IllegalArgumentException} is being thrown.</p>
 * @param param         the parameter to validate
 * @param parameterName the parameter name
 */
private void validateNotEmpty(String param,String parameterName){
  validateNoNull(param,parameterName);
  if (param.trim().length() == 0) {
    throw new IllegalArgumentException(MessageFormat.format("The {0} can not be null or empty string.",parameterName));
  }
}
 

Example 29

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.datatools.enablement.simpledb.editor.ui/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/wizard/.

Source file: SDBTableIdDataWizardPage.java

  29 
vote

private void createContent(){
  Object value;
  this.col=this.editor.getCursor().getColumn();
  StructuredSelection selection=(StructuredSelection)this.editor.getSelectionProvider().getSelection();
  TableDataCell firstElement=(TableDataCell)selection.getFirstElement();
  Object row=firstElement.getRow();
  if (row instanceof RowDataImpl) {
    this.rowData=(RowDataImpl)row;
    value=this.rowData.getValue(this.col);
  }
 else {
    this.rowData=(RowDataImpl)this.editor.getOrCreateRow();
    value="";
  }
  if (value == null) {
    this.t.setText("");
    setPageComplete(true);
  }
 else   if (value instanceof String) {
    this.t.setText((String)value);
    setPageComplete(true);
  }
 else   if (value instanceof SimpleDBItemName) {
    this.t.setText(((SimpleDBItemName)value).getItemName());
    setPageComplete(true);
  }
 else {
    setErrorMessage((MessageFormat.format(Messages.incorrectDataType,value.getClass().getCanonicalName())));
    this.t.setEnabled(false);
    setPageComplete(false);
  }
}
 

Example 30

From project bam, under directory /modules/active-queries/active-collection/src/main/java/org/overlord/bam/active/collection/.

Source file: AbstractActiveCollectionManager.java

  29 
vote

/** 
 * This method performs the cleanup task on the top level active collections.
 */
protected void cleanup(){
  if (LOG.isLoggable(Level.FINEST)) {
    LOG.finest("Running active collection cleanup ....");
  }
synchronized (_activeCollections) {
    for (    ActiveCollection ac : _activeCollections.values()) {
      try {
        ac.cleanup();
      }
 catch (      Exception e) {
        LOG.severe(MessageFormat.format(java.util.PropertyResourceBundle.getBundle("active-collection.Messages").getString("ACTIVE-COLLECTION-3"),ac.getName()));
      }
      if (ac.getHighWaterMark() > 0) {
        if (ac.getHighWaterMarkWarningIssued()) {
          if (ac.getSize() < ac.getHighWaterMark()) {
            LOG.info("Active collection '" + ac.getName() + "' has returned below its high water mark ("+ ac.getHighWaterMark()+ ")");
            ac.setHighWaterMarkWarningIssued(false);
          }
        }
 else         if (ac.getSize() > ac.getHighWaterMark()) {
          LOG.warning("Active collection '" + ac.getName() + "' has exceeded its high water mark ("+ ac.getHighWaterMark()+ ")");
          ac.setHighWaterMarkWarningIssued(true);
        }
      }
    }
  }
}
 

Example 31

From project banshun, under directory /banshun/core/src/main/java/com/griddynamics/banshun/.

Source file: StrictContextParentBean.java

  29 
vote

private void checkClassExist(String location,String beanName,String beanClassName) throws ClassNotFoundException {
  try {
    Class.forName(beanClassName);
  }
 catch (  ClassNotFoundException e) {
    throw new ClassNotFoundException(MessageFormat.format("Class not found {0} in location: {1} for bean: {2}",beanClassName,location,beanName));
  }
}
 

Example 32

From project Birthday-widget, under directory /Birthday/src/main/java/cz/krtinec/birthday/.

Source file: BirthdayDebug.java

  29 
vote

@Override public View getView(int position,View convertView,ViewGroup parent){
  EventDebug contact=list.get(position);
  View v;
  if (convertView == null) {
    LayoutInflater vi=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v=vi.inflate(R.layout.debug_row,null);
  }
 else {
    v=convertView;
  }
  ((TextView)v.findViewById(R.id.name)).setText(contact.getDisplayName());
  ((TextView)v.findViewById(R.id.dateParsed)).setText(MessageFormat.format(ctx.getString(R.string.debug_parsed),contact.getDisplayDate(ctx)));
  ((TextView)v.findViewById(R.id.dateAsString)).setText(MessageFormat.format(ctx.getString(R.string.debug_raw),contact.getbDayString()));
  ImageView check=(ImageView)v.findViewById(R.id.check);
switch (contact.getIntegrity()) {
case FULL:
{
      check.setImageResource(R.drawable.accept);
      break;
    }
case WITHOUT_YEAR:
{
    check.setImageResource(R.drawable.exclamation);
    break;
  }
case NONE:
{
  check.setImageResource(R.drawable.cancel);
  break;
}
}
final ImageView imageView=(ImageView)v.findViewById(R.id.bicon);
imageView.setImageResource(R.drawable.icon);
loader.loadPhoto((ImageView)v.findViewById(R.id.bicon),contact.getContactId());
return v;
}
 

Example 33

From project bndtools, under directory /bndtools.core/src/bndtools/editor/contents/.

Source file: GeneralInfoPart.java

  29 
vote

void checkActivatorIncluded(){
  String warningMessage=null;
  IAction[] fixes=null;
  String activatorClassName=txtActivator.getText();
  if (activatorClassName != null && activatorClassName.length() > 0) {
    int dotIndex=activatorClassName.lastIndexOf('.');
    if (dotIndex == -1) {
      warningMessage="Cannot use an activator in the default package.";
    }
 else {
      final String packageName=activatorClassName.substring(0,dotIndex);
      if (!model.isIncludedPackage(packageName)) {
        warningMessage="Activator package is not included in the bundle. It will be imported instead.";
        fixes=new Action[]{new Action(MessageFormat.format("Add \"{0}\" to Private Packages.",packageName)){
          @Override public void run(){
            model.addPrivatePackage(packageName);
            addDirtyProperty(aQute.bnd.osgi.Constants.PRIVATE_PACKAGE);
          }
        }
,new Action(MessageFormat.format("Add \"{0}\" to Exported Packages.",packageName)){
          @Override public void run(){
            model.addExportedPackage(new ExportedPackage(packageName,null));
            addDirtyProperty(aQute.bnd.osgi.Constants.PRIVATE_PACKAGE);
          }
        }
};
      }
    }
  }
  IMessageManager msgs=getManagedForm().getMessageManager();
  if (warningMessage != null)   msgs.addMessage(UNINCLUDED_ACTIVATOR_WARNING_KEY,warningMessage,fixes,IMessageProvider.WARNING,txtActivator);
 else   msgs.removeMessage(UNINCLUDED_ACTIVATOR_WARNING_KEY,txtActivator);
}
 

Example 34

From project c10n, under directory /core/src/main/java/c10n/.

Source file: DefaultC10NMsgFactory.java

  29 
vote

private String format(String message,boolean raw,Method method,Object... args){
  if (raw) {
    return message;
  }
  Annotation[][] argAnnotations=method.getParameterAnnotations();
  Class[] argTypes=method.getParameterTypes();
  if (args != null && args.length > 0) {
    Object[] filteredArgs=new Object[args.length];
    for (int i=0; i < args.length; i++) {
      Annotation[] annotations=argAnnotations != null ? argAnnotations[i] : NO_ANNOTATIONS;
      filteredArgs[i]=applyArgFilterIfExists(annotations,argTypes[i],args[i]);
    }
    return MessageFormat.format(message,filteredArgs);
  }
  return MessageFormat.format(message,args);
}
 

Example 35

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/templatecompiler/el/.

Source file: ELVisitor.java

  29 
vote

public ELType getVariable(String name) throws ParsingException {
  ELType variableType;
  if (variables.isDefined(name)) {
    variableType=variables.getVariable(name);
  }
 else {
    log.warn(MessageFormat.format("No type found in context for identifier ''{0}'', handling as generic Object",name));
    variableType=TypesFactory.OBJECT_TYPE;
  }
  return variableType;
}
 

Example 36

From project ceres, under directory /ceres-binding/src/main/java/com/bc/ceres/binding/converters/.

Source file: AffineTransformConverter.java

  29 
vote

@Override public AffineTransform parse(String text) throws ConversionException {
  if (text.isEmpty()) {
    return null;
  }
  final double[] array;
  try {
    array=(double[])new ArrayConverter(double[].class,new DoubleConverter()).parse(text);
  }
 catch (  ConversionException e) {
    throw new ConversionException(MessageFormat.format("Cannot parse ''{0}'' into an affine transform: {1}",text,e.getMessage()),e);
  }
  if (array.length != 4 && array.length != 6) {
    throw new ConversionException(MessageFormat.format("Cannot parse ''{0}'' into an affine transform.",text));
  }
  return new AffineTransform(array);
}
 

Example 37

From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/.

Source file: Messages.java

  29 
vote

public static String getString(String key,Object... args){
  try {
    return MessageFormat.format(getString(key),args);
  }
 catch (  Exception e) {
    LogUtils.severe("Error fomatting message for " + key + ": "+ e.getMessage());
    return getString(key);
  }
}
 

Example 38

From project Chess_1, under directory /src/chess/gui/.

Source file: GridPanel.java

  29 
vote

private String getToolTipText(Location loc){
  if (!toolTipsEnabled || loc == null || !grid.isValid(loc))   return null;
  Object f=grid.get(loc);
  if (f != null)   return MessageFormat.format(resources.getString("cell.tooltip.nonempty"),new Object[]{loc,f});
 else   return MessageFormat.format(resources.getString("cell.tooltip.empty"),new Object[]{loc,f});
}
 

Example 39

From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/commands/.

Source file: AbstractGSCommand.java

  29 
vote

/** 
 * Gets a formatted message from the given CLIStatusException, using the exception's reason code as the message name and the exception's args field, if not null.
 * @param e The CLIStatusException to base on
 * @return The formatted message
 */
private String getFormattedMessageFromErrorStatusException(final CLIStatusException e){
  String message=getFormattedMessage(e.getReasonCode(),(Object[])null);
  if (message == null) {
    message=e.getReasonCode();
  }
  if (e.getArgs() == null || e.getArgs().length == 0) {
    return message;
  }
 else {
    return MessageFormat.format(message,e.getArgs());
  }
}
 

Example 40

From project codjo-data-process, under directory /codjo-data-process-gui/src/main/java/net/codjo/dataprocess/gui/launcher/result/.

Source file: HTMLReport.java

  29 
vote

private String getHeaderReport(){
  if (getHeaderPattern() != null && getHeaderArguments() != null) {
    return MessageFormat.format(getHeaderPattern(),getHeaderArguments()) + "<p>";
  }
 else {
    return "";
  }
}
 

Example 41

From project Core_2, under directory /scaffold-faces/src/test/java/org/jboss/forge/scaffold/faces/metawidget/inspector/propertystyle/.

Source file: ForgePropertyStyleTest.java

  29 
vote

@Test public void testAnnotationProxy() throws Exception {
  Project project=initializeJavaProject();
  JavaSourceFacet java=project.getFacet(JavaSourceFacet.class);
  ScaffoldUtil.createOrOverwrite(null,java.getJavaResource("org/jboss/forge/scaffold/faces/metawidget/inspector/propertystyle/MockAnnotatedClass.java"),getClass().getResourceAsStream("/org/jboss/forge/scaffold/faces/metawidget/inspector/propertystyle/MockAnnotatedClass.java"),true);
  ForgePropertyStyle propertyStyle=new ForgePropertyStyle(new ForgePropertyStyleConfig().setProject(project));
  Map<String,Property> properties=propertyStyle.getProperties("org.jboss.forge.scaffold.faces.metawidget.inspector.propertystyle.MockAnnotatedClass");
  Property property=properties.get("mockAnnotatedProperty");
  MockAnnotationSimple mockAnnotationSimple=property.getAnnotation(MockAnnotationSimple.class);
  assertEquals(MockAnnotationSimple.class,mockAnnotationSimple.annotationType());
  assertEquals((byte)1,mockAnnotationSimple.aByte());
  assertEquals((short)2,mockAnnotationSimple.aShort());
  assertEquals(3,mockAnnotationSimple.anInt());
  assertEquals(4l,mockAnnotationSimple.aLong());
  assertEquals(5f,mockAnnotationSimple.aFloat(),0.01);
  assertEquals(0d,mockAnnotationSimple.aDouble(),0.01);
  assertEquals('a',mockAnnotationSimple.aChar());
  assertEquals(false,mockAnnotationSimple.aBoolean());
  assertEquals("",mockAnnotationSimple.aString());
  testMockAnnotationComplex(property);
  propertyStyle=new ForgePropertyStyle(new ForgePropertyStyleConfig().setProject(project).setPrivateFieldConvention(new MessageFormat("m{1}")));
  properties=propertyStyle.getProperties("org.jboss.forge.scaffold.faces.metawidget.inspector.propertystyle.MockAnnotatedClass");
  property=properties.get("mockAnnotatedProperty");
  mockAnnotationSimple=property.getAnnotation(MockAnnotationSimple.class);
  assertEquals(MockAnnotationSimple.class,mockAnnotationSimple.annotationType());
  assertEquals((byte)0,mockAnnotationSimple.aByte());
  assertEquals((short)0,mockAnnotationSimple.aShort());
  assertEquals(0,mockAnnotationSimple.anInt());
  assertEquals(0l,mockAnnotationSimple.aLong());
  assertEquals(0f,mockAnnotationSimple.aFloat(),0.01);
  assertEquals(6d,mockAnnotationSimple.aDouble(),0.01);
  assertEquals('a',mockAnnotationSimple.aChar());
  assertEquals(true,mockAnnotationSimple.aBoolean());
  assertEquals("Foo",mockAnnotationSimple.aString());
  testMockAnnotationComplex(property);
}
 

Example 42

From project core_4, under directory /api/src/main/java/org/ajax4jsf/javascript/.

Source file: PropertyUtils.java

  29 
vote

public static Object readPropertyValue(Object bean,PropertyDescriptor descriptor) throws Exception {
  Method readMethod=descriptor.getReadMethod();
  if (readMethod == null) {
    throw new NoSuchMethodException(MessageFormat.format("Read method for property ''{0}'' not found",descriptor.getName()));
  }
  try {
    return readMethod.invoke(bean);
  }
 catch (  InvocationTargetException e) {
    Throwable cause=e.getCause();
    if (cause instanceof Exception) {
      throw (Exception)cause;
    }
 else     if (cause instanceof Error) {
      throw (Error)cause;
    }
 else {
      throw e;
    }
  }
}