Search Results

Search found 399 results on 16 pages for 'kerrek sb'.

Page 12/16 | < Previous Page | 8 9 10 11 12 13 14 15 16  | Next Page >

  • How to configure a Custom Datacontract Serializer or XMLSerializer

    - by user364445
    Im haveing some xml that have this structure <Person Id="*****" Name="*****"> <AccessControlEntries> <AccessControlEntry Id="*****" Name="****"/> </AccessControlEntries> <AccessControls /> <IdentityGroups> <IdentityGroup Id="****" Name="*****" /> </IdentityGroups></Person> and i also have this entities [DataContract(IsReference = true)] public abstract class EntityBase { protected bool serializing; [DataMember(Order = 1)] [XmlAttribute()] public string Id { get; set; } [DataMember(Order = 2)] [XmlAttribute()] public string Name { get; set; } [OnDeserializing()] public void OnDeserializing(StreamingContext context) { this.Initialize(); } [OnSerializing()] public void OnSerializing(StreamingContext context) { this.serializing = true; } [OnSerialized()] public void OnSerialized(StreamingContext context) { this.serializing = false; } public abstract void Initialize(); public string ToXml() { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); } return sb.ToString(); } } [DataContract()] public abstract class Identity : EntityBase { private EntitySet<AccessControlEntry> accessControlEntries; private EntitySet<IdentityGroup> identityGroups; public Identity() { Initialize(); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "AccessControlEntries")] public EntitySet<AccessControlEntry> AccessControlEntries { get { if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false))) { return null; } return accessControlEntries; } set { accessControlEntries.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] [Association(Name = "IdentityGroups")] public EntitySet<IdentityGroup> IdentityGroups { get { if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false))) { return null; } return identityGroups; } set { identityGroups.Assign(value); } } private void attach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Add(this); } private void dettach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Remove(this); } private void attach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } private void dettach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } public override void Initialize() { this.accessControlEntries = new EntitySet<AccessControlEntry>( new Action<AccessControlEntry>(this.attach_accessControlEntry), new Action<AccessControlEntry>(this.dettach_accessControlEntry)); this.identityGroups = new EntitySet<IdentityGroup>( new Action<IdentityGroup>(this.attach_IdentityGroup), new Action<IdentityGroup>(this.dettach_IdentityGroup)); } } [XmlType(TypeName = "AccessControlEntry")] public class AccessControlEntry : EntityBase, INotifyPropertyChanged { private EntitySet<Service> services; private EntitySet<Identity> identities; private EntitySet<Permission> permissions; public AccessControlEntry() { services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service)); identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity)); permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission)); } [DataMember(Order = 3, EmitDefaultValue = false)] public EntitySet<Permission> Permissions { get { if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false))) { return null; } return permissions; } set { permissions.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] public EntitySet<Identity> Identities { get { if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false))) { return null; } return identities; } set { identities.Assign(identities); } } [DataMember(Order = 5, EmitDefaultValue = false)] public EntitySet<Service> Services { get { if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false))) { return null; } return services; } set { services.Assign(value); } } private void attach_Permission(Permission entity) { entity.AccessControlEntires.Add(this); } private void dettach_Permission(Permission entity) { entity.AccessControlEntires.Remove(this); } private void attach_Identity(Identity entity) { entity.AccessControlEntries.Add(this); } private void dettach_Identity(Identity entity) { entity.AccessControlEntries.Remove(this); } private void attach_Service(Service entity) { entity.AccessControlEntries.Add(this); } private void dettach_Service(Service entity) { entity.AccessControlEntries.Remove(this); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } #endregion public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "Person")] public class Person : Identity { private EntityRef<Login> login; [DataMember(Order = 3)] [XmlAttribute()] public string Nombre { get; set; } [DataMember(Order = 4)] [XmlAttribute()] public string Apellidos { get; set; } [DataMember(Order = 5)] public Login Login { get { return login.Entity; } set { var previousValue = this.login.Entity; if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.login.Entity = null; previousValue.Person = null; } this.login.Entity = value; if ((value != null)) value.Person = this; } } } public override void Initialize() { base.Initialize(); } } [DataContract()] [XmlType(TypeName = "Login")] public class Login : EntityBase { private EntityRef<Person> person; [DataMember(Order = 3)] public string UserID { get; set; } [DataMember(Order = 4)] public string Contrasena { get; set; } [DataMember(Order = 5)] public Domain Dominio { get; set; } public Person Person { get { return person.Entity; } set { var previousValue = this.person.Entity; if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.person.Entity = null; previousValue.Login = null; } this.person.Entity = value; if ((value != null)) value.Login = this; } } } public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "IdentityGroup")] public class IdentityGroup : Identity { private EntitySet<Identity> memberIdentities; public IdentityGroup() { Initialize(); } public override void Initialize() { this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity)); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "MemberIdentities")] public EntitySet<Identity> MemberIdentites { get { if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false))) { return null; } return memberIdentities; } set { memberIdentities.Assign(value); } } private void attach_Identity(Identity entity) { entity.IdentityGroups.Add(this); } private void dettach_Identity(Identity entity) { entity.IdentityGroups.Remove(this); } } [DataContract()] [XmlType(TypeName = "Group")] public class Group : Identity { public override void Initialize() { throw new NotImplementedException(); } } but the ToXml() response something like this <Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person> but what i want is something like this <Person Id="****" Name="***" Nombre="****"> <AccessControlEntries/> <IdentityGroups/> </Person>

    Read the article

  • ASP.NET File Picker

    - by Patrick
    I am trying to find a File Picker that runs on ASPX.Net. I need it to insert images in TinyMCE since the one with TinyMCE is licensed. I have been looking for a Silverlight solution, like Silverlight Bridge. I tried to implement SLFileManager that is based on SB, but with little success. I need to be able to upload images, delete/rename etc and also insert the image inside TinyMCE. Any ideas?

    Read the article

  • change cat-art.php into cat/art.php

    - by user338635
    Hi i got a problem with changing urls. I have files: cat-art.php (cat- category, art- title of an article) and i would like to have nicer access to them: cat/art.php so i wrote some code in .htaccess but it doesnt work. RewriteCond %{REQUEST_URI} ^/([^-]+)/([^-]+).html$ RewriteRule ^([^-]+)/([^-]+).html$ $1-$2.html [L] Can sb help me please? Thanks for your help

    Read the article

  • Raw XML Push from input stream captures only the first line of XML

    - by pqsk
    I'm trying to read XML that is being pushed to my java app. I originally had this in my glassfish server working. The working code in glassfish is as follows: public class XMLPush implements Serializable { public void processXML() { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getReader (); String s = null; while((s = br.readLine ()) != null) { sb.append ( s ); } //other code to process xml ........... ............................. }catch(Exception ex) { XMLCreator.exceptionOutput ( "processXML","Exception",ex); } .... ..... }//processXML }//class It works perfect, but my client is unable to have glassfish on their server. I tried grabbing the raw xml from php, but I couldn't get it to work. I decided to open up a socket and listen for the xml push manually. Here is my code for receiving the push: public class ListenerService extends Thread { private BufferedReader reader = null; private String line; public ListenerService ( Socket connection )thows Exception { this.reader = new BufferedReader ( new InputStreamReader ( connection.getInputStream () ) ); this.line = null; }//ListenerService @Override public void run () { try { while ( (this.line = this.reader.readLine ()) != null) { System.out.println ( this.line ); ........ }//while } System.out.println ( ex.toString () ); } } catch ( Exception ex ) { ... }//catch }//run I haven't done much socket programing, but from what I read for the past week is that passing the xml into a string is bad. What am I doing wrong and why is it that in glassfish server it works, and when I just open a socket myself it doesn't? this is all that I receive from the push: PUT /?XML_EXPORT_REASON=ResponseLoop&TIMESTAMP=1292559547 HTTP/1.1 Host: ************************ Accept: */* Content-Length: 470346 Expect: 100-continue <?xml version="1.0" encoding="UTF-8" ?> Where did the xml go? Is it because I am placing it in a string? I just need to grab the xml and save it into a file and then process it. Everything else works, but this.Any help would be greatly appreciated.

    Read the article

  • JDOM Parser and Namespace how to get clean Content

    - by senzacionale
    MY xml: <?xml version="1.0"?> <company xmlns="http://www.xx.com/xx"> <staff> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>200000</salary> </staff> </company> Reader in = new StringReader(message); Document document = (Document)saxBuilder.build(in); Element rootNode = document.getRootElement(); List<?> list = rootNode.getChildren("staff", Namespace.getNamespace("xmlns="http://www.infonova.com/MediationFeed"")); XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getCompactFormat()); for (int ii = 0; ii < list.size(); ii++) { Element node = (Element)list.get(ii); StringWriter sw = new StringWriter(); outp.output(node.getContent(), sw); StringBuffer sb = sw.getBuffer(); String xml = sb.toString(); } but my xml object looks like this <firstname xmlns="http://www.xx.com/xx">yong</firstname> <lastname xmlns="http://www.xx.com/xx">mook kim</lastname> <nickname xmlns="http://www.xx.com/xx">mkyong</nickname> <salary xmlns="http://www.xx.com/xx">100000</salary> every elemnt has namespace. why this? i don't want namespace... I want the same output as is in xml example like <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary>

    Read the article

  • std::ostream interface to an OLE IStream

    - by PaulH
    I have a Visual Studio 2008 C++ application using IStreams. I would like to use the IStream connection in a std::ostream. Something like this: IStream* stream = /*create valid IStream instance...*/; IStreamBuf< WIN32_FIND_DATA > sb( stream ); std::ostream os( &sb ); WIN32_FIND_DATA d = { 0 }; // send the structure along the IStream os << d; To accomplish this, I've implemented the following code: template< class _CharT, class _Traits > inline std::basic_ostream< _CharT, _Traits >& operator<<( std::basic_ostream< _CharT, _Traits >& os, const WIN32_FIND_DATA& i ) { const _CharT* c = reinterpret_cast< const _CharT* >( &i ); const _CharT* const end = c + sizeof( WIN32_FIND_DATA ) / sizeof( _CharT ); for( c; c < end; ++c ) os << *c; return os; } template< typename T > class IStreamBuf : public std::streambuf { public: IStreamBuf( IStream* stream ) : stream_( stream ) { setp( reinterpret_cast< char* >( &buffer_ ), reinterpret_cast< char* >( &buffer_ ) + sizeof( buffer_ ) ); }; virtual ~IStreamBuf() { sync(); }; protected: traits_type::int_type FlushBuffer() { int bytes = std::min< int >( pptr() - pbase(), sizeof( buffer_ ) ); DWORD written = 0; HRESULT hr = stream_->Write( &buffer_, bytes, &written ); if( FAILED( hr ) ) { return traits_type::eof(); } pbump( -bytes ); return bytes; }; virtual int sync() { if( FlushBuffer() == traits_type::eof() ) return -1; return 0; }; traits_type::int_type overflow( traits_type::int_type ch ) { if( FlushBuffer() == traits_type::eof() ) return traits_type::eof(); if( ch != traits_type::eof() ) { *pptr() = ch; pbump( 1 ); } return ch; }; private: /// data queued up to be sent T buffer_; /// output stream IStream* stream_; }; // class IStreamBuf Yes, the code compiles and seems to work, but I've not had the pleasure of implementing a std::streambuf before. So, I'd just like to know if it's correct and complete. Thanks, PaulH

    Read the article

  • How do I get the PreviewDialog of Apache FOP to actually display my document?

    - by JRSofty
    Search as I may I have not found a solution to my problem here and I'm hoping the combined minds of StackOverflow will push me in the right direction. My problem is as follows, I'm developing a print and print preview portion of a messaging system's user agent. I was given specific XSLT templates that after transforming XML will produce a Formatting Objects document. With Apache FOP I've been able to render the FO document into PDF which is all fine and good, but I would also like to display it in a print preview dialog. Apache FOP contains such a class called PreviewDialog which requires in its constructor a FOUserAgent, which I can generate, and an object implementing the Renderable Interface. The Renderable Interface has one implementing class in the FOP package which is called InputHandler which takes in its constructor a standard io File object. Now here is where the trouble begins. I'm currently storing the FO document as a temp file and pass this as a File object to an InputHandler instance which is then passed to the PreviewDialog. I see the dialog appear on my screen and along the bottom in a status bar it says that it is generating the document, and that is all it does. Here is the code I'm trying to use. It isn't production code so it's not pretty: import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; import org.apache.fop.cli.InputHandler; import org.apache.fop.render.awt.viewer.PreviewDialog; public class PrintPreview { public void showPreview(final File xslt, final File xmlSource) { boolean err = false; OutputStream out = null; Transformer transformer = null; final String tempFileName = this.getTempDir() + this.generateTempFileName(); final String tempFoFile = tempFileName + ".fo"; final String tempPdfFile = tempFileName + ".pdf"; System.out.println(tempFileName); final TransformerFactory transformFactory = TransformerFactory .newInstance(); final FopFactory fopFactory = FopFactory.newInstance(); try { transformer = transformFactory .newTransformer(new StreamSource(xslt)); final Source src = new StreamSource(xmlSource); out = new FileOutputStream(tempFoFile); final Result res = new StreamResult(out); transformer.transform(src, res); System.out.println("XSLT Transform Completed"); } catch (final TransformerConfigurationException e) { err = true; e.printStackTrace(); } catch (final FileNotFoundException e) { err = true; e.printStackTrace(); } catch (final TransformerException e) { err = true; e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("Initializing Preview"); transformer = null; out = null; final File fo = new File(tempFoFile); final File pdf = new File(tempPdfFile); if (!err) { final FOUserAgent ua = fopFactory.newFOUserAgent(); try { transformer = transformFactory.newTransformer(); out = new FileOutputStream(pdf); out = new BufferedOutputStream(out); final Fop fop = fopFactory.newFop( MimeConstants.MIME_PDF, ua, out); final Source foSrc = new StreamSource(fo); final Result foRes = new SAXResult(fop.getDefaultHandler()); transformer.transform(foSrc, foRes); System.out.println("Transformation Complete"); } catch (final FOPException e) { err = true; e.printStackTrace(); } catch (final FileNotFoundException e) { err = true; e.printStackTrace(); } catch (final TransformerException e) { err = true; e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (!err) { System.out.println("Attempting to Preview"); final InputHandler inputHandler = new InputHandler(fo); PreviewDialog.createPreviewDialog(ua, inputHandler, true); } } // perform the clean up // f.delete(); } private String getTempDir() { final String p = "java.io.tmpdir"; return System.getProperty(p); } private String generateTempFileName() { final String charset = "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890"; final StringBuffer sb = new StringBuffer(); Random r = new Random(); int seed = r.nextInt(); r = new Random(seed); for (int i = 0; i < 8; i++) { final int n = r.nextInt(71); seed = r.nextInt(); sb.append(charset.charAt(n)); r = new Random(seed); } return sb.toString(); } } Any help on this would be appreciated.

    Read the article

  • Not able to get data from Json completely

    - by Abhinav Raja
    i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated. You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/ i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this: if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me. this is my code : public class MainActivity extends Activity { // URL to get contacts JSON private static String url = "http://abinet.org/?json=1"; // JSON Node names private static final String TAG_POSTS = "posts"; static final String TAG_TITLE = "title"; private ProgressDialog pDialog; JSONArray contacts = null; TextView img_url; ArrayList<HashMap<String, Object>> contactList; ListView lv; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.newslist); contactList = new ArrayList<HashMap<String, Object>>(); new GetContacts().execute(); } private class GetContacts extends AsyncTask<Void, Void, Void> { protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } protected Void doInBackground(Void... arg0) { // Making a request to url and getting response JSONParser jParser = new JSONParser(); // Getting JSON from URL JSONObject jsonObj = jParser.getJSONFromUrl(url); // if (jsonStr != null) { try { // Getting JSON Array node contacts = jsonObj.getJSONArray(TAG_POSTS); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { // JSONObject c = contacts.getJSONObject(i); JSONObject posts = contacts.getJSONObject(i); String title = posts.getString(TAG_TITLE).replace("&#8217;", "'"); JSONArray attachment = posts.getJSONArray("attachments"); for (int j = 0; j< attachment.length(); j++){ JSONObject obj = attachment.getJSONObject(j); JSONObject image = obj.getJSONObject("images"); JSONObject image_small = image.getJSONObject("thumbnail"); String imgurl = image_small.getString("url"); HashMap<String, Object> contact = new HashMap<String, Object>(); contact.put("image_url", imgurl); contact.put(TAG_TITLE, title); contactList.add(contact); } } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); adapter=new LazyAdapter(MainActivity.this, contactList); lv.setAdapter(adapter); } } } this is my JsonParser class (although its not required): public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } and this is adapter class: public class LazyAdapter extends BaseAdapter { private Activity activity; private ArrayList<HashMap<String, Object>> data; private static LayoutInflater inflater=null; public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.third_row, null); TextView title = (TextView)vi.findViewById(R.id.headline3); // title SmartImageView iv = (SmartImageView) vi.findViewById(R.id.imageicon); HashMap<String, Object> song = new HashMap<String, Object>(); song = data.get(position); // Setting all values in listview title.setText((CharSequence) song.get(MainActivity.TAG_TITLE)); iv.setImageUrl((String) song.get("image_url")); thumb_image); return vi; } } Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.

    Read the article

  • SQL DataReader how to show null-values from query

    - by cc0
    I have a DataReader and a StringBuilder (C#.NET) used in the following way; while (reader.Read()) { sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]); } Which works great for my use, but when a row is null I need it to return "null", instead of just "". What would be a good way of accomplishing that? Suggestions are very appreciated

    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

  • Parsing XML file using a for loop

    - by Johnny Spintel
    I have been working on this program which inserts an XML file into a MYSQL database. I'm new to the whole .jar idea by inserting packages. Im having an issue with parse(), select(), and children(). Can someone inform me how I could fix this issue? Here is my stack trace and my program below: Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method select(String) is undefined for the type Document The method children() is undefined for the type Element The method children() is undefined for the type Element The method children() is undefined for the type Element The method children() is undefined for the type Element at jdbc.parseXML.main(parseXML.java:28) import java.io.*; import java.sql.*; import org.jsoup.Jsoup; import org.w3c.dom.*; import javax.xml.parsers.*; public class parseXML{ public static void main(String xml) { try{ BufferedReader br = new BufferedReader(new FileReader(new File("C:\\staff.xml"))); String line; StringBuilder sb = new StringBuilder(); while((line=br.readLine())!= null){ sb.append(line.trim()); } Document doc = Jsoup.parse(line); StringBuilder queryBuilder; StringBuilder columnNames; StringBuilder values; for (Element row : doc.select("row")) { // Start the query queryBuilder = new StringBuilder("insert into customer("); columnNames = new StringBuilder(); values = new StringBuilder(); for (int x = 0; x < row.children().size(); x++) { // Append the column name and it's value columnNames.append(row.children().get(x).tagName()); values.append(row.children().get(x).text()); if (x != row.children().size() - 1) { // If this is not the last item, append a comma columnNames.append(","); values.append(","); } else { // Otherwise, add the closing paranthesis columnNames.append(")"); values.append(")"); } } // Add the column names and values to the query queryBuilder.append(columnNames); queryBuilder.append(" values("); queryBuilder.append(values); // Print the query System.out.println(queryBuilder); } }catch (Exception err) { System.out.println(" " + err.getMessage ()); } } }

    Read the article

  • Error with my Android Application httpGet

    - by Coombes
    Basically I'm getting a strange issue with my Android application, it's supposed to grab a JSON Array and print out some values, the class looks like this: ShowComedianActivity.class package com.example.connecttest; public class ShowComedianActivity extends Activity{ TextView name; TextView add; TextView email; TextView tel; String id; // Progress Dialog private ProgressDialog pDialog; //JSON Parser class JSONParser jsonParser = new JSONParser(); // Single Comedian url private static final String url_comedian_details = "http://86.9.71.17/connect/get_comedian_details.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_COMEDIAN = "comedian"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_ADDRESS = "address"; private static final String TAG_EMAIL = "email"; private static final String TAG_TEL = "tel"; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.show_comedian); // Getting Comedian Details from intent Intent i = getIntent(); // Getting id from intent id = i.getStringExtra(TAG_ID); new GetComedianDetails().execute(); } class GetComedianDetails extends AsyncTask<String, String, String>{ protected void onPreExecute(){ super.onPreExecute(); pDialog = new ProgressDialog(ShowComedianActivity.this); pDialog.setMessage("Fetching Comedian details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... params) { runOnUiThread(new Runnable(){ public void run(){ int success; try{ //Building parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("id",id)); // Getting comedian details via HTTP request // Uses a GET request JSONObject json = jsonParser.makeHttpRequest(url_comedian_details, "GET", params); // Check Log for json response Log.d("Single Comedian details", json.toString()); //JSON Success tag success = json.getInt(TAG_SUCCESS); if(success == 1){ // Succesfully received product details JSONArray comedianObj = json.getJSONArray(TAG_COMEDIAN); //JSON Array // get first comedian object from JSON Array JSONObject comedian = comedianObj.getJSONObject(0); // comedian with id found name = (TextView) findViewById(R.id.name); add = (TextView) findViewById(R.id.add); email = (TextView) findViewById(R.id.email); tel = (TextView) findViewById(R.id.tel); // Set text to details name.setText(comedian.getString(TAG_NAME)); add.setText(comedian.getString(TAG_ADDRESS)); email.setText(comedian.getString(TAG_EMAIL)); tel.setText(comedian.getString(TAG_TEL)); } } catch (JSONException e){ e.printStackTrace(); } } }); return null; } } } And my JSON Parser class looks like: package com.example.connecttest; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET method public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } Now when I run a debug it's querying the correct address with ?id=1 on the end of the URL, and when I navigate to that url I get the following JSON Array: {"success":1,"comedian":[{"id":"1","name":"Michael Coombes","address":"5 Trevethenick Road","email":"[email protected]","tel":"xxxxxxxxxxxx"}]} However my app just crashes, the log-cat report looks like this: 03-22 02:05:02.140: E/Trace(3776): error opening trace file: No such file or directory (2) 03-22 02:05:04.590: E/AndroidRuntime(3776): FATAL EXCEPTION: main 03-22 02:05:04.590: E/AndroidRuntime(3776): android.os.NetworkOnMainThreadException 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.IoBridge.connect(IoBridge.java:112) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.Socket.connect(Socket.java:842) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.example.connecttest.JSONParser.makeHttpRequest(JSONParser.java:62) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.example.connecttest.ShowComedianActivity$GetComedianDetails$1.run(ShowComedianActivity.java:89) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Handler.handleCallback(Handler.java:615) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Handler.dispatchMessage(Handler.java:92) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Looper.loop(Looper.java:137) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.app.ActivityThread.main(ActivityThread.java:4745) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.lang.reflect.Method.invokeNative(Native Method) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.lang.reflect.Method.invoke(Method.java:511) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-22 02:05:04.590: E/AndroidRuntime(3776): at dalvik.system.NativeStart.main(Native Method) From this I'm guessing the error is in the jsonParser.makeHttpRequest however I can't for the life of me figure out what's going wrong and was hoping someone brighter than I could illuminate me.

    Read the article

  • Optimizing GDI+ drawing?

    - by user146780
    I'm using C++ and GDI+ I'm going to be making a vector drawing application and want to use GDI+ for the drawing. I'v created a simple test to get familiar with it: case WM_PAINT: GetCursorPos(&mouse); GetClientRect(hWnd,&rct); hdc = BeginPaint(hWnd, &ps); MemDC = CreateCompatibleDC(hdc); bmp = CreateCompatibleBitmap(hdc, 600, 600); SelectObject(MemDC,bmp); g = new Graphics(MemDC); for(int i = 0; i < 1; ++i) { SolidBrush sb(Color(255,255,255)); g->FillRectangle(&sb,rct.top,rct.left,rct.right,rct.bottom); } for(int i = 0; i < 250; ++i) { pts[0].X = 0; pts[0].Y = 0; pts[1].X = 10 + mouse.x * i; pts[1].Y = 0 + mouse.y * i; pts[2].X = 10 * i + mouse.x; pts[2].Y = 10 + mouse.y * i; pts[3].X = 0 + mouse.x; pts[3].Y = (rand() % 600) + mouse.y; Point p1, p2; p1.X = 0; p1.Y = 0; p2.X = 300; p2.Y = 300; g->FillPolygon(&b,pts,4); } BitBlt(hdc,0,0,900,900,MemDC,0,0,SRCCOPY); EndPaint(hWnd, &ps); DeleteObject(bmp); g->ReleaseHDC(MemDC); DeleteDC(MemDC); delete g; break; I'm wondering if I'm doing it right, or if I have areas killing the cpu. Because right now it takes ~ 1sec to render this and I want to be able to have it redraw itself very quickly. Thanks In a real situation would it be better just to figure out the portion of the screen to redraw and only redraw the elements withing bounds of this?

    Read the article

  • Delete last 3 lines within while ((line = r.ReadLine()) != null) but not open a new text file to delete the lines?

    - by user1473672
    This is the code I've seen so far to delete last 3 lines in a text file, but it's required to determine string[] lines = File.ReadAllLines(); which is nt necessary for me to do so. string[] lines = File.ReadAllLines(@"C:\\Users.txt"); StringBuilder sb = new StringBuilder(); int count = lines.Length - 3; // except last 3 lines for (int s = 0; s < count; s++) { sb.AppendLine(lines[s]); } The code works well, but I don't wanna re-read the file as I've mentioned the streamreader above : using (StreamReader r = new StreamReader(@"C:\\Users.txt")) Im new to C#, as far as I know, after using streamreader, and if I wanna modify the lines, I have to use this : while ((line = r.ReadLine()) != null) { #sample codes inside the bracket line = line.Replace("|", ""); line = line.Replace("MY30", ""); line = line.Replace("E", ""); } So, is there any way to delete the last 3 lines in the file within the "while ((line = r.ReadLine()) != null)" ?? I have to delete lines, replace lines and a few more modications in one shot, so I can't keep opening/reading the same text file again and again to modify the lines. I hope the way I ask is understable for you guys .< Plz help me, I know the question sounds simple but I've searched so many ways to solve it but failed =( So far, my code is : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication11 { public class Read { static void Main(string[] args) { string tempFile = Path.GetTempFileName(); using (StreamReader r = new StreamReader(@"C:\\Users\SAP Report.txt")) { using (StreamWriter sw = new StreamWrite (@"C:\\Users\output2.txt")) { string line; while ((line = r.ReadLine()) != null) { line = line.Replace("|", ""); line = line.Replace("MY30", ""); line = line.Replace("E", ""); line = System.Text.RegularExpressions.Regex.Replace(line, @"\s{2,}", " "); sw.WriteLine(line); } } } } } } Now my next task is to delete the last 3 lines in the file after these codes, and I need help on this one. Thank you.

    Read the article

  • Javascript update before page loads in ASP.NET

    - by user204588
    Hello, I'm trying to update values from a xml file into textboxes. I have this javascript being called in the Page_Load event this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", sb.ToString(), true); I click the continue button which does a post back but the values are not updated until I refresh the page again which makes me think the js isn't being run until after the page is returned. I'm wondering how to have the values updated when the page is refreshed after the button postback. thanks

    Read the article

  • T4 Performance Counters explained

    - by user13346607
    Now that T4 is out for a few month some people might have wondered what details of the new pipeline you can monitor. A "cpustat -h" lists a lot of events that can be monitored, and only very few are self-explanatory. I will try to give some insight on all of them, some of these "PIC events" require an in-depth knowledge of T4 pipeline. Over time I will try to explain these, for the time being these events should simply be ignored. (Side note: some counters changed from tape-out 1.1 (*only* used in the T4 beta program) to tape-out 1.2 (used in the systems shipping today) The table only lists the tape-out 1.2 counters) 0 0 1 1058 6033 Oracle Microelectronics 50 14 7077 14.0 Normal 0 false false false EN-US JA X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:Cambria; mso-ascii-font-family:Cambria; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Cambria; mso-hansi-theme-font:minor-latin;} pic name (cpustat) Prose Comment Sel-pipe-drain-cycles, Sel-0-[wait|ready], Sel-[1,2] Sel-0-wait counts cycles a strand waits to be selected. Some reasons can be counted in detail; these are: Sel-0-ready: Cycles a strand was ready but not selected, that can signal pipeline oversubscription Sel-1: Cycles only one instruction or µop was selected Sel-2: Cycles two instructions or µops were selected Sel-pipe-drain-cycles: cf. PRM footnote 8 to table 10.2 Pick-any, Pick-[0|1|2|3] Cycles one, two, three, no or at least one instruction or µop is picked Instr_FGU_crypto Number of FGU or crypto instructions executed on that vcpu Instr_ld dto. for load Instr_st dto. for store SPR_ring_ops dto. for SPR ring ops Instr_other dto. for all other instructions not listed above, PRM footnote 7 to table 10.2 lists the instructions Instr_all total number of instructions executed on that vcpu Sw_count_intr Nr of S/W count instructions on that vcpu (sethi %hi(fc000),%g0 (whatever that is))  Atomics nr of atomic ops, which are LDSTUB/a, CASA/XA, and SWAP/A SW_prefetch Nr of PREFETCH or PREFETCHA instructions Block_ld_st Block loads or store on that vcpu IC_miss_nospec, IC_miss_[L2_or_L3|local|remote]\ _hit_nospec Various I$ misses, distinguished by where they hit. All of these count per thread, but only primary events: T4 counts only the first occurence of an I$ miss on a core for a certain instruction. If one strand misses in I$ this miss is counted, but if a second strand on the same core misses while the first miss is being resolved, that second miss is not counted This flavour of I$ misses counts only misses that are caused by instruction that really commit (note the "_nospec") BTC_miss Branch target cache miss ITLB_miss ITLB misses (synchronously counted) ITLB_miss_asynch dto. but asynchronously [I|D]TLB_fill_\ [8KB|64KB|4MB|256MB|2GB|trap] H/W tablewalk events that fill ITLB or DTLB with translation for the corresponding page size. The “_trap” event occurs if the HWTW was not able to fill the corresponding TLB IC_mtag_miss, IC_mtag_miss_\ [ptag_hit|ptag_miss|\ ptag_hit_way_mismatch] I$ micro tag misses, with some options for drill down Fetch-0, Fetch-0-all fetch-0 counts nr of cycles nothing was fetched for this particular strand, fetch-0-all counts cycles nothing was fetched for all strands on a core Instr_buffer_full Cycles the instruction buffer for a strand was full, thereby preventing any fetch BTC_targ_incorrect Counts all occurences of wrongly predicted branch targets from the BTC [PQ|ROB|LB|ROB_LB|SB|\ ROB_SB|LB_SB|RB_LB_SB|\ DTLB_miss]\ _tag_wait ST_q_tag_wait is listed under sl=20. These counters monitor pipeline behaviour therefore they are not strand specific: PQ_...: cycles Rename stage waits for a Pick Queue tag (might signal memory bound workload for single thread mode, cf. Mail from Richard Smith) ROB_...: cycles Select stage waits for a ROB (ReOrderBuffer) tag LB_...: cycles Select stage waits for a Load Buffer tag SB_...: cycles Select stage waits for Store Buffer tag combinations of the above are allowed, although some of these events can overlap, the counter will only be incremented once per cycle if any of these occur DTLB_...: cycles load or store instructions wait at Pick stage for a DTLB miss tag [ID]TLB_HWTW_\ [L2_hit|L3_hit|L3_miss|all] Counters for HWTW accesses caused by either DTLB or ITLB misses. Canbe further detailed by where they hit IC_miss_L2_L3_hit, IC_miss_local_remote_remL3_hit, IC_miss I$ prefetches that were dropped because they either miss in L2$ or L3$ This variant counts misses regardless if the causing instruction commits or not DC_miss_nospec, DC_miss_[L2_L3|local|remote_L3]\ _hit_nospec D$ misses either in general or detailed by where they hit cf. the explanation for the IC_miss in two flavours for an explanation of _nospec and the reasoning for two DC_miss counters DTLB_miss_asynch counts all DTLB misses asynchronously, there is no way to count them synchronously DC_pref_drop_DC_hit, SW_pref_drop_[DC_hit|buffer_full] L1-D$ h/w prefetches that were dropped because of a D$ hit, counted per core. The others count software prefetches per strand [Full|Partial]_RAW_hit_st_[buf|q] Count events where a load wants to get data that has not yet been stored, i. e. it is still inside the pipeline. The data might be either still in the store buffer or in the store queue. If the load's data matches in the SB and in the store queue the data in buffer takes precedence of course since it is younger [IC|DC]_evict_invalid, [IC|DC|L1]_snoop_invalid, [IC|DC|L1]_invalid_all Counter for invalidated cache evictions per core St_q_tag_wait Number of cycles pipeline waits for a store queue tag, of course counted per core Data_pref_[drop_L2|drop_L3|\ hit_L2|hit_L3|\ hit_local|hit_remote] Data prefetches that can be further detailed by either why they were dropped or where they did hit St_hit_[L2|L3], St_L2_[local|remote]_C2C, St_local, St_remote Store events distinguished by where they hit or where they cause a L2 cache-to-cache transfer, i.e. either a transfer from another L2$ on the same die or from a different die DC_miss, DC_miss_\ [L2_L3|local|remote]_hit D$ misses either in general or detailed by where they hit cf. the explanation for the IC_miss in two flavours for an explanation of _nospec and the reasoning for two DC_miss counters L2_[clean|dirty]_evict Per core clean or dirty L2$ evictions L2_fill_buf_full, L2_wb_buf_full, L2_miss_buf_full Per core L2$ buffer events, all count number of cycles that this state was present L2_pipe_stall Per core cycles pipeline stalled because of L2$ Branches Count branches (Tcc, DONE, RETRY, and SIT are not counted as branches) Br_taken Counts taken branches (Tcc, DONE, RETRY, and SIT are not counted as branches) Br_mispred, Br_dir_mispred, Br_trg_mispred, Br_trg_mispred_\ [far_tbl|indir_tbl|ret_stk] Counter for various branch misprediction events.  Cycles_user counts cycles, attribute setting hpriv, nouser, sys controls addess space to count in Commit-[0|1|2], Commit-0-all, Commit-1-or-2 Number of times either no, one, or two µops commit for a strand. Commit-0-all counts number of times no µop commits for the whole core, cf. footnote 11 to table 10.2 in PRM for a more detailed explanation on how this counters interacts with the privilege levels

    Read the article

  • Need help with fixing Genetic Algorithm that's not evolving correctly

    - by EnderMB
    I am working on a maze solving application that uses a Genetic Algorithm to evolve a set of genes (within Individuals) to evolve a Population of Individuals that power an Agent through a maze. The majority of the code used appears to be working fine but when the code runs it's not selecting the best Individual's to be in the new Population correctly. When I run the application it outputs the following: Total Fitness: 380.0 - Best Fitness: 11.0 Total Fitness: 406.0 - Best Fitness: 15.0 Total Fitness: 344.0 - Best Fitness: 12.0 Total Fitness: 373.0 - Best Fitness: 11.0 Total Fitness: 415.0 - Best Fitness: 12.0 Total Fitness: 359.0 - Best Fitness: 11.0 Total Fitness: 436.0 - Best Fitness: 13.0 Total Fitness: 390.0 - Best Fitness: 12.0 Total Fitness: 379.0 - Best Fitness: 15.0 Total Fitness: 370.0 - Best Fitness: 11.0 Total Fitness: 361.0 - Best Fitness: 11.0 Total Fitness: 413.0 - Best Fitness: 16.0 As you can clearly see the fitnesses are not improving and neither are the best fitnesses. The main code responsible for this problem is here, and I believe the problem to be within the main method, most likely where the selection methods are called: package GeneticAlgorithm; import GeneticAlgorithm.Individual.Action; import Robot.Robot.Direction; import Maze.Maze; import Robot.Robot; import java.util.ArrayList; import java.util.Random; public class RunGA { protected static ArrayList tmp1, tmp2 = new ArrayList(); // Implementation of Elitism protected static int ELITISM_K = 5; // Population size protected static int POPULATION_SIZE = 50 + ELITISM_K; // Max number of Iterations protected static int MAX_ITERATIONS = 200; // Probability of Mutation protected static double MUTATION_PROB = 0.05; // Probability of Crossover protected static double CROSSOVER_PROB = 0.7; // Instantiate Random object private static Random rand = new Random(); // Instantiate Population of Individuals private Individual[] startPopulation; // Total Fitness of Population private double totalFitness; Robot robot = new Robot(); Maze maze; public void setElitism(int result) { ELITISM_K = result; } public void setPopSize(int result) { POPULATION_SIZE = result + ELITISM_K; } public void setMaxIt(int result) { MAX_ITERATIONS = result; } public void setMutProb(double result) { MUTATION_PROB = result; } public void setCrossoverProb(double result) { CROSSOVER_PROB = result; } /** * Constructor for Population */ public RunGA(Maze maze) { // Create a population of population plus elitism startPopulation = new Individual[POPULATION_SIZE]; // For every individual in population fill with x genes from 0 to 1 for (int i = 0; i < POPULATION_SIZE; i++) { startPopulation[i] = new Individual(); startPopulation[i].randGenes(); } // Evaluate the current population's fitness this.evaluate(maze, startPopulation); } /** * Set Population * @param newPop */ public void setPopulation(Individual[] newPop) { System.arraycopy(newPop, 0, this.startPopulation, 0, POPULATION_SIZE); } /** * Get Population * @return */ public Individual[] getPopulation() { return this.startPopulation; } /** * Evaluate fitness * @return */ public double evaluate(Maze maze, Individual[] newPop) { this.totalFitness = 0.0; ArrayList<Double> fitnesses = new ArrayList<Double>(); for (int i = 0; i < POPULATION_SIZE; i++) { maze = new Maze(8, 8); maze.fillMaze(); fitnesses.add(startPopulation[i].evaluate(maze, newPop)); //this.totalFitness += startPopulation[i].evaluate(maze, newPop); } //totalFitness = (Math.round(totalFitness / POPULATION_SIZE)); StringBuilder sb = new StringBuilder(); for(Double tmp : fitnesses) { sb.append(tmp + ", "); totalFitness += tmp; } // Progress of each Individual //System.out.println(sb.toString()); return this.totalFitness; } /** * Roulette Wheel Selection * @return */ public Individual rouletteWheelSelection() { // Calculate sum of all chromosome fitnesses in population - sum S. double randNum = rand.nextDouble() * this.totalFitness; int i; for (i = 0; i < POPULATION_SIZE && randNum > 0; ++i) { randNum -= startPopulation[i].getFitnessValue(); } return startPopulation[i-1]; } /** * Tournament Selection * @return */ public Individual tournamentSelection() { double randNum = rand.nextDouble() * this.totalFitness; // Get random number of population (add 1 to stop nullpointerexception) int k = rand.nextInt(POPULATION_SIZE) + 1; int i; for (i = 1; i < POPULATION_SIZE && i < k && randNum > 0; ++i) { randNum -= startPopulation[i].getFitnessValue(); } return startPopulation[i-1]; } /** * Finds the best individual * @return */ public Individual findBestIndividual() { int idxMax = 0; double currentMax = 0.0; double currentMin = 1.0; double currentVal; for (int idx = 0; idx < POPULATION_SIZE; ++idx) { currentVal = startPopulation[idx].getFitnessValue(); if (currentMax < currentMin) { currentMax = currentMin = currentVal; idxMax = idx; } if (currentVal > currentMax) { currentMax = currentVal; idxMax = idx; } } // Double check to see if this has the right one //System.out.println(startPopulation[idxMax].getFitnessValue()); // Maximisation return startPopulation[idxMax]; } /** * One Point Crossover * @param firstPerson * @param secondPerson * @return */ public static Individual[] onePointCrossover(Individual firstPerson, Individual secondPerson) { Individual[] newPerson = new Individual[2]; newPerson[0] = new Individual(); newPerson[1] = new Individual(); int size = Individual.SIZE; int randPoint = rand.nextInt(size); int i; for (i = 0; i < randPoint; ++i) { newPerson[0].setGene(i, firstPerson.getGene(i)); newPerson[1].setGene(i, secondPerson.getGene(i)); } for (; i < Individual.SIZE; ++i) { newPerson[0].setGene(i, secondPerson.getGene(i)); newPerson[1].setGene(i, firstPerson.getGene(i)); } return newPerson; } /** * Uniform Crossover * @param firstPerson * @param secondPerson * @return */ public static Individual[] uniformCrossover(Individual firstPerson, Individual secondPerson) { Individual[] newPerson = new Individual[2]; newPerson[0] = new Individual(); newPerson[1] = new Individual(); for(int i = 0; i < Individual.SIZE; ++i) { double r = rand.nextDouble(); if (r > 0.5) { newPerson[0].setGene(i, firstPerson.getGene(i)); newPerson[1].setGene(i, secondPerson.getGene(i)); } else { newPerson[0].setGene(i, secondPerson.getGene(i)); newPerson[1].setGene(i, firstPerson.getGene(i)); } } return newPerson; } public double getTotalFitness() { return totalFitness; } public static void main(String[] args) { // Initialise Environment Maze maze = new Maze(8, 8); maze.fillMaze(); // Instantiate Population //Population pop = new Population(); RunGA pop = new RunGA(maze); // Instantiate Individuals for Population Individual[] newPop = new Individual[POPULATION_SIZE]; // Instantiate two individuals to use for selection Individual[] people = new Individual[2]; Action action = null; Direction direction = null; String result = ""; /*result += "Total Fitness: " + pop.getTotalFitness() + " - Best Fitness: " + pop.findBestIndividual().getFitnessValue();*/ // Print Current Population System.out.println("Total Fitness: " + pop.getTotalFitness() + " - Best Fitness: " + pop.findBestIndividual().getFitnessValue()); // Instantiate counter for selection int count; for (int i = 0; i < MAX_ITERATIONS; i++) { count = 0; // Elitism for (int j = 0; j < ELITISM_K; ++j) { // This one has the best fitness newPop[count] = pop.findBestIndividual(); count++; } // Build New Population (Population size = Steps (28)) while (count < POPULATION_SIZE) { // Roulette Wheel Selection people[0] = pop.rouletteWheelSelection(); people[1] = pop.rouletteWheelSelection(); // Tournament Selection //people[0] = pop.tournamentSelection(); //people[1] = pop.tournamentSelection(); // Crossover if (rand.nextDouble() < CROSSOVER_PROB) { // One Point Crossover //people = onePointCrossover(people[0], people[1]); // Uniform Crossover people = uniformCrossover(people[0], people[1]); } // Mutation if (rand.nextDouble() < MUTATION_PROB) { people[0].mutate(); } if (rand.nextDouble() < MUTATION_PROB) { people[1].mutate(); } // Add to New Population newPop[count] = people[0]; newPop[count+1] = people[1]; count += 2; } // Make new population the current population pop.setPopulation(newPop); // Re-evaluate the current population //pop.evaluate(); pop.evaluate(maze, newPop); // Print results to screen System.out.println("Total Fitness: " + pop.totalFitness + " - Best Fitness: " + pop.findBestIndividual().getFitnessValue()); //result += "\nTotal Fitness: " + pop.totalFitness + " - Best Fitness: " + pop.findBestIndividual().getFitnessValue(); } // Best Individual Individual bestIndiv = pop.findBestIndividual(); //return result; } } I have uploaded the full project to RapidShare if you require the extra files, although if needed I can add the code to them here. This problem has been depressing me for days now and if you guys can help me I will forever be in your debt.

    Read the article

  • org.apache.http.conn.HttpHostConnectException:Connection to http://172.20.38.143 refused

    - by Passion
    I have developed client server Application .I am accessing mysql with php running on my machine and client running on my cell which is connected to machine.WI-FI is also switched ON. Internet Permission are also added in Manifest file but then also the i encounter error 172.20.38.143 is IP OF MY MACHINE 06-01 13:20:10.391: W/System.err(11157): org.apache.http.conn.HttpHostConnectException: Connection to http://172.20.38.143 refused 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:674) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.library.JSONParser.getJSONFromUrl(JSONParser.java:42) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.library.UserFunctions.registerUser(UserFunctions.java:59) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.RegisterActivity$1.onClick(RegisterActivity.java:52) 06-01 13:20:10.411: W/System.err(11157): at android.view.View.performClick(View.java:3567) 06-01 13:20:10.411: W/System.err(11157): at android.view.View$PerformClick.run(View.java:14224) 06-01 13:20:10.411: W/System.err(11157): at android.os.Handler.handleCallback(Handler.java:605) 06-01 13:20:10.411: W/System.err(11157): at android.os.Handler.dispatchMessage(Handler.java:92) 06-01 13:20:10.411: W/System.err(11157): at android.os.Looper.loop(Looper.java:137) 06-01 13:20:10.411: W/System.err(11157): at android.app.ActivityThread.main(ActivityThread.java:4517) 06-01 13:20:10.411: W/System.err(11157): at java.lang.reflect.Method.invokeNative(Native Method) 06-01 13:20:10.411: W/System.err(11157): at java.lang.reflect.Method.invoke(Method.java:511) 06-01 13:20:10.411: W/System.err(11157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 06-01 13:20:10.421: W/System.err(11157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 06-01 13:20:10.421: W/System.err(11157): at dalvik.system.NativeStart.main(Native Method) 06-01 13:20:10.421: W/System.err(11157): Caused by: java.net.ConnectException: failed to connect to /172.20.38.143 (port 80): connect failed: ENETUNREACH (Network is unreachable) 06-01 13:20:10.431: W/System.err(11157): at libcore.io.IoBridge.connect(IoBridge.java:114) 06-01 13:20:10.431: W/System.err(11157): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 06-01 13:20:10.431: W/System.err(11157): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 06-01 13:20:10.431: W/System.err(11157): at java.net.Socket.connect(Socket.java:848) 06-01 13:20:10.431: W/System.err(11157): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 06-01 13:20:10.431: W/System.err(11157): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 06-01 13:20:10.431: W/System.err(11157): ... 20 more 06-01 13:20:10.431: W/System.err(11157): Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.Posix.connect(Native Method) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.IoBridge.connect(IoBridge.java:112) 06-01 13:20:10.441: W/System.err(11157): ... 25 more 06-01 13:20:10.441: E/Buffer Error(11157): Error converting result java.lang.NullPointerException 06-01 13:20:10.451: E/JSON Parser(11157): Error parsing data org.json.JSONException: End of input at character 0 of 06-01 13:20:10.451: D/AndroidRuntime(11157): Shutting down VM 06-01 13:20:10.451: W/dalvikvm(11157): threadid=1: thread exiting with uncaught exception (group=0x40c0aa68) 06-01 13:20:10.451: E/AndroidRuntime(11157): FATAL EXCEPTION: main 06-01 13:20:10.451: E/AndroidRuntime(11157): java.lang.NullPointerException 06-01 13:20:10.451: E/AndroidRuntime(11157): at nineandroid.net.example.RegisterActivity$1.onClick(RegisterActivity.java:56) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.view.View.performClick(View.java:3567) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.view.View$PerformClick.run(View.java:14224) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Handler.handleCallback(Handler.java:605) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Handler.dispatchMessage(Handler.java:92) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Looper.loop(Looper.java:137) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.app.ActivityThread.main(ActivityThread.java:4517) 06-01 13:20:10.451: E/AndroidRuntime(11157): at java.lang.reflect.Method.invokeNative(Native Method) 06-01 13:20:10.451: E/AndroidRuntime(11157): at java.lang.reflect.Method.invoke(Method.java:511) 06-01 13:20:10.451: E/AndroidRuntime(11157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 06-01 13:20:10.451: E/AndroidRuntime(11157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 06-01 13:20:10.451: E/AndroidRuntime(11157): at dalvik.system.NativeStart.main(Native Method) UserFunctions.java to call jsonParser public class UserFunctions { private JSONParser jsonParser; private static String loginURL = "http://172.20.38.143/ah_login_api/"; private static String registerURL = "http://172.20.38.143/ah_login_api/"; private static String login_tag = "login"; private static String register_tag = "register"; // constructor public UserFunctions(){ jsonParser = new JSONParser(); } /** * function make Login Request * @param email * @param password * */ public JSONObject loginUser(String email, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", login_tag)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); JSONObject json = jsonParser.getJSONFromUrl(loginURL, params); // return json // Log.e("JSON", json.toString()); return json; } /** * function make Login Request * @param name * @param email * @param password * */ public JSONObject registerUser(String name, String email, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", register_tag)); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); // getting JSON Object JSONObject json = jsonParser.getJSONFromUrl(registerURL, params); // return json return json; } /** * Function get Login status * */ public boolean isUserLoggedIn(Context context){ DatabaseHandler db = new DatabaseHandler(context); int count = db.getRowCount(); if(count > 0){ // user logged in return true; } return false; } /** * Function to logout user * Reset Database * */ public boolean logoutUser(Context context){ DatabaseHandler db = new DatabaseHandler(context); db.resetTables(); return true; } } jsonParser.java public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); Log.e("JSON", json); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } RegisterActivity.java public class RegisterActivity extends Activity { Button btnRegister; Button btnLinkToLogin; EditText inputFullName; EditText inputEmail; EditText inputPassword; TextView registerErrorMsg; // JSON Response node names private static String KEY_SUCCESS = "success"; private static String KEY_UID = "uid"; private static String KEY_NAME = "name"; private static String KEY_EMAIL = "email"; private static String KEY_CREATED_AT = "created_at"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); // Importing all assets like buttons, text fields inputFullName = (EditText) findViewById(R.id.registerName); inputEmail = (EditText) findViewById(R.id.registerEmail); inputPassword = (EditText) findViewById(R.id.registerPassword); btnRegister = (Button) findViewById(R.id.btnRegister); btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); registerErrorMsg = (TextView) findViewById(R.id.register_error); // Register Button Click event btnRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputFullName.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.registerUser(name, email, password); // check for login response try { if (json.getString(KEY_SUCCESS) != null) { registerErrorMsg.setText(""); String res = json.getString(KEY_SUCCESS); if(Integer.parseInt(res) == 1){ // user successfully registred // Store user details in SQLite Database DatabaseHandler db = new DatabaseHandler(getApplicationContext()); JSONObject json_user = json.getJSONObject("user"); // Clear all previous data in database userFunction.logoutUser(getApplicationContext()); db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT)); // Launch Dashboard Screen Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class); // Close all views before launching Dashboard dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(dashboard); // Close Registration Screen finish(); }else{ // Error in registration registerErrorMsg.setText("Error occured in registration"); } } } catch (JSONException e) { e.printStackTrace(); } } }); // Link to Login Screen btnLinkToLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); // Close Registration View finish(); } }); } }

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16  | Next Page >