Search Results

Search found 37 results on 2 pages for 'resourcebundle'.

Page 1/2 | 1 2  | Next Page >

  • How do I avoid repetition in Java ResourceBundle strings?

    - by Trejkaz
    We had a lot of strings which contained the same sub-string, from sentences about checking the log or how to contact support, to branding-like strings containing the company or product name. The repetition was causing a few issues for ourselves (primarily typos or copy/paste errors) but it also causes issues in that it increases the amount of text our translator has to translate. The solution I came up with went something like this: public class ExpandingResourceBundleControl extends ResourceBundle.Control { public static final ResourceBundle.Control EXPANDING = new ExpandingResourceBundleControl(); private ExpandingResourceBundleControl() { } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { ResourceBundle inner = super.newBundle(baseName, locale, format, loader, reload); return inner == null ? null : new ExpandingResourceBundle(inner, loader); } } ExpandingResourceBundle delegates to the real resource bundle but performs conversion of {{this.kind.of.thing}} to look up the key in the resources. Every time you want to get one of these, you have to go: ResourceBundle.getBundle("com/acme/app/Bundle", EXPANDING); And this works fine -- for a while. What eventually happens is that some new code (in our case autogenerated code which was spat out of Matisse) looks up the same resource bundle without specifying the custom control. This appears to be non-reproducible if you write a simple unit test which calls it with and then without, but it occurs when the application is run for real. Somehow the cache inside ResourceBundle ejects the good value and replaces it with the broken one. I am yet to figure out why and Sun's jar files were compiled without debug info so debugging it is a chore. My questions: Is there some way of globally setting the default ResourceBundle.Control that I might not be aware of? That would solve everything rather elegantly. Is there some other way of handling this kind of thing elegantly, perhaps without tampering with the ResourceBundle classes at all?

    Read the article

  • List all avilable ResourceBundle Files

    - by shay
    Hello all , i am using ResourceBundle and i want to give the user an option to select a language for the GUI. i want to get a list of all resource files that are under a specific package. i don't know what resource i will have since this application based on plug-ins is there an option to ask from java to search all available resources under a package ? (if no i guess the plug-in should give all available local for it) thank you all

    Read the article

  • Is ResourceBundle fallback resolution broken in Resin3x?

    - by LES2
    Given the following ResourceBundle properties files: messages.properties messages_en.properties messages_es.properties messages_{some locale}.properties Note: messages.properties contains all the messages for the default locale. messages_en.properties is really empty - it's just there for correctness. messages_en.properties will fall back to messages.properties! And given the following config params in web.xml: <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>messages</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name> <param-value>en</param-value> </context-param> I would expect that if the chosen locale is 'es', and a resource is not translated in 'es', then it would fall back to 'en', and finally to 'messages.properties' (since messages_en.properties is empty). This is how things work in Jetty. I've also tested this on WebSphere. Resin Is the Problem The problem is when I get to Resin (3.0.23). Fallback resolution does not work at all! In order to get an messages to display, I must do the following: Rename messages.properties to messages_en.properties (essentially, swap the contents of messages.properties and messages_en.properties) Make sure ever key in messages_en.properties is also defined in messages_{every other locale}.properties (even if the exact same). If I don't do this, I get "???some.key???" in the JSPs. Please help! This is perplexing. -- LES SOLUTION Add following to pom.xml (if you're using maven) ... <properties> <taglibs.version>1.1.2</taglibs.version> </properties> ... <!-- Resin ships with a crappy JSTL implementation that doesn't work with fallback locales for resource bundles correctly; we therefore include our own JSTL implementation in the WAR, and avoid this problem. This can be removed if the target container is not resin. --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibs.version}</version> <scope>compile</scope> </dependency>

    Read the article

  • IntelliJ: Adding resources to the class path, but still gives me "java.util.MissingResourceException: Can't find bundle.... locale en_US"

    - by Martin
    I am quite new to intellij and i have loaded in a project that i wish to compile, everything seems to be going well, but when i compile it. I get the bundle cannot be found. java.util.MissingResourceException: Can't find bundle for base name openfire_i18n, locale en_US at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499) After doing some investigation, it appears i have to include the resources in the class path, is this correct? I have done Project Settings, Modules, Dependencies, and i added a "Jars or directories" There is a checkbox that says Export, i have tried clicking it and unclicking it :-) My resources i can see are in i8n\ResourceBundle I tried adding the i8n and it asked me for a category for selected files, i put classes RUN - but still same error.. so i tried adding the i8n/ResourceBundle directory RUN - still same error. I notice under my ResourceBundle directory there are C:\Dev\Java\openfire_src_3_7_1\openfire_src\src\i18n\openfire_i18n_en.properties but there is no specific en_US but i thought it supposed to fallback to EN ?? SO i think everything is ok. Can anyone help I am really stuck Thanks

    Read the article

  • [java] Trying to use ResourceBundle to fetch messages from external file

    - by bumperbox
    Essentially I would like to have a messages.properties files external to the jar files in my application. So that users can add languages and edit the files easily if my translations are wrong at the moment i use ResourceBundle.getBundle("package.MessageBundle"); But i would like to do something like this ResourceBundle.getBundle("lang/MessageBundle"); Where lang is a folder under my application installation directory. is this a good idea (if not, why not)? can someone point me in the right direction, or some sample code that does this thanks Alex

    Read the article

  • JSF:Resourcebundle Problem with Internationalization

    - by Sven
    I implemented internationalization like in that tutorial! When I change the language in my app. It works. But only until the next request happens. Then language settings are reset to my standard language -.- What am I missing here: LanguageBean.java @ManagedBean(name="language") @SessionScoped public class LanguageBean implements Serializable{ private static final long serialVersionUID = 1L; private String localeCode; private static Map<String,Object> countries; static{ countries = new LinkedHashMap<String,Object>(); countries.put("Deutsch", Locale.GERMAN); //label, value countries.put("English", Locale.ENGLISH); } public Map<String, Object> getCountriesInMap() { return countries; } public String getLocaleCode() { return localeCode; } public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } //value change event listener public void countryLocaleCodeChanged(ValueChangeEvent e){ String newLocaleValue = e.getNewValue().toString(); //loop country map to compare the locale code for (Map.Entry<String, Object> entry : countries.entrySet()) { if(entry.getValue().toString().equals(newLocaleValue)){ FacesContext.getCurrentInstance() .getViewRoot().setLocale((Locale)entry.getValue()); } } } } my facelets template: <h:selectOneMenu value="#{language.localeCode}" onchange="submit()" valueChangeListener="#{language.countryLocaleCodeChanged}"> <f:selectItems value="#{language.countriesInMap}" /> </h:selectOneMenu> faces-config: <application> <locale-config> <default-locale>de</default-locale> </locale-config> <resource-bundle> <base-name>org.dhbw.stg.wwi2008c.mopro.ui.text</base-name> <var>msg</var> </resource-bundle> </application>

    Read the article

  • JSF2 ResourceBundleLoader override?

    - by CDSO1
    I need to have resource messages that contain EL expressions be resolved when loaded from a ResourceBundle. Basically I have a number of properties files containing the text. Some of the text will look like the following: welcomeText=Welcome #{userbean.name} The only possible way I can see this working currently is implementing a custom taglib so that instead of saying: <f:loadBundle var="messages" basename="application.messages"/> I would have to use <mytaglib:loadBundle var="messages" basename="application.messages"/> #{messages.welcomeText} Given a user with username "User1", this should output Welcome User1 My implementation would then use a custom ResourceBundle class that would override handleGetObject, use the ELResolver to resolve variables etc....Ideas? suggestings? Implementations that are already available? I appreciate your assistance.

    Read the article

  • How to load a resource bundle from a file resource in Java?

    - by user143794
    I have a file called mybundle.txt in c:/temp - c:/temp/mybundle.txt how do I load this file into a java.util.resource bundle? The file is a valid resource bundle. This does not seem to work: java.net.URL resourceURL = null; String path = "c:/temp/mybundle.txt"; java.io.File fl = new java.io.File(path); try { resourceURL = fl.toURI().toURL(); } catch (MalformedURLException e) { } URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL}); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle( path , java.util.Locale.getDefault(), urlLoader ); What is the best way to do this?

    Read the article

  • No properties file found Error for ReloadableResourceBundleMessageSource

    - by samspot
    I'm trying to use a reloadable spring resource bundle but spring cannot find the file. I've tried tons of different paths, but can't get it to work anywhere. In the code below you'll see that i load both the spring bundle and the regular one from the same path variable but only one works. I've been banging my head against this for far too long. Anybody have any ideas? logfile INFO 2010-04-28 11:38:31,805 [main] org.myorg.test.TestMessages: C:\www\htdocs\messages.properties INFO 2010-04-28 11:38:31,805 [main] org.myorg.data.Messages: initializing Spring Message Source to C:\www\htdocs\messages.properties INFO 2010-04-28 11:38:31,821 [main] org.myorg.data.Messages: Attempting to load properties from C:\www\htdocs\messages.properties DEBUG 2010-04-28 11:38:31,836 [main] org.springframework.context.support.ReloadableResourceBundleMessageSource: No properties file found for [C:\www\htdocs\messages.properties_en_US] - neither plain properties nor XML DEBUG 2010-04-28 11:38:31,842 [main] org.springframework.context.support.ReloadableResourceBundleMessageSource: No properties file found for [C:\www\htdocs\messages.properties_en] - neither plain properties nor XML DEBUG 2010-04-28 11:38:31,848 [main] org.springframework.context.support.ReloadableResourceBundleMessageSource: No properties file found for [C:\www\htdocs\messages.properties] - neither plain properties nor XML INFO 2010-04-28 11:38:31,848 [main] org.myorg.test.TestMessages: I am C:\www\htdocs\messages.properties Messages.java package org.myorg.data; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.ReloadableResourceBundleMessageSource; public class Messages { protected static final Log logger = LogFactory.getLog(Messages.class); private static ReloadableResourceBundleMessageSource msgSource = null; private static ResourceBundle RESOURCE_BUNDLE; public static final String PATH = "C:" + File.separator + "www" + File.separator + "htdocs" + File.separator + "messages.properties"; private Messages() { } public static String getString(String key) { initBundle(); return msgSource.getMessage(key, null, RESOURCE_BUNDLE.getString(key), null); } private static void initBundle(){ if(null == msgSource || null == RESOURCE_BUNDLE){ logger.info("initializing Spring Message Source to " + PATH); msgSource = new ReloadableResourceBundleMessageSource(); msgSource.setBasename(PATH); msgSource.setCacheSeconds(1); /* works, but you have to hardcode the platform dependent path starter. It also does not cache */ FileInputStream fis = null; try { logger.info("Attempting to load properties from " + PATH); fis = new FileInputStream(PATH); RESOURCE_BUNDLE = new PropertyResourceBundle(fis); } catch (Exception e) { logger.info("couldn't find " + PATH); } finally { try { if(null != fis) fis.close(); } catch (IOException e) { } } } } } TestMessages.java package org.myorg.test; import org.myorg.data.Messages; public class TestMessages extends AbstractTest { public void testMessage(){ logger.info(Messages.PATH); logger.info(Messages.getString("OpenKey.TEST")); } }

    Read the article

  • How to create a bundle

    - by flohei
    Hi there, how do I create a bundle with resources like images and xibs to share it between apps? I saw that there's a way to do it when creating a new project, but there must be a way to do it based on a finished project, right? Thanks in advance –f

    Read the article

  • java.util.MissingResourceException

    - by ashwani66476
    Hello Crew I am getting below exception while running an application. This application read abc.properties file, Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name abc, locale en_US at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:853) at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:822) at java.util.ResourceBundle.getBundle(ResourceBundle.java:566) at com.ibm.dst.DailyExtract.getResourceBundle(DailyExtract.java:104) at com.ibm.dst.DailyExtract.main(DailyExtract.java:131) abc.properties file reside at the workspace. I am using RSA7 as IDE, is there any setting problem? any suggestions are welcome..... Thanks a lot in advance

    Read the article

  • Internationalization in a website

    - by bhardwaj
    Dear All, I m using ResourceBundle method getBundle(Propertyfilename,Local.languagename) class which returns an object of ResourceBundle of the local rb = ResourceBundle.get Bundle("Locale Strings", Locale.ARABIC);-Not Supported How can i use this to support arabic,band english.

    Read the article

  • where to put .properties files in an Eclipse project?

    - by Jason S
    I have a very simple properties file test I am trying to get working: (the following is TestProperties.java) package com.example.test; import java.util.ResourceBundle; public class TestProperties { public static void main(String[] args) { ResourceBundle myResources = ResourceBundle.getBundle("TestProperties"); for (String s : myResources.keySet()) { System.out.println(s); } } } and TestProperties.properties in the same directory: something=this is something something.else=this is something else which I have also saved as TestProperties_en_US.properties When I run TestProperties.java from Eclipse, it can't find the properties file: java.util.MissingResourceException: Can't find bundle for base name TestProperties, locale en_US Am I doing something wrong?

    Read the article

  • What would be a correct implemantation of JSF Converter if I need to get an Integer to run a query?

    - by Ignacio
    HI here's my code: List.xhmtl <h:selectOneMenu value="#{produtosController.items}"> <f:selectItems value="#{produtosController.itemsAvailableSelectOne}"/> </h:selectOneMenu> <h:commandButton action="#{produtosController.createByCodigos}" value="Buscar" /> My Controller Class with innner Converter implemantation @ManagedBean (name="produtosController") @SessionScoped public class ProdutosController { private Produtos current; private DataModel items = null; @EJB private controladores.ProdutosFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public ProdutosController() { } public Produtos getSelected() { if (current == null) { current = new Produtos(); selectedItemIndex = -1; } return current; } private ProdutosFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem()+getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Produtos)getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Produtos(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProdutosCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String createByMarcas() { items = new ListDataModel(ejbFacade.findByMarcas(current.getIdMarca())); updateCurrentItem(); return "List"; } public String createByModelos() { items = new ListDataModel(ejbFacade.findByModelos(current.getIdModelo())); updateCurrentItem(); return "List"; } public String createByCodigos(){ items = new ListDataModel(ejbFacade.findByCodigo(current.getCodigo())); updateCurrentItem(); return "List"; } public String prepareEdit() { current = (Produtos)getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProdutosUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Produtos)getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProdutosDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count-1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex+1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass=Produtos.class) public static class ProdutosControllerConverter implements Converter{ public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } ProdutosController controller = (ProdutosController)facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "produtosController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.decode(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Produtos) { Produtos o = (Produtos) object; return getStringKey(o.getCodigo()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+ProdutosController.class.getName()); } } } } and my EJB @Entity @ViewScoped @Table(name = "produtos") @NamedQueries({ @NamedQuery(name = "Produtos.findAll", query = "SELECT p FROM Produtos p"), @NamedQuery(name = "Produtos.findById", query = "SELECT p FROM Produtos p WHERE p.id = :id"), @NamedQuery(name = "Produtos.findByCodigo", query = "SELECT p FROM Produtos p WHERE p.codigo = :codigo"), @NamedQuery(name = "Produtos.findByDescripcion", query = "SELECT p FROM Produtos p WHERE p.descripcion = :descripcion"), @NamedQuery(name = "Produtos.findByImagen", query = "SELECT p FROM Produtos p WHERE p.imagen = :imagen"), @NamedQuery(name = "Produtos.findByMarcas", query="SELECT m FROM Produtos m WHERE m.idMarca.id = :idMarca"), @NamedQuery(name = "Produtos.findByModelos", query="SELECT m FROM Produtos m WHERE m.idModelo.id = :idModelo")}) public class Produtos implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "codigo") private Integer codigo; @Column(name = "descripcion") private String descripcion; @Column(name = "imagen") private String imagen; @JoinColumn(name = "id_modelo", referencedColumnName = "id") @ManyToOne(optional = false) private Modelos idModelo; @JoinColumn(name = "id_marca", referencedColumnName = "id") @ManyToOne(optional = false) private Marcas idMarca; public Produtos() { } public Produtos(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCodigo() { return codigo; } public void setCodigo(Integer codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public Modelos getIdModelo() { return idModelo; } public void setIdModelo(Modelos idModelo) { this.idModelo = idModelo; } public Marcas getIdMarca() { return idMarca; } public void setIdMarca(Marcas idMarca) { this.idMarca = idMarca; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Produtos)) { return false; } Produtos other = (Produtos) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "" + codigo + ""; } }

    Read the article

  • How to Plug a Small Hole in NetBeans JSF (Join Table) Code Generation

    - by MarkH
    I was asked recently to provide an assist with designing and building a small-but-vital application that had at its heart some basic CRUD (Create, Read, Update, & Delete) functionality, built upon an Oracle database, to be accessible from various locations. Working from the stated requirements, I fleshed out the basic application and database designs and, once validated, set out to complete the first iteration for review. Using SQL Developer, I created the requisite tables, indices, and sequences for our first run. One of the tables was a many-to-many join table with three fields: one a primary key for that table, the other two being primary keys for the other tables, represented as foreign keys in the join table. Here is a simplified example of the trio of tables: Once the database was in decent shape, I fired up NetBeans to let it have first shot at the code. NetBeans does a great job of generating a mountain of essential code, saving developers what must be millions of hours of effort each year by building a basic foundation with a few clicks and keystrokes. Lest you think it (or any tool) can do everything for you, however, occasionally something tosses a paper clip into the delicate machinery and makes you open things up to fix them. Join tables apparently qualify.  :-) In the case above, the entity class generated for the join table (New Entity Classes from Database) included an embedded object consisting solely of the two foreign key fields as attributes, in addition to an object referencing each one of the "component" tables. The Create page generated (New JSF Pages from Entity Classes) worked well to a point, but when trying to save, we were greeted with an error: Transaction aborted. Hmm. A quick debugger session later and I'd identified the issue: when trying to persist the new join-table object, the embedded "foreign-keys-only" object still had null values for its two (required value) attributes...even though the embedded table objects had populated key attributes. Here's the simple fix: In the join-table controller class, find the public String create() method. It will look something like this:     public String create() {        try {            getFacade().create(current);            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("JoinEntityCreated"));            return prepareCreate();        } catch (Exception e) {            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));            return null;        }    } To restore balance to the force, modify the create() method as follows (changes in red):     public String create() {         try {            // Add the next two lines to resolve:            current.getJoinEntityPK().setTbl1id(current.getTbl1().getId().toBigInteger());            current.getJoinEntityPK().setTbl2id(current.getTbl2().getId().toBigInteger());            getFacade().create(current);            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("JoinEntityCreated"));            return prepareCreate();        } catch (Exception e) {            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));            return null;        }    } I'll be refactoring this code shortly, but for now, it works. Iteration one is complete and being reviewed, and we've met the milestone. Here's to happy endings (and customers)! All the best,Mark

    Read the article

  • Include static file in JSP with variable filename on WebSphere 6

    - by cringe
    I'm struggling with including a static file into my JSPs on Websphere 6.0.2.17. I tried this: <% final String MY_DIR = ResourceBundle.getBundle("mybundle").getString("props.pages.wcm"); %> <% final String page = ResourceBundle.getBundle("mybundle").getString("page"); %> <% final String inc = MY_DIR + "/" + bonus; %> <%@include file="<%= inc %>"%> The path is /wcm/some/other/dir/page and I can happily print that out with out.write(inc). Unfortunatly the include (and the jsp:include) isn't including the file at all. There is no error message, but the content isn't included... The file is accessible via the browser though. Do I have to create a full JSP for this to work? I just need a HTML file.

    Read the article

  • Object as itemValue in <f:selectItems>

    - by Ehsun
    Is it possible to have objects as itemValue in tag? for example I have a class Foo: public class Foo { private int id; private String name; private Date date; } And another class Bar public class Bar { private Foo foos; } public class BarBean { private Set<Foo> foos; } Now in a Bean called BarBean I need to have a to get the Foo of the current Bar from User like this: <h:selectOneMenu value="#{barBean.bar.foo}" required="true"> <f:selectItems value="#{barBean.foos}" var="foo" itemLabel="#{foo.name}" itemValue="#{foo}" /> </h:selectOneMenu> ---------------edited: my converter: package ir.khorasancustoms.g2g.converters; import ir.khorasancustoms.g2g.persistance.CatalogValue; import java.util.ResourceBundle; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; @FacesConverter("ir.khorasancustoms.CatalogValueConverter") public class CatalogValueConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); try { int id = Integer.parseInt(value); CatalogValue catalogValue = (CatalogValue) session.load(CatalogValue .class, id); return catalogValue; } catch (Exception ex) { Transaction tx = session.getTransaction(); if (tx.isActive()) { tx.rollback(); } ResourceBundle rb = ResourceBundle.getBundle("application"); String message = rb.getString("databaseConnectionFailed"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message)); } finally { session.close(); } return null; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { return ((CatalogValue) value).getId() + ""; } } and my facelet: <h:outputText value="#{lbls.paymentUnit}:"/> <h:selectOneMenu id="paymentUnit" label="#{lbls.paymentUnit}" value="#{price.price.ctvUnit}" required="true"> <f:selectItems value="#{price.paymentUnits}"/> <f:converter converterId="ir.khorasancustoms.CatalogValueConverter"/> </h:selectOneMenu> <h:message for="paymentUnit" infoClass="info" errorClass="error" warnClass="warning" fatalClass="fatal"/>

    Read the article

  • Actionscript project that loads a Flex SWF, "Could not find resource bundle" Error when using Layout

    - by Leeron
    Hi guys. I'm using an actionsciprt only project (under FlashDevelop) to load an .swf flex file built by another department of the company I work for. Using the follwing code: var mLoader:Loader = new Loader(); var mRequest:URLRequest = new URLRequest('flexSWF.swf'); mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler); mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler); mLoader.load(mRequest); That worked fine until I wanted to use Flex's mx.managers.LayoutManager. I've added the this line to my class: import mx.managers.ILayoutManagerClient; import mx.managers.LayoutManager; . . . private var _layoutManager:LayoutManager; And I get this run time error: Error: Could not find resource bundle messaging at mx.resources::ResourceBundle$/getResourceBundle()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\resources\ResourceBundle.as:143] at mx.utils::Translator$cinit() at global$init() at mx.messaging.config::ServerConfig$cinit() at global$init() at _app_FlexInit$/init() at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:3217] at mx.managers::SystemManager/docFrameListener()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:3069] commenting the LayoutManager line, the swf works fine. But I do want to use LayoutManager. Any hints?

    Read the article

  • How to read properties file in Greek using Java

    - by Subhendu Mahanta
    I am trying to read from a properties file which have keys in English & values in greek.My code is like this: public class I18NSample { static public void main(String[] args) { String language; String country; if (args.length != 2) { language = new String("el"); country = new String("GR"); } else { language = new String(args[0]); country = new String(args[1]); } Locale currentLocale; ResourceBundle messages; currentLocale = new Locale(language, country); messages = ResourceBundle.getBundle("MessagesBundle",currentLocale, new CustomClassLoader("E:\\properties")); System.out.println(messages.getString("greetings")); System.out.println(messages.getString("inquiry")); System.out.println(messages.getString("farewell")); } } import java.io.File; import java.net.MalformedURLException; import java.net.URL; public class CustomClassLoader extends ClassLoader { private String path; public CustomClassLoader(String path) { super(); this.path = path; } @Override protected URL findResource(String name) { File f = new File(path + File.separator + name); try { return f.toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } return super.findResource(name); } } MessagesBundle_el_GR.properties greetings=??µ. ?a??et? farewell=ep?f. a?t?? inquiry=t? ???e?s, t? ???ete I am compiling like this javac -encoding UTF8 CustomClassLoader.java javac -encoding UTF8 I18Sample.java When I run this I get garbled output.If the properies file is in English,French or German it works fine. Please help. Regards, Subhendu

    Read the article

  • Is Java's ElementCollection Considered a Bad Practice?

    - by SoulBeaver
    From my understanding, an ElementCollection has no primary key, is embedded with the class, and cannot be queried. This sounds pretty hefty, but it allows me the comfort of writing an enum class which also helps with internationalization (using the enum key for lookup in my ResourceBundle). Example: We have a user on a media site and he can choose in which format he downloads the files @Entity @Table(name = "user") public class User { /* snip other fields */ @Enumerated @ElementCollection( targetClass = DownloadFilePreference.class, fetch = FetchType.EAGER ) @CollectionTable(name = "download_file_preference", joinColumns = @JoinColumn(name = "user_id") ) @Column(name = "name") private Set<DownloadFilePreference> downloadFilePreferences = new HashSet<>(); } public enum DownloadFilePreference { MP3, WAV, AIF, OGG; } This seems pretty great to me, and I suppose it comes down to "it depends on your use case", but I also know that I'm quite frankly only an initiate when it comes to Database design. Some best practices suggest to never have a class without a primary key- even in this case? It also doesn't seem very extensible- should I use this and gamble on the chance I will never need to query on the FilePreferences?

    Read the article

  • NetBeans, JSF, and MySQL Primary Keys using AUTO_INCREMENT

    - by MarkH
    I recently had the opportunity to spin up a small web application using JSF and MySQL. Having developed JSF apps with Oracle Database back-ends before and possessing some small familiarity with MySQL (sans JSF), I thought this would be a cakewalk. Things did go pretty smoothly...but there was one little "gotcha" that took more time than the few seconds it really warranted. The Problem Every DBMS has its own way of automatically generating primary keys, and each has its pros and cons. For the Oracle Database, you use a sequence and point your Java classes to it using annotations that look something like this: @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="POC_ID_SEQ") @SequenceGenerator(name="POC_ID_SEQ", sequenceName="POC_ID_SEQ", allocationSize=1) Between creating the actual sequence in the database and making sure you have your annotations right (watch those typos!), it seems a bit cumbersome. But it typically "just works", without fuss. Enter MySQL. Designating an integer-based field as PRIMARY KEY and using the keyword AUTO_INCREMENT makes the same task seem much simpler. And it is, mostly. But while NetBeans cranks out a superb "first cut" for a basic JSF CRUD app, there are a couple of small things you'll need to bring to the mix in order to be able to actually (C)reate records. The (RUD) performs fine out of the gate. The Solution Omitting all design considerations and activity (!), here is the basic sequence of events I followed to create, then resolve, the JSF/MySQL "Primary Key Perfect Storm": Fire up NetBeans. Create JSF project. Create Entity Classes from Database. Create JSF Pages from Entity Classes. Test run. Try to create record and hit error. It's a simple fix, but one that was fun to find in its completeness. :-) Even though you've told it what to do for a primary key, a MySQL table requires a gentle nudge to actually generate that new key value. Two things are needed to make the magic happen. First, you need to ensure the following annotation is in place in your Java entity classes: @GeneratedValue(strategy = GenerationType.IDENTITY) All well and good, but the real key is this: in your controller class(es), you'll have a create() function that looks something like this, minus the comment line and the setId() call in bold red type:     public String create() {         try {             // Assign 0 to ID for MySQL to properly auto_increment the primary key.             current.setId(0);             getFacade().create(current);             JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CategoryCreated"));             return prepareCreate();         } catch (Exception e) {             JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));             return null;         }     } Setting the current object's primary key attribute to zero (0) prior to saving it tells MySQL to get the next available value and assign it to that record's key field. Short and simple…but not inherently obvious if you've never used that particular combination of NetBeans/JSF/MySQL before. Hope this helps! All the best, Mark

    Read the article

  • javaf, problem...plz help someone...urgent [closed]

    - by innovative_aj
    i have made a word guessing game, when i click myButton to check if the guessed word is right or wrong, ball1 is moved into the "container" if its right, i want that when i click the button again and if the typed word is right, the 2nd ball should move into the container too... means one ball per correct answer...plz help me someone and provide me with the code that i can implement, its quite urgent... controller class coding /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package project3; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.StackPane; import javafx.scene.shape.Circle; /** * FXML Controller class * * @xxx */ public class MyFxmlController implements Initializable { @FXML // fx:id="ball1" private Circle ball1; // Value injected by FXMLLoader @FXML // fx:id="ball2" private Circle ball2; // Value injected by FXMLLoader @FXML // fx:id="ball3" private Circle ball3; // Value injected by FXMLLoader @FXML // fx:id="ball4" private Circle ball4; // Value injected by FXMLLoader @FXML // fx:id="container" private Circle container; // Value injected by FXMLLoader @FXML // fx:id="myButton" private Button myButton; // Value injected by FXMLLoader @FXML // fx:id="myLabel1" private Label myLabel1; // Value injected by FXMLLoader @FXML // fx:id="myLabel2" private Label myLabel2; // Value injected by FXMLLoader @FXML // fx:id="pane" private StackPane pane; // Value injected by FXMLLoader @FXML // fx:id="txt" private TextField txt; // Value injected by FXMLLoader @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { assert ball1 != null : "fx:id=\"ball1\" was not injected: check your FXML file 'MyFxml.fxml'."; assert ball2 != null : "fx:id=\"ball2\" was not injected: check your FXML file 'MyFxml.fxml'."; assert ball3 != null : "fx:id=\"ball3\" was not injected: check your FXML file 'MyFxml.fxml'."; assert ball4 != null : "fx:id=\"ball4\" was not injected: check your FXML file 'MyFxml.fxml'."; assert container != null : "fx:id=\"container\" was not injected: check your FXML file 'MyFxml.fxml'."; assert myButton != null : "fx:id=\"myButton\" was not injected: check your FXML file 'MyFxml.fxml'."; assert myLabel1 != null : "fx:id=\"myLabel1\" was not injected: check your FXML file 'MyFxml.fxml'."; assert myLabel2 != null : "fx:id=\"myLabel2\" was not injected: check your FXML file 'MyFxml.fxml'."; assert pane != null : "fx:id=\"pane\" was not injected: check your FXML file 'MyFxml.fxml'."; assert txt != null : "fx:id=\"txt\" was not injected: check your FXML file 'MyFxml.fxml'."; // initialize your logic here: all @FXML variables will have been injected myButton.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event) { int count = 0; String guessed=txt.getText(); boolean result; result=MyCode.check(guessed); if(result) { ball1.setTranslateX(600); ball1.setTranslateY(250-container.getRadius()); //ball2.setTranslateX(600); // ball2.setTranslateY(250-container.getRadius()); } else System.out.println("wrong"); } }); } } word guessing logic public class MyCode { static String x="Netbeans"; static String y[]={"net","beans","neat","beat","bet"}; //static int counter; // public MyCode() { // counter++; //} static boolean check(String guessed) { int count=0; boolean result=false; //counter++; //System.out.println("turns"+counter); for(count=0;count<5;count++) { if(guessed.equals(y[count])) { result=true; break; } } if(result) System.out.println("Right"); else System.out.println("Wrong"); return result; } }

    Read the article

  • java.lang.Error: "Not enough storage is available to process this command" when generating images

    - by jhericks
    I am running a web application on BEA Weblogic 9.2. Until recently, we were using JDK 1.5.0_04, with JAI 1.1.2_01 and Image IO 1.1. In some circumstances (we never figured out exactly why), when we were processing large images (but not that large - a few MB), the JVM would crash without any error message or stack trace or anything. This didn't happen much in production, but enough to be a nuisance and eventually we were able to reproduce it. We decided to switch to JRockit90 1.5.0_04 and we were no longer able to reproduce the problem in our test environment, so we thought we had it licked. Now, however, after the application server has been up for a while, we start getting the error message, "Not enough storage is available to process this command" during image operations. For example: java.lang.Error: Error starting thread: Not enough storage is available to process this command. at java.lang.Thread.start()V(Unknown Source) at sun.awt.image.ImageFetcher$1.run(ImageFetcher.java:279) at sun.awt.image.ImageFetcher.createFetchers(ImageFetcher.java:272) at sun.awt.image.ImageFetcher.add(ImageFetcher.java:55) at sun.awt.image.InputStreamImageSource.startProduction(InputStreamImageSource.java:149) at sun.awt.image.InputStreamImageSource.addConsumer(InputStreamImageSource.java:106) at sun.awt.image.InputStreamImageSource.startProduction(InputStreamImageSource.java:144) at sun.awt.image.ImageRepresentation.startProduction(ImageRepresentation.java:647) at sun.awt.image.ImageRepresentation.prepare(ImageRepresentation.java:684) at sun.awt.SunToolkit.prepareImage(SunToolkit.java:734) at java.awt.Component.prepareImage(Component.java:3073) at java.awt.ImageMediaEntry.startLoad(MediaTracker.java:906) at java.awt.MediaEntry.getStatus(MediaTracker.java:851) at java.awt.ImageMediaEntry.getStatus(MediaTracker.java:902) at java.awt.MediaTracker.statusAll(MediaTracker.java:454) at java.awt.MediaTracker.waitForAll(MediaTracker.java:405) at java.awt.MediaTracker.waitForAll(MediaTracker.java:375) at SfxNET.System.Drawing.ImageLoader.loadImage(Ljava.awt.Image;)Ljava.awt.image.BufferedImage;(Unknown Source) at SfxNET.System.Drawing.ImageLoader.loadImage(Ljava.net.URL;)Ljava.awt.image.BufferedImage;(Unknown Source) at Resources.Tools.Commands.W$zw(Ljava.lang.ClassLoader;)V(Unknown Source) at Resources.Tools.Commands.getContents()[[Ljava.lang.Object;(Unknown Source) at SfxNET.sfxUtils.SfxResourceBundle.handleGetObject(Ljava.lang.String;)Ljava.lang.Object;(Unknown Source) at java.util.ResourceBundle.getObject(ResourceBundle.java:320) at SoftwareFX.internal.ChartFX.wxvw.yxWW(Ljava.lang.String;Z)Ljava.lang.Object;(Unknown Source) at SoftwareFX.internal.ChartFX.wxvw.vxWW(Ljava.lang.String;)Ljava.lang.Object;(Unknown Source) at SoftwareFX.internal.ChartFX.CommandBar.YWww(LSoftwareFX.internal.ChartFX.wxvw;IIII)V(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.xxvw.YzzW(LSoftwareFX.internal.ChartFX.Internet.Server.ChartCore;Z)LSoftwareFX.internal.ChartFX.CommandBar;(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.xxvw.XzzW(LSoftwareFX.internal.ChartFX.Internet.Server.ChartCore;)V(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.ChartCore.OnDeserialization(Ljava.lang.Object;)V(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.ChartCore.Zvvz(LSoftwareFX.internal.ChartFX.Base.wzzy;)V(Unknown Source) Has anyone seen something like this before? Any clue what might be happening?

    Read the article

1 2  | Next Page >