Download ConsolidatedMentionResolutionBenchmark.csv from UWECProgrammer/ConsolidatedMentionResolutionBenchmark: direct link, hf CLI and curl.
- Browser
- Download file 446 kB
-
https://huggingface.co/datasets/UWECProgrammer/ConsolidatedMentionResolutionBenchmark/resolve/main/ConsolidatedMentionResolutionBenchmark.csv
- Command line
-
hf download hf://datasets/UWECProgrammer/ConsolidatedMentionResolutionBenchmark/ConsolidatedMentionResolutionBenchmark.csv
-
curl -L -o ConsolidatedMentionResolutionBenchmark.csv https://huggingface.co/datasets/UWECProgrammer/ConsolidatedMentionResolutionBenchmark/resolve/main/ConsolidatedMentionResolutionBenchmark.csv
446 kB
| sentence,label | |
| JAXB Bindings File Sets @XmlElement type to String instead of XMLGregorianCalendar.,o | |
| I'm trying to create an CODETERM1 that takes in an CODETERM2 and outputs an CODETERM3 .,o | |
| The purpose is simlply to remove timezone data from the element when unmarshalling data.,o | |
| It looks like this: CODESNIPPET_JAVA1 .,o | |
| This works fine for the following code: CODESNIPPET_JAVA2 .,p | |
| "Unfortunately, when I generate the code using a CODETERM4 file, the above code looks like this: CODESNIPPET_JAVA3 .",n | |
| "It sets the type to CODETERM5 , so my above method doesn't work.",o | |
| The type CODETERM6 setting is overriding the CODETERM7 type that it should be.,o | |
| "I can manually change it, but I'd rather not have to remember to update it every time the jaxb files are regenerated.",o | |
| Does anyone know if there's an option to manually set the CODETERM8 type or have it ignored?,o | |
| Here is the relevant portion of the CODETERM9 file: CODESNIPPET_JAVA4 .,o | |
| It might be that the XPath term in your Binding is not finding the required element.,o | |
| You don't need the dot since // searches in the entire document.,o | |
| And more importantly try surrounding the element name with ''.,o | |
| "Resulting term should look like this: node=""//xs:element[@name='bar-date']"".",o | |
| What does the XSD look like?,o | |
| Is the bar-date element defined as xs:string or a complexType?,o | |
| "maybe i'm wrong, but i think marshall/unmarshall pursuit a different goal, what you are trying to do is conceptually incorrect.",n | |
| "maybe the timezone removal itself is incorrect, why would someone do it?",o | |
| "Please provide the xsd, without it its difficult to guess the issue, or recreate it.",n | |
| the bar-date element should be defined with a xsd:date type.,o | |
| Is this the case ?,o | |
| "sorry, too long for a comment... i can't understand: 1. why the hell are you using CODETERM1 ?",o | |
| 2. why should you CODETERM2 / CODETERM3 ( CODETERM4 / CODETERM5 ) to the very same data structure?,o | |
| 3. why should you remove timezone??,o | |
| and 1. i use straight and simple CODETERM6 2.,p | |
| CODETERM7 / CODETERM8 should always involve CODETERM9 s (at least for XML) 3. i really don' see a good reason to arbitrarily remove a piece of a date representation.,p | |
| maybe you want to serialize it in an absolute way.,o | |
| however CODESNIPPET_JAVA1 .,o | |
| HTML/XML Parser for Java.,o | |
| "What HTML parsers have the following features: | |
| Fast | |
| Thread-safe | |
| Reliable and bug-free | |
| Parses HTML and XML | |
| Handles erroneous HTML | |
| Has a DOM implementation | |
| Supports HTML4, JavaScript, and CSS tags | |
| Relatively simple, object-oriented API What parser you think is better?",o | |
| Thank you.,p | |
| "what do you mean by ""support HTML4, javascript and CSS"" ?",o | |
| "A parser is just that, a parser, it won't interpret your page.",o | |
| "If you want to simulate a browser, please rephrase your question.",o | |
| No.,o | |
| Some parsers do not understand things like CSS.,o | |
| This is what I mean.,o | |
| "If CSS is in a <style> tag, it will be interpreted as text.",o | |
| Check out URL_http://web-harvest.sourceforge.net/ [Web-Harvest] .,o | |
| "It's both a library you can use and a data extraction tool, which sounds to me that's exactly what you want to do.",o | |
| You create XML script files to instruct the scraper how to extract the information you need and from where.,o | |
| The provided GUI is very useful to quickly test the scripts.,p | |
| Check out the URL_http://web-harvest.sourceforge.net/samples.php [project's -samples-page] to see if it's a good fit for what you are trying to do.,p | |
| +1 for Web Harvest -- if you are trying to do page scraping it is the way to go.,o | |
| The best known are URL_http://nekohtml.sourceforge.net/ [NekoHTML] and URL_http://jtidy.sourceforge.net/ [JTidy] .,p | |
| "NekoHTML is based on Xerces, and provides a simple adaptable URL_http://nekoht ml.sourceforge.net/javadoc/org/cyberneko/html/parsers/SAXParser.html [SAXParser] which implements URL_http://java.sun.com/javase/6/docs/api/org/xml/sax/XMLReader.html [XMLReader] JavaSE interface.",p | |
| "JTidy is more intented into formatting your html code into something XML- valid, but is still very useful as an XML parser, producing a DOM tree if needed.",o | |
| You could have a look at URL_http://java-source.net/open-source/html-parsers [this-list] for other alternatives.,o | |
| Another choice could be to use URL_http://github.com/whymirror/hpricot [hpricot] through jRuby.,o | |
| Why?,o | |
| which features do they have?,o | |
| added some details.,o | |
| SAX is not what I want and main purpose of JTidy is cleaning an XML.,p | |
| Are you sure that it does what i want better than others?,o | |
| "what do you want exactly, then ?",o | |
| It should be DOM based.,o | |
| and I want extraction as it's main job not transformation.,o | |
| "It doesn't matter what its ""main"" job is, as long as it does what you want it to do.",o | |
| "URL_http://about.validator.nu/htmlparser/ [Validator.nu's-HTML-parser] , definitely.",o | |
| "It's an implementation of the HTML5 parsing algorithm, and Gecko is in the process of replacing its own HTML parser with a C++ translation of this one.",o | |
| URL_http://tika.apache.org/ [Apache-Tika] is the best choice.,p | |
| Apache has recently extracted many sub-projects out of the existing projects and made them public.,o | |
| Tika is one of them that was previously a component of Apache Lucene.,o | |
| Because of Apache's support and reputation and the widely-used parent project Lucene it must be a very good choice.,p | |
| "Furthermore, it is open-source.",o | |
| "A brief introduction from Apache Tika web site: | |
| The Apache Tika toolkit detects and extracts metadata and structured text content from various documents using existing parser libraries.",o | |
| "And the supported formats are: | |
| CODESNIPPET_JAVA1 .",o | |
| Apache Tika is an excellent suggestion.,p | |
| "Even if you are not interested in reading XML/HTML/MS DOC formats you can just specify ""text/plain"".",o | |
| It will stream in the data so it doesn't need to preload the whole file first.,o | |
| List of benefits: URL_http://tika.apache.org/1.4/parser.html Article with sample code: URL_http://www.openlogic.com/wazi/bid/314389/Content-mining-with-Apache-Tika .,p | |
| "I came for a solid HTML Parser, and left with one that I won't have to spend the time to generalize.",o | |
| I love this game.,p | |
| you probably want to look at doing something like running Mozilla in headless mode.,o | |
| "Here is a URL_http://www.holovaty.com/writing/headless-html-rendering- engine/ [link] to get you started, I am sure you can use Google to find out more information.",o | |
| "Well: there aren't so many good HTML parsers in java as you need, but here are some alternatives: URL_http://java-source.net/open-source/html-parsers [http ://java-source.net/open-source/html-parsers] Very few of them support Javascript.",p | |
| "Actually, I think you'll have to do this part on your own using Rhino ( URL_http://www.mozilla.org/rhino/) .",o | |
| I think that URL_http://htmlcleaner.sourceforge.net/ [HTML-Cleaner] is what you're looking for.,o | |
| "See its URL_http://www.theserverside.com/news/thread.tss?thread_id=50059 [announcement] on TheServerSide to see how it compare to JTidy, TagSoup, NekoHtml.",o | |
| But this is also for transforming into well XMLs.,p | |
| My main goal is extracting data from it.,o | |
| @Shayan So what?,o | |
| Doesn't it allow you to extract data from it?,o | |
| Doesn't it offer DOM manipulation?,o | |
| Doesn't it allow to parse nasty HTML?,o | |
| I don't get you.,o | |
| Which is the best library for XML parsing in java.,o | |
| "I'm searching the java library for parsing XML (complex configuration and data files), I googled a bit but couldn't found other than dom4j (Seems like they are working on V2)..",n | |
| "I have taken look at commons configuration but didn't liked it, Other apache projects on XML seems under hibernation.",o | |
| I haven't evaluated dom4j by myself but just wanted to know - Do java has other (Good) open source xml parsing library?,o | |
| and how's your experience with dom4j?,o | |
| After the @Voo's answer let me ask another one - Should I use java's in built classes or any third library like dom4j.. What are the advantages?,o | |
| Can you define good?,o | |
| "Performance, quality of API, something else?",o | |
| "Performance and ease of use (yes, Quality of API).",o | |
| You've not posted any specific reasons for not using Java's native implementations.,o | |
| vtd-xml will be the one to beat for performance/memory usage and ease of use.,n | |
| Actually Java supports 4 methods to parse XML out of the box: DOM Parser/Builder: The whole XML structure is loaded into memory and you can use the well known DOM methods to work with it.,n | |
| DOM also allows you to write to the document with Xslt transformations.Example: CODESNIPPET_JAVA1 .,o | |
| SAX Parser: Solely to read a XML document.,o | |
| The Sax parser runs through the document and calls callback methods of the user.,o | |
| "There are methods for start/end of a document, element and so on.",o | |
| They're defined in org.xml.sax.ContentHandler and there's an empty helper class DefaultHandler.,o | |
| CODESNIPPET_JAVA2 .,o | |
| StAx Reader/Writer: This works with a datastream oriented interface.,p | |
| The program asks for the next element when it's ready just like a cursor/iterator.,o | |
| You can also create documents with it.,o | |
| Read document: CODESNIPPET_JAVA3 .,o | |
| Write document: CODESNIPPET_JAVA4 .,o | |
| JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2.,o | |
| This allows us to serialize java objects from a document.,o | |
| You read the document with a class that implements a interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance).,o | |
| "The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes.You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!",n | |
| ) CODESNIPPET_JAVA5 .,o | |
| Write document: CODESNIPPET_JAVA6 .,o | |
| "Examples shamelessly copied from some old lecture slides ;-) Edit: About ""which API shoild I use?"".",o | |
| "Well it depends - not all APIs have the same capabilities as you see, but if you have control over the classes you use to map the XML document JAXB is my personal favorite, really elegant and simple solution (though I haven't used it for really large documents, it could get a bit complex).",p | |
| "SAX is pretty easy to use too and just stay away from DOM if you don't have a really good reason to use it - old, clunky API in my opinion.",p | |
| "I don't think there are any modern 3rd party libraries that feature anything especially useful that's missing from the stl and the standard libraries have the usual advantages of being extremely well tested, documented and stable.",p | |
| I want to note one thing: old doesn't mean bad.,n | |
| "2005 is not Jurassic period and I think you shouldn't dismiss a library (in Java, at least) because it hasn't been updated for 5 years.",o | |
| "In fact, the last major update of Java we had approximately at the same time.",o | |
| And when was XML standard finalized?,o | |
| I bet more than 10 years ago.,o | |
| I'm not saying it is bad.. but there may be other libraries which are worth noticing :).,n | |
| "+1 - Just because a standard is 5 years old doesn't mean implementations of that standard don't continue to release new versions which are faster, more robust, and contain extensions.",p | |
| I would be more concerned about using a proprietary library that hasn't released so much as a patch in a couple of years.,o | |
| Nikita's point is an excellent one: don't confuse mature with bad.,p | |
| XML hasn't changed much.,o | |
| JDOM would be another alternative to DOM4J.,o | |
| Which one will you choose and why?,o | |
| It doesn't really much matter.,o | |
| Both are wrappers of the SAX and DOM parsers built into the JDK.,o | |
| "The W3C Document hierarchy is verbose and hard to use, so both DOM4J and JDOM try to make it easier.",n | |
| "I like Elliott Rusty Harold, so I tend to reach for JDOM first.",n | |
| Java supports two methods for XML parsing out of the box.,o | |
| " | |
| You can use this parser if you want to parse large XML files and/or don't want to use a lot of memory.",n | |
| "URL_http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAXParserFa ctory.html [ URL_http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAX ParserFactory.html] Example: URL_http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax- parser/ [ URL_http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/ ] | |
| You can use this parser if you need to do XPath queries or need to have the complete DOM available.",o | |
| URL_http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBui lderFactory.html [ URL_http://download.oracle.com/javase/6/docs/api/javax/xml/parse rs/DocumentBuilderFactory.html] Example: URL_http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom- parser/ [ URL_http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ ] .,o | |
| "For folks interested in using JDOM, but afraid that hasn't been updated in a while (especially not leveraging Java generics), there is a fork called CoffeeDOM which exactly addresses these aspects and modernizes the JDOM API, read more here: URL_http://cdmckay.org/blog/2011/05/20/introducing-coffeedom-a-jdom-fork-for- java-5/ [ URL_http://cdmckay.org/blog/2011/05/20/introducing-coffeedom-a-jdom-fork - for-java-5/] and download it from the project page at: URL_http://coffeedom.googlecode.com/ [ URL_http://coffeedom.googlecode.com/ ] .",o | |
| "Sax parser is a good one, it is simple with their event-driven API, Have a look at: URL_http://www.asjava.com/java-xml/how-to-read-xml-file-via-sax- parser-in-java/ [ URL_http://www.asjava.com/java-xml/how-to-read-xml-file-via-sax - parser-in-java/] .",p | |
| You don't need an external library for parsing XML in Java.,o | |
| Java has come with built-in implementations for SAX and DOM for ages.,o | |
| "Look at vtd-XML, DOM and SAX are somewhat ancient APIs that has not been updated/improved for a while.",o | |
| "If you want a DOM-like API - that is, one where the XML parser turns the document into a tree of Element and Attribute nodes - then there are at least four to choose from: DOM itself, JDOM, DOM4J, and XOM.",o | |
| "The only possible reason to use DOM is because it's perceived as a standard and is supplied in the JDK: in all other respects, the others are all superior.",p | |
| "My own preference, for its combination of simplicity, power, and performance, is XOM.",o | |
| "And of course, there are other styles of processing: low-level parser interfaces (SAX and StAX), data-object binding interfaces (JAXB), and high- level declarative languages (XSLT, XQuery, XPath).",n | |
| Which is best for you depends on your project requirements and your personal taste.,o | |
| DOM is a W3C standard ( URL_http://www.w3.org/DOM/) .,p | |
| The Java implementation of this standard is covered by the JAXP standard ( URL_http://jcp.org/en/jsr/detail?id=206) .,p | |
| "JAXP is then implemented by different providers such as: Oracle, Apache, etc.",o | |
| XML serialization in Java?,o | |
| Is there a (preferably free) Java analogue of .NET's XML serialization?,o | |
| URL_http://xstream.codehaus.org/ [XStream] is pretty good at serializing object to XML without much configuration and money!,p | |
| (it's under BSD license).,o | |
| We used it in one of our project to replace the plain old java-serialization and it worked almost out of the box.,o | |
| "Very useful, it can have problems on complecated tree structures such as JGraph with non string node objects though.",o | |
| Simpler and better then other solutions.,o | |
| I like XStream.,o | |
| Only thing is that I don't understand why a character is added before the actual XML.,o | |
| "The ""Official"" Java API for this is now JAXB - Java API for XML Binding.",o | |
| The reference implementation lives at URL_http://jaxb.java.net/ [ URL_http://jaxb.java.net/ ] .,o | |
| "That's right, JAXB is definitely the best option!.",p | |
| "You may want to look at URL_http://simple.sourceforge.net/ [Simple] , its the closest thing I've found to the System.Xml.Serialization in .Net.",p | |
| It does however require mapping annotations for each field.,o | |
| "Not true, I doesn't require.",o | |
| You can change default behaviour and it will use only present fields.,o | |
| JAXB is part of JDK standard edition version 1.6+.,p | |
| So it is CODETERM1 and no extra libraries to download and manage.A simple example can be found URL_ht tp://www.java2s.com/Code/Java/JDK-6/MarshalJavaobjecttoxmlandoutputtoconsole.h tm [here] XStream seems to be dead.,p | |
| Last update was on Dec 6 2008.,o | |
| CODETERM2 seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.,p | |
| "XStream is not dead, it is just mature and stable -- meaning there isn't much to add to core functionality.",o | |
| "Same is actually true for JAXB reference implementation, not much activity for past couple of years.",o | |
| URL_http://xmlbeans.apache.org/ [XMLBeans] works great if you have a schema for your XML.,p | |
| It creates Java objects for the schema and creates easy to use parse methods.,p | |
| "Worth mentioning that since version 1.4, Java had the classes java.beans.XMLEncoder and java.beans.XMLDecoder.",p | |
| These classes perform XML encoding which is at least very comparable to XML Serialization and in some circumstances might do the trick for you.,o | |
| "If your class sticks to the JavaBeans specification for its getters and setters, this method is straightforward to use and you don't need a schema.",p | |
| "With the following caveats: | |
| As with normal Java serialization | |
| coding and decoding run over a InputStream and OutputStream | |
| the process uses the familar writeObject and readObject methods | |
| In contrast to normal Java serialization | |
| the encoding but also decoding causes constructors and initializers to be invoked | |
| encoding and decoding work regardless if your class implements Serializable or not | |
| transient modifiers are not taken into account | |
| works only for public classes, that have public constructors For example, take the following declaration: CODESNIPPET_JAVA1 .",p | |
| Executing this code: CODESNIPPET_JAVA2 .,o | |
| Would result in the following file: CODESNIPPET_JAVA3 .,o | |
| Usually I use URL_http://jaxb.java.net/ [jaxb] or URL_http://xmlbeans.apache.org/ [XMLBeans] if I need to create objects serializable to XML.,o | |
| "Now, I can see that URL_http://xstream.codehaus.org/ [XStream] might be very useful as it's nonintrusive and has really simple api.",p | |
| I'll play with it soon and probably use it.,o | |
| The only drawback I noticed is that I can't create object's id on my own for cross referencing.,o | |
| @Barak Schiller Thanks for posting link to XStream!,o | |
| Problem is jaxb and xmlbeans require a mapping schema and arent auto ...,o | |
| Don't forget URL_http://jibx.sourceforge.net/ [JiBX] .,o | |
| "if you want a | |
| solution** (like ORM) then JAXB2 is a good solution.",p | |
| If you want a serialization like DOT NET then you could use URL_http://java.sun.com/products/jfc/tsc/articles/persistence3/ [Long-Term- Persistence-of-JavaBeans-Components] The choice depends on use of serialization.,o | |
| "If you're talking about automatic XML serialization of objects, check out URL_http://www.castor.org/ [Castor] : | |
| Castor is an Open Source data binding framework for Java[tm].",p | |
| "It's the shortest path between Java objects, XML documents and relational tables.",o | |
| "Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.",o | |
| Rhino print function.,o | |
| I'm using Rhino 1.7R4 and env.js 1.2 to run Javascript code inside Java I want to print from my Javascript code a string to the Java console.,o | |
| "According to: URL_http://evilroundabout.blogspot.com.au/2009/11/javascript- printing-rhino.html [ URL_http://evilroundabout.blogspot.com.au/2009/11/javascript - printing-rhino.html] I should use: print(""Hello world""); but when I do I get: CODESNIPPET_JAVA1 .",o | |
| If I use document.write I don't see any output.,o | |
| Bring your javascript and java code.,o | |
| You can use the same scope that the rhino shell uses quite easily.,o | |
| "The rhino shell relies on a specially constructed scope instance called Global which defines several functions like ""print"".",o | |
| "The sample below demonstrates how to use Global and the ""print"" function.This will print ""Hello World!",o | |
| """ twice to stdout.",o | |
| CODESNIPPET_JAVA1 .,o | |
| I discovered this through experimentation after digging through the URL_https: //github.com/mozilla/rhino/blob/master/toolsrc/org/mozilla/javascript/tools/sh ell/Main.java [Rhino-shell-executable] .,o | |
| And for the sake of completeness here are the other global functions defined by URL_https://github.com/mozilla/rhino/blob/master/toolsrc/org/mozilla/javasc ript/tools/shell/Global.java [Global] : CODESNIPPET_JAVA2 .,o | |
| see update in my answer.,o | |
| "I don't think that will work in embedded mode, I think that will only work in the Rhino console.",o | |
| You can use java.lang.system.out.println.,o | |
| This should work:- CODESNIPPET_JAVA1 .,o | |
| You can create your own: CODESNIPPET_JAVA1 .,o | |
| "as of january, 2014, the list of methods and properties on CODESNIPPET_JAVA1 .",o | |
| would appear to be the following: CODESNIPPET_JAVA2 .,o | |
| How to trace a NullPointerException in a chain of getters.,o | |
| If I get a NullPointerException in a call like this: CODESNIPPET_JAVA1 .,o | |
| I get a rather useless exception text like: CODESNIPPET_JAVA2 .,n | |
| "I find it rather hard to find out wich call actually returend null, often finding myself refactoring the code to something like this: CODESNIPPET_JAVA3 .",n | |
| and then waiting for a more descriptive NullPointerException that tells me which line to look for.,p | |
| "Some of you might argue that concatening getters is bad style and should be avoided anyway, but my Question is: Can I find the bug without changing the code?",o | |
| "Hint: I'm using eclipse and I know what a debugger is, but I can't figuere out how to apply it to the problem.",o | |
| " | |
| conclusion on the answers:** Some answers told me that I should not chain getters one after another, some answers showed my how to debug my code if I disobayed that advice.",o | |
| "I've accepted an answer that taught me excactly when to chain getters: | |
| If they cannot return null, chain them as long as you like.",o | |
| "No need for checking != null, no need to worry about NullPointerExceptions (_be warned that chaining still vialotes the law of demeter, but I can live with that_) | |
| If they may return null, don't ever, never ever chain them, and perform a check for null values on each one that may return null This makes any good advice on actual debugging useless.",n | |
| Now I see that this could have been two seperate questions: 1.,o | |
| "How can I avoid a NPE when using chained getters, 2.",o | |
| How can I trace the probrem if I didn't avoid the NPE.,o | |
| "I'm glad I got good answers to both questions, but it makes it rather hard to chose which answer to accept.",p | |
| In IntelliJ IDEA you can set _exceptionbreakpoints_.,o | |
| Those breakpoints fire whenever a specified exception is thrown (you can scope this to a package or a class).,n | |
| That way it should be easy to find the source of your NPE.,p | |
| "I would assume, that you can do something similar in netbeans or eclipse.",o | |
| EDIT: URL_http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.jdt.doc.,o | |
| user/reference/views/breakpoints/ref-addexception_viewaction.htm [Here] is an explanation on how to add an exceptionbreakpoint in eclipse .,o | |
| You can set exception breakpoints in Eclipse as well.,n | |
| You cannot scope them by class/package but that should not be a problem in this case because the breakpoint needs to be activated only one execution reaches the chained getters.,o | |
| This technique is only useful if your tests identify the source of every possible NPE.,o | |
| In production you cannot run your code in a debugger so any NPE will still generate an unhelpful stack trace.,o | |
| If you find yourself often writing: CODESNIPPET_JAVA1 .,o | |
| this is probably a code smell and should be avoided.,n | |
| "You can refactor, for example, into CODETERM1 which calls CODETERM2 which calls CODETERM3 which calls CODETERM4 .",o | |
| "(This example may not make sense for your particular use case, but it's one pattern for fixing this code smell.",n | |
| ") See also the URL_http://c2.com/cgi/wiki?LawOfDemeter [Law-of-Demeter] , which says: | |
| Your method can call other methods in its class directly | |
| Your method can call methods on its own fields directly (but not on the fields' fields) | |
| When your method takes parameters, your method can call methods on those parameters directly.",o | |
| " | |
| When your method creates local objects, that method can call methods on the local objects.",o | |
| "Therefore, one should not have a chain of messages, e.g.",o | |
| CODETERM5 .,o | |
| "Following this ""law"" has many more benefits apart from making NullPointerExceptions easier to debug.",p | |
| "NPE is the most useless Exception in Java, period.",n | |
| "It seems to be always lazily implemented and never tells exactly what caused it, even as simple as ""class x.y.Z is null"" would help a lot in debugging such cases.",p | |
| "Anyway, the only good way I've found to find the NPE thrower in these cases is the following kind of refactoring: CODESNIPPET_JAVA1 .",p | |
| "There you have it, now NPE points to correct line and thus correct method which threw the actual NPE.",o | |
| "Not as elegant solution as I'd want it to be, but it works.",p | |
| "Wow, didn't ever try that because it seemed too easy.",p | |
| I just thought Java would still treat it like one single line.,o | |
| I will have a try on it...,o | |
| The answer depends on how you view (the contract of) your getters.,o | |
| If they may return CODETERM1 you should really check the return value each time.,o | |
| "If the getter should not return CODETERM2 , the getter should contain a check and throw an exception ( CODETERM3 ?",o | |
| ") instead of returning CODETERM4 , that you promised never to return.",p | |
| The stacktrace will point you to the exact getter.,o | |
| You could even put the unexpected state your getter found in the exception message.,n | |
| "Getters should never contain side-effect logic, this muddles the code and causes even more confusion than the original problem.",n | |
| "Especially since a popular testing paradigm to take is to not test the getters and setters, since they're supposed to be simple.",p | |
| "@rblasch: I really like that answer, as it points me to the original problem: There are methods which may return null, and others that may not.",o | |
| I was not always aware of this 'contract' thingy.,o | |
| "@MeteroidFan2002: I agree that getters should not contain side effect logic, but what rblasch suggests does not seem like a side effect to me.",o | |
| "A side effect would be changing the inner state of the object, or something like that.",o | |
| It seems a rather good idea to check if it fullfills its contract.,p | |
| Brian got this completely right.,o | |
| "MetroidFan2002, note that I'm not proposing any side effects, which we all agree would be bad.",n | |
| "By the way, the same rationale applies to setters, but I'd use an IllegalArgumentException there.",o | |
| If all accessors must be dumb I see little value over public fields.,n | |
| "Getters and setters are used in reflection, that's why they are autogenerated.",o | |
| Fields don't play nicely with reflection.,p | |
| Getters and setters should be dumb if possible.,n | |
| "Setters could do a side-effect, but having it in your getter will cause more confusion than it solves.",n | |
| "An exception is a side-effect, by the way.",n | |
| "A getter is supposed to get the property, anything other than that and it is a side effect.",o | |
| "Why don't fields ""play nicely"" with reflection?",o | |
| "And no, that's not a side effect.",o | |
| A side effect is an action that changes something outside of a method.,o | |
| "Changing a global variable, the state of an object or writing to a log is a side effect.",o | |
| An exception instead of returning a value isn't.,n | |
| Fields don't play nicely with reflection because most reflection apis are built upon a property inspection methodology that conforms to the Javabean contract.,p | |
| "I.e., setters and getters.",o | |
| "And it is a side-effect because it performs an action that is not the intent of a method, ...",o | |
| A getter's purpose is to return a property.,o | |
| "An exception that the property is null is a side-effect of invoking the getter, because it is something that occurred within the getter method invocation that forces the caller to adapt to its effects directly, instead of indirectly via a null check.",n | |
| "I understand the JavaBeans argument, but please don't call it ""fields don't play nicely with reflection.",p | |
| """ Regarding side effects, I'm using the term in a CS sense, which is different from API conventions, which we probably won't agree on here (and don't have to.",o | |
| ) ;-).,o | |
| I generally do not chain getters like this where there is more than one nullable getter.,o | |
| "If you're running inside your ide you can just set a breakpoint and use the ""evaluate expression"" functionality of your ide on each element successively.",o | |
| But you're going to be scratching your head the moment you get this error message from your production server logs.,o | |
| So best keep max one nullable item per line.,p | |
| Meanwhile we can dream of URL_http://groovy.codehaus.org/Operators#Operators- SafeNavigationOperator(%3F.,p | |
| ) [groovy's-safe-navigation-operator] .,o | |
| Early failure is also an option.,o | |
| "Anywhere in your code that a null value can be returned, consider introducing a check for a null return value.",o | |
| CODESNIPPET_JAVA1 .,o | |
| Agreed -- but throw NullPointerException() if the problem is a null reference!.,o | |
| "If the result of a computation or database lookup is null, when I expected something different then IllegalStateException is a valid choice.",o | |
| "Here's how to find the bug, using Eclipse.",n | |
| "First, set a breakpoint on the line: CODESNIPPET_JAVA1 .",o | |
| "Run the program in debug mode, allow the debugger to switch over to its perspective when the line is hit.",o | |
| "Now, highlight ""someObject"" and press CTRL+SHIFT+I (or right click and say ""inspect"").",p | |
| Is it null?,o | |
| You've found your NPE.,o | |
| Is it non-null?Then highlight someObject.getSomething() (including the parenthesis) and inspect it.Is it null?,o | |
| Etc.,o | |
| "Continue down the chain to figure out where your NPE is occurring, without having to change your code.",o | |
| "If you're having to get to the point where you're splitting up the line or doing elaborate debugging to spot the problem, then that's generally God's way of telling you that your code isn't checking for the null early enough.",p | |
| "If you have a method or constructor that takes an object parameter and the object/method in question cannot sensibly deal with that parameter being null, then just check and throw a NullPointerException there and then.",p | |
| "I've seen people invent ""coding style"" rules to try and get round this problem such as ""you're not allowed more than one dot on a line"".",o | |
| But this just encourages programming that spots the bug in the wrong place.,n | |
| "I don't see how any early checking can be done without breaking the single statement into multiple, essentially following the style rule you disapprove of.",n | |
| "It's more about WHERE you break it up: I'm talking about null checks at the beginning of constructors and methods before the actual logic of the code starts, so that you're not trying to break lines up in the MIDDLE of a method/piece of logic.",o | |
| I am afraid I am not getting it.,o | |
| Can you please clarify what null checks you would use in this case before the changed getters of someObject?,o | |
| You may want to refer to URL_http://stackoverflow.com/questions/271526/how-to- avoid-null-statements-in-java#271874 [this-question-about-avoiding-!=-null] .,o | |
| "Basically, if null is a valid response, you have to check for it.",o | |
| "If not, assert it (if you can).",o | |
| "But whatever you do, try and minimize the cases where null is a valid response for this amongst other reasons.",o | |
| Chained expressions like that are a pain to debug for NullPointerExceptions (and most other problems that can occur) so I would advise you to try and avoid it.,n | |
| You have probably heard that enough though and like a previous poster mentioned you can add break points on the actual NullPointerException to see where it occurred.,p | |
| In eclipse (and most IDEs) you can also use watch expressions to evaluate code running in the debugger.,o | |
| You do this bu selecting the code and use the contet menu to add a new watch.,o | |
| If you are in control of the method that returns null you could also consider the Null Object pattern if null is a valid value to return.,o | |
| Place each getter on its own line and debug.,o | |
| Step over (F6) each method to find which call returns null .,o | |
| Secure Debugging for Production JVMs.,p | |
| "We have some applications that sometimes get into a bad state, but only in production (of course!).",n | |
| "While taking a heap dump can help to gather state information, it's often easier to use a remote debugger.",n | |
| "Setting this up is easy -- one need only add this to his command line: -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=PORT There seems to be no available security mechanism, so turning on debugging in production would effectively allow arbitrary code execution (via hotswap).",p | |
| We have a mix of 1.4.2 and 1.5 Sun JVMs running on Solaris 9 and Linux (Redhat Enterprise 4).,o | |
| How can we enable secure debugging?,o | |
| Any other ways to achieve our goal of production server inspection?,o | |
| " | |
| For JDK 1.5+ JVMs, one can specify an interface and port to which the debugger should bind.",o | |
| "So, KarlP's suggestion of binding to loopback and just using a SSH tunnel to a local developer box should work given SSH is set up properly on the servers.",o | |
| " | |
| it seems that JDK1.4x does not allow an interface to be specified for the debug port.",o | |
| "So, we can either block access to the debug port somewhere in the network or do some system-specific blocking in the OS itself (IPChains as Jared suggested, etc.)?",o | |
| " | |
| This is a hack that will let us limit our risk, even on 1.4.2 JVMs: Command line params: CODESNIPPET_JAVA1 .",n | |
| Java Code to turn on debugger: CODESNIPPET_JAVA2 .,o | |
| TurnOnDebuggerException can be any exception guaranteed not to be thrown anywhere else.,n | |
| "I tested this on a Windows box to prove that (1) the debugger port does not receive connections initially, and (2) throwing the TurnOnDebugger exception as shown above causes the debugger to come alive.",n | |
| "The launch parameter was required (at least on JDK1.4.2), but a garbage value was handled gracefully by the JVM.",p | |
| "We're planning on making a small servlet that, behind appropriate security, can allow us to turn on the debugger.",o | |
| "Of course, one can't turn it off afterward, and the debugger still listens promiscuously once its on.",o | |
| "But, these are limitations we're willing to accept as debugging of a production system will always result in a restart afterward.",o | |
| " | |
| I ended up writing three classes: (1) TurnOnDebuggerException, a plain 'ol Java exception, (2) DebuggerPoller, a background thread the checks for the existence of a specified file on the filesystem, and (3) DebuggerMainWrapper, a class that kicks off the polling thread and then reflectively calls the main method of another specified class.",n | |
| This is how its used: 1.,o | |
| "Replace your ""main"" class with DebuggerMainWrapper in your start-up scripts 2.",o | |
| "Add two system (-D) params, one specifying the real main class, and the other specifying a file on the filesystem.",o | |
| 3.,o | |
| Configure the debugger on the command line with the onthrow=com.whatever.TurnOnDebuggerException part added 4.,o | |
| Add a jar with the three classes mentioned above to the classpath.,o | |
| "Now, when you start up your JVM everything is the same except that a background poller thread is started.",o | |
| "Presuming that the file (ours is called TurnOnDebugger) doesn't initially exist, the poller checks for it every N seconds.",o | |
| "When the poller first notices it, it throws and immediately catches the TurnOnDebuggerException.",o | |
| "Then, the agent is kicked off.",o | |
| "You can't turn it back off, and the machine is not terribly secure when its on.",p | |
| "On the upside, I don't think the debugger allows for multiple simultaneous connections, so maintaining a debugging connection is your best defense.",p | |
| We chose the file notification method because it allowed us to piggyback off of our existing Unix authen/author by specifying the trigger file in a directory where only the proper uses have rights.,o | |
| You could easily build a little war file that achieved the same purpose via a socket connection.,n | |
| "Of course, since we can't turn off the debugger, we'll only use it to gather data before killing off a sick application.",o | |
| "If anyone wants this code, please let me know.",o | |
| "However, it will only take you a few minutes to throw it together yourself.",o | |
| If you use SSH you can allow tunneling and tunnel a port to your local host.,o | |
| "No development required, all done using sshd, ssh and/or putty.",o | |
| The debug socket on your java server can be set up on the local interface 127.0.0.1. .,o | |
| "If this works (testing now), it seems like the best option for us.",p | |
| "It's not like we debug regularly, but we do want the ability to catch a JVM in a misbehaving state.",n | |
| "I think this will only work on JDK 1.5+: URL_http://java.sun.com/j2se/1.5.0/docs/guide/jpda/enhancements.htmlSee ""the dt_socket transport has been amended to take a local address when running in server mode"" in the above link.",o | |
| "@Shabby - yep - looks like this would work 1.5+, and is a great solution.",n | |
| The alternate is to lock down the debug ports via a firewall (software or hardware.,o | |
| ) Maybe checkout ipchains for your linux hosts?,o | |
| ( URL_http://tldp.org/HOWTO/IPCHAINS-HOWTO.html) .,o | |
| One of our infrastructure folks noted that binding to loopback limits access to those with rights on the machine in question -- perhaps a bit broad for some applications.,o | |
| "However, this is probably good enough in many cases.",o | |
| You're absolutely right: the Java Debugging API is inherently insecure.,o | |
| "You can, however, limit it to UNIX domain sockets, and write a proxy with SSL/SSH to let you have authenticated and encrypted external connections that are then proxied into the UNIX domain socket.",p | |
| "That at least reduces your exposure to someone who can get a process into the server, or someone who can crack your SSL.",o | |
| Can one map a port on the default interface to a domain socket?,o | |
| The problem I have (which I found out after my initial post) is that the 1.4.x Sun JVM can only bind to the default(?,o | |
| ) interface.,o | |
| "Therefore, some magical mapping would be required so that this port wouldn't be exposed outside the VM.",p | |
| Export information/services into JMX and then use RMI+SSL to access it remotely.,o | |
| Your situation is what JMX is designed for (the M stands for Management).,o | |
| I agree that common metrics ought to be exposed via JMX.,o | |
| "We're actually using a lightweight production profiler (Wily), but it isn't very good at capturing state information, and can only perform well when limited to coarse-grained traces.",n | |
| "The other issue is that some of these apps are (partially) third- party, so we'll be debugging with decompiled source at best.",p | |
| I still maintain that hooking up your debugger to a production application is a bad idea.,n | |
| Users are going to have no idea whats going on when you hit a breakpoint and spend a few moments grepping through memory.I would try to find the spots in your code that are having problems and expose the current state via JMX and keep detailed audit logs of what is happening.,n | |
| We'd actually be taking the badly behaving instance out of our load-balanced cluster before debugging.,n | |
| I do agree that debugging an app w/ active users would be a really bad idea.,n | |
| Good question.,p | |
| I'm not aware of any built-in ability to encrypt connections to the debugging port.,o | |
| "There may be a much better/easier solution, but I would do the following: 1.",p | |
| Put the production machine behind a firewall that blocks access to the debugging port(s).,o | |
| 2.,o | |
| "Run a proxy process on the host itself that connects to the port, and encrypts the input and output from the socket.",o | |
| 3.,o | |
| Run a proxy client on the debugging workstation that also encrypts/decrypts the input.,o | |
| Have this connect to the server proxy.,o | |
| Communication between them would be encrypted.,p | |
| 4.,o | |
| Connect your debugger to the proxy client.,o | |
| "As a side note: Our production servers are behind a firewall, but they are exposed to some internal network segments.",o | |
| Printing Java collections nicely (toString doesn't return pretty output).,p | |
| "I wish to print a CODETERM1 object as nicely as the Eclipse debugger does, i.e., CODETERM2 etc, but printing it with CODETERM3 doesn't return this nice result.",p | |
| "Just to clarify, I'm talking about Java's built-in collection so I can't override its CODETERM4 .",o | |
| How can I get a nice printable version of the stack?,o | |
| You could convert it to an array and then print that out with CODETERM1 : CODESNIPPET_JAVA1 .,o | |
| I like it.,o | |
| "Simple, clean.",p | |
| "To be honest Collections needs a toString method too, but this works also.",p | |
| "@Tovi7 It probably doesn't because most OOTB Collections already provide readable toString()s, whereas arrays don't.",p | |
| Implement toString() on the class.,o | |
| I recommend the URL_http://commons.apache.org/proper/commons-lang/javadocs /api-release/org/apache/commons/lang3/builder/ToStringBuilder.html [Apache- Commons-ToStringBuilder] to make this easier.,p | |
| "With it, you just have to write this sort of method: CODESNIPPET_JAVA1 .",o | |
| "In order to get this sort of output: | |
| Person@7f54[name=Stephen,age=29] There is also a URL_http://commons.apache.org/proper/commons-lang/javadocs /api-release/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html [reflective-implementation] .",o | |
| "ToStringBuilder is usually more applicable for beans and objects that carry information, less so for complex data structures.",n | |
| "If the stack object doesn't print all stored items, this won't help.",o | |
| "usage of reflection ToStringBuilder, HashCodeBuilder and EqualsBuilder is highly inefective.",n | |
| "Though the output is ok, these classes are hardly the performance peak of the week...",n | |
| "Also, be careful.",o | |
| ToStringBuilder uses threadlocal!?!,o | |
| ?,o | |
| "The question explicitly says the class is a built-in collection, so toString() can't be modified.",o | |
| I agree with the above comments about overriding CODETERM1 on your own classes (and about automating that process as much as possible).,o | |
| "For classes you | |
| define, you could write a CODETERM2 class with an overloaded method for each library class you want to have handled to your own tastes: CODESNIPPET_JAVA1 .",o | |
| "EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.",o | |
| CODESNIPPET_JAVA2 .,o | |
| "This isn't a full-blown implementation, but just a starter.",o | |
| I know that DP.,o | |
| But how can I easily print them in a readable format?,o | |
| The MapUtils class offered by the Apache Commons project offers a MapUtils.debugPrint method which will pretty print your map.,o | |
| Anything similar in Guava?,o | |
| Not that I know of.,o | |
| I'm not terribly familiar with the Guava library but I wouldn't be surprised if there was.,o | |
| System.out.println(Collection c) already print any type of collection in readable format.,p | |
| "Only if collection contains user defined objects , then you need to implement toString() in user defined class to display content.",o | |
| Just Modified the previous example to print even collection containing user defined objects.,o | |
| CODESNIPPET_JAVA1 .,o | |
| line 21: ToStringBuilder cannot be resolved.,o | |
| "If this is your own collection class rather than a built in one, you need to override its toString method.",o | |
| Eclipse calls that function for any objects for which it does not have a hard-wired formatting.,o | |
| And how does eclipse format those classes w/ hard-wired formatting?,o | |
| That's what I'm looking for.,o | |
| "Be careful when calling Sop on Collection, it can throw CODETERM1 Exception.",n | |
| Because internally CODETERM2 method of each Collection internally calls CODETERM3 over the Collection.,o | |
| "which java http client library is easy to use for programmatically doing posts, setting cookies and maybe ajax?",o | |
| "which java http client library is easy to use for programmatically doing posts, setting cookies and maybe ajax?",o | |
| "Apache HTTP Component (HttpClient 4.0), URL_http://hc.apache.org/httpcomponents-client-4.0.1/index.html [ URL_http://hc.apache.org/httpcomponents-client-4.0.1/index.html ] Normally, I would just use HttpURLConnection but its cookie handling is too weak to simulate browser behavior.",o | |
| Looks like the URL has changed.,o | |
| Try URL_http://hc.apache.org/httpcomponents - client-ga/index.html.,o | |
| "You can use URL_http://www.rexsl.com/rexsl- test/apidocs-0.10/com/rexsl/test/request/JdkRequest.html [CODETERM1] from URL_http://www.rexsl.com/rexsl-test [rexsl-test] (I'm a developer), which does all this work for you, decorating CODETERM2 , firing HTTP requests and parsing responses, for example: CODESNIPPET_JAVA1 .",o | |
| Async request like AJAX: URL_http://hc.apache.org/httpcomponents-asyncclient- dev/ [ URL_http://hc.apache.org/httpcomponents-asyncclient-dev/ ] Sync request: URL_http://hc.apache.org/httpcomponents-client-4.0.1/index.html [ URL_http://hc.apache.org/httpcomponents-client-4.0.1/index.html ] Cookies is A kind of Header.,o | |
| Add cookies like A Header: CODESNIPPET_JAVA1 .,o | |
| Best solution for Java HTTP push (messaging).,p | |
| We want to push data from a server to clients but can only use HTTP (port 80).,o | |
| What is the best solution for messaging?,o | |
| One idea is URL_http://en.wikipedia.org/wiki/Comet%5F%28programming%29 [Comet] .,o | |
| Are there other ideas or frameworks which offer lets say JMS over HTTP.,o | |
| "(Yes, ActiveMQ supports it too, but waggly IMHO.",o | |
| And JXTA supports it too but the configuration is complicated.,o | |
| Something simple is preferred.,p | |
| ) .,o | |
| "The simplest solution for many, many reasons is to use a Comet based approach (like you mention).",p | |
| "This means the clients (to whom you want to ""push"" messages) open long-lived HTTP connections.",o | |
| Those connections stay open until they time out or you send the client a message.,o | |
| As soon as either happens the client opens a new connection.,o | |
| "Directly connecting to clients could be problematic for many reasons: they could be behind firewalls that disallow that, they could be behind proxies and so on.",n | |
| "Unless your clients are real servers (in which case you're really the client), have them contact you and send a response to mimic push.",o | |
| Is that right?,o | |
| When the message arrives at the browser a new connection is opened?,o | |
| The client should be programmed to open a new connection.,o | |
| If it doesn't the server has no way of communicating with the client.,o | |
| I'm sorry.,n | |
| Having trouble understanding.,o | |
| The client has opened an long-lived HTTP connection.,o | |
| Server sends messages up there - right?,o | |
| "You then say ""Those connections stay open until they time out or you send the client a message.",o | |
| As soon as either happens the client opens a new connection.,o | |
| """ Sounds like we are opening a second connection.",o | |
| Why?,o | |
| "The message we just received contained the data we want, doesn't it?",o | |
| The new connection is to listen for the next message.,o | |
| The idea here is to keep an open connection to the server at all times that is just waiting for the server to do something with it.,o | |
| This allows the server to (in effect) initiate communications.,o | |
| "Once the server uses the connection to send a message, a new connection needs to be opened up for the next message.",o | |
| All of this assumes we have a client that the server needs to be able to push data to.,o | |
| "The alternative is to poll for changes at regular intervals, but that may create a delay in the event reaching a client.",o | |
| "(Apologies for labouring the point, but this simply doesn't correspond to my experience).",o | |
| "The connection is long lived, server squirts up data periodically, browser thread sucks that data and displays it.",n | |
| I don't see why we need to keep opening more connections.,o | |
| "Right now, I've got real-time measurements updating in my browser, and just one connection (I think).",o | |
| URL_https://github.com/Atmosphere/atmosphere [Atmosphere] and URL_http://directwebremoting.org/dwr/index.html [DWR] are both open source frameworks that can make Comet easy in Java.,p | |
| "I created an example app using Comet, Raphael, Bayeux, Java and Maven running PaaS Cloudbees and wrote a blog post about it, hopefully it will be helpful to someone.",p | |
| URL_http://geeks.aretotally.in/thinking-in-reverse-not-taking-orders-from-yo [ URL_http://geeks.aretotally.in/thinking-in-reverse-not-taking-orders-from-yo ] .,o | |
| We used COMET in conjunction with JMS using URL_http://www.ibm.com/developerwo rks/websphere/techjournal/0802%5Fhaverlock/0802%5Fhaverlock.html [WAS-Web-2.0 -Feature-Pack] ; in effect the server did the JMS subscribe and COMET-pushed the message to the browser.,o | |
| "as a developer it ""felt"" like the browser was subscribing to JMS.",o | |
| "This ""just worked"" so we didn't look further for alternatives.",o | |
| "I could imagine a pure JavaScript JMS implementation in the browser, using HTTP as a transport but my instict is that this would be very heavyweight.",n | |
| I know of no such implementations.,o | |
| The alternative approach to those already discussed (i.e.,o | |
| Comet etc.,o | |
| ) is to implement polling in the client.,o | |
| The downside of that approach is that you inevitably have a delay from the time of the message/event and until the client receives it.,n | |
| "If your application is very sensitive to such delays, polling is out.",o | |
| "If a certain amount of delay (at minimum in the order of a few seconds) is acceptable, polling is less of an abuse of the HTTP protocol.",n | |
| It is also more robust against temporary network troubles as the server by default queues messages and wont get upset if the client isn't available on its schedule.,p | |
| There is really no big difference between polling and long-lived connections.,o | |
| "In both cases you initate a poll, and it will return immediatelly, or with some delay.",o | |
| The longer the delay is the less connections you have to open.,n | |
| In all cases problems like terminated or unanswered calls are just lead to the next poll.,n | |
| Inside the HTTP/1.1 the (TCP)connection typically stays open.,o | |
| Alternatives to Apache HttpComponents?,o | |
| "So, I've come to the conclusion that Apache HttpComponents 4 is one of the most overwrought APIs I've ever come across.",n | |
| Things that seem like they should be simple are taking hundreds of lines of code (and I'm _still_ not sure resources get cleaned up correctly).,p | |
| Plus it wants me to do things like: CODESNIPPET_JAVA1 .,o | |
| "Which, just... no.",o | |
| "I know it's Java, and we're not into the whole brevity thing, but that's a little much.",n | |
| Not to mention the jars are up to 700KB.,o | |
| "Anyway, enough ranting, I wanted to see what kind of experiences people have had with other HTTP client libraries?",o | |
| "The ones I'm aware of are: URL_http://docs.codehaus.org/display/JETTY/Jetty+HTTP+Client [Jetty] , URL_http://hotpotato.biasedbit.com/ [hotpotato] , and URL_https://github.com/sonatype/async-http-client [AsyncHttpClient] .",o | |
| "This is for server-side use, I'm mostly interested in performance for many concurrent gets and large file transfers.",o | |
| Any recommendations?,o | |
| "PS I know the venerable HttpClient 3.1 is still there, but I'd like to use something that's supported.",p | |
| " | |
| Update @oleg: this is what the docs suggest: CODESNIPPET_JAVA2 .",o | |
| I still get unexpected errors when consuming entity content when using CODETERM1 .,o | |
| "I'm sure it's my fault, but at this point I don't really want to have to figure it out.",n | |
| "Hey, I don't mean to disparage anyone's work here, but I've been making a good-faith effort to use HttpComponents since 4.0 came out and it's just not working for me.",n | |
| "While not flawless, have you considered the standard URLConnection/HTTPUrlConnection ?",o | |
| "Having to call InputStream#close() to release allocated resources is massively over-complex, isn't it?",o | |
| I would really like to hear what you have discovered since posting this.,o | |
| I'm in the same boat :).,o | |
| "Adding a comment since the Jetty http client link mentioned above is so so old, here is the actual client docs.",o | |
| URL_https://www.eclipse.org/jetty/documentation/current/http-client.html .,o | |
| Complexity of HttpClient API simply reflects the complexity of its problem domain.,o | |
| Contrary to a popular misconception HTTP is a fairly complex protocol.,n | |
| Being a low level transport library HC 4.0 API was primarily optimised for performance and flexibility rather than simplicity.,n | |
| "It is regrettable that you are not able to figure it out, but so be it.",o | |
| You are welcome to use whatever library that suits your needs best.,p | |
| I personally like Jetty HttpClient a lot.,o | |
| It is a great alternative that might work better for you.,p | |
| I agree with both you (+1) and the OP.,o | |
| "The power and flexibility is necessary, but there should also a set of facade methods somewhere that simplify the process.",o | |
| "Methods like public static InputStream httpGetAsStream(String baseUrl, Map<string, object=""""> parameters).",o | |
| "HTTP is complex, but Apache's HttpComponents library | |
| ridiculously over- engineered and contains a lot of complexity not essential to protocol operation.",n | |
| It objectively has a really bad API.,n | |
| "@Alex B: HttpComponents are being used in all sorts of different applications randing from simple URL fetchers to complex transports and web crawlers with different, often conflicting requirements.",n | |
| What may seem as non-essential to some can be absolutely essential to others.,o | |
| HttpClient has to deal with several dozen customization parameters and context specific strategies and objects.,o | |
| "So, flexibility has to come before simplicity.",o | |
| For those who are not able to wrap their head around HttpClient API there is fluent facade API: URL_http://hc.apache.org/httpcomponents-client-dev/fluent-hc/index.html .,o | |
| """Complexity of HttpClient API simply reflects the complexity of its problem domain.",o | |
| """ If HC 4.0 was perfect then that would be a good point, but it is not.",p | |
| It has many problems and I imagine a lack of direction lead it into the mess it is today.,n | |
| "I think Alex B is right when he says that objectively the API is bad and could have been | |
| better.",n | |
| Could have been.,o | |
| Answering my own question since this got resurrected for some reason.,o | |
| "I ended up writing a few simple wrappers around CODETERM1 , seems it's come a long way since the last time I seriously considered it.",n | |
| "HttpComponents is great, but can be overkill for simple tasks.",p | |
| "Also, at least in my scenario, HUC is noticeably faster (mostly single-threaded, haven't done any testing under heavy load).",n | |
| HttpURLConnection instances are significantly cheaper to create than due to the fact that they share one static JRE wide pool of connections.,n | |
| Per default HttpClient always creates a new pool of connections and therefore is slower to start up and warm up.,n | |
| One can address this problem by re-using the same instance of HttpClient for new requests.,o | |
| "This approach is used by HttpClient's fluent facade, for isntance: URL_http://hc.apache.org/httpcomponents-client-dev /fluent-hc/index.html.",o | |
| In all other cases I can think of HttpClient should be comfortably faster.,p | |
| "Maybe I'm doing something wrong, this isn't exactly rigorous benchmarking.",n | |
| I do always use a single HttpClient instance.,o | |
| "Just ran a quick test: fetching from localhost, very small document (150 bytes) x 5000 times takes roughly 10 seconds with HttpClient (4.1) and under 2 seconds with HUC.",o | |
| "This actually isn't just academic, my main use-case is lots of small lookups against services on the same machine.",o | |
| I can only give you my (biased) perspective.,o | |
| Any HTTP performance test that lasts 2 second is simply not representative.,o | |
| One need to be running the benchmark for a few minutes to get more or less reliable numbers.,o | |
| Here is the benchmark and some results that we use internally: URL_http://wiki.apache.org/HttpComponents/HttpClient3vsHttpClient4vsHttpCore .,o | |
| HttpClient 4.x performance seems to be quite all right compared to HUC and other clients.,o | |
| Of course.,o | |
| "Like I said, it's by no means a comprehensive benchmark.",o | |
| "Then again, in _my_ particular case, which is not covered by your benchmark, there is a noticeable difference.",o | |
| "I would not generalize from that (certainly isn't representative), but it does factor into my decision of what to use in my scenario.",o | |
| For simple use cases you can use URL_http://hc.apache.org/httpcomponents- client-ga/fluent-hc/ [HttpClient-Fluent-API] .,p | |
| See URL_https://hc.apache.org /httpcomponents-client-ga/tutorial/html/fluent.html [tutorials] .,o | |
| " | |
| This module provides an easy to use facade API for HttpClient based on the concept of a fluent interface.",p | |
| Fluent facade API exposes only the most fundamental functions of HttpClient and is indended for simple use cases that do not require the full flexibility of HttpClient.,p | |
| "For instance, fluent facade API relieves the users from having to deal with connection management and resource deallocation CODESNIPPET_JAVA1 .",o | |
| Maven artifact.,o | |
| CODESNIPPET_JAVA2 .,o | |
| You could use URL_http://www.jboss.org/netty [Netty] or URL_http://mina.apache.org/ [Apache-Mina] albeit they are very low level and I'm not sure you will end up with less verbose code.,n | |
| "HTTPUnit has a great interface (not much code needed), but the latest version of it submits duplicate requests.",p | |
| "HTMLUnit will work, but for me it has seemed to have limited support for Javascript.",o | |
| I'vebeen able to use it for basic web pages though.,o | |
| You could have a look at URL_http://www.restlet.org [Restlet] 's client capabilities.,o | |
| It's a layer above that can be supported by Apache HttpComponents or Java's Net API for example.,o | |
| "I've used Jersey's client, which is conceptually pretty similar.",o | |
| It is pretty convenient for a lot of cases.,o | |
| How to send HTTP request in java?,o | |
| I want to compose a HTTP request message in java and then want to send it to a HTTP WebServer.I also want the document content of the page recieved which I would have recieved if I had sent the same HTTP request from a webpage.,o | |
| "URL_http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html In particular, getHeaderField, getHeaderFieldKey, and getContent.",o | |
| [There's a mini tutorial here at SO]( URL_http://stackoverflow.com/questions/2793150/how-to-use-java-net - urlconnection-to-fire-and-handle-http-requests).,o | |
| From URL_http://java.sun.com/docs/books/tutorial/networking/urls/readingWritin g.html [Sun's-java-tutorial] CODESNIPPET_JAVA1 .,o | |
| The strange thing is that some servers will reply you back with strange ?,o | |
| characters (which seems like an encoding error related to request headers but not) if you don't open an output stream and flush it first.,o | |
| I have no idea why this happens but will be great if someone can explain why?,o | |
| @Gorky: Make a new question.,o | |
| You can use URL_http://download.oracle.com/javase/7/docs/api/java/net/HttpURLC onnection.html [java.net.HttpUrlConnection] .,o | |
| "Or maybe this link is easier to read: URL_http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to- web-server/139 [ URL_http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection - post-data-to-web-server/139] If Java Almanac is down, try URL_http://www.xyzws.com/Javafaq/how-to-use- httpurlconnection-post-data-to-web-server/139 [this-one] .",p | |
| Microsoft?,o | |
| This is Java.,o | |
| What does Microsoft have to do with it?,o | |
| I know I'm late to the party here...but I'm currently frustrated with the Java APIs lack of examples.,n | |
| I guess MSDN spoiled us.,n | |
| "Late, indeed.",o | |
| The response is three years old.,o | |
| What didn't you find at Java Almanac?,o | |
| And how is this comment helping?,o | |
| Nothing stops you from going back to Microsoft.,o | |
| Or stay and learn to like all the open source stuff that Java gives you.,p | |
| FYI the Java Almanac link is dead (or at least there are no code snippets).,o | |
| FYI - I answered this three years ago.,o | |
| Here is another nice code snippet in replace for Java Almanac: [HttpUrlConnection-Example]( URL_http://www.xyzws.com/Javafaq/how-to-use - httpurlconnection-post-data-to-web-server/139).,p | |
| Can you show some example code perhaps?,o | |
| "Scott, isn't the link in the comment just above yours enough for you?",o | |
| And did you have the gall to downvote this?,o | |
| BTW the Java Almanac link from above now goes to Adult Friend Finder (surprise!,o | |
| - NSFW).,o | |
| "Dude, I wrote that answer four years ago.",o | |
| Thanks for alerting me.,o | |
| URL_http://hc.apache.org/ [Apache-HttpComponents] .,o | |
| The examples for the two modules - URL_http://hc.apache.org/httpcomponents-core-ga/examples.html [HttpCore] and URL_http://hc.apache.org/httpcomponents-client-ga/examples.html [HttpClient] will get you started right away.,o | |
| "Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away.",n | |
| "I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code.",p | |
| "By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.",o | |
| "FWIW, our code started with java.net.HttpURLConnection, but when we had to add SSL and work around some of the weird use cases in our screwy internal networks, it became a real headache.",n | |
| "Apache HttpComponents saved the day.Our project currently still uses an ugly hybrid, with a few dodgy adapters to convert java.net.URLs to the URIs HttpComponents uses.",n | |
| I refactor those out regularly.,o | |
| The only time HttpComponents code turned out significantly more complicated was for parsing dates from a header.,o | |
| But the [solution]( URL_http://stackoverflow.com/a/1930240/1450294 ) for that is still simple.,p | |
| "I know others will recommend Apache's http-client, but it adds complexity (i.e., more things that can go wrong) that is rarely warranted.",n | |
| "For a simple task, CODETERM1 will do.",p | |
| CODESNIPPET_JAVA1 .,o | |
| "That doesn't help if you want to monkey with request headers, something that's particularly useful when dealing with sites that will only respond a certain way to popular browsers.",p | |
| "You can monkey with request headers using URLConnection, but the poster doesn't ask for that; judging from the question, a simple answer is important.",p | |
| This will help you.,o | |
| Don't forget to add the JAR CODETERM1 to the classpath.,o | |
| CODESNIPPET_JAVA1 .,o | |
| There's a great link about sending a POST request URL_http://web.archive.org/w eb/20120101100355/ URL_http://www.exampledepot.com/egs/java.net/Post.html [here] by Example Depot:: CODESNIPPET_JAVA1 .,p | |
| If you want to send a GET request you can modify the code slightly to suit your needs.,o | |
| Specifically you have to add the parameters inside the constructor of the URL.,o | |
| "Then, also comment out this CODETERM1 One thing that's not written and you should beware of, is the timeouts.",o | |
| "Especially if you want to use it in WebServices you have to set timeouts, otherwise the above code will wait indefinitely or for a very long time at least and it's something presumably you don't want.",n | |
| Timeouts are set like this CODETERM2 the input parameter is in milliseconds .,o | |
| Here's a complete Java 7 program: CODESNIPPET_JAVA1 .,o | |
| "The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.",o | |
| You may use Socket for this like CODESNIPPET_JAVA1 .,o | |
| shouldn't it be \r\n instead of \n?,o | |
| @Troelsen yes correct!.,p | |
| Suggest a simple NoSQL database for java project.,p | |
| I am developing a simple internal use application with an intended user base of around 100 people.,p | |
| The application does a lot of reads and very few writes.,o | |
| The dataset size is fairly small and we do not want to use a RDBMS if possible.,o | |
| "In fact, the relational requirements are fairly small.",o | |
| I am looking at using some NoSQL database and I am looking for one with the following requirements.,o | |
| 1.,o | |
| "A simple, stable implementation which can be accessed easily from Java (i.e has a Java client).",p | |
| 2.,o | |
| I would like to be able to run a test application from a Windows box although the final deployment is on a Linux box.,o | |
| 3.,o | |
| Setup of the NoSQL DB should be minimal.,o | |
| 4.,o | |
| I am not concerned with scaling the DB because we expect to limit the dataset size and trim old data occasionally.,o | |
| Any suggestions would be helpful.,p | |
| "I am currently considering URL_http://code.google.com/p/redis/ [redis] + URL_http://code.google.com/p/jredis/ [jredis] | |
| One of my main motivations for this project is also to look into the programming model and ways of usage of NoSql DBs.",p | |
| "I understand I can use flat files, blobs etc.",o | |
| "Since simple flat files require no setup and don't use SQL, what are you asking?",o | |
| @S.Lott - Agreed.,o | |
| I also want to use the opportunity to do a starter project using a NoSQL database.,o | |
| Serializing is simple.,p | |
| URL_http://download.oracle.com/javase/6/docs/api/java/io/Serializable.html .,o | |
| @Thimmayya: then this is a rhetorical question.,n | |
| Use what you think will be fun.,n | |
| @msw - It is rhetorical :).,n | |
| Just want to see if there are any suggestions that I may not have found while googling.,o | |
| "@offtopic but I don't like these databases being called NoSQL, it seems that the emphasis is on not having sql though the reality is that these database lack relational schema and thats why people want it not because they don't want to use sql.",n | |
| """I also want to use the opportunity to do a starter project using a NoSQL database""?",o | |
| What does that matter?,o | |
| "Since simple flat files require no setup and don't use SQL, what are you asking?",o | |
| What's wrong with flat files?,o | |
| Why ask?,o | |
| @S.Lott - There is nothing wrong with flat files for a simple app.,n | |
| I just want to explore some of the new NoSQL DB systems and the programming model associated with them.,o | |
| "I am not sure if you are upset with the question, but since I did not find the same question already answered and the community here is friendly enough with such questions, I figured I would go ahead and ask for opinions.",p | |
| Relax man.,o | |
| "@Thimmayya: Then don't use ""NoSQL"" -- it's too vague to have any meaning.",o | |
| The Flat File is the perfect NoSQL database.,p | |
| Why not use it?,o | |
| "In this case, you don't want to use flat files because when you say ""NoSQL"" you mean something specific -- ""redis"".",o | |
| "Please fix your question to remove the vague and poorly- defined ""NoSQL"" and be more specific about what you want opinions on.",n | |
| @S.Lott - Thanks.,o | |
| "I see ""NoSQL' is more of a buzzword and Hasan suggested the same above.",o | |
| "You're tagging this question with [key-value-store] and many answers below are about graph oriented db, document oriented db, OODB.",o | |
| This doesn't make any sense.,o | |
| "If you just want to use something because of the hype, pick anything.",o | |
| But this question doesn't make any sense.,o | |
| @Pascal - You are right.,o | |
| The question is superfluous....,n | |
| "Some of the answers were helpful in the sense that they led me to learn a bit about graph databases, but that is irrelevant to the question.",n | |
| "Naturally, there is no ""correct answer"" here for me to accept.",p | |
| The easiest thing to do is to go to URL_http://en.wikipedia.org/wiki/NoSQL and pick any of the technologies mentioned there.,p | |
| Thanks.,o | |
| "Definitely URL_http://www.orientechnologies.com [OrientDB] ( URL_http://www.orientechnologies.com) : | |
| It's 100% written in Java (requires JRE 1.6 for the client/server version, otherwise JRE 1.5) | |
| Elegant Java APIs | |
| Really fast.",p | |
| "About 50.000 insert/sec on common HW | |
| Small: less than 1Mb for all | |
| Support for SQL with extension for links, graphs and objects | |
| Native support for Security | |
| Run as embedded or in client/server configuration.",o | |
| "Next releases will support clustering and partitioning | |
| Apache 2 license: free for any use | |
| Much more .",p | |
| I've had great success with URL_http://neo4j.org [Neo4J] .,p | |
| The database is embedded so the amount of effort required to get the system running is minimal.,o | |
| Additionally the client interface to the DB is a pleasure to work with.,p | |
| The entire setup is two additional jars on the classpath.,o | |
| Thanks.,o | |
| I will look it up.,o | |
| +1 for neo4j.,o | |
| I've been using it in a project and found it integrates very easily into a project.,o | |
| "My only gripe is version 1.1 doesn't have a way to get a relationship between two nodes by providing a method getRelationship(node1, node2).",n | |
| "Otherwise, it's been awesome.",p | |
| I'd recommend it.,p | |
| "If you're looking for a simple stable implementation of a NoSQL DB system, look no further than Apache (they have over 10 years of development experience).",p | |
| "Few that comes to mind: | |
| URL_http://couchdb.apache.org/ [CouchDB] | |
| URL_http://cassandra.apache.org/ [Cassandra] .",o | |
| Developed by Facebook but now under Apache.,o | |
| "Twitter, Facebook, Digg, etc.",o | |
| are using Cassandra.,o | |
| It's fully written in Java and can be accessed via Java using URL_http://incubator.apache.org/thrift/ [Thrift] or URL_http://avro.apache.org/ [Avro] .,o | |
| " | |
| Redis (although Redis doesn't run flexibly well on Windows OS).",p | |
| It's owned by VMWare.,o | |
| "You do | |
| want to use Cassandra for this.",o | |
| It would be the exact wrong choice for your requirements.,n | |
| @ericflo - Can you elaborate a bit more please?,o | |
| Cassandra != easy if you ask me!,p | |
| "It scales very well if I have to believe digg,facebook, twitter, etc.",p | |
| "@Alfred, it's easier once you get the hang of it.",n | |
| It's just creating your column families that's a schlep.,o | |
| Apache is an organization.,o | |
| "Being an Apache project tells not much about the code quality; in the end Apache grants a good legal quality, nothing else.",p | |
| "@Ansgar, You're confusing Apache License with Apache projects.",n | |
| I'm basically saying that Apache has good java-based products for NoSQL databases.,p | |
| "The fact that they've been consistent in java based software development for over 10 years and with huge support shows that they are a ""trustworthy"" organization.",p | |
| A document database has a very simple storage model and basic query abilities.,p | |
| "URL_http://www.mongodb.org/downloads [MongoDB] for example, seems to have everything you need in terms of compatibility and is very easy to set up.",p | |
| I would choose between 2 options: 1) URL_http://en.wikipedia.org/wiki/Berkeley_DB [Berkeley-DB] : it's very mature and at the same time very simple key-value storage.,p | |
| It could be the best choice in not one big issue: it was bought by Oracle and some licensing issues can occur now.,p | |
| Read carefully info about licensing and it your requirements don't break the agreement then go with it.,o | |
| 2) MySql on MyISAM engine without any foreign keys (i.e.,o | |
| several independent not normalized tables).,o | |
| You'll use it just as a key-value storage.,o | |
| Read this answer about URL_http://stackoverflow.com/questions/2285045/what-scalability- problems-have-you-solved-using-a-nosql-data-store/2316921#2316921 [using- MySql-as-NoSql-storage] .,o | |
| "If I were in your shoes, I'd go with this option just because I know that it would show great performance, there are mature tools for working with MySql, many people have experience with it and at any time you can easily use all its relational potential if you eventually decide to go back to RDBMS solutions.",p | |
| The SQL database you have most experience with.,o | |
| "MySQL, Postgre, HyperDB, whatever.",o | |
| "If you want to learn something, then any NoSQL database is fine - you'd learn a lot about distributing data and scalability in the process.",o | |
| "Cassandra, Neo4j, MongoDB, etc.",o | |
| Lotus Notes Domino would meet all of your requirements.,o | |
| It would also provide robust security and potential scalability as well.,p | |
| Welcome to Stack Overflow.,p | |
| We can hear you loud and clear.,p | |
| There's no need for ALL CAPS.,o | |
| edit to remove the SHOUTY CAPS.,o | |
| ;).,o | |
| What is the best api/library for Java to use Cassandra?,o | |
| I'm looking for an API with the following requirements 1.,o | |
| It's simple to use and is concise.,p | |
| It is not bloated.,p | |
| 2.,o | |
| "Works with Spring way of doing things, or is at least easy to make it work with Spring 3.",p | |
| "Has a Maven repository, preferably it's already in the main repositories 4.",o | |
| "Is production-tested, meaning a fair number of people are using it in production applications.",o | |
| Help?,o | |
| Thanks!,o | |
| "URL_http://github.com/rantav/hector [Hector] and URL_http://code.google.com/p/pelops/ [Pelops] are, as far as I know, the two that are most widely used (4).",o | |
| I dont think any of the two are mavenized (3).,o | |
| Both should work in a Spring framework environment(2).,o | |
| Your first criteria might be a little bit subjective.,n | |
| I dont find any of these two bloated.,n | |
| "You might do, if you do, please tell me.",o | |
| Hector is mavenized.,o | |
| Pelops is mavenized as well.,p | |
| Pelops documentation is very poor.,o | |
| i know this is an old question but I'd like to point future viewer of the question to URL_https://github.com/Netflix/astyanax [Astyanax] .,o | |
| It's a URL_https://github.com/Netflix/astyanax/wikihttp:// [very-well-documented] Cassandra API with many examples and support very high level features such as locking and all versions of cql.,o | |
| Astyanax is also URL_http://mvnrepository.com/artifact/com.netflix.astyanax/astyanax [Mavenized] .,o | |
| "Kundera is a object-datastore mapping tool for Cassandra, Hbase and MongoDB.",o | |
| "Some of the salient features are: | |
| JPA 2.0 compliant.",p | |
| " | |
| Column/ super column indexing using lucene.",o | |
| " | |
| Support for entity relationships and JPA queries.",o | |
| " | |
| Cross-datastore persistence It's hosted here: URL_https://github.com/impetus-opensource/Kundera [ URL_https://github.com/impetus-opensource/Kundera ] .",o | |
| From JPA to NOSQL.,o | |
| "I am trying to add a NOSQL data into my JPA-based application, following URL_http://static.springsource.org/spring-data/data-graph/snapshot- site/reference/html/#cross-store [this-tutorial] .",o | |
| "The entity I want to add, was befored modeled without NOSQL in this way: Triple.java | |
| CODESNIPPET_JAVA1 .",o | |
| "ConceptPk.java | |
| CODESNIPPET_JAVA2 .",o | |
| "I am omiting repetitions, but the 3 CODETERM1 s are part of the primary key, of the @Id.",o | |
| Adapting this entity to NOSQL: CODESNIPPET_JAVA3 .,o | |
| "Now the question, which actually are two questions: A) CODETERM2 gives me error on Eclipse, and advises me to add a cast, but this doesn't solve the error.",o | |
| "I don't know if I must an annotation or any other additional thing to CODETERM3 B) As I have specified, the primery key is composed by 3 concepts, and CODETERM4 is required.",o | |
| "JPA modelling is ok, but I don't know how to do the same in NOSQL .",o | |
| "Well, you haven't said _which_ NoSQL engine you're going to, which is pretty important.",p | |
| Most NoSQL data stores don't support the concept of a composite primary key - and some of them won't allow you unique columns in the first place.,o | |
| "First, note that I work for a NoSQL vendor, URL_http://gigaspaces.com/ [ URL_http://gigaspaces.com/ ] - I'm not unbiased.",o | |
| "However, going from JPA to NoSQL is not hard, no matter what your engine is.",o | |
| "For GigaSpaces, you can use JPA to talk to the data grid with very few changes, for example, although then you're still stuck with JPA.",o | |
| "To really think about JPA, you need to think about your data as _data_ and not organizational stuff; you have a triplet, basically, which means your NoSQL data items consist of three data items (predicate, subject, object, like you've used.)",o | |
| "For most NoSQL engines you'll probably want an id there, too, just for efficiency's sake.",o | |
| "The ID is the ""primary key,"" and enforcing unique triplets after that is going to be on _your_ end more than the NoSQL engine's end; this is one area where NoSQL ""suffers"" compared to SQL, but it's also where you find the greatest speed and storage improvements.",p | |
| "For some NoSQL engines, then, you'll build a document, consisting of the three data items, and you'd just query for that document before writing it into the database.",o | |
| I could give you an example for many NoSQL engines (and certainly can for GigaSpaces) but I don't know which one you're targeting or why.,o | |
| Thank you for your explanation.,p | |
| "I am using Spring Data Graph, and the neo4j, and I have read that composed Id aren't allowed.",o | |
| "Your idea of having an Id is not exaclty what I need, because I need to prove that there are no equal triplets.",o | |
| "You'd have to start a transaction, run a query, update the data if the query fails, in that case.",o | |
| "Neo4J is okay, although obviously I prefer our own product.",p | |
| :).,o | |
| I can imagine... :) Thank you very much!.,p | |
| "Mujer, your domain looks like it would be much easier modelled in the graph database itself.",p | |
| As it is RDF like triplets that are annotated here.,o | |
| You are right in that Spring Data Graph right now does not support compound keys.,o | |
| "We will look into that in the future, but I can't promise anything.",n | |
| In the graph you could model your nodes being Concepts (URIs) and the type of relationship representing what you want to represent with that Concept.,o | |
| CODESNIPPET_JAVA1 .,o | |
| This could be easily modelled with Spring Data Graph (or also with the pure Neo4j API) CODESNIPPET_JAVA2 .,o | |
| "The eclipse error is annoying but just a wrong visualization, the AspectJ team is in the process of fixing that.",o | |
| "Hope that helps, if you need further advice just ask Michael .",o | |
| Have a look at Kundera.,o | |
| URL_http://mevivs.wordpress.com/2012/02/13/how-to-crud-and-jpa-association- handling-using-kundera/ [ URL_http://mevivs.wordpress.com/2012/02/13/how-to-crud - and-jpa-association-handling-using-kundera/] Use JPA over NoSql .,o | |
| PlayOrm is another solution which is JPA-like but with noSQL specific features like you can do @NoSqlEmbedded on a List of Strings and it is embedded in that row leading to a table where each row is a different length than the other rows...this is a noSql common pattern which is why NoSql ORM's need a slight break from JPA.,o | |
| PlayOrm also supports joins and S-SQL (scalable SQL).,p | |
| "later,Dean .",o | |
| Alternative/compatible datastores for App Engine?,o | |
| "What other ""nosql"" databases are compatible (more or less) with the Google Appe Engine datastore.",o | |
| "Alternatively, what is a good abstraction layer/solution (free of charge) that abstracts between multiple database implementations including google app engine and my application for db access.",p | |
| "I'd like to develop an app for GAE but later deploy it on my own server, but I do not want to have to rewrite the db code.",o | |
| "Important Update: The app is developed in Java | |
| so ideally the Data Abstraction Layer or any alternatives must be ""Java friendly"".",p | |
| possible duplicate of [GAE webapp alternative working outside of GAE environment]( URL_http://stackoverflow.com/questions/5278308/gae-webapp - alternative-working-outside-of-gae-environment).,p | |
| possible duplicate of [Use Google AppEngine datastore outside of AppEngine project]( URL_http://stackoverflow.com/questions/1149639/use-google-appengine - datastore-outside-of-appengine-project).,o | |
| related to [Breaking out of the Google App Engine Python lock- in?,o | |
| ]( URL_http://stackoverflow.com/questions/892411/breaking-out-of-the-google-app - engine-python-lock-in).,o | |
| Thanks for the comments.,o | |
| Some of the links I found prior to posting.,o | |
| "The problem is, the application is developed in Java not python.",o | |
| All the links mentioned are specific to python.,o | |
| AppScale 1.4 supports GAE 1.3.5's Java runtime (link in my answer).,o | |
| The URL_http://appscale.cs.ucsb.edu/ [AppScale] project has decoupled the database backend so that you can potentially run GAE on a variety of databases.,p | |
| They currently provide support for URL_http://hbase.apache.org/ [HBase] and URL_http://www.hypertable.org/ [Hypertable] ( URL_https://launchpad.net/appscale [ref] ).,o | |
| AppScale is open source and lets you run your GAE app on EC2 or your own cluster.,p | |
| "Strange as this sounds, but there is a great deal of similarity between AppEngine Datastore and the Lotus Domino: you may need to write an abstraction layer to handle the two APIs, but the capabilities are quite similar.",p | |
| "However, you need to be very familar with both models to see the parallels.",o | |
| Which is the standard Java crypto API?,o | |
| I want to implement a tool in Java to learn more about cryptography.,o | |
| I know that there is a security package with some crypto stuff inside.,o | |
| Now I saw there is a dedicated javax.crypto package inside the SDK.,p | |
| Where is the difference?,o | |
| Are they both up to date?,o | |
| I wanted to start my tool with some historical ciphers.,o | |
| But it should not be limited to them.,o | |
| So I need a nice abstraction through interfaces or something like that.,p | |
| Whats the better choice of the two APIs?,o | |
| Is there another API I should have a look at?,o | |
| Thanks in advance.,o | |
| "To answer the question asked: javax.crypto deals with low level crypto: encryption, decryption, and hashing.",n | |
| It's where the Cipher class is defined.,o | |
| "java.security deals with everything else: key management, certtificate management, and signatures.",o | |
| "Those interfaces abstract JCE providers, which implement specific algorithms.",o | |
| "Sun provides some, and BouncyCastle is another good one.",p | |
| "If you are planning some custom ciphers for which there is not already an implementation, you'll be implementing your own JCE provider, and specifically extending CODETERM1 .",o | |
| "It's not difficult, but you have to URL_http://java.sun.com/javase/6/docs/tech notes/guides/security/crypto/HowToImplAProvider.html [read-through-the- documentation-on-how-to-do-that] .",n | |
| "In order for the JCE to allow your provider, you will have to apply to Sun for a certificate, basically faxing them a signed statement that you are aware of the US export restrictions on crypto libraries.",o | |
| It's a mix of the two packages.,o | |
| URL_http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoS pec.html [Here] are the relevant docs .,o | |
| Thanks.,o | |
| "But before further reading: Can you tell me if I can use this API to implement cryptogrphic algorithms which are not part of the JCA, yet.",o | |
| E.g.,o | |
| historical ciphers?,o | |
| Thx.,o | |
| "JCA is just an API, it doesn't define ciphers.",o | |
| "The SPI (service provider interface) defines them, and you can extend the API to define your own.",o | |
| You could take a look at URL_http://www.bouncycastle.org [The-Legion-of-the- Bouncy-Castle] .,o | |
| "When we tried to do something that was compatible with openssl, only bouncycastle worked.",o | |
| The sun java security stuff was just too buggy to work in a compatible manner.,o | |
| "It should be compatible with itself, however.",o | |
| Also: bouncycastle doesn't require you to run inside that security sandbox stuff (which is mostly for applets - remember them?,o | |
| "), so debugging the program actually becomes possible.",o | |
| Check out URL_http://www.keyczar.org/ [keyczar] .,o | |
| +1000 for Keyczar.,o | |
| URL_http://www.jasypt.org [ URL_http://www.jasypt.org ] is also a good option.,p | |
| URL_http://java.sun.com/j2se/1.5.0/docs/api/ [The-updated-docs] .,o | |
| I have add another vote for Bouncy Castle.,o | |
| I recently needed an encryption algorithm that worked across multiple platforms (Java & C#).,o | |
| We tried to use the standard Java and C# encryption packages but we found too many issues with the encrypt/decrypt.,p | |
| "Looking around, Bouncy Castle had a .NET implementation in addition to a Java.",o | |
| "Although, .NET implementation of Bouncy Castle is not well documented, it is essentially the same as Java.",p | |
| Java Cryptography Extensions (The Practical Guide Series) by Jason Weiss.,o | |
| "I spent a lot on books, I have a lot of books, all of them very good.",p | |
| "( if you have a masters in math ) This book gets to the point, I had a cipher working in 5-6 hours.",p | |
| I had been working 5-6 years to get one running.,p | |
| Much practical advice from decades of doing actual infosec.,o | |
| 128 bit data encryption using Java.,o | |
| I need to store some sensitive data by encrypting it with atleast 128 bit key.,o | |
| "I investigated into javax.crypto package and found that there are certain Cipher names, like PBEWithMD5AndDES or PBEWithSHA1AndDESede which provides encryption upto 56 bit and 80 bit ( URL_http://en.wikipedia.org/wiki/DESede [ URL_http://en.wikipedia.org/wiki/DESede ] ).",o | |
| I referred other guys posts but those are mainly using RSA and in my understanding RSA is generally suitable for encrypting the communication data (with private-public key pair).,o | |
| "My need is different, I just want to store the data and retrieve it back by decrypting it.",o | |
| Therefore I don't need any private-public key pairs.,o | |
| Please let me know if you have any idea about this.,o | |
| Thanks in advance.,o | |
| Use URL_http://en.wikipedia.org/wiki/Advanced_Encryption_Standard [Advanced- Encryption-Standard] (AES).,o | |
| "It supports Key lengths of 128, 192, or 256 bits.",o | |
| The URL_http://www.hoozi.com/Articles/AESEncryption.htm [algorithm] is simple.,p | |
| The Sun Java website has a URL_http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html [section-explaining-how-to-do-AES] encryption in Java.,o | |
| "From Wikipedia... | |
| ... the Advanced Encryption Standard (AES), also known as Rijndael, is a block cipher adopted as an encryption standard by the U.S. government.",p | |
| "It has been analyzed extensively and is now used worldwide, as was the case with its predecessor, the Data Encryption Standard (DES)...",p | |
| So as a rule of thumb you are not supposed to use DES or its variants because it is being phased out.,o | |
| "As of now, it is better to use AES.",o | |
| "There are other options like URL_http://en.wikipedia.org/wiki/Twofish [Twofish] , URL_http://en.wikipedia.org/wiki/Blowfish_(cipher) [Blowfish] etc also.",o | |
| Note that Twofish can be considered as an advanced version of Blowfish.,o | |
| I have had good success in the past with URL_http://www.bouncycastle.org/ [ URL_http://www.bouncycastle.org/ ] (they have a C# version as well).,p | |
| You need to download and install the unlimited strength JCE policy file for your JDK.,o | |
| "For JDK 6, it is on URL_http://java.sun.com/javase/downloads/index.jsp [ URL_http://java.sun.com/javase/downloads/index.jsp ] at the very bottom.",o | |
| Isn't it required only for AES-192 or 256?,o | |
| I believe AES-128 doesn't require the unlimited strength JCE policy files.,o | |
| Combining 3 different replies gives what I think is the correct answer.,p | |
| "Download encryption libraries from URL_http://www.bouncycastle.org/java.html [Bouncycastle] then you need to download the ""Unlimited Strength Jurisdiction Policy"" from URL_http://www.oracle.com/technetwork/java/javase/downloads/index.html [Oracle] (the files are at the bottom of the download page).",o | |
| Make sure you read the Readme-file on how to install it.,o | |
| "Once you have done this, and using the sample code supplied with the Bountycastle package you should be able to encrypt your data.",o | |
| "You can go with a tripple DES implementation, which will give you 112 bits key (often referred to as 128 bit, but only 112 of them are actually secure), or as previously stated, you can use AES.",p | |
| My money would be on AES.,o | |
| "Heads Up: It's BounCycastle, not BounTycastle.",o | |
| "I'm not a crypto expert by any means (so take this suggestion with a grain of salt), but I have used URL_http://en.wikipedia.org/wiki/Blowfish_(cipher) [Blowfish] before, and I think you can use it for what you need.",o | |
| There is also a newer algorithm by the same guy called URL_http://en.wikipedia.org/wiki/Twofish [Twofish] .,o | |
| "Here is a URL_http://www.hotpixel.net/software.html [website-with-a-Java- implementation] , but be careful of the license (it says free for non- commercial use).",p | |
| You can find that link also from URL_http://www.schneier.com /blowfish-download.html [Bruce-Schneier's-website] (the creator of both algorithms).,o | |
| "the link in ""website with java implementation"" is dead.",o | |
| plz update it...,o | |
| "Thanks Michael, after trying out many things in JCE, I finally settled for bouncycastle.",o | |
| JCE supports AES for encryption and PBE for password based encryption but it does not support combination of both.,o | |
| I wanted the same thing and that I found in bouncycastle.,o | |
| The example is at : URL_http://forums.sun.com/thread.jspa?messageID=4164916 [ URL_http://forums.sun.com/thread.jspa?messageID=4164916 ] .,o | |
| Is Bouncy Castle API Thread Safe?,o | |
| Is URL_http://bouncycastle.org/java.html [Bouncy-Castle-API] Thread Safe ?,o | |
| "Especially, CODESNIPPET_JAVA1 .",o | |
| I am planning to write a singleton Spring bean for basic level cryptography support in my app.,o | |
| "Since it is a web application, there are greater chances of multiple threads accessing this component at a time.",p | |
| So tread safety is essential here.,o | |
| Please let me know if you have come across such situations using Bouncy Castle.,o | |
| Thanks in advance.,o | |
| It really does not matter if the API/Code is thread safe.,p | |
| CBC encryption in itself is not thread safe.,n | |
| Some terminology - CODESNIPPET_JAVA1 .,o | |
| "A really simple CBC implementation can look like:P1, P2, P3 | |
| Plain text messages CODESNIPPET_JAVA2 .",p | |
| "As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order).",o | |
| "So, in a CBC implementation, order is important.",o | |
| "Any algorithm where order is important can not, by definition, be thread safe.",p | |
| "You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe.",p | |
| "Yes, Tnilsson, your reasoning is right.",o | |
| "I found the following post, URL_http://www.bouncycastle.org/devmailarchive/msg04715.html from bouncy castle's mailing list.",o | |
| It's not completely thread safe (atleast AES engine).,p | |
| The J2ME version is not thread safe.,n | |
| Java 256-bit AES Password-Based Encryption.,o | |
| "I need to implement 256 bit AES encryption, but all the examples I have found online use a ""KeyGenerator"" to generate a 256 bit key, but I would like to use my own passkey.",o | |
| How can I create my own key?,o | |
| "I have tried padding it out to 256 bits, but then I get an error saying that the key is too long.",n | |
| "I do have the unlimited jurisdiction patch installed, so thats not the problem :) Ie.",o | |
| The KeyGenerator looks like this ... CODESNIPPET_JAVA1 .,o | |
| "URL_http://java.sun.com/developer/technicalArticles/Security/AES/AES%5Fv1.html [Code-taken-from-here] | |
| I was actually padding the password out to 256 bytes, not bits, which is too long.",n | |
| The following is some code I am using now that I have some more experience with this.,o | |
| CODESNIPPET_JAVA2 .,o | |
| "The ""TODO"" bits you need to do yourself :-) .",o | |
| Could you clarify: does calling kgen.init(256) work?,o | |
| "Yes, but this automatically generates a key ... but since I want to encrypt data between two places, I need to know the key beforehand, so I need to specify one instead of ""generate"" one.",o | |
| I can specify a 16bit one which works for 128bit encryption which works.,p | |
| "I have tried a 32bit one for 256bit encryption, but it did not work as expected.",o | |
| "If I understand correctly, you are trying to use a pre-arranged, 256-bit key, specified, for example, as an array of bytes.",p | |
| "If so, DarkSquid's approach using SecretKeySpec should work.",o | |
| "It's also possible to derive an AES key from a password; if that's what you are after, please let me know, and I'll show you the correct way to to do it; simply hashing a password isn't the best practice.",p | |
| "Be careful about padding a number, you may be making your AES less secure.",p | |
| @erickson: that is exatly what i need to do (derive an AES key from a password).,o | |
| @Nippysaurus: Any luck?,o | |
| Please comment on my answer if you still have problems it doesn't address.,o | |
| @erickson: Nope.,o | |
| "I got both .NET and Java to compile something in what I thought was 256bit, but the results were different.",o | |
| I might not need to do the Java side after all.,o | |
| As a last resort we will probably use bouncycastle :).,o | |
| @Nippysaurus Were you able to get this to work?,o | |
| "If so, would you mind posting the complete solution including the code from AES_v1.html?",o | |
| Sorry this was more than two years ago and I havent done any Java since.,n | |
| Share the CODETERM1 (a CODETERM2 ) and CODETERM3 (a CODETERM4 8 bytes selected by a CODETERM5 makes a good saltwhich doesn't need to be kept secret) with the recipient out-of-band.,p | |
| Then to derive a good key from this information (in Java 6): CODESNIPPET_JAVA1 .,p | |
| Now send the CODETERM6 and the CODETERM7 to the recipient.,o | |
| "The recipient generates a CODETERM8 in exactly the same way, using the same salt and password.",o | |
| Then initialize the cipher with the key _and_ the initialization vector.,o | |
| CODESNIPPET_JAVA2 .,o | |
| " | |
| A CODETERM9 with the message ""Illegal key size or default parameters"" means that the cryptography strength _is_ limited; the unlimited strength jurisdiction policy files are not in the correct location.",n | |
| "In a JDK, they should be placed under CODETERM10 Based on the problem description, it sounds like the policy files are not correctly installed.",p | |
| Systems can easily have multiple Java runtimes; double- check to make sure that the correct location is being used.,p | |
| Argh.,o | |
| Salts are not necessary for symmetric encryption.,o | |
| "IVs serve a similar purpose, and are prepended to the ciphertext by most (all?",o | |
| ) crypto libraries.,o | |
| "@Nick: Read PKCS | |
| ",o | |
| "Salts are necessary for PBKDF2, which is why the API for password-based encryption requires them as input for key derivation.",o | |
| "Without salts, a dictionary attack could be used, enabling a pre-computed list of the most likely symmetric encryption keys.",o | |
| Cipher IVs and key-derivation salts serve different purposes.,o | |
| IVs allow one reuse the same key for multiple messages.,o | |
| Salts prevent dictionary attacks on the key.,o | |
| Does this usage of SecureKey and PBEKeySpec produce a Password-based key that is RFC2898-compliant?,o | |
| URL_http://www.ietf.org/rfc/rfc2898.txt .,o | |
| "Yes, that is the ""PBKDF2"" of the SecretKeyFactory algorithm name.",o | |
| "It is referring to PKCS | |
| PBKDF2 (Password-Based Key Derivation Function | |
| ",o | |
| "If you were storing encrypted data in a database using the method above, would you store the ciphertext (blob) and the iv (char) in the database, and the password and salts would be supplied to the client application by the user or in the application's configuration files?",o | |
| "In that case, I'd store the ciphertext in one field, the IV in another, and the ""salt"" and ""iterations"" together in a third.",o | |
| "I'd prompt the user in the client application for the password, and derive the key using the stored salt and iterations.",o | |
| "Then initialize the cipher with the derived key and stored IV, and decrypt the content.",o | |
| "@erickson: in case you store iv, salt, etc.",o | |
| "in the database, why not just use 'PBEWithMD5AndDES' and append the salt to the encrypted text, after loading u can strip the salt and use it for decryption.",p | |
| This way PBE is implemented in jasypt framework: URL_www.jasypt.org.,o | |
| "First, that would be DES encryption, not AES.",o | |
| "Most providers don't have good support for the PBEwithand algorithms; for example, the SunJCE doesn't provide and PBE for AES.",p | |
| "Second, enabling jasypt is a non-goal.",o | |
| A package that purports to offer security without requiring an understanding of the underlying principles seems dangerous prima facie.,o | |
| @erickson so the lack of support is the only criteria not to use 'PBEWithMD5AndDES'?,o | |
| Are there any further criterias not to use this algo for enryption of data stored in a db?,o | |
| "Although MD5 is ""broken"" in some applications, I don't think that it is a problem here.",n | |
| But the weakness of DES is definitely a problem.,n | |
| The tiny key of DES can be broken in hours or days using a few thousand dollars worth of equipment.,n | |
| "I've implemented @erickson's answer as a class: URL_https://github.com/mrclay/jSecureEdit/tree/master/src/org/mrclay/crypto (PBE does the work, PBEStorage is a value object for storing the IV/ciphertext together.",o | |
| ).,o | |
| "@erickson Could you post your answer implemented in the example: URL_http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html , I am not sure how the password and salt should be correct specified or generated in the latter case?",o | |
| "@Astron Sorry, I don't really understand your question.",n | |
| Are you asking why the example you linked to doesn't use salt and password?,o | |
| "If so, that's because they aren't doing password-based encryption there; the key is a random sequence of bytes, not derived from a password.",o | |
| "@erickson Sorry, I meant I am looking for a working implementation of the example linked using your password-based encryption.",n | |
| I tried plugging in your respective examples into the example but have yet been able to get it to work correctly.,p | |
| I could start a new question but figured it would be helpful for others if it were here as I am not looking for any deviation.,p | |
| "This solution does not provide authenticated encryption, does it?",o | |
| Don't we also need to MAC the ciphertext to get authenticated encryption?,o | |
| "@EricConner You're right, there is no integrity or authentication provided, only privacy.",o | |
| "In order to get authentication, I'd recommend a different mode, like CCM, if your provider supports it (the SunJCE provider doesn't implement any authenticating cipher modes, at least not up through Java 7).",p | |
| Trying to implement this with Doug's code below.,o | |
| "erickson says to ""Share the password (a char[]) and salt (a byte[]8"" with recipient but then ""send the ciphertext and the iv to the recipient"" which is it?",o | |
| the iv or the salt?,o | |
| They are different correct?,o | |
| "@wufoo They | |
| different, and you share both.",o | |
| "You'll probably share the salt (for key derivation) one time, at the same time you set up the password itself.",o | |
| "But every message you send after that should include the unique IV that was used to encrypt that message (and | |
| that message.",o | |
| "@wufoo By the way, Doug's code has a number of security flaws.",o | |
| I can't recommend it as an example.,n | |
| @erickson - thanks for the reply.,o | |
| Planning on posting my fixes for feedback when I get to that point.,o | |
| "It's not an ideal place for neophytes (bouncycastle license won't work for me), but with 83k views to the thread a more polished example is really needed.",p | |
| "I see you've graciously offered to do that below, so I'll wait and see.",p | |
| "@wufoo The problem with a more developed example is that doing things the ""right way"" would require some encoded structures for transmitting the message and IV, and the PBE parameters.",o | |
| "It ends up being not fitting well into this Q&A format, and it's code that you probably don't need to write yourself.",p | |
| "@erickson I'm new here, not sure how this works but would you be interested in bounty points to fix up Dougs code?",o | |
| Or maybe a link to a more developed example?,o | |
| I've combed google for days and this exact thread keeps coming up.,o | |
| I've only got a couple other examples: URL_http://www.digizol.org/2009/10/java - encrypt-decrypt-jce-salt.html and URL_http://cs.saddleback.edu/rwatkins/CS4B/Crypto/FileEncryptor.html but they are not complete.,o | |
| "Requring, as Doug put it, Frankensteining something.",o | |
| @erickson I am just storing hashed/encrypted passwords in a database.,p | |
| "Can your example be used for safe storage of passwords, rather than using a sha1sum of the password and a salt?",o | |
| "@AndyNuss This example is for reversible encryption, which generally should not be used for passwords.",o | |
| "You | |
| use the PBKDF2 key derivation to ""hash"" passwords securely.",o | |
| "That means that in the example above, you'd store the result of tmp.getEncoded() as the hash.",o | |
| You should also store the salt and the iterations (65536 in this example) so that you can recompute the hash when someone tries to authenticate.,o | |
| "In this case, generate the salt with a cryptographic random number generator each time the password is changed.",p | |
| "For running this code, make sure you have the right Unlimited Strength Jurisdiction Policy Files in your JRE as stated in URL_http://www.ngs.ac.uk/tools/jcepolicyfiles .",o | |
| Is there a way of doing this without Unlimited Strength Jurisdiction Policy files?,o | |
| @ArchimedesTrajano Not with the Java Cryptography Architecture.,o | |
| I would suggest using AES-128.,o | |
| AES-128 is good.,p | |
| NIST recommends it for applications through 2030.,p | |
| "If you really need AES-256 and can't get it through the JCA, you can use a non-standard API, like BouncyCastle's ""lightweight"" crypto API directly to bypass the restrictions.",p | |
| I can't speak to the legal ramifications of doing so (your software might be illegal to import into certain regions).,n | |
| +1 but if you send the encrypted data over the network as implied in the answer you have to make sure that integrity of the message is ensured.,p | |
| "In other words you need to generate another key to use a MAC, or you could use an authenticated mode of encryption such as GCM.",p | |
| "After reading through erickson's suggestions, and gleaning what I could from a couple other postings and this example URL_http://cs.saddleback.edu/rwatkins/CS4B/Crypto/FileEncryptor.html [here] , I've attempted to update Doug's code with the recommended changes.",p | |
| Feel free to edit to make it better.,p | |
| " | |
| Initialization Vector is no longer fixed | |
| encryption key is derived using code from erickson | |
| 8 byte salt is generated in setupEncrypt() using SecureRandom() | |
| decryption key is generated from the encryption salt and password | |
| decryption cipher is generated from decryption key and initialization vector | |
| removed hex twiddling in lieu of org.apache.commons URL_http://commons.apache.org/codec/download_codec.cgi [codec] Hex routines Some notes: This uses a 128 bit encryption key - java apparently won't do 256 bit encryption out-of-the-box.",o | |
| Implementing 256 requires installing some extra files into the java install directory.,o | |
| "Also, I'm not a crypto person.",o | |
| Take heed.,o | |
| CODESNIPPET_JAVA1 .,o | |
| " | |
| Consider using the URL_http://docs.spring.io/spring- security/site/docs/3.1.x/reference/crypto.html [Spring-Security-Crypto-Module] | |
| The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding.",o | |
| The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code.,o | |
| "It's provides a simple abstraction for encryption and seems to match what's required here, | |
| The ""standard"" encryption method is 256-bit AES using PKCS | |
| PBKDF2 (Password-Based Key Derivation Function | |
| ",p | |
| This method requires Java 6.,o | |
| The password used to generate the SecretKey should be kept in a secure place and not be shared.,p | |
| The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised.,p | |
| A 16-byte random initialization vector is also applied so each encrypted message is unique.,p | |
| A look at the URL_http://grepcode.com/file/repo1.maven.org/maven2/org.springfr amework.security/spring-security-core/3.1.4.RELEASE/org/springframework/securi ty/crypto/encrypt/AesBytesEncryptor.java#53 [internals] reveals a structure similar to URL_http://stackoverflow.com/a/992413/277307 [erickson's-answer] .,o | |
| "As noted in the question, this also requires the _Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy_ (else you'll encounter URL_http://stackoverflow.com/questions/3862800/invalidkeyexception-illegal- key-size/3864325 [CODETERM1] ).",o | |
| It's downloadable for URL_http://www.oracle.co m/technetwork/java/javase/downloads/jce-6-download-429243.html [Java-6] and UR L_ URL_http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-43212 4.html [Java-7] .,o | |
| " | |
| Example usage CODESNIPPET_JAVA1 .",o | |
| "And sample output, CODESNIPPET_JAVA2 .",o | |
| "What I've done in the past is hash the key via something like SHA256, then extract the bytes from the hash into the key byte[].",o | |
| After you have your byte[] you can simply do: CODESNIPPET_JAVA1 .,o | |
| For others: this isn't a very secure method.,p | |
| You should use PBKDF 2 specified in PKCS#5.,o | |
| erickson said how to do this above.,o | |
| DarkSquid's method is vulnerable to password attacks and also doesn't work unless your plaintext's size is a multiple of AES's block size (128 bits) because he left out padding.,p | |
| Also it doesn't specify the mode; read Wikipedia's Block Cipher Modes of Operation for concerns.,n | |
| Generating your own key from a byte array is easy: CODESNIPPET_JAVA1 .,p | |
| But creating a 256-bit key isn't enough.,n | |
| "If the key generator cannot generate 256-bit keys for you, then the URL_http://java.sun.com/javase/6/docs/api/javax/crypto/Cipher.html [CODETERM1] class probably doesn't support AES 256-bit either.",o | |
| "You say you have the unlimited jurisdiction patch installed, so the AES-256 cipher should be supported (but then 256-bit keys should be too, so this might be a configuration problem).",o | |
| CODESNIPPET_JAVA2 .,o | |
| "A workaround for lack of AES-256 support is to take some freely available implementation of AES-256, and use it as a custom provider.",n | |
| "This involves creating your own URL_http://java.sun.com/javase/6/docs/api/java/security/Provider.html [CODETERM2] subclass and using it with URL_http://java.sun.com/javase/6/docs/a pi/javax/crypto/Cipher.html#getInstance%28java.lang.String,%20java.security.Pr ovider%29 [CODETERM3] .",o | |
| But this can be an involved process.,o | |
| You should always indicate the mode and padding algorithm.,o | |
| Java uses the unsafe ECB mode by default.,o | |
| "I've implemented the erickson's answer in a really simple class: URL_http://pastebin.com/YiwbCAW8 [Java-AES-256-bit-Encryption/Decryption- class] If you get the CODETERM1 you have to install the Java Cryptography Extension (JCE) unlimited strength jurisdiction policy files: | |
| URL_http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html [Java-6-link] | |
| URL_http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html [Java-7-link] Just place the jars in your CODETERM2 .",p | |
| You appear to be sharing the same fixed salt value between all key instances.,o | |
| That's probably not a good idea.,p | |
| It works fine.,p | |
| "However, if I am decrypting using a different instance of the AESEncrypter, the decrypted file tends to have some issues in the first few bytes (9 bytes).",o | |
| I encrypted a file using a passphrase then later I tried to decrypt using the same passphrase.,p | |
| All contents of the file except the first 9 bytes were decrypted properly.,o | |
| "Might work fine, but fixed salt is akin to WEP encryption on your wi-fi router.",o | |
| Maybe you should try the URL_http://www.bouncycastle.org/ [BouncyCastle] crypto provider.,o | |
| It is free and you can use larger key sizes than the default JDK.,p | |
| Use this class for encryption.,o | |
| It works.,p | |
| CODESNIPPET_JAVA1 .,o | |
| } And these are ivBytes and a random key; CODESNIPPET_JAVA2 .,o | |
| NLP Library in java.,o | |
| " | |
| Possible | |
| Duplicate:** URL_http://stackoverflow.com/questions/870460/java-is-there-a-good-natural- language-processing-library [Java-:-Is-there-a-good-natural-language- processing-library] I need a simple Natural Language Processing library written in java which can be used to process a search query/question.",p | |
| "What I want actually is to separate | |
| the main subject which is being searched in a query**.",o | |
| "For an example, considering a query like ""What is an apple?",o | |
| """, it's perfect if the main search word apple can be extracted.",p | |
| This is for a semantic search engine development purpose.,o | |
| Can anyone please suggest a suitable nlp library for this??,o | |
| Thank You!!,p | |
| "The easiest way for you that I see is to use concept | |
| tagging** from URL_http://www.alchemyapi.com/api/ [AlchemyAPI] .",p | |
| "You can also use some plugins for libraries from questions, pointed in comments, especially pay attention to | |
| URL_http://incubator.apache.org/opennlp/ [OpenNLP] | |
| and | |
| URL_http://gate.ac.uk/ [GATE] . | |
| ",o | |
| "If you are going to build ontology-based | |
| search engine**, I recommend you reading URL_http://www.springerlink.com/content/462t8871w5255l13/ [this] paper on ontology-based interpretation of keywords, that shows some tendencies in user's habits ( URL_http://videolectures.net/iswc07_tran_obi/ [video-version] ).",p | |
| "Otherwise, you'll better use some statistical | |
| techniques** like URL_http://en.wikipedia.org/wiki/Latent_semantic_analysis [LSA] .",o | |
| Jakarta Lucene/Solr?,o | |
| URL_http://lucene.apache.org/java/docs/index.html [ URL_http://lucene.apache.org/java/docs/index.html ] .,o | |
| Named entity recognition with Java.,o | |
| I would like to use named entity recognition (NER) to find adequate tags for texts in a database.,o | |
| Instead of using tools like NLTK or Lingpipe I want to build my own tool.,o | |
| "So my questions are: | |
| Which algorithm should I use?",o | |
| " | |
| How hard is to build this tool?",o | |
| "Since there are so many ways to go about it, we could better inform you if you shared your goals and why you're trying to to DIY.",o | |
| "And are you willing to use any libraries at all, such as machine learning?",o | |
| I did this some time ago when I studied Markov chains.,o | |
| "Anyway, the answers are: | |
| Which algorithm should I use?",o | |
| Stanford NLP for example uses Conditional Random Field (CRF).,o | |
| "If you are not trying to do this effectively, you are like dude from Jackass 3d who was CODETERM1 .",o | |
| "There is no simple way to parse human language, as it's construction is complex and it has tons of exceptions.",n | |
| " | |
| How hard is to build this tool?",o | |
| "Well if you know what you are doing, then it's not that hard at all.",p | |
| "The process of entering the rules and logic can be annoying and time consuming, and fixing bugs can be nontrivial.",n | |
| "But in 20 years, you can make something almost useful (for yourself).",o | |
| 1.,o | |
| "There is vast of Information Extraction algorithms, to name a few: regular expressions, statical methods, machine learning based, dictionaries, etc.",o | |
| You can find a complete overview on methods in URL_http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.164.2388&rep=rep1&type=pdf [this-survey] .,o | |
| 2.,o | |
| "Yes, it is hard to build a tool, which find tags with high precision, because it requires a lot of testing and tuning.",n | |
| "The -- easiest to implement -- algorithm for finding tags will consists of two steps: | |
| Extract candidates for tags | |
| Find most significant tags - most disti.",o | |
| "In the first step you can take one of two approaches: | |
| Use entity names to use as tag candidates (here you need to use Information Extraction framework) | |
| Use nouns or noun groups as tag candidates (here you need to use part-of-speech tagger) In the second step, you should use tf-idf to weight tags across document corpus and discard all tags which has tf-idf weight below a given trash-hold If you need a more powerful algorithm look for topic detection frameworks or URL_http://scholar.google.de/scholar?q=topic%20detection [research-papers-on- this-topic] .",p | |
| "Check also URL_http://ttp://en.wikipedia.org/wiki/Latent_semantic_analysis [LSA] , after wikipedia: | |
| Latent semantic analysis (LSA) is a technique in natural language processing, in particular in vectorial semantics, of analyzing relationships between a set of documents and the terms they contain by producing a set of concepts related to the documents and terms.",o | |
| Please check also his question - URL_http://stackoverflow.com/questions/5544475 /does-an-algorithm-exist-to-help-detect-the-primary-topic-of-an-english- sentence.,o | |
| !,o | |
| "Please check also this post - URL_http://nlpers.blogspot.com/2011/04/seeding - transduction-out-of-sample.html , it describes researcher's -- hands on -- experience in creating taggers.",o | |
| NLTK is an open-source project.,o | |
| "You might want to explore it a little bit - see how it is done, maybe get involved in the community, rather than trying to completely solve the problem by yourself from scratch... .",n | |
| "Look for a copy of this paper: | |
| Name Tagging with Word Clusters and Discriminative Training | |
| Scott Miller, Jethran Guinness, Alex Zamanian .",o | |
| "This may not be a satisfactory answer to your question, still: You might want to evaluate existing service providers for the task and either include their product or integrate one via web services.",p | |
| My experience is that for certain well-defined and very domain-specific tasks (for example: recognizing names of medicaments within Wikipedia web pages) you _can_ manually build NER solutions.,o | |
| "URL_http://alias-i.com/lingpipe/ [LingPipe] , URL_http://opennlp.sourceforge.net/projects.html [OpenNLP] , etc.",o | |
| are good tools for this.,p | |
| "But for generic tasks (for example: find person names in any web page on the internet), you need a lot of experience, tools, and man-power to get satisfactory results.",p | |
| It might therefore be more effective to use an external provider.,o | |
| "URL_http://www.opencalais.com/ [OpenCalais] is a free service, for example; many commercial ones exist.",p | |
| Natural Language date and time parser for java.,o | |
| "I am working on a Natural Language parser which examines a sentence in english and extracts some information like name, date etc.",p | |
| "for example: ""_Lets meet next tuesday at 5 PM at the beach._"" So the output will be something like : ""_Lets meet 15/09/2009 at 1700 hr at the beach_"" So basically, what i want to know is that | |
| there any framework or library available for JAVA to do these kind of operations like parsing dates from a sentence and give a output with some specified format.",o | |
| " | |
| Regards,Pranav | |
| Thanks for the replies.",o | |
| "I have looked on few NLPs like URL_http://alias-i.com/lingpipe/index.html [LingPipe] , OpenPL, URL_http://nlp.stanford.edu/index.shtml [Stanford-NLP] .",o | |
| I wanted to ask do they hav anything for date parsing for java.,o | |
| URL_http://natty.joestelmach.com/ [Natty] is a really good replacement for JChronic.,p | |
| I swear Natty handles pretty much everything.,n | |
| "For example, 2 wednesdays from now can't be parsed by any other solution I've found.",o | |
| +1.,o | |
| "I have a system where I'm being fed strings from which I need to (on a best guess basis) remove URLs, anything which might be HTML and anything which might be a date - I've found Natty is excellent for the latter, but I've built exceptions for April, May and June, which are valid girls' names.",p | |
| "You can use URL_https://github.com/samtingleff/jchronic [JChronic] , the Java port of URL_http://chronic.rubyforge.org/ [Chronic] .",o | |
| Have you tried URL_https://github.com/samtingleff/jchronic [jchronic] ?,o | |
| "However, I doubt any library could directly work with sentences: you'd have to extract sentence fragments and feeding them to a NLP date parsing framework yourself, perhaps on a trial-n-error basis (larger and larger fragments until the framework throws an error).",o | |
| I don't think there's any framework out there that does that out of the box.,o | |
| What you can do is create a set of regular expressions to match those patterns.,o | |
| I would suggest using URL_http://uima.apache.org/ [UIMA] with URL_http://opennlp.sourceforge.net/projects.html [OpenNLP] connectors and same hand made regexp rules.,o | |
| fuzzy string search in Java.,o | |
| I'm looking for high performance Java library for fuzzy string search.,o | |
| "There are numerous algorithms to find similar strings, Levenshtein distance, Daitch-Mokotoff Soundex, n-grams etc.",o | |
| What Java implemenations exists?,o | |
| Pros and cons for them?,o | |
| "I'm aware of Lucene, any other solution or Lucene is best?",o | |
| "I found these, anyone has experience with them?",o | |
| URL_http://www.dcs.shef.ac.uk/~sam/simmetrics.html [SimMetrics] URL_http://ngramj.sourceforge.net/ [NGramJ] .,o | |
| "Commons Lang has an implementation of URL_http://commons.apache.org/lang/apido cs/org/apache/commons/lang3/StringUtils.html#getLevenshteinDistance%28java.lan g.CharSequence,%20java.lang.CharSequence%29 [Levenshtein-distance] .",o | |
| Commons Codec has an implementation of URL_http://commons.apache.org/proper /commons-codec/apidocs/org/apache/commons/codec/language/Soundex.html [soundex] and URL_http://commons.apache.org/proper/commons- codec/apidocs/org/apache/commons/codec/language/Metaphone.html [metaphone] .,o | |
| SimMetrics is probably what you need: URL_http://sourceforge.net/projects/simmetrics/ [ URL_http://sourceforge.net/projects/simmetrics/ ] It has several algorithms for calculating various flavours of edit-distance.,o | |
| "Lucene is a very powerful full-text search engine, but FT search isn't exactly the same thing as fuzzy string matching (eg.",p | |
| given a list of strings find me the one that is most similar to some candidate string).,o | |
| "simmetrics looks to be GPL v2, however, so not compatible with commercially developed software.",o | |
| To Lucene I would add SOLR URL_http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters [ URL_http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters ] .,o | |
| "URL_http://lucene.apache.org/ [Apache-Lucene] is the only way, I think.",o | |
| I don't know any better search lib.,o | |
| " | |
| Apache Lucene(TM) is a high-performance, full-featured text search engine library written entirely in Java.",p | |
| "It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.",n | |
| You can try bitap.,o | |
| I was playing with bitap written in ANSI C and it was pretty fast there is java implementation in URL_http://www.crosswire.org [ URL_http://www.crosswire.org ] .,p | |
| File Manipulation libraries.,o | |
| I have a project which I need to manipulate files.,o | |
| "things like: create new file by a defined structure(header,data,trail).",o | |
| and then I need to things like search/validate/create/read.,o | |
| basically I want to map the files to objects and vise versa.,o | |
| (I am willing to map them to objects coz it will be much more comfortable for me to manipulate the fields inside each file via object) I wonder if any of you deal with such things before?,o | |
| and maybe could recommend me on libraries which could easy my work.,p | |
| "thanks,ray.",o | |
| You may want to look at serialization and de-serialization .,o | |
| serialization wont help me here.,o | |
| I want my own structure in the file since some1 else need to read it by a specific structure.,o | |
| serialization wont map the object to the file in the way I want it.,o | |
| "If you want custom mapping, you need custom coding.",o | |
| I would suggest you look at DataInputStream and DataOutputStream.,o | |
| "Using these you can control the header, records and footer in any binary format you want.",o | |
| I suggest you generate your serialization (if you need to have the afstest possible speed) or use reflections to do the translation.,o | |
| Just using reflection is pretty fast and much simpler than generating code.,p | |
| ;) .,o | |
| but Serialization will make it binary.,o | |
| I want it to remine text.,o | |
| In that case I would serialize as text.,o | |
| ";) With the built in Serialization you have no choice, but if you do it yourself, you can make it anything you want.",o | |
| "For example, all my objects serialize and deserialize in CSV format i.e.",o | |
| you can read it in excel.,p | |
| ;) You could use XML or JSon with XStream.,o | |
| If you have a defined file layout with different content you should consider to use a template engine like URL_http://freemarker.sourceforge.net/ [FreeMarker] or URL_http://velocity.apache.org/ [Velocity] to generate your files.You can define templates here which will be filled with your dynamic content which you have to provide.,o | |
| Definitly better than to use CODETERM1 (I mean hard code your template text).,n | |
| A library which helps for basic file manipulation is URL_http://commons.apache.org/io/ [Apache-Commons-IO] .,o | |
| If you realy want to map your files to objects than it would be a Serialization/Deserialization as Angelom mentions.,o | |
| "Many libraries help you to do this but the file format is fixed: JSON: URL_http://jackson.codehaus.org/ [Jackson] , URL_http://code.google.com/p/google-gson/ [GSON] XML: URL_http://jaxb.java.net/ [JAXB] .",o | |
| Are those libraries able to sanely produce binary output?,o | |
| As far as I know they are focused on text-based output formats.,p | |
| @Joachim The libraries work with text output (that is what _rayman_ needs if I understand it correct).,p | |
| "He doesn't mention if he wants text or binary, actually but from what I understand he want's the library to help him with parsing/reading as well.",p | |
| And that's where those template libraries fall flat.,o | |
| He want's text (see comment in answer from Lawrey).,o | |
| Using templates to generate his files will definitly help - particularly if his files contains lot text around the object info.,o | |
| You are right - reading is not included - thus I only mentioned generation of his files.,o | |
| I tried to give help and some ideas - I thought that would be requested.,o | |
| Unfortunately I do not know the library he want's.,n | |
| "If you want the file read by 3rd party as well, how about using some popular existing exchange format such as CSV or XML?",o | |
| XML is fully supported in standard library.,p | |
| "There's plenty of CSV libraries out there, including URL_http://commons.apache.org/sandbox/csv/ [Apache- Commons-CSV] .",o | |
| I am not required to use XML format.,o | |
| only a specific format which is defined by the company.,o | |
| that format is TXT and I wanted to convert all those files to objects.. something like ORM.,o | |
| In the end I Found a ORM framework called Canyon which mapping Files to Objects.,o | |
| but still had difficulties.,n | |
| so I have implemented my own ORM file to objects and vise versa.,o | |
| java.net versus java.nio.,o | |
| At what point is it better to switch from java.net to java.nio?,o | |
| ".net (not the Microsoft entity) is easier to understand and more familiar, while nio is scalable, and comes with some extra nifty features.",p | |
| "Specifically, I need to make a choice for this situation: We have one control center managing hardware at several remote sites (each site with one computer managing multiple hardware units (a transceiver, TNC, and rotator)).",o | |
| "My idea was to have write a sever app on each machine that acts as a gateway from the control center to the radio hardware, with one socket for each unit.",o | |
| "From my understanding, NIO is meant for one server, many clients, but what I'm thinking of is one client, many servers.",o | |
| "I suppose a third option is to use MINA, but I'm not sure if that's throwing too much at a simple problem.",p | |
| " | |
| Each remote server will have up to 8 connections, all from the same client (to control all the hardware, and separate TX/RX sockets).",o | |
| "The single client will want to connect to several servers at once, though.",o | |
| "Instead of putting each server on different ports, is it possible to use channel selectors on the client side, or is it better to go multi-threaded io on the client side of things and configure the servers differently?",o | |
| " | |
| Actually, since the remote machines serve only to interact with other hardware, would RMI or IDL/CORBA be a better solution?",o | |
| "Really, I just want to be able to send commands and receive telemetry from the hardware, and not have to make up some application layer protocol to do it.",o | |
| Avoid NIO unless you have a good reason to use it.,p | |
| URL_http://blog.uncommons.org/2008/09/03/avoid-nio-get-better-throughput/ [It's-not-much-fun-and-may-not-be-as-beneficial-as-you-would-think] .,o | |
| "You may get better scalability once you are dealing with tens of thousands of connections, but at lower numbers you'll probably get better throughput with blocking IO.",n | |
| "As always though, make your own measurements before committing to something you might regret.",n | |
| "Something else to consider is that if you want to use SSL, NIO makes it extremely painful.",o | |
| "Thanks for the remark about SSL, this will probably drive my decision.",o | |
| Scalability will probably drive your choice of package.,o | |
| java.net will require one thread per socket.,o | |
| Coding it will be significantly easier.,o | |
| "java.nio is much more efficient, but can be hairy to code around.",n | |
| I would ask yourself how many connections you expect to be handling.,o | |
| "If it's relatively few (say, < 100), I'd go with java.net.",o | |
| With a modern 64-bit OS you can have hundreds of thousands of threads.,o | |
| "Sure, but that's not necessarily the most scalable way to architect an application.",p | |
| But a socket is much more resource intensive than a thread...,o | |
| The question is not one of more sockets versus more threads.,o | |
| It's how many threads per socket.,o | |
| @Zombies in what sense?,o | |
| Beyond the fact that a thread costs you half a megabyte and a socket costs you a few dozen kilobytes they are barely comparable at all.,o | |
| The number of connections you're talking about tells me you should use java.net.,o | |
| "Really, there's no reason to complexify your task with non-blocking I/O.",o | |
| "(Unless your remote systems are underpowered, but then why are you using Java on them?",o | |
| ) Take a look at URL_http://ws.apache.org/xmlrpc/ [Apache's-XML-RPC] package.,o | |
| "It's easy to use, completely hides the network stuff from you, and works over good ol' HTTP.",p | |
| "No need to worry about protocol issues ... it'll all look like method calls to you, on both ends.",n | |
| "XML-RPC looks interesting, but I'm using SE, and I think adding/switching to EE is much more complicated than even NIO, but correct me if I'm wrong (do they run on the same JVM?",o | |
| ).,o | |
| It's a plain library and should work in SE and EE.,o | |
| "Like another commentator mentioned, it does have its scalability issues.",o | |
| "but for the 98% case, I think it's pretty solid.",o | |
| "Given the small number of connections involved, java.net sounds like the right solution.",o | |
| Other posters talked about using XML-RPC.,o | |
| "This is a good choice if the volumes of data being shipped are small, however I have had bad experiences with XML- based protocols when writing inter-process communications that ship large amounts of data (e.g.",n | |
| "large request/responses, or frequent small amounts of data).",o | |
| The cost of XML parsing is typically orders of magnitude higher than more optimised wire formats (e.g.,p | |
| ASN.1).,o | |
| For low volume control applications the simplicity of XML-RPC should outweigh the performance costs.,n | |
| For high volume data communications it may be better to use a more efficient wire protocol.,p | |
| There is almost no reason to write this kind of networking code from scratch now.,o | |
| Packages like URL_http://netty.io/ [netty.io] will almost always get you more reliable and flexible code with fewer lines of code than a hand-crafted solution will.,p | |
| "Also, with Netty, you can get SSL support w/o complicating your implementation at all.",o | |
| "Libraries like netty also obviate the ""async vs threads"" question almost entirely, gives you good performance, and still lets you tweak the threading model as needed.",p | |
| Java multithreaded file downloading performance.,p | |
| "Having recently worked on a project which required some more IO interaction than I'm used to, I felt like I wanted to look past the regular libraries (Commons IO, in particular) and tackle some more in depth IO issues.",o | |
| "As an academic test, I decided to implement a basic, multi-threaded HTTP downloader.",o | |
| "The idea is simple: provide a URL to download, and the code will download the file.",p | |
| "To increase download speeds, the file is chunked and each chunk is downloaded concurrently (using the HTTP CODETERM1 header) to use as much bandwidth as possible.",o | |
| "I have a working prototype, but as you may have guessed, it's not exactly ideal.",n | |
| "At the moment I manually start 3 ""downloader"" threads which each download 1/3 of the file.",o | |
| "These threads use a common, synchronized ""file writer"" instance to actually write the files to disk.",o | |
| "When all threads are done, the ""file writer"" is completed and any open streams are closed.",o | |
| Some snippets of code to give you an idea: The thread start-up: CODESNIPPET_JAVA1 .,o | |
| "Each ""downloader"" thread downloads a chunk (buffered) and uses the ""file writer"" to write to disk: CODESNIPPET_JAVA2 .",o | |
| "The ""file writer"" writes to disk using a CODETERM2 to CODETERM3 and CODETERM4 the chunks to disk: CODESNIPPET_JAVA3 .",o | |
| "All things considered, this approach seems to work.",o | |
| "However, it doesn't work very well.",o | |
| I'd appreciate some advice/help/opinions on the following points.,p | |
| Much appreciated.,p | |
| 1.,o | |
| "The | |
| usage** of this code is through the roof.",o | |
| "It's using half my CPU (50% of each of the 2 cores) to do this, which is exponentially more than comparable downloading tools which barely stress the CPU at all.",o | |
| "I'm a bit mystified as to where this CPU usage comes from, as I wasn't expecting this.",n | |
| 2.,o | |
| "Usually, there seems to be 1 of the 3 threads that is | |
| behind** significantly.",o | |
| "The other 2 threads will finish, after which it takes the third thread (which seems to be mostly the first thread with the first chunk) 30 or more seconds to complete.",o | |
| "I can see from the task manager that the javaw process is still doing small IO writes, but I don't really know why this happens (I'm guessing race conditions?).",n | |
| 3.,o | |
| "Despite the fact that I've chosen quite a big buffer (1MB), I get the feeling that the CODETERM5 almost never actually fills the buffer, which causes more IO writes than I would like.",o | |
| "I'm under the impression that in this scenario, it would be best to keep the IO access to a minimum, but I don't know for sure whether this is the best approach.",p | |
| 4.,o | |
| "I realise Java may not be the ideal language to do something like this, but I'm convinced there's much more performance to be had than I get in my current implementation.",p | |
| Is NIO worth exploring in this case?,o | |
| "_Note:_ I use Apache HTTPClient to do the HTTP interaction, which is where the CODETERM6 comes from (in case anyone is wondering).",o | |
| Found a good related topic here: URL_http://stackoverflow.com/questions/921262 /how-to-download-and-save-a-file-from-internet-using-javaMight give that a try tonight when I get home :).,p | |
| Update: the high CPU usage was due to a while() loop on the ExecutorService isTerminated() method call.,o | |
| Doh!.,o | |
| To answer my own questions: 1.,o | |
| The increased CPU usage was due to a CODETERM1 loop that was waiting for the threads to finish.,o | |
| "As it turns out, CODETERM2 is a much better alternative to wait for an CODETERM3 to finish :) 2.",o | |
| "(And 3 and 4) This seems to be the nature of the beast; in the end I achieved what I wanted to do by using careful synchronization of the different threads that each download a chunk of data (well, in particular the writes of these chunks back to disk).",n | |
| "Presumably the Apache HTTP client will be doing some buffering, with a smaller buffer.",o | |
| "It will need a buffer to read the HTTP header reasonably, and probably handling chunked encoding.",o | |
| My immediate thought for best performance on Windows would be to use URL_http://msdn.microsoft.com/en-us/library/aa365198%28VS.85%29.aspx [IO- completions-ports] .,p | |
| "What I don't know is (a) whether there are similar concepts in other OSes, and (b) whether there are any suitable Java wrappers?",o | |
| "If portability isn't important to you, though, it may be possible to roll your own wrapper with JNI.",o | |
| Set a very large socket receive buffer.,o | |
| "But really your performance will be limited by the network bandwidth, not CPU bandwidth.",o | |
| All you're doing really is allocating 1/3 of the network bandwidth to each downloader.,o | |
| I'd be surprised if you get much benefit.,p | |
| "Three connections can be faster than one, briefly at the start of a transfer.",p | |
| "It takes TCP a little whiel to find the optimal window size, so if you use parallel connections, this process goes 3x faster!.",p | |
| "This is the reason I'm chunking in the first place, splitting the file in 3 chunks allows me to download the same file 3 times faster, presuming a single chunk is too slow to saturate the connection.",n | |
| "The download speed is maxed out though, so this is not an issue.",o | |
| It's the CPU usage that I'm worried about.,n | |
| Could it be related to the fact that the code is executing in Eclipse?,o | |
| "Well you're doing N-1 redundant seeks, and last time I looked at it, which is decades ago, seek was a surprisingly expensive operation.",p | |
| Each writer only needs to seek once; after that it is just sequential I/O.,o | |
| Read/convert an InputStream to a String.,o | |
| "If you have CODETERM1 object, how should you process that object and produce a CODETERM2 ?",o | |
| " | |
| Suppose I have an CODETERM3 that contains text data, and I want to convert this to a CODETERM4 (for example, so I can write the contents of the stream to a log file).",o | |
| What is the easiest way to take the CODETERM5 and convert it to a CODETERM6 ?,o | |
| CODESNIPPET_JAVA1 .,o | |
| "Boy, I'm absolutely in love with Java, but this question comes up so often you'd think they'd just figure out that the chaining of streams is somewhat difficult and either make helpers to create various combinations or rethink the whole thing.",n | |
| You are right.,o | |
| "I tend to use a set of helper classes that do it once for me, so I don't need keep referring to Google or even StackOverflow for the answer.",o | |
| "In this case, I was away from my utility code and couldn't remember exactly how to do it.",o | |
| What better way to open my account on the site.,o | |
| "Yeah, it really shouldn't require so much boilerplate to do something as simple as read strings from a stream.",n | |
| "It's not that difficult, just annoying.",n | |
| @Adam: It really depends on what kind of Stream you're working with.,p | |
| "For instance, System.console().readLine() (new in Java 6) is pretty easy.",p | |
| Same with BufferedReader's readLine().,o | |
| The only hard part is when you don't know how many characters you need to read.,n | |
| The answers to this question only work if you want to read the stream's contents _fully_ (until it is closed).,o | |
| "Since that is not always intended (http requests with a keep-alive connection won't be closed), these method calls block (not giving you the contents).",o | |
| "You | |
| to know and specify the character encoding for the stream, or you | |
| have character encoding bugs, since you will be using a randomly chosen encoding depending on which machine/operating system/platform or version thereof your code is run on.",n | |
| "That is, do | |
| use methods that depend on the platform default encoding.",o | |
| "I don't really know Java, but ""InputStream | |
| "" seems wrong.",n | |
| "@Hello71: It is ok in Java, since the instanceof operator is spelled differently.",o | |
| @Ronald: Erm... never mind that.,o | |
| I must have been partially asleep while writing that.,o | |
| "Here's a way using only standard Java library (note that the stream is not closed, YMMV).",o | |
| CODESNIPPET_JAVA1 .,o | |
| "I learned this trick from URL_http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html [""Stupid-Scanner-tricks""] article.",o | |
| "The reason it works is because URL_http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html [Scanner] iterates over tokens in the stream, and in this case we separate tokens using ""beginning of the input boundary"" (\A) thus giving us only one token for the entire contents of the stream.",p | |
| " | |
| if you need to be specific about the input stream's encoding, you can provide the second argument to CODETERM1 constructor that indicates what charset to use (e.g.",o | |
| """UTF-8"").",o | |
| " | |
| Hat tip goes also to URL_http://stackoverflow.com/users/68127/jacob-gabrielson [Jacob,] who once pointed me to the said article.",o | |
| " | |
| Thanks to a suggestion from URL_http://stackoverflow.com/users/101272/patrick [Patrick] , made the function more robust when handling an empty input stream.",p | |
| " | |
| more edit:** nixed try/catch, Patrick's way is more laconic.",n | |
| "Thanks, for my version of this I added a finally block that closes the input stream, so the user doesn't have to since you've finished reading the input.",o | |
| Simplifies the caller code considerably.,o | |
| "I think this should be public | |
| String convertStreamToString .",o | |
| "@PavelRepin @Patrick in my case, an empty inputStream caused a NPE during Scanner construction.",o | |
| "I had to add if (is | |
| null) return """"; right at the beginning of the method; I believe this answer needs to be updated to better handle null inputStreams.",o | |
| The problem with this approach I find is it does not handle CR/LF translations too well.,p | |
| So you have to make sure your line endings are consistent.,o | |
| "@ArchimedesTrajano does IOUtils.copy(inputStream, writer, encoding) deal with CR/LF translations better?",o | |
| I think CR/LF consistency is entirely unrelated issue.,o | |
| Not saying it isn't an issue.,o | |
| "For Java 7 you can close in a try-with: try(java.util.Scanner s | |
| new java.util.Scanner(is)) { return s.useDelimiter(""\\\A"").hasNext() ?",o | |
| "s.next() : """"; }.",o | |
| Unfortunately this solution seems to go and lose the exceptions thrown in my underlying stream implementation.,o | |
| excellent trick!,p | |
| any ideas about performance of Scanner vs reading the stream in a more verbose way?,o | |
| @Igal I didn't measure it.,o | |
| "If you do, gist it and I'll append your results to the answer.",o | |
| A nice way to do this is using URL_http://commons.apache.org/ [Apache-commons] URL_http://commons.apache.org/proper/commons- io/apidocs/org/apache/commons/io/IOUtils.html [IOUtils] to copy the CODETERM1 into a CODETERM2 ... something like CODESNIPPET_JAVA1 .,p | |
| "Alternatively, you could use CODETERM3 if you don't want to mix your Streams and Writers .",o | |
| I hope IOUtils takes an optional Charset (or at least the name of the encodding to use).,o | |
| Best not to leave this kind of thing to chance :).,p | |
| Haha - of course it does!,o | |
| "URL_http://commons.apache.org/io/apidocs/org/apache/comm ons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.Writer,%20java.lang.St ring).",o | |
| Why copy the inputstream to a writer?,o | |
| Why not just use a reader?,o | |
| "Or read all bytes and use new String(bytes, charset)?",o | |
| "You really, | |
| should be using IOUtils.copy(inputStream, writer, encoding); unless you really, | |
| know what you're doing, which people never do with character encoding related programming.",o | |
| "Or in this case, IOUtils.toString(inputStream, encoding).",o | |
| "Methods that use the platform default encoding are almost never correct to use, like every other method that gives different results depending on which machine/operating system/platform or version thereof it is run on.",n | |
| I think the below answer (IOUtils.toString()) is simpler since there is no need for a StringWriter.,p | |
| A quick but not clean solution.,p | |
| I would rather prefer a solution without adding additional libraries as mentioned in the post below: URL_http://stackoverflow.com/a/6938341/411951 .,p | |
| "Only works for closes streams, I believe.",p | |
| Apache Commons allows: CODESNIPPET_JAVA1 .,o | |
| "Of course, you could choose other character encodings besides UTF-8.",o | |
| "Also see: ( URL_http://commons.apache.org/proper/commons-io/javadocs/api-2.4/o rg/apache/commons/io/IOUtils.html#toString%28java.io.InputStream,%20java.lang.",o | |
| String [Docs] ) .,o | |
| IOUtils.toString is deprecated.,n | |
| No it isn't.,o | |
| Only the version that takes a byte[] parameter is.,o | |
| "Also, there is a method that only take a inputStream argument, if you are find with the default encoding.",o | |
| "@Guillaume Cot I guess the message here is that you never should be ""fine with the default encoding"", since you cannot be sure of what it is, depending on the platform the java code is run on.",o | |
| @Per Wiklander I disagree with you.,o | |
| Code that is going to work on a single could be quite sure that default encoding will be fine.,o | |
| "For code that only open local file, it is a reasonable option to ask them to be encoded in the platform default encoding.",o | |
| This function is corrupting my input stream.,n | |
| To save anyone the hassle of Googling - org.apache.commons commons-io 1.3.2 .,o | |
| I don't know that I'd say the default encoding is NEVER fine.,o | |
| "On the other hand, I disagree with Guillaume also.",o | |
| "In fact, it's not a matter of fine or not; it's a matter of which is CORRECT.",p | |
| "In the situation where you want to take something that you know is encoded in the default encoding for the platform, then the default version is correct.",p | |
| "However, I believe this is a very rare use case.",o | |
| "The more normal case is that you need to specify what the encoding is, so specifying the encoding is correct.",p | |
| There is no optional case: either one or (more likely) the other is correct.,p | |
| "Also little improvement would be to use apache io (or other) constant for character encoding instead of using plain string literal - eg: IOUtils.toString(myInputStream, Charsets.UTF_8);.",n | |
| Taking into account file one should first get a CODETERM1 instance.,o | |
| "This can then be read and added to a CODETERM2 (we don't need CODETERM3 if we are not accessing it in multiple threads, and CODETERM4 is faster).",p | |
| "The trick here is that we work in blocks, and as such don't need other buffering streams.",o | |
| The block size is parameterized for run-time performance optimization.,o | |
| CODESNIPPET_JAVA1 .,o | |
| I like how this works without adding more libraries to your project.,p | |
| is there a chance to broke multi-bytes character in this solution?,o | |
| This solution uses multibyte characters.,o | |
| The example uses the UTF-8 encoding that allows expression of the full unicode range (Including Chinese).,o | |
| "Replacing ""UTF-8"" with another encoding would allow that encoding to be used.",o | |
| @User1 - I like using libraries in my code so I can get my job done faster.,p | |
| "It's awesome when your managers say ""Wow James!",p | |
| "How did you get that done so fast?!"".",o | |
| "But when we have to spend time reinventing the wheel just because we have misplaced ideas about including a common, reusable, tried and tested utility, we're giving up time we could be spending furthering our project's goals.",p | |
| "When we reinvent the wheel, we work twice as hard yet get to the finish line much later.",o | |
| "Once we're at the finish line, there is no one there to congratulate us.",p | |
| "When building a house, don't build the hammer too.",o | |
| "Sorry, after re-reading my comment, it comes off a little arrogant.",n | |
| "I just think it's important to have a good reason to avoid libraries and that the reason is a valid one, which there very well could be :).",p | |
| isn't it better to close stream/streamreader ?,o | |
| "Yes, I guess the reader should be closed at the end.",o | |
| "@jmort253 Many libraries are large, slow but powerful.",n | |
| "However there are many chances that we need a small, fast one.",o | |
| "In our product, I even replaced many JDK classes with our own implement.",o | |
| @coolcfan - I do agree with you on that point.,o | |
| Sometimes speed is of the utmost importance and is a hard requirement.,n | |
| "Many times, good enough is good enough.",p | |
| I question how often we put effort into optimizing something that no one notices.,o | |
| The answer of whether the reward is greater than the cost is a decision not to be taken lightly.,p | |
| Thank you for indicating that there are times when this is necessary.,p | |
| @jmort253 We noticed performance regression after updating some library in our product for several times.,o | |
| Luckily we are building and selling our own product so we don't really have the so called deadlines.,p | |
| "Unfortunately we are building a product that is available on many JVMs, databases and app servers on many operation systems so we have to think for the users using poor machines... And a string operation optimizing can improve the perf by 30~40%.",n | |
| "And a fix: In our product, I even replaced should be 'we even replaced'.",o | |
| "@jmort253 If you would already use apache commons I would say, go for it.",o | |
| "At the same time, there is a real cost to using libraries (as the dependency proliferation in many apache java libraries shows).",o | |
| "If this would be the only use of the library, it would be overkill to use the library.",o | |
| "On the other hand, determining your own buffer size(s) you can tune your memory/processor usage balance.",n | |
| How about this?,o | |
| "InputStream in | |
| _/* your InputStream | |
| is | |
| new InputStreamReader(in);StringBuilder sb=new StringBuilder();BufferedReader br | |
| new BufferedReader(is);String read | |
| br.readLine();while(read != null) { //System.out.println(read); sb.append(read); read | |
| sb.toString(); .",o | |
| Doesn't answer the question.,o | |
| "This shows how to iterate over the lines in a stream, not how to read the entire stream into a string.",o | |
| you can concat all string in to one String.that is simple.....,p | |
| "The thing is, you're first splitting into lines, and then undoing that.",o | |
| It's easier and faster to just read arbitrary buffers.,p | |
| "Also, readLine does not distinguish between \n and \r, so you cannot reproduce the exact stream again.",o | |
| "@PauldeVrieze how many lines, and how quickly do you need to process them!?",o | |
| "I would hazard a guess that any performance loss would be small, or could be handled by every once in a while logging them to a file and destroying the old String obj's.",o | |
| If you are using Google-Collections/Guava you could do the following: CODESNIPPET_JAVA1 .,o | |
| Note that the second parameter (i.e.,o | |
| "Charsets.UTF_8) for the CODETERM1 isn't necessary, but it is generally a good idea to specify the encoding if you know it (which you should!",p | |
| ) .,o | |
| "@harschware: Given the question was: ""If you have java.io.InputStream object how should you process that object and produce a String?",o | |
| """ I assumed that a stream is already present in the situation.",o | |
| "You didn't explain your answer very well, and had extraneous variables; user359996 said the same thing as you, but much more clearly.",p | |
| it returns to me boxes instead of actual text characters.,o | |
| plz advise.,o | |
| "+1 for guava, -1 for not specifying the encoding of the input stream.",o | |
| eg.,o | |
| "new InputStreamReader(stream, ""UTF-8"").",o | |
| Downvoting as doesn't close inputstream.,n | |
| "@plasma147 Instead of downvoting, consider editing the example (I just submitted that, adding Closeables.closeQuietly(stream);).",n | |
| "@Chris Noldus On the other hand, some people already have guava in their project, like me, and think this solution is more elegant than the sdk-only version.",p | |
| CODESNIPPET_JAVA1 .,o | |
| Works well on Android in comparison with other answers which work only in enterprise java.,p | |
| That's where it came from... My Android tools library :).,o | |
| "Crashed in Android with OutOfMemory error on the "".write"" line, every time, for short strings.",n | |
| What on earth do you copy...???,o | |
| I copy 5 - 10 mb files easy...,p | |
| Please specify the encoding - it's a very common bug.,n | |
| I've added the encoding.,o | |
| "just as a side note, the original readFully method I have in my code does not return String, it returns byte[] for a more general purpose functionality.",o | |
| Implementing the new String(...) with encoding is the responsibility of the on that uses the API!.,o | |
| "Here's the most elegant, pure-Java (no library) solution I came up with after some experimentation: CODESNIPPET_JAVA1 .",p | |
| Isn't there a reader.close() missing?,o | |
| Ideally with try/finally...,o | |
| "@TorbenKohlmeier, readers and buffers don't need to be closed.",o | |
| The provided InputStream should be closed by the caller.,o | |
| Don't forget to mention that there's a more preferable constructor in InputStreamReader that takes a CharSet.,p | |
| newlines are gone after this.,o | |
| How about: CODESNIPPET_JAVA1 .,o | |
| "As an alternative to the Commons libraries, Google's excellent URL_http://code.google.com/p/guava-libraries/ [guava-libraries] let you do this fairly concisely; given an _InputStream_ named _inputStream_: CODESNIPPET_JAVA1 .",p | |
| "Note this method is particularly convenient if, instead of an | |
| you have a | |
| ",o | |
| "For example, if you're getting the body of an HTTP request via | |
| it's just | |
| request.getReader() )**.",o | |
| "Here's more-or-less sampath's answer, cleaned up a bit and represented as a function: CODESNIPPET_JAVA1 .",p | |
| use a StringBuilder.,o | |
| Changed to use StringBuilder.,o | |
| Thanks @trnl.,o | |
| again no encoding.,o | |
| "I ran some timing tests because time matters, always.",o | |
| I attempted to get the response into a String 3 different ways.,o | |
| (shown below) I left out try/catch blocks for the sake readability.,o | |
| "To give context, this is the preceding code for all 3 approaches: CODETERM1 CODETERM2 CODETERM3 CODETERM4 1) CODETERM5 2) CODETERM6 CODETERM7 CODETERM8 CODETERM9 CODETERM10 CODETERM11 CODETERM12 CODETERM13 CODETERM14 3) CODETERM15 CODETERM16 CODETERM17 CODETERM18 So, after running 500 tests on each approach with the same request/response data, here are the numbers.",o | |
| "Once again, these are my findings and your findings may not be exactly the same, but I wrote this to give some indication to others of the efficiency differences of these approaches.",o | |
| "Ranks: Approach | |
| Approach | |
| - 2.6% slower than | |
| Approach | |
| - 4.3% slower than | |
| Any of these approaches is an appropriate solution for grabbing a response and creating a String from it.",n | |
| "2) contains an error, it adds always ""null"" at the end of the string as you are always makeing one more step then necessary.",o | |
| Performance will be the same anyway I think.,o | |
| "This should work:String read | |
| null; StringBuffer sb | |
| new StringBuffer();while((read | |
| br.readLine()) != null) { sb.append(read);}.",o | |
| If you can't use Commons IO (FileUtils/IOUtils/CopyUtils) here's an example using a BufferedReader to read the file line by line: CODESNIPPET_JAVA1 .,o | |
| or if you want raw speed I'd propose a variation on what Paul de Vrieze suggested (which avoids using a StringWriter (which uses a StringBuffer internally) : CODESNIPPET_JAVA2 .,o | |
| "In order to make your code work, I had to use this.getClass().getClassLoader().getResourceAsStream() (using Eclipse with a maven project).",o | |
| "If you were feeling adventurous, you could mix Scala and Java and end up with this: CODESNIPPET_JAVA1 .",o | |
| Mixing Java and Scala code and libraries has it's benefits.,o | |
| See full description here: URL_http://stackoverflow.com/q/5221524/828757 [Idiomatic-way-to-convert-an-InputStream-to-a-String-in-Scala] .,o | |
| CODESNIPPET_JAVA1 .,o | |
| Please give a description on what you are trying to accomplish.,o | |
| CODESNIPPET_JAVA1 .,o | |
| here s is your InputStream object which will get convert into String :) .,o | |
| make sure to close the streams at end if you use Stream Readers CODESNIPPET_JAVA1 .,o | |
| Well you can program it for yourself.. it's not complicated.. CODESNIPPET_JAVA1 .,o | |
| "Since you're using buffer variable locally with no chance of being shared across multiple threads you should consider changing its type to StringBuilder, to avoid the overhead of (useless) synchronization.",o | |
| That's a good point alex!.,p | |
| I thing that we both agree that this method isn't thread-safe in many ways.,n | |
| Even the input stream operations aren't thread-safe.,n | |
| The below code worked for me.,o | |
| CODESNIPPET_JAVA1 .,o | |
| "Please note, according to Java docs, the available() method might not work with InputStream but always works with BufferedInputStream.In case you don't want to use available() method we can always use the below code CODESNIPPET_JAVA2 .",p | |
| I am not sure if there will be any encoding issues.,o | |
| "Please comment, if there will be any issues with the code .",o | |
| "The whole point of using InputStream is, that a) you don't know the length of the _complete_ stream (which bails out anything depending on available) and b) the stream can be anything - a file, a socket, something internal (which bails out anything based on File.size()).",o | |
| Regarding available: This will cut off data if the stream is longer than the buffer size.,o | |
| You can use apache commons.In the IOUtils you can find the toString metod with 3 helpfull implementations.,p | |
| CODESNIPPET_JAVA1 .,o | |
| JDK 7/8 answer that closes the stream and still throws an IOException: CODESNIPPET_JAVA1 .,o | |
| CODESNIPPET_JAVA1 .,o | |
| See the commet by ChristofferHammarstrm in the answer by HarryLime.,o | |
| "First ,you have to know the encoding of string that you want to convert.Because the java.io.InputStream operates an underlying array of bytes,however,a string is composed by a array of character that needs an encoding, e,g.",o | |
| "UTF-8,the JDK will take the default encoding that is taken from System.getProperty(""file.encoding"",""UTF-8""); CODESNIPPET_JAVA1 .",o | |
| "If inputStream's byte array is very big, you could do it in loop.",o | |
| :EOF .,o | |
| "From the javadocs: Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not.",o | |
| It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.,n | |
| This is a bad idea!,n | |
| Don't be burnt by misunderstanding what available() gives you.,n | |
| "As mentioned above, available() is not the way to go.",o | |
| It's highly recommended to ignore this method so much so that you could treat this to be a restricted API.,p | |
| Quick and easy: CODESNIPPET_JAVA1 .,p | |
| I get java.io.StreamCorruptedException: invalid stream header.,n | |
| "ObjectInputStream is about deserialization, and the stream have to respect the serialization protocol to work, which may not always true in the context of this question.",o | |
| Shiro vs. SpringSecurity.,o | |
| "I have currently evaluating Java based security frameworks, I am a Spring 3.0 user so it seemed that SpringSecurity would be the right Choice, but Spring security seems to suffer from excessive complexity, it certainly does not seem like it is making security easier to implement, Shiro seems to be much more coherent and easier to understand.",n | |
| I am looking for lists of pros and cons between these two frameworks.,o | |
| I too agree that Spring Security feels too complicated (to me).,o | |
| "Sure, they have done things to reduce complexity, like creating custom XML namespaces to reduce the quantity of XML configuration, but for me, these don't address _my_ personal fundamental issue with Spring Security: its names and concepts are often confusing in general to me.",n | |
| It's hard to just 'get it'.,n | |
| "The second you start using Shiro though, you just 'get it'.",o | |
| What was hard to understand in the security world is just that much easier to understand.,o | |
| Things that are unbearably difficult to use in the JDK (e.g.,n | |
| "Ciphers) are simplified to a level that is not just bearable, but often a joy to use.",n | |
| "For example, how do you hash+salt a password and base64 encode it in Java or Spring Security?",o | |
| Neither are as simple and intuitive as Shiro's solution: CODESNIPPET_JAVA1 .,p | |
| No need for commons-codec or anything else.,o | |
| Just the Shiro jar.,o | |
| "Now with regards to Spring environments, most of the Shiro developers use Spring as their primary application environment.",o | |
| That means Shiro's Spring integration is superb and it all works exceptionally well.,p | |
| "You can rest assured that if you're writing a Spring app, you'll have a well-rounded security experience.",p | |
| "For example, consider the Spring XML config example in another post in this thread.",o | |
| Here's how you'd do (essentially) the same thing in Shiro: CODESNIPPET_JAVA2 .,o | |
| "Although slightly more verbose than the other Spring example, it is easier to read IMO.",n | |
| You'll also find using Shiro's filter chain definitions are probably the easiest way to define general filter chains and web-based security rules ever!,p | |
| Much nicer than defining them in web.xml.,p | |
| "Finally, Shiro offers extreme 'pluggability' as well.",p | |
| You'll see that you can configure and/or replace just about anything because of Shiro's POJO /injection-friendly architecture.,o | |
| Shiro defaults almost everything to sane defaults and you can override or configure only what you need.,p | |
| "At the end of the day, I think choosing either of these two is more about your mental model - which of the two make more sense and is more intuitive for you?",o | |
| "For some it will be Shiro, for others it will be Spring Security.",o | |
| "Shiro works great in Spring environments, so I would say choose based on which of the two you enjoy more and makes the most sense to you.",p | |
| For more on Shiro's Spring integration: URL_http://shiro.apache.org/spring.html [ URL_http://shiro.apache.org/spring.html ] .,o | |
| I've read all this before start using shiro.,o | |
| Shiro annotations seem to suffer some issues in spring.Information on how to solve it are very har and there are various posts in stackoverflow (1 or 2 posted by myself) which most of the time found no answers.,o | |
| "I was seriously thinking i should go spring security despite it said complication, with that i'm sure i can have people to point me to the right direction.",o | |
| "I don't have experience using Shiro, and I ""partly"" agree with what you said about Spring Security.",o | |
| "Prior to Spring Security 3.x, Spring Security (or Acegi) was very painful to set up.",o | |
| A simple role-based configuration will take at least 140 lines of cryptic XML configuration...,n | |
| I know this because I actually counted the lines myself.,o | |
| "It was something where you set up one time, and you pray that it will work forever without you touching the configuration again, because you can assure you have forgotten what all the configuration means.",p | |
| ":) With Spring Security 3.x, it has tremendously improved upon.",p | |
| It introduces CODETERM1 namespace that drastically shorten the configuration from 140 lines to ~30 lines.,n | |
| Here's an example of Spring Security 3.x of one of my projects:- CODESNIPPET_JAVA1 .,o | |
| "The beauty of Spring Security 3.x is it is extremely configurable, which contributes to one of the main cons: too complicated to understand.",p | |
| The documentation isn't easy to read either because I'm only partially familiar with the some of the terms Spring Security used.,n | |
| "However, the options are there if you need to create your custom configuration or control how granular you want your security to be.",o | |
| "Or else, you can stick with the above < 30 lines to perform a role-based security check.",o | |
| What I really like about Spring Security is once it is set up the security is integrated into the project seamlessly.,o | |
| "It is as if the actual project code doesn't know the existence of the security... and that is good, because it allows me to easily detach or upgrade the security component in the future (ex: change database auth to LDAP/CAS auth).",p | |
| Would you like to say something about when it is good to move from container based security to alternatives like shiro or others?,o | |
| See more focussed question here: URL_http://stackoverflow.com/questions/7782720/when-to-move-from - container-managed-security-to-alternatives-like-apache-shiro.,o | |
| "I have tried both shiro and spring security, and I personally feel the shiro is quite easy to understand where as spring security feels complex.",n | |
| "I have yet to figureout how to setup permissions, that I can assign to roles/groups/users in spring security- (I think ACL may be the solution).",o | |
| "With shiro it was quite easy.I am not expert of spring security or shiro, its just my personal experience as user of both.",o | |
| I had been using Spring Security (version 3.1) for a few months and was quite happy with it.,p | |
| "It is really powerful and has some very nice feature, especially after implementing everything by hand as I did before !",p | |
| "It was though, like I read somewhere, sort of something that you set up once near the beginning of the develoepment of the app, and then pray for it to keep working till the end, because if you have to go fix it you'll probably have forgotten most of the stuff you had to parameter.",p | |
| "But then a new project came along, with more complex security requirements.",n | |
| "In short, we had to implement some sort of custom SSO between a couple of related webapps.",o | |
| "I knew exactly what I wanted to achieve in terms of HTTP logic, cookies, session id's and stuff, and what should happen in what order, but I spent the better part of a day struggling with the Spring Security APIs, and still could not figure out exactly what class or interface I shoud implement or override, and how to plug them in the context.",n | |
| The whole API felt really complex and a bit esoteric at times.,n | |
| "And while the doc is quite good for the general use cases and even some customization, it did not go deep enough to cover my needs.",p | |
| "After reading the answers here and on some other places on the web, I got the impression that Shiro would be easier to understand and customize to my needs.",p | |
| So I gave it a try.,o | |
| "And I am glad I did, because after a day working on it I managed to learn enough about the APIs not only to set up a basic authentication and authorization system in my Spring webapp without trouble, but also to implement the custom SSO behaviour I was looking for.",p | |
| "I only had to extend 2 or 3 classes, and the whole thing took only about 25 lines of XML config in my spring context.",o | |
| "So as a conclusion, on the ease of use and learning curve aspects, Shiro is really quite likeable, and I think I will probably go with it in the future, unless I encounter some features lacking or some other problem (which I haven't so far).",n | |
| "TL;DR: Both are powerful, but Shiro is much easier to learn.",p | |
| JAAS for human beings.,o | |
| I am having a hard time understanding JAAS.,n | |
| It all seems more complicated than it should be (especially the Sun tutorials).,o | |
| I need a simple tutorial or example on how to implement security (authentication + authorization) in java application based on Struts + Spring + Hibernate with custom user repository.,n | |
| Can be implemented using ACEGI.,o | |
| Awesome question.,p | |
| Great pithy title for a legitimate documentation failure.,p | |
| Other users have provide some very useful links above so I am not going to bother with links.,n | |
| "I have done a similar research in JAAS for web application and has ran into a ""mind roadblock"" until I finally realize JAAS is a framework tackling security at a different ""layer"" then web applications in the Java World.",o | |
| It is build to tackle security issues in Java SE not Java EE.,o | |
| JAAS is a security framework build for securing things at a much lower level then web-application.,n | |
| "Some example of these things are code and resources available at the JVM level, hence all these ability to set policy files in the JVM level.",o | |
| "However, since Java EE is build on top of Java SE, a few modules from JAAS was reuses in Java EE security such as the LoginModules and Callbacks.",o | |
| "On the other hand, Acegi, or now aka Spring security, tackles a much higher ""layer"" in the securing web-application problem.",o | |
| It is build on top of Java EE security hence Java SE hence JAAS.,o | |
| "Unless you are looking to secure resources in the Java SE level (classes, System resources), I don't see any real use of JAAS other than the using the common class and interfaces.",p | |
| Just focus on using Acegi or plain old Java EE security which solves a lot of common web application security problems.,o | |
| "Java EE 6 Tutorial assumes understanding basic security concepts, so a little overview of JAAS won't hurt.",n | |
| Here are some of the links I used to help understand JAAS: URL_http://www.owasp.org/index.php/JAAS_Tomcat_Login_Module [ URL_http://www.owasp.org/index.php/JAAS_Tomcat_Login_Module ] URL_http://www.javaworld.com/jw-09-2002/jw-0913-jaas.html [ URL_http://www.javaworld.com/jw-09-2002/jw-0913-jaas.html ] URL_http://www.jaasbook.com/ [ URL_http://www.jaasbook.com/ ] URL_http://roneiv.wordpress.com/2008/02/18/jaas-authentication-mechanism-is- it-possible-to-force-j_security_check-to-go-to-a-specific-page/ [ URL_http://roneiv.wordpress.com/2008/02/18/jaas-authentication-mechanism-is-it - possible-to-force-j_security_check-to-go-to-a-specific-page/] Also have a look at the Apache tomcat realms configuration how-to: URL_http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html [ URL_http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html ] .,o | |
| thanks :) jaas book is really good.,p | |
| javax.security is imho overcomplicated API.,o | |
| "As a result there are implementors of not only LoginModules, but the entire authentication and authorization api, that creates abstraction layer above, like Authentication & Authorization managers.",o | |
| "For starters, it is good to print | |
| URL_http://media.techtarget.com/tss/static/articles/content/Pramati- JAAS/interaction.gif [this] | |
| into your memory.",n | |
| "Secondly, imho the most simple, setup & go library for JAAS is Jboss URL_http://www.jboss.org/picketbox [PicketBox] .",p | |
| It says how to do authentication and authorization via JBossAuthenticationManager and JBossAuthorizationManager ...,o | |
| Easily configurable via XML or Annotations.,p | |
| You can use it for managing both webapps and standalone applications.,p | |
| "If you need the authorization part for managing repository access, in terms of ACL for resources, this is what you are looking for sure.",o | |
| "Problem with the security is, that usually you need to customize it to your needs, so you may end up implementing : | |
| \- verifies userName + Password | |
| is used like this CODETERM1 CallbackHandler is passed to the underlying LoginModules so they may communicate and interact with users - prompting for a username and password via a graphical user interface, for example.",o | |
| So inside of the Handler you get the username and password from user and it is passed to the LoginModule.,o | |
| " | |
| \- then you just call lc.login(); and authenticate the credentials.",o | |
| LoginContext is populated with the authenticated Subject.,p | |
| "However Jboss picketbox gives you a really easy way to go, unless you need something specific.",o | |
| "I can't speak too much to JAAS itself, but this URL_http://static.springsource.org/spring-security/site/start-here.html [""suggested-steps""-guide] on Spring Security and URL_http://static.springframework.org/spring-security/site/reference.html [the-reference-manual] are both pretty good resources on Spring Security - if your setup is anything close to simple, you don't really need to do much more than read these.",p | |
| "The ""suggested steps"" guide has moved here: URL_http://static.springsource.org /spring-security/site/start-here.html.",o | |
| "thanks, updated the link.",o | |
| For a purely JAAS tutorial check out URL_http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html [this] .,o | |
| It's old but should help with the JAAS basics.,o | |
| "lsiu's answer is one the few answers here that really ""get it"" ;) Adding to that answer, a really good reference on this topic is URL_http://java.sys-con.com/node/1002315 [Whatever-Happened-to-JAAS?",o | |
| ] .,o | |
| "It explains how JASPIC is the link in Java EE between the Servlet and EJB security models and potentially a JAAS login module, but that in many cases JAAS' role is reduced to that of a relatively simple username and roles provider in Java EE.",p | |
| "From the same author is URL_http://raymondkng.sys-con.com/node/171477 [JAAS- in-the-Enterprise] , which is an older article but provides a lot of historical background on why the Java SE (JAAS) and Java EE models diverged the way they did.",o | |
| "Overall but a few types from JAAS are directly used in Java EE, basically CODETERM1 , CODETERM2 , and CODETERM3 .",o | |
| The latter two are mainly used by JASPIC.,o | |
| I've explained JASPIC in the article URL_http://arjan- tijms.blogspot.com/2012/11/implementing-container-authentication.html [Implementing-container-authentication-in-Java-EE-with-JASPIC] .,o | |
| What's the best way to share business object instances between Java web apps using JBoss and Spring?,o | |
| "We currently have a web application loading a Spring application context which instantiates a stack of business objects, DAO objects and Hibernate.",o | |
| "We would like to share this stack with another web application, to avoid having multiple instances of the same objects.",o | |
| "We have looked into several approaches; exposing the objects using JMX or JNDI, or using EJB3.",o | |
| "The different approaches all have their issues, and we are looking for a lightweight method.",p | |
| Any suggestions on how to solve this?,o | |
| "Edit: I have received comments requesting me to elaborate a bit, so here goes: The main problem we want to solve is that we want to have only one instance of Hibernate.",o | |
| This is due to problems with invalidation of Hibernate's 2nd level cache when running several client applications working with the same datasource.,p | |
| "Also, the business/DAO/Hibernate stack is growing rather large, so not duplicating it just makes more sense.",o | |
| "First, we tried to look at how the business layer alone could be exposed to other web apps, and Spring offers JMX wrapping at the price of a tiny amount of XML.",o | |
| "However, we were unable to bind the JMX entities to the JNDI tree, so we couldn't lookup the objects from the web apps.",o | |
| Then we tried binding the business layer directly to JNDI.,o | |
| "Although Spring didn't offer any method for this, using JNDITemplate to bind them was also trivial.",n | |
| "But this led to several new problems: 1) Security manager denies access to RMI classloader, so the client failed once we tried to invoke methods on the JNDI resource.",n | |
| "2) Once the security issues were resolved, JBoss threw IllegalArgumentException: object is not an instance of declaring class.",o | |
| "A bit of reading reveals that we need stub implementations for the JNDI resources, but this seems like a lot of hassle (perhaps Spring can help us?",o | |
| ") We haven't looked too much into EJB yet, but after the first two tries I'm wondering if what we're trying to achieve is at all possible.",o | |
| "To sum up what we're trying to achieve: One JBoss instance, several web apps utilizing one stack of business objects on top of DAO layer and Hibernate.",o | |
| "Best regards, Nils .",p | |
| Could you comment on 1.,o | |
| What problem you're trying to solve; 2.,o | |
| The issues you found with the respective approaches you mention.,o | |
| This would allow a more focused answer...,p | |
| "It was difficult to say it all in 300 characters, so I edited the question to add more details :-).",n | |
| Are the web applications deployed on the same server?,o | |
| "I can't speak for Spring, but it is straightforward to move your business logic in to the EJB tier using Session Beans.",p | |
| The application organization is straight forward.,o | |
| "The Logic goes in to Session Beans, and these Session Beans are bundled within a single jar as an Java EE artifact with a ejb-jar.xml file (in EJB3, this will likely be practically empty).",o | |
| Then bundle you Entity classes in to a seperate jar file.,o | |
| "Next, you will build each web app in to their own WAR file.",o | |
| "Finally, all of the jars and the wars are bundled in to a Java EE EAR, with the associated application.xml file (again, this will likely be quite minimal, simply enumerating the jars in the EAR).",o | |
| This EAR is deployed wholesale to the app server.,o | |
| "Each WAR is effectively independent -- their own sessions, there own context paths, etc.",o | |
| "But they share the common EJB back end, so you have only a single 2nd level cache.",o | |
| You also use local references and calling semantic to talk to the EJBs since they're in the same server.,o | |
| No need for remote calls here.,o | |
| "I think this solves quite well the issue you're having, and its is quite straightforward in Java EE 5 with EJB 3.",p | |
| "Also, you can still use Spring for much of your work, as I understand, but I'm not a Spring person so I can not speak to the details.",o | |
| "Yes, everything is deployed to the same server.",o | |
| "This looks quite interesting, I'll give EJB a shot today.",p | |
| My point about Spring is that it offers to wrap beans for e.g.,o | |
| "JMX without any code, but apparently not for EJB.",o | |
| "Anyway, I look at the EJB approach today.",o | |
| What about spring parentContext?Check out this article: URL_http://springtips.blogspot.com/2007/06/using-shared-parent-application- context.html [ URL_http://springtips.blogspot.com/2007/06/using-shared-parent - application-context.html] .,o | |
| URL_http://www.terracotta.org/ [Terracotta] might be a good fit here (disclosure: I am a developer for Terracotta).,p | |
| "Terracotta transparently clusters Java objects at the JVM level, and integrates with both Spring and Hibernate.",o | |
| It is free and open source.,p | |
| "As you said, the problem of more than one client web app using an L2 cache is keeping those caches in synch.",o | |
| With Terracotta you can cluster a single Hibernate L2 cache.,o | |
| "Each client node works with it's copy of that clustered cache, and Terracotta keeps it in synch.",p | |
| "URL_http://www.terracotta.org/web/display/orgsite/Hibernate+Integration | |
| [This-link] explains more.",o | |
| "As for your business objects, you can use Terracotta's URL_http://www.terracotta.org/web/display/orgsite/Spring+Integration [Spring- integration] to cluster your beans - each web app can share clustered bean instances, and Terracotta keeps the clustered state in synch transparently.",o | |
| You should take a look at the Terracotta Reference Web Application - Examinator.,o | |
| "It has most of the components you are looking for - it's got Hibernate, JPA, and Spring with a MySQL backend.",o | |
| "It's been pre-tuned to scale up to 16 nodes, 20k concurrent users.",o | |
| Check it out here: URL_http://reference.terracotta.org/examinator [ URL_http://reference.terracotta.org/examinator ] .,o | |
| "Actually, if you want a lightweight solution and don't need transactions or clustering just use Spring support for RMI.",p | |
| It allows to expose Spring beans remotely using simple annotations in the latest versions.,p | |
| See URL_http://stati c.springframework.org/spring/docs/2.0.x/reference/remoting.html [ URL_http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html ] .,o | |
| I have used this approach to access shared Spring beans from a webapp.,o | |
| It works though I still feel there is probably a better/cleaner solution.,p | |
| "If you don't like RMI, Spring offers a few other remoting options - Hessian, Burlap, and HttpInvoker (Spring's custom remoting solution - Java serialization over HTTP).",o | |
| Of course there are always web services as well.,p | |
| Spring does have an integration point that might be of interest to you: URL_http://static.springframework.org/spring/docs/2.5.x/reference/ejb.html [EJB-3-injection-nterceptor] .,o | |
| This enables you to access spring beans from EJBs.,o | |
| Thank you for your answers so far.,p | |
| "We're still not quite there, but we have tried a few things now and see things more clearly.",o | |
| Here's a short update: The solution which appears to be the most viable is EJB.,o | |
| "However, this will require some amount of changes in our code, so we're not going to fully implement that solution right now.",o | |
| I'm almost surprised that we haven't been able to find some Spring feature to help us out here.,o | |
| "We have also tried the JNDI route, which ends with the need for stubs for all shared interfaces.",o | |
| "This feels like a lot of hassle, considering that everything is on the same server anyway.",o | |
| "Yesterday, we had a small break through with JMX.",o | |
| "Although JMX is definately not meant for this kind of use, we have proven that it can be done - with no code changes and a minimal amount of XML (a big Thank You to Spring for MBeanExporter and MBeanProxyFactoryBean).",p | |
| The major drawbacks to this method are performance and the fact that our domain classes must be shared through JBoss' server/lib folder.,o | |
| "I.e., we have to remove some dependencies from our WARs and move them to server/lib, else we get ClassCastException when the business layer returns objects from our own domain model.",o | |
| "I fully understand why this happens, but it is not ideal for what we're trying to achieve.",n | |
| "I thought it was time for a little update, because what appears to be the best solution will take some time to implement.",n | |
| I'll post our findings here once we've done that job.,o | |
| "It's been suggested several times on this thread by myself and others, but have you looked at Terracotta?",o | |
| "Unlike all the other solutions presented thus far, it is designed explicitly for state sharing which is what you asked for.",o | |
| "I'm not really sure what you are trying to solve; at the end of the day each jvm will either have replicated instances of the objects, or stubs representing objects existing on another (logical) server.",o | |
| "You could, setup a third 'business logic' server that has a remote api which your two web apps could call.",o | |
| "The typical solution is to use EJB, but I think spring has remoting options built into its stack.",o | |
| "The other option is to use some form of shared cache architecture... which will synchronize object changes between the servers, but you still have two sets of instances.",o | |
| Not so if you use Terracotta.,o | |
| Take a look at URL_http://www.jboss.org/jbosscache/ [JBossCache] .,o | |
| It allows you to easily share/replicate maps of data between mulitple JVM instances (same box or different).,o | |
| "It is easy to use and has lots of wire level protocol options (TCP, UDP Multicast, etc.).",p | |
| Java date time in arabic.,o | |
| How to get arabic date when the user selected language is Arabic and date in english format when selected language is english in spring application ?,o | |
| I tried by setting the default locale to english and arabic based on the request but this doesn't help me in getting calendar api time in arabic for (9 hours 15 mins).,o | |
| Is your question about the locale (language) or the timezone?,o | |
| If suppose i get (9 AM) in english in a lookup service i need corresponding value in arabic based on the user selected language in website.,o | |
| Use Joda time or Java 8 Date time API.,o | |
| Following is the example of Java 8 API CODESNIPPET_JAVA1 .,o | |
| Convert Java AWT code to Android.,o | |
| I developed code in Java using AWT.,o | |
| Now I would like to use that code in Android.,o | |
| "While I used that code in Android, error is showing at ""graphics"".",o | |
| Here is part of code.,o | |
| CODESNIPPET_JAVA1 .,o | |
| "How to convert it to, and use it in, Android?",o | |
| 1) What error?,o | |
| Copy/paste error messages and output.,o | |
| 2) Please use code formatting.,o | |
| "3) Please look to increase that (17%) | |
| [accept rate]( URL_http://meta.stackoverflow.com/a/65088/155831) .",o | |
| OK.Thanks for your valuable suggestion.,o | |
| Android has his own UI library :) so you need to write the code with the android UI standard you cannot use swing or awt in android UI :) For more details about android and java this is a important information you need to know The difference between Dalvik Virtual Machine and Java Virtual Machine and you'll get the all the points .,p | |
| Thanks for your help.Please suggest good link to know more difference b/w DVM and JVM.,p | |
| Swing button vs AWT button?,o | |
| "I'm in the beginnings of making a Minesweeper game for a final class project, but before I begin on making the GUI that is required for it, I would like some advice on what buttons to use.",o | |
| Should I be using an AWT or Swing button?,o | |
| And which would benefit the program more?,o | |
| I'm using Netbeans if that makes a difference.,o | |
| You should use Swing generally.,o | |
| The main reason being is Swing was designed to replace/enhance AWT.,o | |
| "Swing is, generally, more configurable and flexible to use.",p | |
| "You should avoid mixing AWT and Swing components within the same UI, they tend not to play well together.",p | |
| There is more support and information available for Swing components (not to mention a large community of 3rd party components and developers) You could also take a look at URL_http://dn.embarcadero.com/article/26970 [AWT-vs-Swing] and URL_http://stackoverflow.com/questions/408820/what-is-the- difference-between-swing-and-awt [What-is-the-difference-between-swing-and- awt?],o | |
| for more details .,o | |
| Few people develop in AWT anymore.,o | |
| (Hover your mouse over the AWT and Swing buttons in your question.,o | |
| You will see 61 people follow AWT questions and 1.3k follow Swing).,o | |
| I would use Swing.,o | |
| Spend your time learning a more current API and its features.,o | |
| Start with the URL_http://docs.oracle.com/javase/tutorial/uiswing/TOC.html [Swing-tutorial] for the basics.,o | |
| "If Swing is deprecated, what is the alternative?",o | |
| I heard that apparently Swing is being developed no longer.,o | |
| I like Swing and use it all the time.,o | |
| What should I now be using instead?,o | |
| "Although Oracle has much reduced the work on Swing (apparently, seen from an outsider), the ""new Swing"" JavaFX (I don't like this way to call it actually because it has almost no commonalities with Swing) is, from my point of view, not ready yet for primetime.",o | |
| I'm sure Swing has still a long life to live (at least 2 or 3 more years).,n | |
| _**I never heard such thing and still developing swing apps.,o | |
| " | |
| Don't give wings to rumors.But as an alternative you can use URL_http://javafx.com/ [JavaFx] or URL_http://www.eclipse.org/swt/ [swt] or URL_http://buoy.sourceforge.net/ [buoy] .",o | |
| "In the Netbeans IDE help file, if you search for 'swing' you will find a page titled 'about the swing application framework'.",o | |
| It says: 'The swing application framework (JSR 296) is no longer developed and will not become part of the official java development kit as was originally planned.,o | |
| "It is still included in the IDE and you can use this library as it is, but no further development is expected.",o | |
| "Blah blah...' It suggests to use the netbeans platform instead (which I suppose answers my question, but I have no idea what the netbeans platform is).",o | |
| "@Dean: The application framework was a JSR planned for Java 7, now deferred.",o | |
| "It is not Swing, but rather a planned enhancement to make building Swing applications much easier.",o | |
| Oh!,o | |
| I guess I was confused about the whole thing.,n | |
| Thanks for sorting this out for me.,o | |
| That's a very unfortunate name for Swing.,n | |
| Dean isn't the first one here to confuse those two.,n | |
| "You probably read something about the 'Swing Application Framework', which while _built using_ Swing, is not 'Swing'.",o | |
| " | |
| From URL_http://en.wikipedia.org/wiki/Swing_Application_Framework#Status_and_R oadmap [Swing-Application-Framework---Status-and-Roadmap] .",o | |
| " | |
| Development on an open source Reference Implementation called appframework was begun in 2006.",p | |
| "[1] It was originally expected that this implementation would be the means for integrating JSR 296 into the upcoming Java SE 7 (Dolphin) version of the Java programming language, and the project was scheduled to be included in milestone 5 of the JDK7 development.",o | |
| "However, in August 2009, it was announced that the project would not be included due to an inability to reconcile design flaws and achieve consensus among the JSR 296 team before the milestone 5 deadline.",o | |
| "[2] | |
| The original Swing Application Framework implementation has been put on hold indefinitely.",o | |
| [3] The last public release of the appframework project is version 1.03.,o | |
| [1] .,o | |
| "But SAF has been forked since that time and still exists under the name ""BSAF"".",o | |
| The project still seems active nowadays.,o | |
| URL_http://www.eclipse.org/swt/ [The-Standard-Widget-Toolkit] .,o | |
| There is nothing wrong with swing.,n | |
| Personally i don't like SWT.,o | |
| You have to read input-values from widgets and store them in normal variables before a dialog is disposed.,o | |
| "If you were using SWT, you can use JFace as well.",p | |
| It provides a set of viewers (model driven) similar to a lot of Swing models.,o | |
| What is the difference between swing and awt?,o | |
| Can some one please explain me what is the difference between swing and awt?,o | |
| Are there any cases where awt is more useful/ advised to use then swing or vice-versa?,o | |
| Related: URL_http://stackoverflow.com/questions/2994304/is-java-swing-still-in - use/2994324#2994324.,o | |
| AWT is a Java interface to native system GUI code present in your OS.,o | |
| "It will not work the same on every system, although it tries.",o | |
| Swing is a more-or-less pure-Java GUI.,o | |
| "It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, checkboxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it.",o | |
| "Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a ""pluggable look and feel"" that can make it look more or less like how the native windows and widgets would look).",p | |
| These are vastly different approaches to GUI toolkits and have a lot of consequences.,o | |
| A full answer to your question would try to explore all of those.,o | |
| ":) Here are a couple: AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those toolkits can do.",p | |
| Advanced or newer AWT widgets that might exist on one platform might not be supported on another.,o | |
| "Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform.",n | |
| "People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.",p | |
| "Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view.",n | |
| Swing itself handles your widgets' layout and stacking.,o | |
| "Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.",n | |
| "Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT.",o | |
| This made Swing unfortunately slow to catch on.,n | |
| "However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals.",o | |
| "Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets.",p | |
| "Some will say it took far too long to get to this point, but most will say that it is well worth it.",p | |
| "Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.",o | |
| :) .. please check my edited question.,o | |
| "Um... having done some pretty extensive Swing across multiple platforms, I can tell you that it very much is not the same across platforms.",p | |
| Similar?,o | |
| Sure.,o | |
| Same?,o | |
| No way.,o | |
| thanks a lot skiphoppy...,o | |
| The heavyweight/leightweight problems will disappear with Java 6 update 12 (see URL_http://java.dzone.com/news/a-farewell-heavyweightlightwei) .,n | |
| Wow.,p | |
| "I can't believe they can fix it, and I still can't believe mixing lightweight and heavyweight components would ever be desirable.",p | |
| But it's incredible that they can fix it.,o | |
| Just forget about both.,o | |
| Have a look at WPF.,o | |
| :).,o | |
| "The base difference that which already everyone mentioned is that One is | |
| weight** and other is | |
| weight**.",o | |
| "Let me explain, bacially what the term heavy weight means is that when you are using the awt components the native code used for getting the view component | |
| generated by the Operating System**, thats why it the look and feel changes | |
| OS to OS.",n | |
| " | |
| Where as in swing components its the responsibility of | |
| to generate the view for the components.",o | |
| " | |
| Another statement which i saw is that | |
| is MVC based and awt is not.",o | |
| " | |
| .",o | |
| "actually Swing uses a Model-Delegate approach, which is derived from the MVC approach, where in the View and Controller are combined for a Delegate structure.",o | |
| +1 for more simpler explanation.,p | |
| URL_http://dn.codegear.com/article/26970 [Swing-vs-AWT] .,o | |
| Basically AWT came first and is a set of heavyweight UI components (meaning they are wrappers for operating system objects) whereas Swing built on top of AWT with a richer set of lightweight components.,n | |
| "Any serious Java UI work is done in Swing not AWT, which was primarily used for applets.",o | |
| are there any cases where awt is more useful/ advised to use then swing?,o | |
| "Samiksha, make that another question instead of trying to have a discussion thread in these comments.",o | |
| :).,o | |
| It used to be relevant... 10 years ago.,o | |
| "@Pacerier he was talking about AWT, not SWT.",o | |
| "As far as when AWT may be more useful than Swing - | |
| you may be targeting an older JVM or platform that doesn't support Swing.",o | |
| This used to really come into play if you were building Applets - you wanted to target the lowest common denominator so people wouldn't have to install a newer Java plugin.,n | |
| I'm not sure what the current most widely installed version of the Java plugin is - this may be different today.,o | |
| " | |
| some people prefer the native look of AWT over Swing's 'not quite there' platform skins.",p | |
| (There are better 3rd party native looking skins than Swing's implementations BTW) Lots of people preferred using AWT's FileDialog over Swing's FileChooser because it gave the platform file dialog most people were used to rather than the 'weird' custom Swing one.,n | |
| " | |
| 1.",o | |
| Swing is part of the java foundation classes.,o | |
| 2.,o | |
| Swing components are platform-independent.,p | |
| 3.,o | |
| Swing components are lightweight components because swing sits on the top of awt.,p | |
| " | |
| 1.",o | |
| AWT is called the abstract window tool.,o | |
| 2.,o | |
| AWT components are platform-dependent.,n | |
| 3.,o | |
| AWT components are heavyweight components.,n | |
| " | |
| .",o | |
| AWT occupies more memory space2 .,n | |
| AWT is platform dependent3 .,o | |
| "AWT require javax.awt package | |
| .",o | |
| Swing occupies less memory space2 .,n | |
| Swing component is platform independent3 .,o | |
| Swing requires javax.swing package .,o | |
| Difference between Swing and AWTSeveral consequences result from this difference between AWT and Swing.,o | |
| "AWTis a thin layer of code on top of the OS, whereas Swing is much larger.Swing also has very much richer functionality.",o | |
| "Using AWT, you have toimplement a lot of things yourself, while Swing has them built in.",o | |
| "ForGUI-intensive work, AWT feels very primitive to work with compared to Swing.Because Swing implements GUI functionality itself rather than relying on thehost OS, it can offer a richer environment on all platforms Java runs on.AWT is more limited in supplying the same functionality on all platformsbecause not all platforms implement the same-looking controls in the sameways.Swing components are called ""lightweight"" because they do not require anative OS object to implement their functionality.",p | |
| "JDialog and JFrame areheavyweight, because they do have a peer.",o | |
| "So components like JButton,JTextArea, etc., are lightweight because they do not have an OS peer.",p | |
| "A ""peer"" is awidget provided by the operating system, such as a button object or an entryfield object.",o | |
| " | |
| swing component provide much flexible user interface because itfollow model view controller(mvc).",p | |
| " | |
| awt is not mvc based.",o | |
| " | |
| swing works faster.",p | |
| " | |
| awt does not work faster.",p | |
| " | |
| swing componets are light weight.",o | |
| " | |
| awt componentsare heavy weight.",n | |
| " | |
| swing occupies less memory space.",n | |
| " | |
| awt occupies more memory space.",n | |
| " | |
| swing component is platform independent.",o | |
| " | |
| awt is platform dependent.",o | |
| " | |
| swing require javax.swing package.",o | |
| " | |
| awt require javax.awt package.",o | |
| A better Java JSON library?,o | |
| Can anyone recommend a good CODETERM1 (better than the one from URL_http://json.org/ [ URL_http://json.org/ ] )?,o | |
| "I've also found CODETERM2 , which definitely looks like an improvement, but I'm wondering if there is anything that is even better than that?",o | |
| I have added a hyperlink to my parser in my answer ( URL_http://www.softwaremonkey.org/Code/JsonParser) .,o | |
| "One thing that'd help is to explain in which ways you want alternative to be better -- more functionality, more convenient, more efficient, better documentation or something else?",o | |
| Yes... what is wrong with the existing ones?,o | |
| "Only thing I can think of is type-safety, but when I tried to fix that, it turned out to be impossible.",o | |
| A lot has changed since this question was asked 2 years ago.,o | |
| "Here is a more recent benchmark of java serializers: URL_http://code.google.com/p/thrift - protobuf-compare/wiki/Benchmarking Notable: ""Omitted from the first three charts: json/google-gson and scala.",p | |
| "These serializers are so slow, they would break the scale of our charts.",n | |
| See below for the naked data.,o | |
| """I'm using Jackson Json on an android app, which is incredibly fast, and come a very long way since this question was asked/answered.",n | |
| "One of the shortcomings of the json.org library is that it accepts unquoted strings, breaking the JSON specification.",o | |
| "At the very least, they could have included a parameter to enable strict parsing.",o | |
| "Frederick, I think your link should be in an answer, or at least mentioned in bigger text in the question.",o | |
| """closed as not constructive by Kev"".",o | |
| "Seeing all the information and activity, it does look very constructive and _perhaps_ it shouldn't have been closed so eagerly!.",p | |
| "Open questions that shouldn't be open obviously cause so much more harm than closed questions that shouldn't be closed, so let's be thankful that people err on the side of closing questions.</sarcasm>.",n | |
| "I can live with this being closed (voting to reopen, though), but please let's not delete it (it is awfully close to that).",n | |
| A lot has changed since this question was asked 5 years ago.,o | |
| "Oracle has produced a standard JSON API (JSR 353) for Java EE 6 which is available in Maven, and the reference implementation used in Glassfish is also available in Maven.",p | |
| @ThorbjrnRavnAndersen - consider editing top answer for Java JSON library with your comment.,o | |
| I notice that there is also a library called URL_http://code.google.com/p /google-gson/ [google-gson] .,o | |
| I haven't tried it yet.,o | |
| "Here's how it describes itself: | |
| Gson is a Java library that can be used to convert Java Objects into its JSON representation.",o | |
| It can also be used to convert a JSON string to an equivalent Java object.,o | |
| Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.,o | |
| " | |
| There are a few open-source projects that can convert Java objects to JSON.",o | |
| "However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code.",o | |
| Most also do not fully support the use of Java Generics.,o | |
| Gson considers both of these as very important design goals.,o | |
| "Check out if your version of Java already contains JSON API - see URL_http://www.oracle.com/technetwork/articles/java/json-1973242.html [Java- API-for-JSON-Processing,-July-2013] and URL_https://jcp.org/en/jsr/detail?id=353 [JSR-353] .",o | |
| +1.,o | |
| Gson is great.,p | |
| Here's an use example: URL_http://stackoverflow.com/questions/1688099/converting-json-to - java/1688182#1688182.,o | |
| "This is the solution I went with in the end, and months later I'm very happy with my decision.",p | |
| The problem with Gson (at least in versions up to 1.4) is that it is not able to handle circular references.,o | |
| This is very common in some scenarios (JPA/JDO objects being serialized to JSON...).,o | |
| Most java json libs do not deal with cyclic deps -- that's more domain of object serialization frameworks.,o | |
| "FWIW, XStream with Badgerfish (jettison) does handle them (since it's full object-serialization framework, although resulting json looks ugly, as its xml based, just converts to json via badgerfish).",n | |
| GSon uses the same design protocol JSON.org went with when developing JSONObject and JSONArray.,o | |
| Design protocol meaning... ?,o | |
| "Similar API, or something?",o | |
| I don't see much similarities between the two (which I think is good thing for GSON).,p | |
| "Gson is great, and has high quality documentation too.",p | |
| Check out the [User Guide]( URL_http://sites.google.com/site/gson/gson-user-guide ) to get started.,o | |
| "GSON is awesome, brings a python like feel to Java, well, atleast for JSON purposes.",p | |
| "When I wanted to use JSONLib; I found out that the jar file that is available in URL_http://json-lib.sourceforge.net has some class dependencies and it needs to be used by some other jar files, that contain that classes.",o | |
| So I used Gson.,o | |
| "Incredibly, GSON types [don't implement Serializable nor Cloneable...]( URL_http://code.google.com/p/google-gson/issues/detail?id=485) .",n | |
| Really too bad.,n | |
| "GSON is a good library, we have been using it in our project from past 2years, and it works fine.",p | |
| Gson is very slow.,n | |
| "I've a situation with a client that makes use of gson that converts, 300 objects at a time, from json to objects with gson and there are about 9-50k objects to convert.",o | |
| This takes 10-60 minutes on a mobilephone/hand held computer.,o | |
| @Johan What would be more reasonable performance and what other libraries deliver?,o | |
| "@eflat it seems to depend on object size and how you handle the mobile phone memory etc, not only gson/jackson etc.",n | |
| "However, Jackson performed better for us.",o | |
| "I've used URL_http://json-lib.sourceforge.net/ [JSONLib] , URL_http://flexjson.sourceforge.net/ [FlexJSON] and URL_http://code.google.com/p/google-gson/ [Gson] all with great success.",p | |
| Each has its best use.,o | |
| " | |
| JSONLib is awesome as a core JSON library when you just want to process all elements of a JSON.",p | |
| CODESNIPPET_JAVA1 .,o | |
| " | |
| FlexJSON shines with its deepSerialize method that can properly handle serializing all get methods presented in a bean obtained from Hibernate (lazy loaded).",p | |
| CODESNIPPET_JAVA2 .,o | |
| " | |
| Gson seems to be the best API to use when you want to convert a json to a Java class.",p | |
| Other API only call set methods on the high level classes in the bean structure.,o | |
| "If you have a deep bean structure, everything else will be implemented with dyna beans.",o | |
| Causes havoc elsewhere.,o | |
| "Gson fully populates all | |
| low level values by calling all set methods for all data found in the JSON.",n | |
| CODESNIPPET_JAVA3 .,o | |
| URL_http://en.wiktionary.org/wiki/your_mileage_may_vary [YMMV] .,o | |
| """Gson fully populates all low level values by calling all set methods for all data found in the JSON.""",n | |
| "Actually, Gson does not use set methods when deserializing (nor does it use get methods when serializing).",o | |
| "Instead, Gson uses reflection to directly reference the fields.",o | |
| Some future version of Gson will reportedly support using getters/setters instead of fields.,o | |
| A comment on issue 232 includes the possible changes necessary to enable getter support.,o | |
| "When I wanted to use JSONLib; I found out that the jar file that is available in URL_http://json-lib.sourceforge.net has some class dependencies and it needs to be used by some other jar files, that contain that classes.",o | |
| So I used Gson.,o | |
| "I can't _truly_ recommend this, because I've never used it, but URL_http://jackson.codehaus.org/ [Jackson] sounds promising.",p | |
| "The main reason I mention it is that the author, Tatu Saloranta, has done some really great stuff (including URL_http://woodstox.codehaus.org/ [Woodstox] , the StAX implementation that I use).",p | |
| "UPDATE: | |
| A year ago I started actually using Jackson and I can confirm that it is awesome :-).",p | |
| "I especially like being able to switch back and forth between using a ""tree model"" (similar to XML DOM) and object mapping.",o | |
| "For example, let's say I have the following JSON: CODESNIPPET_JAVA1 .",o | |
| The data I really want is inside CODETERM1 .,o | |
| The rest is fluff that I don't care about (maybe returned by some REST API).,o | |
| "In addition, I have the following Java class: CODESNIPPET_JAVA2 .",o | |
| I can use the following code to navigate through the JSON document and then map the object I want: CODESNIPPET_JAVA3 .,o | |
| "Without this capability, I would be stuck writing extra wrapper classes.",o | |
| "Another impressive Jackson feature is the ability to _map classes that you don't own_ (in other words, map a third-party Java class when you can't change the source code).",p | |
| See URL_http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html [this- blog-entry] for more details.,o | |
| Jackson is amazingly customizable.,p | |
| "I could list many, many more features :-).",o | |
| "Finally, don't miss URL_http://www.cowtowncoder.com/blog/archives/2010/11/entry_434.html [7 -Killer-Features-that-set-Jackson-apart-from-competition] .",o | |
| "I second that, Jackson is a wonderful piece of work- much more efficient.",p | |
| Just curious - why the downvote?,o | |
| Does someone have different (i.e.,o | |
| negative) feedback about Jackson?,o | |
| I tried Jackson when I was doing interoperability between .NET and Java and dates was a mess for me.,n | |
| I don't understand why it's done the way it's done in Jackson.,o | |
| "The idea behind JSON is that I should just be able to shuffle data around, I don't have to care about date formats, timezones and all that crap.",o | |
| When I was sending data back and forth between js and c# I had zero problems whatsoever.,o | |
| Hi Anders!,o | |
| "JSON does not have a Date type (just strings, numbers, booleans), and each lib therefore has to define its own convention.",o | |
| "That can lead to interoperability problems, esp.",p | |
| since default serializations for different languages are different.,o | |
| "One thing that might be interesting wrt Jackson is the performance aspect (Jackson is specifically designed as a very high performance JSON package), see [ URL_http://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking ] and [ URL_http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html ].",p | |
| "I've just ran into some problems with Jackson, Hibernate and Spring, however, I don't know if this issue is related to Jackson or Spring or Hibernate ... see URL_http://stackoverflow.com/questions/3325387/infinite-recursion-with - jackson-json-and-hibernate-jpa-issue.",o | |
| "user268098: I think most Java JSON handling libraries have issues with cyclic dependencies, and most have some ways to either exclude just references, or handle them with annotations (I added an answer in the other question to point out one way to do that with Jackson).",o | |
| "Of alternatives I think only XStream+Jettison handles cyclic dependencies automatically, if enabled.",o | |
| I second this.,o | |
| Jackson is also easy to use.,p | |
| See: URL_http://spring-java - ee.blogspot.com/2010/12/how-to-dumpinspect-object-or-variable.html.,o | |
| "I have used Jackson a lot, and it blows the competition away.",n | |
| "FYI, it appears that Jackson has moved to a new home within codehaus.org.",o | |
| Can you update your original link?,o | |
| To wit: URL_http://jackson.codehaus.org/ .,o | |
| I second Jackson in favour of FlexJson; FlexJson lacks a default Jax-RS provider and doesn't correctly parse generics (like SomeObject).Also Jackson has very elegant configuration (once you find out how to plug it in!),p | |
| and mixins allow great flexibility!.,p | |
| Just went through this exercise.,o | |
| I wanted to represent arbitrary JSON as nearest Java equivalent.,o | |
| For me that is a HashMap/ArrayList Object.,o | |
| "URL_http://code.google.com/p/json-simple/ [json-simple] was excellent: tiny, with a simple API that generates HashMap/ArrayList with a single call.",p | |
| It also has extensions for object serialization/deserialization.,o | |
| "I also tried gson: API was very object serialization oriented, and type safe, could not do what I needed simply.",o | |
| "+1 The way it encodes/decodes to maps, lists and primitive objects appeals to my Python experience too.",o | |
| "FWIW, almost all Java JSON libraries support this conversion mode, including GSON, Jackson and Genson.",o | |
| I can recommend URL_http://json-lib.sourceforge.net/ [ URL_http://json - lib.sourceforge.net/] .,p | |
| We have used it in few projects without problems.,o | |
| This bug has made me sad: URL_http://sourceforge.net/tracker/?func=detail&aid=2062 744&group_id=171425&atid=857928.,n | |
| "also, it has dependencies.",o | |
| "I have no personal experience with the following approach,but it could make sense to consider: URL_http://xstream.codehaus.org/index.html [XStream] (xml <-> java data binding) with URL_http://jettison.codehaus.org/ [Jettison] driver (xml<->json mapper), more details are available URL_http://xstream.codehaus.org/json- tutorial.html [here] .",o | |
| "That's from their site: | |
| CODESNIPPET_JAVA1 .",o | |
| JAXB 2.0 also has support for JSON serialization using Jettison.,o | |
| "Actually, any XML package that can use Stax API can use Jettison -- JAXB does, so there's no extra work involved (same is mostly true for XStream too, although it may have some additional support).",o | |
| I found XSteam useful when converting Objects back and forth between Java & XML or JSON with the Jettison driver.,o | |
| "If you want to influence the representation in XML/JSON to a larger degree than just naming tags and ignore properties, you'll be better of using one of the other libraries mentioned above.",o | |
| Isn't this a little perverse?,o | |
| Gson can also be used to serialize arbitrarily complex objects.,n | |
| Here is how you use it: CODESNIPPET_JAVA1 .,o | |
| Gson will automatically convert collections to JSON arrays.,o | |
| Gson can serialize private fields and automatically ignores transient fields.,o | |
| "While deserializing, Gson can automatically convert JSON arrays to collections or arrays.",o | |
| Gson uses the specified class as the primary specification for deserialization.,o | |
| "So, any extra fields available in the JSON stream are ignored.",o | |
| This helps design secure systems that prevent injection attacks.,p | |
| You can also extend Gson's default serialization and/or deserialization behavior by registering custom type adapters.,o | |
| For more details: see the user guide at the project: URL_http://code.google.com/p/google-gson/ [ URL_http://code.google.com/p/google - gson/] Disclosure: I am one of the co-authors of Gson.,o | |
| And yet another example is here: URL_http://stackoverflow.com/questions/2496494 /library-to-encode-decode-from-json-to-java-util-map/2496528#2496528.,o | |
| Any plans to support circular dependencies in the near future?,o | |
| "You can file a feature request for the project, if there isn't one.",o | |
| I know many developers would like to have this.,o | |
| I've been meaning to try URL_http://flexjson.sourceforge.net/ [Flexjson] .,o | |
| "It looks like it uses reflection on bean-style properties and uses similar rules as Hibernate/JPA lazy-loading for serialization, so if you give it an object to serialize it will leave out collections (unless you tell it to include them) so you don't end up serializing the entire object graph.",o | |
| "The json.org library does pretty well with serializing basic beans with reflection, but doesn't have these advanced features.",p | |
| "Might be worth checking out, especially if you use an ORM solution.",p | |
| I like FlexJSON as well and even modified it to be compatible with Microsoft's JSON serializer really easily.,p | |
| You may try using GSON.It's downloadable at URL_http://google- gson.googlecode.com/files/google-gson-1.4-release.zip [ URL_http://google - gson.googlecode.com/files/google-gson-1.4-release.zip] Quite simple to use actually.I used it to parse JSON results from Yelp and there is a simple example here: CODESNIPPET_JAVA1 .,n | |
| "Hi, based on ur experience, is the GSON support JDK1.4 by any chance?",o | |
| I can't find the documentation re the JDK it supports.,o | |
| Thanks.,o | |
| I've used URL_http://jsontools.berlios.de/ [JSON-Tools-library] and it works well.,p | |
| "works I was looking for a very simple way to do Php json encode in (server) and Java json decode (client), all seems too much to do only to achieve this.",p | |
| I came out to this which is really simple and it works perfect.,p | |
| Please see: URL_http://stackoverflow.com/questions/3831680/httpservletrequest-get-post- data/5539252#5539252 [more-details-click-here] .,o | |
| "I recommend URL_http://code.alibabatech.com/jira/browse/FASTJSON [fastjson] ,just as its name,really fast .",p | |
| "I wrote a JSON ""pull-api"" parser (3 classes, 18K), which I really like using.",o | |
| "I find the pull metaphor much more usable than the event metaphor, and creating a document tree using pull is trivial.",n | |
| FWIW I didn't much care for the www.json.org parser either.,o | |
| My biggest complaint with the offerings out there is the size of them - we target a download-constrained applet market.,o | |
| "I remember lying in bed one night at about 2am wondering ""how hard could it be"", after a bit I got up and started writing - URL_http://www.softwaremonkey.org/Code/JsonParser [this-tiny-parser-is-the- result] .",o | |
| JSON Tools looks good too.,p | |
| " | |
| The following generalized recursive code uses my parser to parse a JSON file into a ""DataStruct"" - essentially a map of lists (Note that DataStruct and Callback are objects from another package which are not published with this parser: CODESNIPPET_JAVA1 .",p | |
| "crtmbrcbk.invoke(crtprm,psr,tgt,nam,psr.getMemberValue()); What are you, Polish?",o | |
| ":) Joking, of course.",o | |
| I liked URL_http://sourceforge.net/projects/json2java/ [J2J---Json2Java] from Sourceforge.,o | |
| Really easy to map JSON to almost any java object by only annotating the class using JsonElement and then passing the java and class to JsonReader like: CODESNIPPET_JAVA1 .,p | |
| "After exploring and actually using most of the major libraries listed here, I ended up writing a simplified API that is much easier to use and more fun to work with: URL_http://sharegov.blogspot.com/2011/06/json-library.html [ URL_http://sharegov.blogspot.com/2011/06/json-library.html ] .",n | |
| "I will add one more tip for excelent JSON<->JAVA binding lib PoJSON, it is written specifically for the URL_http://netbeans.org [NetBeans-IDE] (by Petr Hrebejk) and thus it is used in production on large project.",o | |
| "It is easy to use in any project, it is just not placed on the web as a separate project (afaik), however it is in a separate package ""org.codeviation"" here: URL_http://hg.netbeans.org/main/file/9609b899e64d/kenai/src/org/codeviation [ URL_http://hg.netbeans.org/main/file/9609b899e64d/kenai/src/org/codeviation ] .",p | |
| I've used URL_http://jettison.codehaus.org/ [Jettison] and it works well.,p | |
| A nice new library for Java is URL_http://code.google.com/p/serotonin-json/ [Serotonin-JSON] .,p | |
| It has lots of nice features.,p | |
| "I say ""new"", but it's really been around for years, just not as open source.",p | |
| "You might want to list some of the nice features, since there are so many alternatives -- project page lists many, although most exist in other libs as well.",p | |
| I have developed an Add-on for Android's in-built JSON Parser (or.json.,o | |
| "), | |
| which helps to convert JSON to Java Object- URL_http://prasanta- paul.blogspot.com/2011/04/json-to-java-bean-conversion-for.html [http ://prasanta-paul.blogspot.com/2011/04/json-to-java-bean-conversion-for.html] .",o | |
| Converting JSON to Java.,o | |
| I want to be able to access properties from a JSON string within my Java action method.,o | |
| The string is available by simply saying CODETERM1 .,o | |
| Below is an example of what the string can look like: CODESNIPPET_JAVA1 .,o | |
| In this string every JSON object contains an array of other JSON objects.,o | |
| The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects.,o | |
| I looked at Google's Gson as a potential JSON plugin.,o | |
| Can anyone offer some form of guidance as to how I can generate Java from this JSON string?,o | |
| " | |
| _I looked at Google's Gson as a potential JSON plugin.",o | |
| Can anyone offer some form of guidance as to how I can generate Java from this JSON string?_ URL_http://code.google.com/p/google-gson/ [Google-Gson] supports generics and nested beans.,o | |
| The CODETERM1 in JSON represents an array and should map to a Java collection such as URL_http://docs.oracle.com/javase/6/docs/api/java/util/List.html [CODETERM2] or just a plain Java array.,o | |
| The CODETERM3 in JSON represents an object and should map to a Java URL_http://docs.oracle.com/javase/6/docs/api/java/util/Map.html [CODETERM4] or just some JavaBean class.,o | |
| You have a JSON object with several properties of which the CODETERM5 property represents an array of nested objects of the very same type.,o | |
| This can be parsed with Gson the following way: CODESNIPPET_JAVA1 .,o | |
| "Fairly simple, isn't it?",o | |
| Just have a suitable JavaBean and call URL_http ://google-gson.googlecode.com/svn/tags/1.3/docs/javadocs/com/google/gson/Gson.,o | |
| "html#fromJson%28java.lang.String,%20java.lang.Class%29 [CODETERM6] .",o | |
| " | |
| See also: | |
| URL_http://json.org/ [Json.org] - Introduction to JSON | |
| URL_https://sites.google.com/site/gson/gson-user-guide [Gson-User-Guide] - Introduction to Gson .",o | |
| "Thanks BalusC, I used Gson and the concept is quite simple to grasp.",p | |
| Performant?,o | |
| Have you actually measured it?,o | |
| "While GSON has reasonable feature set, I thought performance was sort of weak spot (as per [ URL_http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html])As to example: I thought GSON did not really need setters, and was based on fields.",o | |
| So code could be simplified slightly.,o | |
| "It is fast enough, sure if you see what it all can do with javabeans, nested javabeans and generics.",p | |
| The javabean getters/setters have other purposes in other layers and does not slowdown so I would just keep them there.,o | |
| I use it in an android app.,o | |
| It is not the fastest possible solution but it is simple enough to program to justify the lack of performance for the user until now.,p | |
| Maybe in a later version of the app it will be removed for a faster solution.,p | |
| "Wrt speed, if it's fast enough, it's fast enough.",p | |
| "I just commented on reference to expected good performance.Feature-set wise Jackson handles all the same nesting, layering, generics, so that's not where speed difference comes from.Having getters and setters does not impact performance in any measurable way (for packages I am aware of), so definitely can have them there.",p | |
| what is Data here?,o | |
| Do I need to create any class?,o | |
| ?,o | |
| @Fahim: scroll down in the code example.,o | |
| @BalusC : Actually I need to convert mysql data to json (xml) and vice-versa.,o | |
| Any link?,o | |
| "+1 for the ""package com.stackoverflow.q1688099;"".",o | |
| For some reason it made me chuckle.,o | |
| Bewaaaaare of Gson!,o | |
| "It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't _that_ hard).",p | |
| "Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST!",n | |
| The full objects won't even be copied!,o | |
| Use XStream..,o | |
| "Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything.",o | |
| A small price to pay (ugly json) for true serialization.,n | |
| "Note that URL_http://wiki.fasterxml.com/JacksonHome [Jackson] fixes these issues, and is URL_https://github.com/eishay/jvm-serializers/wiki [faster] than GSON.",p | |
| +1 I agree.,o | |
| I find jackson or simple json much easier to use then gson.,p | |
| "Oddly, the only decent JSON processor mentioned so far has been GSON.",n | |
| "Here are more good choices: | |
| URL_http://wiki.fasterxml.com/JacksonHome [Jackson] -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access) | |
| URL_http://flexjson.sourceforge.net/ [Flex-JSON] -- highly configurable serialization EDIT (Aug/2013): One more to consider: | |
| URL_http://code.google.com/p/genson/ [Genson] -- functionality similar to Jackson, aimed to be easier to configure by developer .",p | |
| The XStream library also supports JSON: URL_http://xstream.codehaus.org/json- tutorial.html [ URL_http://xstream.codehaus.org/json-tutorial.html ] .,o | |
| If you visit URL_http://json.org/java/ [this-page] you will find several Java classes that can help with this.,o | |
| "For example, the JSONObject | |
| and the JSONArray | |
| classes.",o | |
| They are designed to read in a JSON String and provide access to their properties via a get() method.,o | |
| I used this library in a project and it stinks.,o | |
| Example: JSONObject#getNames(JSONObject) returns null instead of an empty List or array if no names are available.,o | |
| @Malax Thanks for the heads up.,o | |
| Hopefully one of the other suggestions would work better for the OP.,o | |
| "@Malax Since you have access to the code, couldn't you change JSONObject#getNames to return whatever you'd like in that case?",o | |
| "But that JSON library could still stink for other reasons (never used them personally, but I know we're using them at work).",n | |
| "Well, json.org default lib is rather rudimentary.",n | |
| I wouldn't choose it for any new project -- most alternatives from the page are much better.,o | |
| "People are just using it because it has been around for years, and so others have used, and recommend it to new users... basic s/w development inertia.",p | |
| Or with Jackson: CODESNIPPET_JAVA1 .,o | |
| "If, by any change, you are in an application which already uses URL_http://restfb.com/ [ URL_http://restfb.com/ ] then you can do: CODESNIPPET_JAVA1 .",o | |
| etc.,o | |
| "If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.",o | |
| CODESNIPPET_JAVA1 .,o | |
| "Here's an option from my URL_http://northconcepts.com/data-pipeline/ [data- migration-library] that uses xpath plus the built-in, generic record class instead of creating a new bean class.",o | |
| "You can filter in java code, but here we use CODETERM1 which uses the expression language to auto-convert the CODETERM2 field from a string to a boolean and test if it's true.",o | |
| You can get URL_https://northconcepts.com/data- pipeline/expression-language/ [more-info-on-the-expression-language-here] .,o | |
| CODESNIPPET_JAVA1 .,o | |
| "The above code reads from a file, but you can easily read from a URL as in the following example that reads stock info from google.",o | |
| " | |
| URL_http://northconcepts.com/data-pipeline/examples/read-a-json-stream/ [ URL_http://northconcepts.com/data-pipeline/examples/read-a-json-stream/ ] Good hunting.",p | |
| I use URL_http://www.jsonschema2pojo.org/ [this-tool] shown by @JigarJoshi to generate my schema.,o | |
| Then I use GSON upon the generated classes.,o | |
| Its very handy.,p | |
| Input JSON and get Java classes:) .,o | |
| What's wrong with the standard stuff?,o | |
| CODESNIPPET_JAVA1 .,o | |
| Give boon a try: URL_https://github.com/RichardHightower/boon [ URL_https://github.com/RichardHightower/boon ] It is wicked fast: URL_https://github.com/RichardHightower/json-parsers-benchmark [ URL_https://github.com/RichardHightower/json-parsers-benchmark ] Don't take my word for it... check out the gatling benchmark.,p | |
| "URL_https://github.com/gatling/json-parsers-benchmark [ URL_https://github.com/gatling/json-parsers-benchmark ] (Up to 4x is some cases, and out of the 100s of test.",o | |
| It also has a index overlay mode that is even faster.,p | |
| It is young but already has some users.),o | |
| It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode.,p | |
| "With Boon Index Overlay mode, it is even faster.",p | |
| It also has a very fast JSON lax mode and a PLIST parser mode.,p | |
| ":) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).",n | |
| It also has the fastest JSON to JavaBean mode too.,p | |
| "It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.",p | |
| A better alternative to Jersey/Jackson for building JSON REST APIs?,o | |
| "I need to build the server side of a JSON-REST API, and I've been playing with Jersey to do it (using it's JSON-POJO mapping feature).",o | |
| "The problem is that even testing the simplest possible use-case has required several questions here on SO, and quite a bit of hunting around.",p | |
| "In short, it's not a very fluid API in the style of, say, JSoup, it appears to be a tool that comes from the era where everything was XML, and then it was retrofitted for JSON.",p | |
| "You can see this, for example, in the requirement that POJO objects need to be annotated with @XmlRootElement even though nothing I am doing involves XML.",o | |
| "I'm wondering if there are other libraries, perhaps more recent, that I should consider for this that might be easier to use than Jersey?",o | |
| YES!,o | |
| YES!,o | |
| FOR THE LOVE OF GOD YES!,p | |
| I have been asking this same type of question now over and over again and I keep getting little to nothing back.,n | |
| I even gave up a 300pt bounty and still nothing: [here]( URL_http://stackoverflow.com/questions/6986365/java-rest-client-jax-rs - automatic-type-mapping).,o | |
| [And this one was fun.,n | |
| ]( URL_http://stackoverflow.com/questions/6312030/cxf-no-message-body-writer - found-for-class-automatically-mapping-non-simple-r).,o | |
| I don't know why we haven't got web services in java tied down yet.,o | |
| Jersey can serialize POJOs to JSON without any annotations using Jackson.,o | |
| You configure this by setting the CODETERM1 property to CODETERM2 .,o | |
| "In CODETERM3 , add the following servlet init parameter: CODESNIPPET_JAVA1 .",o | |
| URL_http://jersey.java.net/nonav/documentation/latest/json.html#json.pojo.appr oach.section [See-the-Jersey-documentation] .,o | |
| I highly recommend URL_http://www.jboss.org/resteasy [JBoss-RESTEasy] for the REST API.,p | |
| I've used it on a couple of projects and found it to be trivial to setup.,n | |
| It also integrates nicely with Spring if you need that.,p | |
| I have used both Jackson and Gson for the JSON support with RESTEasy and it is quite simple.,p | |
| All you do is annotate a POJO with JAXB annotations and include the proper libraries.,o | |
| Another really great part of RESTEasy is the good support for multipart form data.,p | |
| They provide an @MultipartForm annotation which allows you to bind a multipart form to a POJO without writing any code...works slick.,o | |
| I would advise against Spring MVC for REST because it is not JAX-RS compliant.,n | |
| Using a JAX-RS compliant interface gives you a little bit better portability if you decide to switch to a different implementation down the road.,n | |
| "Hmm, I'm not sure, it looks like it expects to be deployed in a war file, and I would rather avoid a heavyweight servlet container and all of that infrastructure, the API is just a small part of my project, I don't want to stuff the entire thing in a war just so I can support the API :-/.",n | |
| Run it on Jetty...it will be light-weight!.,p | |
| for converting json to pojos : URL_http://code.google.com/p/google-gson/ [gson] and URL_http://jackson.codehaus.org/ [jackson] .,o | |
| "For URL_http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework- reference/html/ch18s02.html [Restful] I'd use URL_http://blog.springsource.org/2009/03/08/rest-in-spring-3-mvc/ [spring] , or URL_http://www.restlet.org/ [restlet] .",o | |
| "Yes, I'm very familiar with Gson, and Jersey already uses Jackson, but converting JSON to and from POJOs is only one part of the problem, I'm looking for an alternative to Jersey, which is a framework for building REST-HTTP APIs.",o | |
| If one existed I'd prefer a HTTP framework that worked with Gson instead of Jersey as I'm more comfortable with it.,p | |
| "@sanity oh, spring then.",p | |
| "Note: | |
| I'm the URL_http://www.eclipse.org/eclipselink/moxy.php [EclipseLink-JAXB-(MOXy)] lead, a member of the URL_http://jcp.org/en/jsr/detail?id=222 [JAXB-(JSR-222)] expert group and a contributor to the URL_http://jersey.java.net/ [Jersey] project.",o | |
| With Jersey or any JAX-RS project you can use a CODETERM1 / CODETERM2 for complete control over your JSON binding.,o | |
| Below is an example of using this mechanism to leverage MOXy as the JSON provider.,o | |
| " | |
| URL_http://stackoverflow.com/questions/8980204/configuring-cxf-with-spring-to-use-moxy-for-xml-marshalling-unmarshalling/8989659#8989659 [Configuring-CXF-with-Spring-to-use-MOXY-for-XML-marshalling/unmarshalling] .",o | |
| As URL_http://stackoverflow.com/a/9503506/27657 [NimChimpsky-mentioned] restlet will do this out of the box.,o | |
| "Furthermore, if your client is also java you can abstract the functionality into an interface and wrap it with a client side proxy fairly easily.",o | |
| This tutorial page shows how to do what I've mentioned URL_http://wiki.restlet.org/docs_2.0/13-restlet/21-restlet/318-restl et/303-restlet.html [here] .,o | |
| "You can try URL_http://openjpa.apache.org/jest.html [JEST] , it works over URL_http://openjpa.apache.org/ [OpenJPA] .",p | |
| Json conversion.,o | |
| i want to create a Json like this CODESNIPPET_JAVA1 .,o | |
| i have tried below code but that create Json just only for one line CODESNIPPET_JAVA2 .,o | |
| this above code create Json like this CODESNIPPET_JAVA3 .,o | |
| Please let me know about the changes required in that Java code thanks.,o | |
| Change your code as: CODESNIPPET_JAVA1 .,o | |
| "Thanks for reply; but it gives error ""The method toJSONString() is undefined for the type JSONObject"" at jsonArray.push(jsonObj.",o | |
| _toJSONString()_);.,o | |
| @ShYzDaSE : see my edit answer.,o | |
| O yes done thank You very Much Imran Saved alot of my time :-) stay blessed buddy.,p | |
| why you are converting jsonarray to JSONObject?,o | |
| most welcome friend!!!,p | |
| :).,o | |
| Use CODETERM1 method on CODETERM2 .,o | |
| I recommend the URL_http://jackson.codehaus.org/ [jackson-library] it makes things very easy.,p | |
| To use it you would have an object like this... CODESNIPPET_JAVA1 .,o | |
| Then you can use the objectMapper from the library to go from an array that you have in memory to a json String like so CODESNIPPET_JAVA2 .,o | |
| Of course doing it this way depends on how your ids are stored but for me it generally makes my code a lot cleaner and the Jackson Library is pretty good performance wise.,p | |
| Getting Access to HttpServletRequest object in restful web service.,o | |
| "I can get access to the HttpServlet Request object in a soap web service as follows:Declaring a private field for the WebServiceContext in the service implementation, and annotate it as a resource: CODESNIPPET_JAVA1 .",o | |
| "To get the HttpServletRequet object, I write the code as below: CODESNIPPET_JAVA2 .",o | |
| But these things are not working in a restful web service.,n | |
| I am using Apache CXF for developing restful web service.,o | |
| Please tell me how can I get access to HttpServletRequest Object.,o | |
| I'd recommend using CODETERM1 CODESNIPPET_JAVA1 .,p | |
| You can use the CODETERM2 annotation to flag other types (such as ServletContext or the HttpServletRequest specifically).,o | |
| See URL_http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics- Contextannotations [Context-Annotations] .,o | |
| Why use a framework for RESTful services in Java instead of vanilla servlets.,o | |
| "I know there are a few questions regarding the libraries you can use to do RESTful services in Java, but what is the value in using them against vanilla implementations.",o | |
| "I mean, if i was looking to create URL_http://stackoverflow.com/questions/6774904/nested-rest-routing [the-url- structure-described-by-Wim] | |
| URL_www.example.com/images | |
| URL_www.example.com/images/id/num | |
| URL_www.example.com/images/tag/num | |
| URL_www.example.com/images/tag/num/num/num Would it not be easier (for future developers) and faster (to implement and learn) to map the url pattern /images to a servlet and have a line or two that parses the url for the parameters instead of learning, implementing and configuring one of these libraries to do it for you.",o | |
| " | |
| URL_http://en.wikipedia.org/wiki/Apache_CXF [Apache-CXF] | |
| URL_http://jersey.java.net/ [Jersey] (popular) | |
| URL_http://en.wikipedia.org/wiki/Restlet [Restlet] (pioneer of JAX-RS) | |
| URL_http://www.jboss.org/resteasy [RESTEasy] Essentially what I am asking is... What is the value in using a RESTful Java framework?",o | |
| "Would it not be adding a lot of complexity, in the implementation, for a simple problem?",o | |
| EDIT: This jersey code is handled very neatly and everyone should know how to do it in servlet form if they are looking into libraries to do it for them.,o | |
| CODESNIPPET_JAVA1 .,o | |
| "If all you are going to be doing is a ""service"" that returns text that is driven by URL parameters, so plain text returns, is a framework necessary?",o | |
| Actually Jersey is the reference implementation of JAX-RS.,o | |
| "So I'd call it the pioneer, not Restlet.",o | |
| Your edit makes your question answer itself.,o | |
| "If you just want to say ""Hello World"", you don't need JAX-RS.",o | |
| But who just wants to do that?,o | |
| "I should have referenced wikipedia there, personally I am wary of calling things pioneers.",n | |
| "If that's all you're doing, why bother with servlets at all?",o | |
| "After all, with just GET you shouldn't be changing any state anywhere (well, not state worth the name; server logs don't count).",p | |
| Donal I do not follow... What handles the GET request then?,o | |
| "JAX-RS is a very well designed API that makes mapping HTTP requests to methods, extracting parameters from various parts of a HTTP request, handling content negotiating, and many other low level tasks very easy.",p | |
| "Using JAX-RS, mainly via Apache CXF, for roughly two years now, I'd always prefer it over plain Servlets.",p | |
| "But is the time to learn, implement, understand for each developer worth it.",p | |
| I mean does it save time?,o | |
| Is it really more simple?,o | |
| "If it is just about extracting parameters, then surely it is easier to stay closer to the Java standard.",p | |
| It would be rather simple to extract parameters in a servlet.,p | |
| I feel that it is potentially too much added complexity for the value it provides.,o | |
| You don't just want to extract parameters.,o | |
| "You want to set HTTP response codes, map incoming and outgoing bodies to objects, and other stuff.",o | |
| "Yes, JAX- RS helps with this.",o | |
| "@avanderw Maybe your experience is only with simple webapps, because I know from mine that it really helps a lot with more complex applications.",n | |
| "Doing all that stuff directly at the level of a servlet would be a lot of work, but JAXRS lets you focus much more on the resources within your application.",o | |
| (Not that I'd claim it's perfect some surprising things are still very awkward but it definitely makes things a lot easier.,n | |
| ).,o | |
| " | |
| Would it not be easier (for future developers) and faster (to implement and learn) to map the url pattern CODETERM1 to a servlet and have a line or two that parses the url for the parameters instead of learning, implementing and configuring one of these libraries to do it for you.",o | |
| Easier?,o | |
| "It's certainly not easier to write you've got to do all the path extraction yourself and all the method handling and all the content type negotiation (in _both_ directions) and all the cookie handling and the object deserialization/serialization thunks and well, lots of low-level stuff that would all need testing and debugging or easier to maintain either, since the JAX-RS interface lets you operate at the level of resources (the natural characterization of RESTful webapps) instead of requests; with much experience, maintenance is easiest when the gap between conceptual model and implementation is smallest.",p | |
| It's also not faster to implement (because the low-level implementations of JAX-RS have already been tested and debugged for you; less for you to do) and the cost of learning it isn't very high as it is a mostly declarative API with very few surprises.,n | |
| "OK, these benefits might not seem so much when you're only dealing with simple webapps.",p | |
| "After all, you can hack something out in very little time and put the resulting lash-up online.",n | |
| You'll then have to pray that you got it right without significant unexpected avenues for exploits or denial-of-service attacks.,n | |
| And the maintenance programmers will have to understand just what those regular expressions you've sprayed through the code do (Good Luck With That!,p | |
| ) when adding small features or fixing bugs.,n | |
| "But as the webapp gets larger, the benefit of having a tested library to handle all the low-level stuff really does win out.",n | |
| "(Before you ask, some of the libraries you mention will merrily install themselves as servlets; this allows your code to just describe the business logic of the servlet and declare how mapping to the wire is done in abstract terms.",p | |
| That's just enormously easier.,n | |
| ) .,o | |
| When would using regular servlets instead of jersey be appropriate?,o | |
| Should handling doPost in a httpservlet never be done?,o | |
| @jontro When you like doing everything by hand?,o | |
| I'm not convinced that there's really a good reason unless you've got a desperate need to keep the number of libraries down.,n | |
| Frameworks are used to make you task more easier.,o | |
| i agree that we can do the same thing by implementing servlets and then parse the url and then implement the basic logic.,o | |
| Bu if you are using framework like jersey then u don't have to worry about those parsing patterns and other similar tasks.,n | |
| ServletContainer class will take care of this (parsing url in it's service method) and there are lots of other classes also which will make your task easier.,o | |
| And one more thing we are taking only a one scenario (matching patterns) but when our requirements will grow the same code written by our own servlets will become more complicated and complex.,n | |
| "This is just my point, why use a sledgehammer to hammer in a nail.",o | |
| "If the framework is easy enough to adopt then you should be able to go from vanilla to the framework with more ease than from another framework, when the need arises.",p | |
| Why take the whole kitchen sink when all you need is the tap?,o | |
| "Actually JAX-RS is an API while CXF, Jersey, RESTEasy are implementations.",o | |
| "They all have their strong and weak sides, for example how easy they integrate with Spring.",p | |
| But I would definitely recommend using JAX-RS.,p | |
| "I would go with using Jersey or a library in this case, if it does the following (adds enough value): | |
| the config for the URL is all self-contained within one file, with the source | |
| there are no hidden config files or overly verbose configs (e.g.",n | |
| "web.xml) | |
| the parameters are nicely mapped to strongly typed variables (e.g.",p | |
| "use of annotations) | |
| it is not convoluted to get to the values of parameters (e.g.",p | |
| "URL_http://stackoverflow.com/a/1943667/831203 [RESTlet] ) | |
| the overhead for running the library is low (I have had bad experiences with reflection solutions in other libraries) | |
| it is well documented | |
| it is well adopted In such a scenario, I find that using a library would add value to my project for the effort required to use it.",n | |
| "Jersey does seem to mach the requirements quite adequately, although I have not given other frameworks enough investigation yet.",p | |
| Any easy REST tutorials for Java?,o | |
| Every tutorial or explanation of REST just goes too complicated too quickly - the learning curve rises so fast after the initial explanation of CRUD and the supposed simplicity over SOAP.,p | |
| Why can't people write decent tutorials anymore!,o | |
| "I'm looking at Restlet - and its not the best, there are things missing in the tutorial and the language/grammar is a bit confusing and unclear.",n | |
| It has took me hours to untangle their First Steps tutorial (with the help of another Java programmer!,o | |
| ") | |
| Tutorial Comments** Overall I'm not sure exactly who the tutorial was aimed at - because there is a fair degree of assumed knowledge all round, so coming into REST and Restlet framework cold leaves you with a lot of 'catchup work' to do, and re-reading paragraphs over and over again.",o | |
| 1.,o | |
| We had difficulty working out that the jars had to be in copied into the correct lib folder.,p | |
| 2.,o | |
| "Problems with web.xml creating a HTTP Status 500 error - | |
| The server encountered an internal error () that prevented it from fulfilling this request , the tutorial says: | |
| ""Create a new Servlet Web application as usual, add a ""com.firstStepsServlet"" package and put the resource and application classes in.",o | |
| """ This means that your fully qualified name for your class | |
| is | |
| so we had to alter web.xml to refer to the correct class e.g: original: CODESNIPPET_JAVA1 .",p | |
| should be: CODESNIPPET_JAVA2 .,o | |
| " | |
| I was under the impression that the concepts of REST were supposed to be much simpler than SOAP - but it seems just as bad if not more complicated - don't get it at all!",n | |
| grrrr Any good links - much appreciated.,p | |
| "Oh, how do I feel your pain!",n | |
| Definitely an up vote!.,o | |
| Check out URL_http://stackoverflow.com/questions/1710199/which-is-the-best-java - rest-api-restlet-or-jersey and consider if this is an exact duplicate or not.,o | |
| I so agree with you!,o | |
| "One would think that an API like RESTlet would ""help"" you.",o | |
| I could write a simple web service framework in a third of the time it takes me to understand the RESTlet architecture.,p | |
| Could you describe precisely what caused you troubles in our Restlet tutorials?,o | |
| We are interested in fixing/improving what needs to.,o | |
| Did you check the screencasts?,o | |
| "URL_http://www.restlet.org/documentation/1.1/screencast/ [ URL_http://www.restlet.org/documentation/1.1/screencast/ ] Otherwise, there is a Restlet tutorial in the O'Reilly book that we wrote in their Chapter 12.",o | |
| "If you still have troubles, please contact our mailing list: URL_http://www.restlet.org/community/lists [ URL_http://www.restlet.org/community/lists ] Best regards,Jrme Louvel Restlet ~ Founder and Lead developer ~ URL_http://www.restlet.org [ URL_http://www.restlet.org ] Noelios Technologies ~ Co-founder ~ URL_http://www.noelios.com [ URL_http://www.noelios.com ] .",p | |
| Please see my new edits in my question - cheers.,p | |
| "It sounds like you could use a solid understanding of the fundamentals of REST, and for that I _highly_ recommend URL_http://rads.stackoverflow.com/amzn/click/0596529260 [RESTful-Web-Services] by Leonard Richardson and Sam Ruby.",p | |
| I provides a great introduction to REST: what it is and how to implement a (practical) RESTful web service.,p | |
| "Most of the example code in the book is actually Ruby, but it's easy enough to understand even if you're not a Ruby expert.",p | |
| "But one thing that should help you specifically is that one of the later chapters of the book contains overviews of several RESTful frameworks, including Restlet.",o | |
| "It doesn't really get into any code (it's a 50,000-foot flyover) but I think it'll give you just what you need at this stage.",o | |
| Funnily enough I have just ordered RESTful Web Services on Amazon before I read your post.,p | |
| Thanks for your valuable comments too.,o | |
| The Restlet framework is composed of four main parts.,o | |
| " | |
| ",o | |
| "Restlet API** First, there is the ""Restlet API"", a neutral API supporting the concepts of REST and facilitating the handling of calls for both client-side and server- side applications.",o | |
| "This API is backed by the Restlet Engine and both are now shipped in a single JAR (""_org.restlet.jar_"").",o | |
| "This separation between the API and the implementation is similar to the one between the Servlet API and Web containers like Jetty or Tomcat, or between the JDBC API and concrete JDBC drivers.",o | |
| " | |
| ",o | |
| "Retrieving the content of a Web page** As we mentioned in the introduction paper, the Restlet framework is at the same time a client and a server framework.",o | |
| "For example, Restlet can easily work with remote resources using its HTTP client connector.",o | |
| "A connector in REST is a software element that enables the communication between components, typically by implementing one side of a network protocol.",o | |
| Restlet provides several implementations of client connectors based on existing open-source projects.,o | |
| The connectors section lists all available client and server connectors and explain how to use and configure them.,o | |
| Here we will get the representation of an existing resource and output it in the JVM console: CODESNIPPET_JAVA1 .,o | |
| Note that the example above uses a simplified way to issue calls via the _ClientResource_ class.,o | |
| If you need multi-threading or more control it is still possible to manipulate use the _Client_ connector class or the _Request_ objects directly.,o | |
| "The example below how to set some preferences in your client call, like a referrer URI.",o | |
| It could also be the languages and media types you prefer to receive as a response: CODESNIPPET_JAVA2 .,p | |
| " | |
| ",o | |
| "Listening to Web browsers** Now, we want to see how the Restlet framework can listen to client requests and reply to them.",o | |
| "We will use the internal Restlet HTTP server connector (even though it is possible to switch to others such as the one based on Mortbay's Jetty) and return a simple string representation ""hello, world"" as plain text.",p | |
| Note that the _Part03_ class extends the base _ServerResource_ class provided by Restlet: CODESNIPPET_JAVA3 .,o | |
| "If you run this code and launch your server, you can open a Web browser and hit the .",o | |
| "Actually, any URI will work, try also.",o | |
| "Note that if you test your server from a different machine, you need to replace ""localhost"" by either the IP address of your server or its domain name if it has one defined.",o | |
| "So far, we have mostly showed you the highest level of abstraction in the Restlet API, with the ClientResource and ServerResource classes.",o | |
| "But as we move forward, you will discover that those two classes are supported by a rich API, letting you manipulate all the REST artifacts.",o | |
| " | |
| ",o | |
| Overview of a REST architecture** Let's step back a little and consider typical web architectures from a REST point of view.,n | |
| "In the diagram below, ports represent the connector that enables the communication between components which are represented by the larger boxes.",o | |
| "Not specifically Java-related, but I thought these InfoQ articles were quite good: | |
| URL_http://www.infoq.com/articles/rest-introduction [A-Brief-Introduction-to-REST] | |
| URL_http://www.infoq.com/articles/tilkov-rest-doubts [Addressing-Doubts-about-REST] | |
| URL_http://www.infoq.com/articles/rest-anti-patterns [REST-Anti-Patterns] .",p | |
| "you point to an error inside the web.xml, but I've just checked in both Restlet 1.0 and 1.1 documentation, and I don't see this kind of error.I would like to mention that you can find at the end of the page a zip that contains a complete war file and the list of source files in case you want to run in ""standalone"" mode.Did you try the standalone mode?",o | |
| "As explained in the tuto, you only need 2 jars in the classpath, and the source files.",o | |
| "We would like also to point that the ""firstSteps"" tutorial is not a tutorial on REST but on the programmation with Restlet.",o | |
| "You can also have a look at the ""firstResource"" tutorial ( URL_http://www.restlet.org/documentation/1.1/firstResource [ URL_http://www.restlet.org/documentation/1.1/firstResource ] ) which describes how to develop a simple resource and which introduces some concepts of the REST architecture style.",p | |
| It should help you.,o | |
| Here is a well written tutorial on REST.. URL_http://rest.elkstein.org/2008/02 /what-is-rest.html [ URL_http://rest.elkstein.org/2008/02/what-is-rest.html ] .,p | |
| "Whilst this may theoretically answer the question, [it would be preferable]( URL_http://meta.stackoverflow.com/q/8259 ) to include the essential parts of the answer here, and provide the link for reference.",p | |
| "In addition, the qualified named suggested in the tutorial is indeed ""firstStepsServlet.FirstStepsApplication"" and not ""com.firstStepsServlet.FirstStepsApplication"".",o | |
| "Therefore, the suggested param value in web.xml is correct.",p | |
| Could you confirm that this fixes your issue?,o | |
| "Also, did you have Servlet deployment knowledge before reading the tutorial?",o | |
| "If not, that would explain the pain.",n | |
| "In this case, the standalone mode is probably a better fit.",p | |
| See my new edits in my post.,o | |
| We fixed the typo.,o | |
| "Note that in addition to the firstSteps and firstResource pages supposed to get you started quickly, there is a more detailled Tutorial that will walk you through the various concepts of REST and Restlet: URL_http://www.restlet.org/documentation/1.1/tutorial .",p | |
| eSoftHead company has just released a URL_http://blog.esofthead.com/develop- restful-application-with-resteasy/ [short-tutorial] of developing Restful application by using RESTeasy.,o | |
| Rest clients for Java?,o | |
| With JSR 311 and it's implementations we have a powerful standard for exposing Java objects via Rest.,p | |
| However on the client side there seems to be something missing that is comparable to Apache Axis for SOAP - something that hides the web service and marshals the data transparently back to Java objects.,o | |
| How do you create Java RESTful clients?,o | |
| Using HTTPConnection and manual parsing of the result?,o | |
| Or specialized clients for e.g.,p | |
| Jersey or Apache CXR?,o | |
| check this out: URL_http://igorpolevoy.blogspot.com/2011/01/java-rest-with - ease.html thanks igor.,o | |
| "This is an old question (2008) so there are many more options now than there were then: | |
| CXF** has three different URL_http://cxf.apache.org/docs/jax-rs-client-api.html [REST-Client-options] | |
| (mentioned above).",o | |
| " | |
| also has its own called URL_http://blog.springsource.com/2009/03/27/rest-in-spring-3-resttemplate/ [RestTemplate] | |
| HTTP Client** build your own.",o | |
| " | |
| <strike>** URL_https://github.com/sonatype/async-http-client [Async-http-client] | |
| by Sonatype</strike>.",o | |
| URL_https://github.com/AsyncHttpClient/async-http-client [Ning-Async-http-client] .,o | |
| The new kid on the block which provides NIO support (although truthfully I don't think this really improves performance for clients like it does servers).,p | |
| [UniREST]( URL_http://unirest.io /#java) is also pretty good nowadays.,p | |
| As I mentioned in URL_http://stackoverflow.com/questions/165720/how-to-debug- restful-services#166269 [this-thread] I tend to use URL_http://jersey.java.net/ [Jersey] which implements JAX-RS and comes with a nice REST client.,p | |
| The nice thing is if you implement your RESTful resources using JAX-RS then the Jersey client can reuse the entity providers such as for JAXB/XML/JSON/Atom and so forth - so you can reuse the same objects on the server side as you use on the client side unit test.,p | |
| For example URL_http://svn.apache.org/viewvc/activemq/camel/trunk/components /camel-rest/src/test/java/org/apache/camel/rest/resources/EndpointsTest.java?r evision=700513&view=markup [here-is-a-unit-test-case] from the URL_http://activemq.apache.org/camel/ [Apache-Camel-project] which looks up XML payloads from a RESTful resource (using the JAXB object Endpoints).,o | |
| The resource(uri) method is defined in URL_http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-rest/sr c/test/java/org/apache/camel/rest/resources/TestSupport.java?revision=700513&v iew=markup [this-base-class] which just uses the Jersey client API.,o | |
| e.g.,o | |
| CODESNIPPET_JAVA1 .,o | |
| BTW I hope that future version of JAX-RS add a nice client side API along the lines of the one in Jersey .,p | |
| "Is there a method where we can mention REST service server list in ClientResource, in case the server is down try the next server?",o | |
| "Just an update, but to address James' 'BTW' comment, the new version of JAX-RS 2.0 will have a client-side API: URL_http://www.infoq.com/presentations/Java-REST .",o | |
| "The link with text ""here is a unit test case"" is broken.",n | |
| You can use the standard Java SE APIs: CODESNIPPET_JAVA1 .,p | |
| Or you can use the REST client APIs provided by JAX-RS implementations such as Jersey.,o | |
| "These APIs are easier to use, but require additional jars on your class path.",p | |
| CODESNIPPET_JAVA2 .,o | |
| "For more information see: | |
| URL_http://bdoughan.blogspot.com/2010/08/creating-restful-web-service-part-55.html [ URL_http://bdoughan.blogspot.com/2010/08/creating-restful-web-service-part-55.html ] .",o | |
| "You can also check URL_http://www.restlet.org [Restlet] which has full client- side capabilities, more REST oriented that lower-level libraries such as HttpURLConnection or Apache HTTP Client (which we can leverage as connectors).",o | |
| "Best regards,Jerome Louvel .",p | |
| You could try URL_https://github.com/harikrishnan83/rapa/wiki/ [Rapa] .,o | |
| Let us know your feedback about the same.And feel free to log issues or expected features.,p | |
| Rapa has a really nice interface and few dependencies.,p | |
| A good alternative to RestSharp in the .NET world.,p | |
| If you only wish to invoke a REST service and parse the response you can try out URL_http://code.google.com/p/rest-assured/ [REST-Assured] : CODESNIPPET_JAVA1 .,o | |
| I use Apache HTTPClient to handle all the HTTP side of things.,o | |
| I write XML SAX parsers for the XML content that parses the XML into your object model.,o | |
| "I believe that Axis2 also exposes XML -> Model methods (Axis 1 hid this part, annoyingly).",n | |
| XML generators are trivially simple.,p | |
| "It doesn't take long to code, and is quite efficient, in my opinion.",n | |
| In my opinion this is the worst way to do REST.,n | |
| Manually handling serialization in Java is a waste of time when you have so many options like JAXB and Jackson.,o | |
| Even loading the whole document and using XPath is marginally slower than SAX and nothing compared to getting the XML (network speed).,n | |
| "i could say, ""i agree"".",o | |
| "I agree too, and I wrote the original comment.",o | |
| "Back then I had a desire for control of the deserialisation, but nowadays I would use Jackson and decently annotated model classes.",o | |
| "I'd like to point out 2 more options: | |
| URL_http://restfulie.caelum.com.br/ [Restfulie] , based on the VRaptor web framework, has both server and client side implementations with very good Hypermedia support.",p | |
| " | |
| URL_http://www.jboss.org/resteasy [RESTEasy] has a URL_http://docs.jboss.org/resteasy/docs/2.3.0.GA/userguide/html/RESTEasy_Client_Framework.html [JAX-RS-proxy-based-client] implementation.",o | |
| You can do it in a very simple way with resteasy (by Jboss).,p | |
| I wrote a blog post about URL_http://guidogarcia.net/blog/2012/03/02/how-to-develop-java- rest-client/ [how-to-develop-a-Java-REST-client] if you want a getting started guide.,o | |
| "Anyway, there are hundreds of alternatives in Java.",o | |
| Check out URL_http://code.google.com/p/resting [Resting] .,o | |
| It promises to invoke REST services and create list of objects from XML/JSON/YAML response in one step.,p | |
| Resting has issues with POST requests.,o | |
| Just found URL_http://wiki.apache.org/incubator/WinkProposal [Apache-Wink] in the Apache Incubator.,o | |
| Could be a interesting project for creating REST servers and clients.,p | |
| Try URL_http://www.rexsl.com/rexsl- test/apidocs-0.10/com/rexsl/test/request/JdkRequest.html [JdkRequest] from URL_http://www.rexsl.com/rexsl-test/ [rexsl-test] (I'm a developer).,o | |
| This is how it works: CODESNIPPET_JAVA1 .,p | |
| Though its simple to create a HTTP client and make a reuest.,p | |
| "But if you want to make use of some auto generated clients, You can make use of WADL to describe and generate code.",o | |
| "You can use URL_http://tomayac.de/rest-describe/latest/RestDescribe.html [RestDescribe] to generate and compile WSDL, you can generate clients in php, ruby, python, java and C# using this.",o | |
| "It generates clean code and there is a good change that you have to tweak it a bit after code generation, you can find good documentation and underlying thoughts behind the tool URL_https://do cs.google.com/document/edit?id=1uydmzsDFIiw8OsoMdk5v_s1VW7wrujUmGdUU2zge0fs [here] .",p | |
| There are few interesting and useful URL_http://wintermuteblog.blogspot.com/2010/01/wadl-toolbox.html [WADL-tools] mentioned on wintermute.,p | |
| "If you are interesting in Eclipse plugin to generate a java client class from WADL, you can see at link URL_http://stackoverflow.com/questions/9159881 /restful-client-from-wadl/16709008#16709008 [Restful-Client-from-WADL] .",p | |
| Memory leak in JBoss.,n | |
| "I am having a very strange behavior in JBoss, and I'd like avail myself of the Collective Wisdom of the SO Crowd.",p | |
| We're using JBoss (4.0.4 I think) to serve SOAP calls.,o | |
| "In fact, it's used as glorified RPC server, no more.",p | |
| We're running out of memory when we have 20+ clients sending their requests at the same time.,n | |
| The requests consist of the incoming rather small request (proper SOAP) and the returning result packet that is essentially one long SOAP string (and the contents of the string are XML).,n | |
| Yes I realize this is suboptimal.,n | |
| Don't ask.,o | |
| I've traced the leak to an instance of org.jboss.axis.message.SAX2EventRecorder that hold 4 million objects (strings and Integers).,o | |
| "Now, even the longest response does not carry 4MB of data.",n | |
| The requests are all smaller than 40K.,o | |
| "Something is fishy there, but I can't find any documentation on the Web.",o | |
| Can someone tell me what the recorder is used for?,o | |
| And how do I get rid of it?,o | |
| Or may be configure it to be less memory-hungry?,o | |
| Any help is appreciated.,p | |
| " | |
| Update: To clarify - I did do memory dump, and the dump shows an array or 4,000,000+ objects, Strings and Integers.",n | |
| "The array is owned by a org.jboss.axis.message.SAX2EventRecorder which is in turn held by these guys: org.jboss.axis.message.SOAPEnvelopeAxisImpl@0x19c31fd8 (141 bytes) : field recorderorg.jboss.axis.message.RPCParamElementImpl@0x19c32260 (123 bytes) : field recorderorg.jboss.axis.message.SOAPBodyAxisImpl@0x19c32160 (121 bytes) : field recorderorg.jboss.axis.message.RPCElement@0x19c321e0 (124 bytes) : field recorderorg.jboss.axis.encoding.DeserializationContextImpl@0x19c332f0 (67 bytes) : field recorderorg.jboss.axis.message.SAX2EventRecorder$objArrayVector@0x19c33398 (24 bytes) : field this$0 The data structures of our own app are quete bloated, but not to this degree.",n | |
| "Another update: powers that be have found a ""powers-that-be-solution"": we're switching to 64-bit memory.",n | |
| Hurray.,o | |
| @Arkadiy: Don't assume there's a bug in JBoss; assume the bug is in your code.,n | |
| You've already identified one 'sub optimal' condition of your software.,p | |
| Why can't there be more?,o | |
| My question is: what are you doing running such an old version of JBoss?,o | |
| It's 2.5 years old.,o | |
| You'll often find people a hesitance or even reluctance from people to help with outdated software.,n | |
| "@Gortok - I did assume our own fault, but that damned array is responsible for half the meory in use, and it has noting to do with us.",n | |
| "And, the way it's held (see update), it may be allocated for each request in progress-that explains why we fail only when certain number of requests are in progress.",o | |
| "@cletus: - ""Enterprise"" environment - three dev teams on 3 continent and no one ready to take responsibility.",o | |
| Ive just been running a case with bea support on some thing of the same sort.,o | |
| "The info needed for them to do anything was: JRA recordings, MissionControl MemLeak screenshots, garbage collection logs and any dump files from the jvm.",n | |
| Run with the JVM arg -XX:-HeapDumpOnOutOfMemoryError.,n | |
| This will give you heap dumps when you run out of memory.,n | |
| You can then analyze the heap dump with the _jhat_ tool (it comes with your JDK).,n | |
| "Alternatively, you can use the _jconsole_ tool (which also comes with your JDK) to request a heap dump at any time using the memory management MBeans.",n | |
| It will tell you what those 4 million objects actually contain which might give you insight into why the software isn't releasing that memory.,n | |
| EDIT: It seems you're not the only one with this issue.,o | |
| "There are 2 bug reports filed with Axis URL_https://issues.apache.org/jira/browse/AXIS-2698 [AXIS-2698] URL_https://issues.apache.org/jira/browse/AXIS-2749 [AXIS-2749] See also URL_https://issues.apache.org/jira/browse/AXIS-1771 [AXIS-1771] , it has some interesting information regarding deserialization and ways to mediate its impact.",n | |
| Which version of Axis are you using?,o | |
| How do you think I've established that SAX2EventRecorder is the culprit?,o | |
| "Damn, people around here are getting used to newbie questions and don't expect any better.",n | |
| "Voting back up: Arkadiy, it may have been unhelpful for you, but the way you phrased the question made it come across as 'newbie', especially since the title is 'Memory Leak in JBoss'.",n | |
| The first rule of using a commercial tool is to assume the bug is in your code; not the commercial tool.,n | |
| I can only work with the information you give me.,o | |
| Perhaps you should be more specific next time.,o | |
| "Anyway, what is the content of the objects in the SAX2EventRecorder?",o | |
| "Yeah, gotta admit: even though the answer may have covered what you've done, downvoting it and then lambasting the poster leaves me thinking ""you're on your own buddy"".",n | |
| @kevin: to quote the question: SAX2EventRecorder that hold 4 million objects (strings and Integers).,o | |
| That's what the contents is.,o | |
| "@Arkadiy, what are those Strings?",o | |
| Are they snippets of your (de)serialized xml or are they something completely different?,o | |
| Are they mostly the same bits and pieces or random?,o | |
| "Way to jump on the people trying to help you, dude.",o | |
| "Your initial question should have stated the exact troubleshooting steps you took - if you ran jconsole, HeapDumpOnOutOfMemoryError, etc.",n | |
| People posting answers shouldn't assume you took any steps you didn't mention.,o | |
| "@Kevin - Yes, the strings are snippets of HTML.",o | |
| "Thanks for pointing out the bugs - I saw the first two, but not the last one.",n | |
| "It would be nice to know what ""settings and things"" in the last comment.",p | |
| It certainly helps to know about 1.4.,o | |
| We do have 1.4 in our codebase - do we use it?,o | |
| Will find out.,o | |
| "If you can, run the application under Java 6.",o | |
| The latest version includes URL_https://visualvm.dev.java.net/ [VisualVM] for profiling.,o | |
| It should be able to show the growth of memory.,n | |
| "You can attach to a Java 5 VM, but it doesn't show as much.",o | |
| JBoss and different versions of Hibernate.,o | |
| We are using JBoss 4.2.3 which in turn comes with version 3.2.1.ga of Hibernate.,o | |
| I would like to use Hibernate 3.5.1-FINAL which supports JPA 2.0.,o | |
| I've been trying to make this work by putting my own hibernate jars in my WEB- INF/lib folder and creating my own classloader for my WAR in jboss-web.xml CODESNIPPET_JAVA1 .,o | |
| I've also tried: CODESNIPPET_JAVA2 .,o | |
| But I get loads of various issues and this is the exception I'm currently stuck on: CODESNIPPET_JAVA3 .,n | |
| Since the deadline is looming I thought I'd better ask if it is even possible?,o | |
| :) .,o | |
| Perhaps you're better off just upgrading to JBoss AS 5?,o | |
| Is that not an option?,o | |
| I'm afraid not Matt Ball :/.,o | |
| "Maybe too late, but it may help somebody that finds this thread looking for the problem described above about 'Caused by: java.lang.NoSuchMethodException: org.hibernate.validator.ClassValidator....': I'm using Jboss 4.2, Hibernate Core 3.6.5, Hibernate Validator 4.1.0, using maven, and I have the same problem.",o | |
| Finally I've solved it adding also this dependency: CODESNIPPET_JAVA1 .,o | |
| "Upvoting you just in case it does help someone else, too late for me I'm afraid :).",p | |
| Thanks mate.,o | |
| Did help.,o | |
| "I didn't test this personally, but the URL_http://community.jboss.org/message/565026 [following-thread] mentions two approaches that you could try (yeah, I know, it's about JBoss 5 but it looks like the problem is identical).",o | |
| " | |
| Option 1 Disable CODETERM1 (your second jboss-web.xml), bundle your Hibernate JARs into your app and add the following properties to your CODETERM2 (to ""avoid"" the issue you're facing): CODESNIPPET_JAVA1 .",o | |
| One user reported this didn't work for him.,o | |
| " | |
| Option 2 Disable CODETERM3 (your second jboss-web.xml), bundle your Hibernate JARs into your app and override the hibernate-validator JARs | |
| CODETERM4 | |
| ",o | |
| I'm not able to explain why the hibernate-validator from CODETERM5 still gets picked.,o | |
| "Cheers mate, I will try that when I can stop hiding from the big scary dead line looming over me :).",n | |
| @willcodejavaforfood: Sounds like a good decision.,p | |
| "Thanks a lot, Option 1 worked for me!",o | |
| "(Jboss 4.2 with Hibernate 3.2.6.ga on the main app, second app is Play!Framework 1.2.5 bundled with Hibernate 3.6).",o | |
| "Many thanks, Option 1 (which seems more elegant) worked for me with Hibernate 3.6.0.Final and JBoss 4.2.1.GA.",p | |
| It was a BIG pain to resolve that strange conflict !,n | |
| !.,o | |
| Active MQ vs JBoss Messaging.,o | |
| I am going to choose a JMS message broker for a project.,o | |
| It is critical that the JMS server is stable and can handle a high load of messages.,n | |
| I have narrowed down the list to include Active MQ and JBoss Messaging.,o | |
| I was wondering if any of you have any experience with any of these or even better have tried both of them in the same environment.,o | |
| Any link to a research paper or similar would be nice.,p | |
| I'd love to hear about this as well.,p | |
| Should this be community wiki?,o | |
| URL_http://activemq.apache.org/how-does-activemq-compare-to-jbossmq.html [ URL_http://activemq.apache.org/how-does-activemq-compare-to-jbossmq.html ] .,o | |
| I am not interested in JBoss MQ but JBoss Messaging.,o | |
| And an independent report would be nice.....,p | |
| Note for those who don't know: JBoss Messaging is a rewrite of JBoss MQ that advertises much improved performance.,o | |
| "It's not a rewrite, really, it shares nothing in common with JBossMQ at all, other than being a JMS implementation with ""JBoss"" in the title.",o | |
| "JBoss Messaging is now in bug fix mode only, since JBoss / Red Hat has a new Java messaging project called HornetQ.",n | |
| "The web site is here URL_http://hornetq.org [ URL_http://hornetq.org ] HornetQ boasts extreme performance, a full feature set and ease of use.",n | |
| You'll find it's performance compared to ActiveMQ is _extremely_ good.,p | |
| BTW - I am the project lead for JBoss Messaging and HornetQ.,o | |
| HornetQ 2.0.0.GA is out in the next week.,o | |
| "JBoss recently redid their entire implementation of Messaging, ala JBoss MQ has been replaced with JBoss Messaging, and now again as ""HornetQ"".",o | |
| You'll just want to keep that in mind as that above comparison is _very_ dated (not to mention probably biased).,o | |
| "Feature-by-feature comparisons are all very well, but my experience of ActiveMQ (through various versions over the years) is that it is shockingly buggy, and noone seems inclined to fix those bugs.",n | |
| It's deeply frustrating.,n | |
| "Also, the documentation is messy and not properly updated with new versions.",o | |
| "JBossMessaging is relatively feature-light, compared to ActiveMQ, but it's rock-solid, well-documented and reliable.",o | |
| "It's also part of JBossAS 5, and RedHat are doing a good job of supporting it.",p | |
| "So far, I had a great experience with the community wiki and documentation of Jboss, and it pretty much covers everything.",p | |
| "Though, I found quite obvious configuration settings left out in their latest documentations, but I guess this must have been improved since then.",o | |
| "For ActiveMQ, I found very little documentation comparing to Jboss.",n | |
| "I have done certain research using MOM with Jboss and GlassFish, but one of the most important impact was the permanent storage if you are going to use any.",o | |
| "I think this itself is very important, especially their compatibility, support, documentations.",o | |
| Take a look at this.,o | |
| Apparently there are certain concern when it comes to persistent storage in ActiveMQ.,n | |
| URL_http://www.jboss.org/file-access/default/members/jbossmessaging/freezone/d ocs/userguide-2.0.0.alpha1/html/performance.html#performance.results [ URL_http://www.jboss.org/file-access/default/members/jbossmessaging/freezone/docs /userguide-2.0.0.alpha1/html/performance.html#performance.results] .,o | |
| JBoss Messaging replaces JBoss MQ.,o | |
| Here are Messaging performance data: URL_http://www.jboss.org/community/docs/DOC-10640 [ URL_http://www.jboss.org/community/docs/DOC-10640 ] JBoss MQ is not scalable at all: URL_http://www.jboss.org/community/docs/DOC-12452 [ URL_http://www.jboss.org/community/docs/DOC-12452 ] .,n | |
| "JBossMQ may not scale as well as JBM, but to say ""not scalable at all"" is just plain wrong.",n | |
| "We use it for fairly high volumes, and it handles this without a complaint or a problem.",o | |
| "Sorry, I should have said hardly scalable.For example, MQ creates 3 threads per subscriber.",n | |
| "If there is active messaging ongoing, it adds up to 10 other threads for such subscriber.",o | |
| On our MQ system we have an average of 3.5 threads per subscriber.Having 300 users served that makes 1000 threads just for MQ.,o | |
| "If a message is put for all subscribes, 300 of those threads queue for CPU.",o | |
| HornetQ looks good.,p | |
| URL_http://www.spec.org/jms2007/results/jms2007.html [ URL_http://www.spec.org/jms2007/results/jms2007.html ] .,o | |
| Real world comparisons of Glassfish and JBoss 5?,o | |
| Does anyone have experiences with both in the real world?,o | |
| "How do they compare in terms of performance (memory usage, speed, etc)?",o | |
| Stability?,o | |
| Does JBoss Seam work well on Glassfish?,o | |
| "please, rephrase the question as comparing between EITHER: Glassfish 2 vs JBoss 5, ....or.... Glassfish 3 vs JBoss 6.",o | |
| A number of things from my own experience: 1.,o | |
| "GlassFish has much better administration console(JBoss has three consoles, each of them far from being ideal).",p | |
| 2.,o | |
| Hot deployment is more reliable on GlassFish 3.,o | |
| "JMS works better on GlassFish - this applies to GF vs. JBoss 4.X.As far as I see the JMS implementation was drastically modified inJBoss 5.X, so maybe this claim is no longer true 4.",n | |
| "WebServices are working better on GlassFish,I had a number of issues with more advanced configuration on JBoss 5.",p | |
| "GlassFish has more super-high-end entrprise add-ons, like HA-Database, that storesuser session on a cluster in Database, not in memory, so the full failover ispossible, whatever disaster would happen 6.",n | |
| "JBoss is more much popular, there are a lot of administrators, developers, who know it,so it is easier to find someone, who can develop on JBoss, there are also moreresources in the net.",p | |
| "Sometimes this is more important, then technical superiority ofone solution over another.",n | |
| 7.,o | |
| GlassFish is friendlier for developers.,p | |
| Redeployment of the web application on GF 3lasts more or less one second - in oreder to achieve this kind of speedof redeployment for JBoss I need JRebel.,o | |
| "In addition, if someone is using NetBeans,there is a number of smart wizards, that are very helpful.",p | |
| 8.,o | |
| "The future of GlassFish is not certain because of the acquisition of SUN by Oracle.Right now Oracle claims it will support it, but who knows how this support willlook like and how long will it last.",o | |
| "Even though GlassFish is open source, hardly anyone is ready to develop application server for his/her own needs... From my point of view GF is easier to administer, is a better solution from purely technological point of view, but it is far less popular and has uncertain future.",p | |
| "I am not connected in any way with RedHat/JBoss or SUN/GlassFish, my company (erudis.pl) is supporting and developing for both servers.",o | |
| "An excellent summary, can't fault that comparison.",o | |
| "(disclaimer: I work at Sun and I am in the GF team) I agree that Seam works fine on GlassFish; see URL_https://blogs.oracle.com/theaquarium/tags/seam [ URL_https://blogs.oracle.com/theaquarium/tags/seam ] GFv3 is quite different than JBoss 5; in particular: | |
| GFv3 is based on OSGi while JBoss 5's kernel is based on JMX.",o | |
| " | |
| GFv3 supports JavaEE 6; JBoss 5 supports Java EE 5.",o | |
| "GFv3 is designed to be very modular; services start on demand, there is an update center repository, etc.",o | |
| GFv3 is significantly smaller than JBoss 5 and will start much faster.,p | |
| JBoss 5.1 GA is listed as 130MB; GFv3Preview is 50MB.,o | |
| GFv3 starts in a couple of seconds; JBoss in tens (you should try the startup for your own platform).,o | |
| "There are other differences, some inherited from GlassFish v2 like the graphical admin console, or the admin CLI.",o | |
| "A more direct comparison for JBoss 5 would be the GlassFish v2 releases, which are based on Java EE 5.",o | |
| "The latest release in that family is GFv2.1, with a GFv2.1.1 release scheduled in October (see URL_https://blogs.oracle.com/theaquarium/entry/schedule_for_glassfish_v2_1 [ URL_https://blogs.oracle.com/theaquarium/entry/schedule_for_glassfish_v2_1 ] ).",o | |
| Sun also provides patch releases of GlassFish (akin to RedHat's support for JBoss); see URL_https://blogs.oracle.com/glassfishforbusiness [ URL_https://blogs.oracle.com/glassfishforbusiness ] and sun.com/glassfish.,o | |
| Your comparisons are disingenuous.,n | |
| "(1) The JBoss5 kernel is not JMX based (JBoss 4 was, not 5).",o | |
| "(2) JBoss is also modular, you pick which modules you want.",o | |
| The configurations it ships with are just starting points.,o | |
| "(3) Startup time depends which config you pick, it varies from around 3 seconds for a minimal config, to a minute or ttwo for the bells-and-whistles config.",o | |
| "@Pelegi, can you mention just one thing that JBoss does better than Glassfish?",o | |
| It's strictly what you're used to.,o | |
| I found configuring and using JBoss to be about as pleasing as trying to shave with a jagged spoon while riding a unicycle with no seat.,o | |
| "Glassfish however, just seems to work.",o | |
| "My choice is Glassfish: it is faster to start-up, to deploy web applications.the Admin console is very accurate, moreover it is both graphical and command-line.Now it is fully-supported by Oracle, its future is not uncertain any more.It is based upon OSGi: it is really modular.You can install Spring-osgi applications easly.You can freely choice between Eclipse Link , Apache Open JPA and Hibernate without pain.It is greatly integrated in NetBeans (and, of course, Eclipse).",p | |
| "On the other hand, Jboss is more widespread and thus it is easy to find job on it (IMHO because it is an old App Server; glassfish is relatively new).",p | |
| I started developing a Seam application on JBoss and after a few months tried to get it working on Glassfish.,p | |
| I found the Glassfish enviroment very counterintuitive.,o | |
| I had to fix some strange errors on GF and I could not find any information on the web so after a few days I gave up and went back to JBoss.,o | |
| So personally I would not recommend Glassfish.,n | |
| I will have to go with Glassfish on this.,o | |
| "Deploying a diverse range of application built on different webservices, we had major compatibility issues, resulting in customizing the class loading & still faced many issues.",o | |
| Glassfish I never faced any such issues.,o | |
| Merits of Java applet for web applications.,p | |
| What are the advantages and disadvantages of using a Java applet for authentication as part of a web application?,o | |
| I am think of cases where such an applet is only used for authentication and transaction-signing purpose and not otherwise in the web application.,o | |
| What would be the point of using an applet for authentication & signing?,o | |
| Security theatre?,o | |
| "Most servers have built-in SPNEGO support, so you shouldn't have to code something like an applet to do your authentication.",o | |
| Do you need to use any phisical device during authentication.,o | |
| "Such as hard drive, flash-card, smart-card, eToken, iKey, etc.?",o | |
| "In that case you must | |
| use the applet.",o | |
| "Yes, I understand the value when using h/w crypto devices but this is not the general case, including shared-secret and non-machine-readable h/w OTP devices.",o | |
| "As a best practice, an applet should only augment the server's capabilities in the context of authentication.",p | |
| "The server ought to re-verify what has been sent by the applet (client), for the message could have been modified in transit.",o | |
| There are times however where an applet may serve a valid purpose.,o | |
| "For instance, messages sent by the client, may be digitally signed by the applet, with the keys being managed in per-user USB drives (containing the private keys).",o | |
| "In such a context, the applet serves as a mechanism for accessing the JCA libraries in Java, apart from accessing the USB store.",o | |
| The signature produced will have to re-validated by the server on receipt of the message.,o | |
| "When implemented correctly, applets like any client-side security scheme will increase the security posture of an application.",o | |
| "When implemented incorrectly, it results in a security theatre where the server relies on the client to provide trusted input.",o | |
| "Also, if one needs to perform privileged operations (like access drives containing private keys), then the applet must be signed; and an appropriate Java security policy file must be maintained.",p | |
| Any errors in the management process of the Java security model will obviously lower the security of the system.,o | |
| "Also, if native OS specific APIs like MSCAPI have to be accessed, then deployment of native code (DLLs) is a pre-requisite, and the software (not the applet) responsible for doing so, must be coded securely.",o | |
| "Disadvantages: | |
| Client JVM management.",n | |
| " | |
| Session/Proxy coordination management.",o | |
| " | |
| Antiquated technology.",n | |
| "Advantages: | |
| Single language skills?",o | |
| " | |
| ...?",o | |
| "IMHO if you don't need something like powerful GUI support or Java2D (most of which can be done with JQuery, ExtJS, etc) there is no real argument for applets.",p | |
| How to authenticate users from a rest service.,o | |
| I am trying to authenticate users with a REST service I built using drop wizard.,o | |
| "From previous questions I found great example of authenticating with openID on github: URL_https://github.com/gary-rowe/DropwizardOpenID [ URL_https://github.com/gary-rowe/DropwizardOpenID ] However, I don't want to deal with openID at the moment and simply want users to 1.",p | |
| "Signup, 2.",o | |
| Signin My questions/confusions are: 1.,n | |
| For Signup: I'm thinking about sending users's username/password as a CODETERM1 request with the credentials as either form parameters or part of JSON body.,o | |
| "However, isn't there a security risk here of sending password in plain text?",o | |
| 2.,o | |
| For Sing-in I'm thinking about using CODETERM2 in Dropwizard.,o | |
| 3.,o | |
| I don't want to store passwords in plain text.,o | |
| What strategy should I follow after I get the users' password in the CODETERM3 as plain text?,o | |
| I'm looking for some java libraries that can assist in password salt and MD5 .,o | |
| Have you read their [authentication]( URL_http://dropwizard.codahale.com/manual/auth /#oauth2) documentation?,o | |
| "OAuth2 is going to be the most secure and RESTful approach; as for sending creds in plaintext, are you building a web front-end?",o | |
| "If so, serve your site over https and it won't be a problem.",o | |
| I don't envision any external apps using the API for data.,o | |
| My api will just be used by my app's mobile and web interface.,o | |
| Wouldn't Oauth2 be an overdo for this?,o | |
| OAuth2 is a great approach to ensure that each logged in user receives their own access token that you can track and manage.,p | |
| Short of dropping the API altogether (and using just session/cookies) it's still the best and most scalable approach.,p | |
| "Do the work now, it'll last (forever?",o | |
| ).,o | |
| Maybe I'm not following correctly.,p | |
| If I go down OAuth2 route I have to register my app with one of the OAuth2 providers e.g.,o | |
| "google, github, etc.",o | |
| right?,o | |
| And then I can use that token to authorize the user?,o | |
| "No no no... Dropwizard supports OAuth2 on the back end - so you would implement your own OAuth2 service, and then have the browser perform the auth handshake with it; completely independent from Google, et al.",o | |
| "Ah, roger that.",o | |
| much better.,o | |
| I'll find more info on how to implement OAuth2 with drop wizard.,o | |
| "Users can ""signup"" with Oauth2 as well?",o | |
| Yes they can.,o | |
| "Looks like their docs are pretty good too, and being open source, you should find lots of examples.",p | |
| "Looking at the docs, we can see that Dropwizard supports a standalone OAuth2 implementation: URL_http://dropwizard.codahale.com/manual/auth/#oauth2 [ URL_http://dropwizard.codahale.com/manual/auth /#oauth2] OAuth2 has several advantages, many of which can be read about here: URL_http://stackoverflow.com/questions/7561631/oauth-2-0-benefits-and-use- cases-why [OAuth-2.0:-Benefits-and-use-cases-why?]",p | |
| "Things to note: | |
| when dealing with authentication, you should always host over HTTPS to ensure transport encryption | |
| Dropwizard claims their OAuth2 implementation isn't yet finalized, and may change in the future.",o | |
| "As a fall back, they do support Basic auth as well, which when used over HTTPS would be still reasonably secure.",p | |
| " | |
| Implementing this does not involve using any third party ""social"" authentication services such as Google or Facebook.",o | |
| Thanks for the shout out for the Dropwizard OpenID project.,o | |
| Glad it was able to get you started.,p | |
| "If you want a pure web form type approach, take a look at another of my projects URL_https://github.com/gary-rowe/MultiBitMerchant [MultiBit-Merchant] which provides multiple authentication methods (web form, HMAC, cookie).",o | |
| You'll need to dig around to really see it working since this project is not designed as a demo as such and is very much a work in progress.,p | |
| "After loading the project, look for URL_https://github.com/gary- rowe/MultiBitMerchant/blob/develop/mbm-client/src/main/java/org/multibit/mbm/c lient/interfaces/rest/auth/webform/WebFormClientAuthenticator.java [CODETERM1] which will get you in the right area.",o | |
| The general principles involved with Dropwizard authentication URL_http ://gary-rowe.com/agilestack/2012/10/23/multibit-merchant-implementing-hmac- authentication-in-dropwizard [are-discussed-in-this-blog-article] .,o | |
| Although it targets HMAC you can easily adapt it for web form or cookie using the source code referenced earlier.,o | |
| It's all MIT license so just use it as you need.,o | |
| Thanks.,o | |
| I am looking through the code and implementing my simple service in parallel.,p | |
| I had one more question - URL_http://stackoverflow.com/questions/20662871/how-to-do-basic-authentication - of-a-resource-in-dropwizard.,o | |
| Open Source Iris Scanning Library in Java.,p | |
| I am looking for suggestions about open source Iris Scanning libraries in Java.,p | |
| Has anyone used before which can built an unique profile for each scan & be able to authenticate too.,o | |
| Thank you.,p | |
| "I haven't used Java libraries that ""just do"" that entire work you describe, but it's not that difficult to use | |
| ( URL_http://sourceforge.net/projects/javavis/ [ URL_http://sourceforge.net/projects/javavis/ ] ) as in the sample code described in the following paper: URL_http://imai-software.com/openlab/data/IMAI- JOUNALVI.pdf#page=43 [ URL_http://imai-software.com/openlab/data/IMAI - JOUNALVI.pdf#page=43] (see from page 43) - that paper is quite good and for it's length :).",n | |
| "Of course, there are a few ""working"" solutions, e.g.",p | |
| ": | |
| URL_http://mac.softpedia.com/get/Math-Scientific/JIRRM.shtml [ URL_http://mac.softpedia.com/get/Math-Scientific/JIRRM.shtml ] (Java based) | |
| URL_http://projectiris.co.uk/ [ URL_http://projectiris.co.uk/ ] (QT based -but there are more QT <-> Java bridges) but personally I haven't used in production (just for testing) these 2 libraries since the documentation is not very good/detailed, and since this kind of problem is quite ""cutting edge"" so the documentation and an explanation paper is much more important than any source code.",p | |
| "If none of the above approaches work for you, I would suggest to use a MATLAB based iris recognition examples (because there are many MATLAB based implementations, papers, theses) and than convert them to Java or use the directly from Java (since MATLAB has support for this).",o | |
| Link to the paper is broken.,n | |
| I would look into URL_http://opencv.willowgarage.com/wiki/ [OpenCV-which- is-a-C++-library-for-computer-vision] .,o | |
| "Java wrappers are available: | |
| URL_http://ubaa.net/shared/processing/opencv/ [OpenCV-Java-and-Processing-library] | |
| URL_http://code.google.com/p/javacv/ [JavaCV] I believe you will want to look into Hough transforms for circles.",o | |
| URL_http://www.seas.upenn.edu/~bensapp/opencvdocs/ref/opencvref_cv.htm [This- page] mentions them .,o | |
| "IEEE material available , but it needs subscriptions.",o | |
| URL_http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4579428 [ URL_http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4579428 ] .,o | |
| I tried the project iris tool.,o | |
| It has the foundation blocks for IRIS Matching SYstem.It has the following features:* Basic QT UI - Needs qt-make and qt-sdk on top of gc++ and make to build* Iris Detection from Image file.,o | |
| - The Image should be 320x280 windows bmp greyscale 8 bit indexed image.,o | |
| - You can take an iris snap from you camera phone.,o | |
| It took a 12M regular jpeg image and converted it to required format using gimp.,o | |
| " | |
| Iris Image database: Text file db to store Iris Images.",o | |
| - Means you could extend the tool to create a Iris Search database - I could take another iris image and try to match with existing image Image acquisition is not available.,o | |
| Web Application - Authentication / Login Framework.,o | |
| "This is a very simple, probably a most asked question and frequently developed as part of any web application.",p | |
| "Say I'm planning to build a web application and some of the functional requirements include (apart from the usual hard hitting security reqs),- Need to have users sign up for a new account profile- Authenticate user using the native app authentication / Facebook or Google or Yahoo or OpenId login- Allow lost password retrieval- Session handling needs Is there an out of the box frameworks (Drupal, Liferay, Tapestry with Tynamo, Wicket ??",o | |
| ) that I can use to wrap my application which can be a bunch of JSP's or HTML's with JS?,o | |
| I know I'm asking a very simple and maybe a naive question.,n | |
| But this is a topic every web developer guru will go thru.,o | |
| "Any help, advise and pointers much appreciated.",p | |
| I'd recommend taking a look at Apache Shiro: URL_http://shiro.apache.org/ [ URL_http://shiro.apache.org/ ] It handles the security portion of your application and gives you a great deal of flexibility in how to secure things.,p | |
| "For example, you can add an annotation to secure individual methods (for example: you can't run this method unless you are an admin), individual pages (for example: you can't load this page unless you are an admin), and URL patterns (you must be admin to access anything containing /admin/* in the url).",p | |
| "Give how complex it can be do to security right, Shiro is very simple to use.",n | |
| "It may take just a bit to get your head around some of the concepts initially, but Shiro does a very good job of hiding as much of the complexity as possible.",p | |
| Also the user list is very responsive and extremely helpful.,p | |
| "If you use Tapestry, you might look at URL_http://tynamo.org/tapestry- security+guide [ URL_http://tynamo.org/tapestry-security+guide ] It makes it very easy to get Shiro up and running in a Tapestry application and gives you some easy to use tags to use in your templates.",p | |
| "Shiro isn't going to give you OpenID, OAuth or Facebook integration out of the box, but chances are high you will need to customize that part to your application.",o | |
| I believe there is some work being done to help integrate functions that will help enable these types of authentication into the framework.,o | |
| Some of the frameworks that build on Shiro may offer more of what you are looking for.,o | |
| "For example, URL_http://tynamo.org/tynamo-federatedaccounts+guide [ URL_http://tynamo.org/tynamo-federatedaccounts+guide ] will give you more support for federated logins in a tapestry application.",o | |
| "It is still in the early stages, but might be working looking at if you are using Tapestry.",p | |
| "Even if it doesn't do exactly what you need, it might provide some good examples to look at.",p | |
| You also might be interested in: URL_http://static.springsource.org/spring- security/site/ [ URL_http://static.springsource.org/spring-security/site/ ] As a side note: In addition to security there are probably a bunch of other technologies that you will need in a typical web project.,o | |
| "You may need security, persistence, basic user management, etc.",o | |
| "If you create many web applications, it might be worth creating a maven archetype that lets you quickly get a new basic application up and running so you can start coding with all the initial structure already in place.",p | |
| "AppFuse tries to do this, but it aims more at allowing you many different choices when it comes to web frameworks.",o | |
| "If you know what technology you are going to use, having a startup app that is customized for your needs can be a huge timesaver.",o | |
| I'd look at Apache Shiro or Spring Security.,o | |
| Java library to visualize database table relationships.,o | |
| "Does anyone know of a Java library that would assist in creating a GUI component to visualize the relationships between tables in an SQL database, similar to the Relationships pane in Access, or the Diagrams function in SQL Server Enterprise Manager.",o | |
| "The closest I have been able to discover is the Prefuse library, however I would need to extract the database structure and build the graph manually - is there a simpler way to do this?",o | |
| Cheers.,o | |
| I would probably use URL_http://platform.netbeans.org/graph/ [Visual-Library] .,o | |
| "I like Prefuse as well, but Visual Library's api is more Swing like if you are a Swing developer.",p | |
| Another option is URL_http://www.graphviz.org [GraphViz] which some people like.,o | |
| You would still have to extract the database structure yourself though this is fairly straight forward using URL_http://www.roseindia.net/jdbc/Jdbc-meta-data-get-tables.shtml [jdbc] .,o | |
| "Thanks Jay, this looks promising, I'll check it out.",p | |
| yFiles is a commercial graph and visualization library for Java / .NET / Ajax / Flex / Android that has been used for the exact same use in the DBVisualizer (JDBC) SQL client (free & commercial version).,p | |
| GraphXML files exported from yFiles (and yFiles based windows in DBVisualizer) can be edited / (re)formatted in the (free) yEd Graph editor.,p | |
| "Extracting the database structure through the JDBC metadata programmatically might look straightforward, but from experience I can say that there's a fair bit of difference between JDBC drivers/database platforms.",p | |
| "Also, depending on database platform, details needed and authorization levels used the results yielded might differ.",o | |
| (N.B.,o | |
| "I have no affiliation to either product other than being a user of the free editions of yEd and DBVisualizer, and include them in this answer because using the combination of these programs can give a good preview on the library features needed for such a project, and can be used as comparison check for its results).",p | |
| Looking for an embeddable SQL beautifier or reformatter.,o | |
| I am looking for a Java open source beautifier or reformatter for SQL that I can use to clean up DDL statements that I am generating with URL_http://www.openarchitectureware.org [openArchitectureWare] .,p | |
| "Nothing in the answer to "" URL_http://stackoverflow.com/questions/206441 /online-code-beautifier-and-formatter [Online-Code-Beautifier-And-Formatter] "" is of use to me and I have not been able to get URL_http://www.ohloh.net/projects/simplesqlformatter [Simple-SQL-Formatter] to work for me.",o | |
| " | |
| 2:** org.hibernate.jdbc.util.BasicFormatterImpl got moved in release 4.0.",o | |
| It is now located at: org.hibernate.engine.jdbc.internal.BasicFormatterImpl.,o | |
| " | |
| Technology marches on.",o | |
| "As noted by Alex, org.hibernate.pretty.Formatter no longer exists as of version 3.3.2.GA.",o | |
| The replacement is org.hibernate.jdbc.util.BasicFormatterImpl: CODESNIPPET_JAVA1 .,o | |
| "At this writing, this answer has the most upvotes, and ought to have the current correct answer in it, so I have updated it accordingly.",p | |
| Props to Alex for bringing it up.,o | |
| "... | |
| ANSWER:** If you're using Hibernate, they've got one built-in: org.hibernate.pretty.Formatter CODESNIPPET_JAVA2 .",o | |
| "Or DDLFormatter, which will a) Insert newline after each comma; b) Indent three spaces after each inserted newline;.",o | |
| This would appear to be exactly what I am looking for.,o | |
| Hibernate is already a core component of my solution so its not introducing a new dependency.,o | |
| "FYI, BasicFormatterImpl does not handle comments '--' and DDLFormatter is even more primitive see URL_http://www.dil.univ-mrs.fr /~massat/docs/hibernate-3.1/api/o rg/hibernate/pretty/DDLFormatter.html#format().",o | |
| "With Hibernate v3.3.2.GA, _org.hibernate.pretty.Formatter_ doesn't exist anymore.You can use its replacement : _org.hibernate.jdbc.util.BasicFormatterImpl_ CODESNIPPET_JAVA1 .",o | |
| Part of the eclipse URL_http://www.eclipse.org/datatools/ [Data-Tools- Platform] is the URL_http://www.eclipse.org/datatools/project_sqldevtools/ [SQL-Development-Tools-Project] .,o | |
| "The page describing how to use the URL_http://www.eclipse.org/datatools/projec t_sqldevtools/sqltools_doc/SQL%20Query%20Parser%20User%20documentation.htm [SQL-Query-Parser] has an extremely brief use of URL_http://help.eclipse.org/h elp33/index.jsp?topic=/org.eclipse.datatools.doc.isv/html/reference/api/org/ec lipse/datatools/modelbase/sql/query/util/SQLQuerySourceFormat.html [SQLQuerySourceFormat] which provides these options: | |
| preserveSourceFormat | |
| the option to preserve the input source formating when SQL source text is generated | |
| statementTerminator | |
| the character separating multiple SQL statements | |
| hostVariablePrefix | |
| the character that preceedes a host language variable | |
| parameterMarker | |
| the character that identifies a host language parameter | |
| delimitedIdentifierQuote* | |
| the character that encloses delimited identifiers whose writing in case will be preserved | |
| omitSchema | |
| the current schema (omitted in SQL source, implicit to unqualified table references) | |
| qualifyIdentifiers | |
| the flag describing how identifiers in the SQL source will be qualified | |
| preserveComments | |
| the option to preserve comments in the parsed SQL source or/and the generated SQL source | |
| generateCommentsForStatementOnly | |
| the option to generate comments for the SQL source only in the context of the complete statement, or if set to false, for single SQL Query objects outside the context of a statement as well .",o | |
| This solution would definitely work for me but I prefer the simplicity of the Hibernate solution.,p | |
| A pity I could only give you a +1.,n | |
| Have you considered: URL_http://www.sqlinform.com [ URL_http://www.sqlinform.com ] They provide both an API version and a command line version (as well as an online version).,o | |
| No knowledge of costs though.,o | |
| You could just use a URL_http://antlr.org/grammar/list [SQL-grammar] and build the AST with URL_http://antlr.org [antlr] .,o | |
| Then you can output the tree in any format you like.,o | |
| Thanks.,o | |
| That will be my plan of last resort.,o | |
| Fortunately I am too busy with a new job to look at this now and hopefully I'll get an answer before I have to roll up my sleeves.,p | |
| Perhaps URL_http://jsqlparser.sourceforge.net/ [jsqlparser] will work for you.,o | |
| "Not as easy to find as you might think, as there are a fair few defunct projects out there.",n | |
| In fact i failed to find it so ended up doing my own thing (based on the h2 parser - you can contact me if all else fails).,o | |
| "As a consequence i do not know if it has a beautifier, but writing one on top should be straight forward enough.",p | |
| "Its based on a grammar and JavaCC, so probably a better option than reinventing this wheel with antlr in any event.",o | |
| You may find if you need to support various dialects of sql in complex statements that any approach based on a grammar will fail you.,n | |
| Would this work - URL_http://www.wangz.net/cgi- bin/pp/gsqlparser/sqlpp/sqlformat.tpl [SQL-Formatter] .,o | |
| I need to be able to do this off-line as after code generation step in my build process.,o | |
| So SQL Formatter is not an option for me.,o | |
| "So this is definitely what you are looking for: URL_http://www.sqlparser.com/features/sql-formatter.php [A-SQL-formatter- library] that support Oracle, SQL Server, DB2, MySQL, Teradata and PostgreSQL.",o | |
| Is there any good dynamic SQL builder library in Java?,o | |
| Anyone knows some good SQL builder library for Java like URL_http://code.google.com/p/squiggle-sql/ [Squiggle] (not maintained anymore it seems).,p | |
| "Preferably, a project in active development.",o | |
| "Preferably with syntax like URL_http://framework.zend.com/manual/en/zend.db.select.html [Zend_Db_Select] , something that will allow to make a query like CODESNIPPET_JAVA1 .",o | |
| "May I ask what is the advantage of the syntax above against ""SELECT f1..fn FROM products ORDER BY product_id"" ?",o | |
| "@ItayMoav-Malimovka, Well, at least the syntax of SQL query in my case (if we take JOOQ as an example) is checked at the time you write code.",p | |
| You have full syntax autocomplete which speeds up your query-writing and makes it more error-prone.,n | |
| I agree this is something IDEs should improve upon.,o | |
| "@ItayMoav-Malimovka, well... in the case of JOOQ, if I change something in my DB structure, my code will just stop compiling until I fix it according to new DB structure.",p | |
| "If you have queries as a text, they will leave broken.",n | |
| As an example: I am currently working on an application that needs to create statements to work on a massive legacy database.,p | |
| Many statements share custom constraints which we build by a SQL DSL.,o | |
| Thanks to that we can easily create statements that are not known at compile time.,o | |
| URL_http://www.querydsl.com/ [Querydsl] and URL_http://www.jooq.org [jOOQ] are two popular choices.,p | |
| Note: I work for the company behind Querydsl.,o | |
| Which one do you use?,o | |
| :).,o | |
| "JOOQ is maybe a better choice for hardcore SQL development, but Querydsl has a simpler API and supports also other backends (JPA, JDO, Lucene, Mongodb etc.",p | |
| ); I am also in the company behind Querydsl.,o | |
| We use Querydsl SQL in a few of our in house projects.,o | |
| I have no personal experience of jooq but I have heard that it is quite ok.,o | |
| I do hardcore SQL development.,o | |
| I've used both JOOQ and QueryDSL.,o | |
| Both are quite good but I prefer the latter.,p | |
| The code and project management is more mature.,o | |
| The problem with QueryDsl is that you can't use it as a pure query generator as it does not give you the generated query itself.,o | |
| It will generate the query and execute it for you too.,o | |
| You can't get one without another.,o | |
| "@abhinav-sarkar Querydsl supports that, just not as directly as JOOQ.",o | |
| @TimoWestkmper can you point me to the methods to do that?,o | |
| I went through the javadocs and the code but couldn't find anything.,o | |
| "You can for example describe the query as a subquery and then serialize it via the SQLSerializer URL_http://www.querydsl.com/static/querydsl/2.9.0/apidocs/com/my sema/query/sql/SQLSerializer.html#serialize%28com.mysema.query.QueryMetadata,% 20boolean%29 If you want a more convenient way to get the SQL String and bindings for a Querydsl SQL query, just create a ticket for it and provide a suggestion how it should/could look like.",o | |
| "Querydsl and jOOQ seem to be the most popular and mature choices however there's one thing to be aware of: Both rely on the concept of code generation, where meta classes are generated for database tables and fields.",p | |
| "This facilitates a nice, clean DSL but it faces a problem when trying to create queries for databases that are only known at runtime, like in the OP's example above.",p | |
| While jOOQ supports a String based approached there are some quirks.,o | |
| The documentation of Querydsl doesn't mention whether it's possible to not use code generation.,o | |
| Please correct me if I'm wrong.,n | |
| "URL_https://github.com/fuzzylollipop/sqlck [SQL-Construction-Kit] is a very flexilble, no dependency framework.",p | |
| Development recently moved from code.google.com to github.,o | |
| It is also available from Maven Central Repository via Sonatype.,o | |
| "It's a pity they support only mssql, oracle and sql99.",n | |
| "No mysql, firebird etc.",o | |
| Also no documentation visible...,o | |
| SQL99 is a generic implementation that will should work with any database.,o | |
| "If you add support for specific databases, and sent a pull request, I can guarantee it will get into the mainline code base.",o | |
| Thanks.,o | |
| "Can you make some examples, please?",o | |
| Don't want to dig into the code just to find out how it works at all.,p | |
| "about SQL99: I could tell you one thousand reasons why that | |
| be true.",o | |
| "And two thousand reasons, why it | |
| Take a simple select 1, which also comes in at least these flavours: select 1 from dual, select 1 from sysibm.dual, select 1 from sysibm.sysdummy1, select 1 from information_schema.system_users... Oh don't get me started :-).",p | |
| I can recommend URL_http://www.jooq.org [jOOQ] .,p | |
| "It provides a lot of great features, also a intuitive DSL for SQL and a extremly customable reverse- engineering approach.",p | |
| " | |
| jOOQ effectively combines complex SQL, typesafety, source code generation, active records, stored procedures, advanced data types, and Java in a fluent, intuitive DSL.",n | |
| Do you use it?,o | |
| How do you find it?,o | |
| I use it to generate custom source code from DDL.,o | |
| It's working great!.,p | |
| "Hibernate Criteria API (not plain SQL though, but very powerful and in active development): CODESNIPPET_JAVA1 .",p | |
| "The problem is that it doesn't map to SQL as I understand, right?",o | |
| this doesn't generate SQL and is a nightmare to debug when it doesn't follow the rule of least astonishment ( doesn't work as expected ).,o | |
| It does generate SQL (at the end) and it surprises no one.,o | |
| Benefit -- it is portable across databases.,p | |
| +1 Upvoted again to level up.,p | |
| I don't know why this was downvoted.,n | |
| "After all, it's become the standard way of doing this with JPA, even if it's a bit verbose...",n | |
| "What is the level of query complexity that you achieved to reach with the JPA Criteria API, without making the query utterly unreadable?",o | |
| "Do you have an example of a nested select in an IN / EXISTS clause, or of a self-join using aliases for the Sale entity, etc?",o | |
| I'm curious.,o | |
| "Comments do not give much space to provide the examples, but you're welcome to review them at URL_http://docs.jboss.org/hibernate/core/3.5/reference/en/html/querycriteria.html .",p | |
| URL_http://db.apache.org/ddlutils/ [ddlutils] is my best choice: URL_http://db .apache.org/ddlutils/api/org/apache/ddlutils/platform/SqlBuilder.html [http:// db.apache.org/ddlutils/api/org/apache/ddlutils/platform/SqlBuilder.html] here is create example(groovy): CODESNIPPET_JAVA1 .,p | |
| SQL parser library for Java.,o | |
| Is there a good open-source Java library for parsing SQL statements?,o | |
| "If possible, it should be customizable or flexible enough to also be able to parse (or at least ignore) vendor-specific syntax (such as Oracle tablespace definitions or MySQL's LIMIT clause).",p | |
| "If not, strict adherence to the SQL standard is also fine.",p | |
| " | |
| I need this for two things: | |
| providing an SQL interface to a non-SQL database (mapping to internal API calls) | |
| rewriting SQL before it goes to the actual database (e.g.",o | |
| Oracle) .,o | |
| URL_http://jparsec.codehaus.org .,o | |
| how is this question not constructive?,o | |
| "what's wrong with you, Stackoverflow?",o | |
| URL_http://www.antlr3.org/grammar/list.html [ANTLR] has an ANSI SQL grammar available.,o | |
| You can use that to create your own parser.,o | |
| Why use ANTLR when you can implement your own parser generator?,o | |
| Why generate your own parser generator when you can use ANTLR?,o | |
| Any links to how one can use Antlr SQL Grammar to parse these queries?,o | |
| I looked at the grammar of some PL/SQL Parsers as well as Lexers and Parsers but was unable to fathom how to use one.,p | |
| Would appreciate any links.,p | |
| "You feed the grammar to ANTLR, which spits out the lexer/parser classes that you'll then compile and run.",o | |
| The best source I can think of is the ANTLR reference: URL_http://www.amazon.com/Definitive-Antlr-Reference-Domain-Specific - Programmers/dp/0978739256/ref=sr_1_1?ie=UTF8&qid=1327847925&sr=8-1.,p | |
| The link [ URL_http://www.antlr.org/grammar/list](http://www.antlr.org/grammar/list ) is broken.,n | |
| Does anyone know where the sql grammar is located?,o | |
| We're up to ANTLR 4 now.,o | |
| Perhaps the old grammars don't run on the new version.,o | |
| URL_http://www.antlr3.org/grammar/list.html .,o | |
| URL_http://jsqlparser.sourceforge.net/ [JSqlParser] .,o | |
| " | |
| If you need a parser there should be a parser in the code base of URL_http://db.apache.org/derby/ [Apache-Derby] .",o | |
| " | |
| with vendor-specific SQL** You may want to look at the URL_http://java.sun.com/javase/6/docs/api/java/sql /Connection.html#nativeSQL%28java.lang.String%29 [.native()] method on the jdbc Connection object which you can pass it vendor neutral queries that will get postprocessed into vendor specific queries.",o | |
| That native() method looks interesting.,p | |
| Are there any examples as to how it can be used?,o | |
| What kind of conversions are possible there?,o | |
| "URL_http://www.sqlparser.com/sql-parser-java.php [General-SQL-Parser-for-Java] is not open source, but is exactly what you are looking after.",n | |
| The best sql parser for Java +1.,p | |
| Try URL_http://zql.sourceforge.net/ [Zql] .,o | |
| "zql is good for basic queries but when you try to parse a query that contains join statement, it blows up.",n | |
| so i don't suggest it.,o | |
| Hibernate uses ANTLR for sql and hql parsing.,o | |
| JSqlParser is also a good option.although it has some bugs(or some features not implemented) while parsing oracle pl/sql.see its forum for detail.,p | |
| "so if you're parsing oracle pl/sql, ANTLR is recommended.",p | |
| "btw, anltr is under BSD.",o | |
| What you want to do with the parsed SQL?,o | |
| "I can recommend a few Java implementation of Lex/Yacc ( URL_http://byaccj.sourceforge.net/ [BYACC/J] , URL_http://www2.cs.tum.edu/projects/cup/ [Java-Cup] ) that you can use an existing SQL grammar with.",p | |
| "If you want to actually do something with the resulting parsed grammar, I might suggest looking at URL_http://db.apache.org/derby/ [Derby] , an open source SQL database written in Java.",p | |
| Is the SQL parser used in Derby available as an independent JAR ?,o | |
| I don't know.,o | |
| I've never looked at the source for Derby.,o | |
| "I now know the answer to this question: No, the SQL parser for Derby isn't a separate project.",o | |
| You will need pull it apart to use it for something other than Derby.,o | |
| How to transfer files from one computer to another over the network using Java?,o | |
| "I need a simple application, preferably a cross-platform one, that enables sending of files between two computers.",p | |
| "It just need to accept and send the files, and show a progress bar.",o | |
| What applications could I use or how could I write one?,o | |
| Are you pushing or pulling the file?,o | |
| Uploading or downloading?,o | |
| Woof is a cool Python script that might work for you: URL_http://www.home.unix-ag.org/simon/woof.html [ URL_http://www.home.unix - ag.org/simon/woof.html] .,p | |
| " | |
| and Receiving Files** The sending and receiving of a file basically breaks down to two simple pieces of code.",p | |
| Recieving code: CODESNIPPET_JAVA1 .,o | |
| Sending code: CODESNIPPET_JAVA2 .,o | |
| The sending piece of code will be ran on the computer that is sending the code when they want to send a file.,o | |
| "The receiving code needs to be put inside a loop, so that everytime someone wants to connect to the server, the server can handle the request and then go back to waiting on serverSoc.accept().",o | |
| "To allow sending files between both computers, each computer will need to run the server (receiving code) to listen for incoming files, and they will both need to run the sending code when they want to send a file.",o | |
| " | |
| Bar** The CODETERM1 in Swing is easy enough to use.",p | |
| "However, getting it to work properly and show current progress of the file transfer is slightly more difficult.",o | |
| To get a progress bar to show up on a form only involves dropping it onto a CODETERM2 and perhaps setting CODETERM3 so hat it shows that your program is working.,o | |
| To implement a progress bar correctly you will need to create your own implementation of a URL_http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html [CODETERM4] .,p | |
| The Java tutorials have a good example of this in their URL_http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html [lesson-in-concurrency] .,p | |
| This is a fairly difficult issue on its's own though.,n | |
| I would recommend asking this in it's own question if you need more help with it.,p | |
| @jjinguy what IP address should we put for CONNECTION_ADDRESS if the computers are not in a LAN?,o | |
| "For example, my external IP address is 1.2.3.4 but if you put 1.2.3.4 as the CONNECTION_ADDRESS, how is the router going to know which computer (within my home network) to forward the packet to?",o | |
| @Pacerier Your router should handle the address translation for you.,o | |
| "@jjinguy, yes but how is the sender supposed to know | |
| port to send the packet to such that it will be correctly routed?",o | |
| more on URL_http://superuser.com/questions/483033/how-does-peer-to-peer-work-over-the - internet.,o | |
| @Pacerier I believe it should be the same port you specify on your socket.,o | |
| "Unfortunately I'm not a networking expert, so I can't really provide more info.",n | |
| "@jjinguy, Let's say Router-A sends a packet to Router-B through port 30000 (preconfigured), Router-B receives the packet, but how does it know that this packet is to be forwarded to Computer-A, and not Computer-B?",o | |
| Sun's Java 6 includes a light-weight URL_http://java.sun.com/javase/6/docs/jre /api/net/httpserver/spec/com/sun/net/httpserver/package-summary.html [HTTP- server-API] and implementation.,p | |
| "You could fairly easily use this to serve your file, using URLConnection to obtain it.",o | |
| I would strongly consider using FTP.,o | |
| "Apache has a FTP URL_http://commons.apach e.org/net/apidocs/org/apache/commons/net/ftp/FTPClient.html [client] and a URL_http://mina.apache.org/ftpserver/ [server] Edit: spdenne's suggestion of HTTP is also good, especially if everyone has Java 6.",p | |
| "If not, you can use something like URL_http://tjws.sourceforge.net/#download [Tiny-Java-Web-Server] .",o | |
| yes i could.. but I wanted something as simple as possible so that beginners need not install anything... apart from installing Java which I think most people already have.,p | |
| You're definitely going to need code over and above the JRE.,o | |
| "The only question is whether you're writing that code yourself, or using existing libraries.",o | |
| "If you write it yourself, it will probably be non-standard and you will have to maintain it yourself.",o | |
| You can write one by using Socket programming in Java.,o | |
| You would need to write a Server and a Client program.,o | |
| "The server would use a ServerSocket to listen for connections, and the Client would use a Socket to connect to that server on the specified port.",o | |
| Here's a tutorial: URL_http://www.javaworld.com/jw-12-1996/jw-12-sockets.html [ URL_http://www.javaworld.com/jw-12-1996/jw-12-sockets.html ] .,o | |
| Why reinvent the wheel?,o | |
| Why not?,o | |
| "It's pretty quick to do, and it would be in Java.",o | |
| I just did it !.,o | |
| "Yes, you did : ).",o | |
| "Quick to do at first (and a good learning experience), but slow to maintain for production.",n | |
| "Check out URL_http://www.rgagnon.com/javadetails/java-0542.html [this] tutorial, it's a really basic example.",o | |
| "You would probably also want to send control headers prior to the actual file being sent, containing the size of the file, filename, etc.",o | |
| "Alternatively, base it on an existing protocol, like URL_http://sourceforge.net/projects/juggle/ [this] project.",o | |
| Thanks that's what I was looking for.,o | |
| To transfer over a network more efficiently.,p | |
| Take a look at URL_http://www.ibm.com/developerworks/java/library/j-zerocopy/index.html [this-article] that explains efficient data transfer through zero copy .,p | |
| "Two popular apps are ""scp"" and ""rsync"".",p | |
| "These are standard on Linux, are generally available on Unix and can be run on Windows under cygwin, although you may be able to find windows-native apps that can do it as well.",p | |
| (PuTTY can serve as an SCP client).,o | |
| "For any sort of pc-to-pc file transfer, you need to have a listener on the destination PC.",o | |
| "This can be a daemon app (or Windows system process), or it can be a Unix-style ""superserver"" that's configured to load and run the actual file-copy app when someone contacts the listening port.",o | |
| SCP and one of the rsync modes do require that there be some sort of remote login capability.,o | |
| Rsync can also publish resources that it will handle directory.,o | |
| "Since the concept of a Windows ""remote login"" isn't as well- established as it is under Linux, this may be preferable.",p | |
| Plus it limits remote access to defined sources/targets on the destination machine instead of allowing access to any (authorized) part of the filesystem.,p | |
| Can you install FTP servers on (one of) your machines ?,o | |
| "If you can, you will just have to use a FTP client (FileZilla for example, which have a progress bar).",o | |
| deleting folder from java.,o | |
| i want to delete all the contents that are present in a folder which includes files and folder too.,o | |
| I have written a java code to delete all the files but i am unable to delete the folders.,o | |
| below is the code i am using.. CODESNIPPET_JAVA1 .,o | |
| Please help me if i am missing something in the code??..,o | |
| possible duplicate of [Delete files recursively in Java]( URL_http://stackoverflow.com/questions/779519/delete-files-recursively-in - java).,o | |
| If you use URL_http://commons.apache.org/io [Apache-Commons-IO] it's a one- liner: CODESNIPPET_JAVA1 .,o | |
| "See URL_http://commons.apache.org/proper/commons-io///apidocs/org/apache/commo ns/io/FileUtils.html#deleteDirectory%28java.io.File%29 [FileUtils.deleteDirectory()] | |
| <s>Also with URL_http://code.google.com/p/guava-libraries [Guava] :</s> <s> CODETERM1 </s> This has been removed from Guava several releases ago.",o | |
| I have something like this : CODESNIPPET_JAVA1 .,o | |
| It could be problem with nested folders.,o | |
| "Your code deletes the folders in the order they were found, which is top-down, which does not work.",o | |
| It might work if you reverse the folder list first.,o | |
| But I would recommend you just use a library like Commons IO for this.,p | |
| "The javadoc for URL_http://download.oracle.com/javase/1.4.2/docs/api/java/io/F ile.html#delete%28%29 [File.delete()] | |
| public boolean delete() | |
| Deletes the file or directory denoted by this abstract pathname.",o | |
| "If this pathname | |
| a directory, then the directory must be empty in order to be deleted.",o | |
| So a folder has to be empty or deleting it will fail.,o | |
| "Your code currently fills the folder list with the top most folder first, followed by its sub folders.",o | |
| "Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.",o | |
| Changing these line CODESNIPPET_JAVA1 .,o | |
| to this CODESNIPPET_JAVA2 .,o | |
| should cause your code to delete the sub folders first.,o | |
| "The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.",n | |
| close - he's not using arrays but lists.,o | |
| So the replacement code needs to to adapted in order to fit in his solution.,o | |
| "@Andreas_D thats right, fixed it.^^.",o | |
| "You're storing all (sub-) files and folder recursively in a list, but with your current code you store the parent folder _before_ you store the children.",o | |
| And so you try to delete the folder before it is empty.,o | |
| Try this code: CODESNIPPET_JAVA1 .,o | |
| Try this: CODESNIPPET_JAVA1 .,o | |
| Just wanted to tell you I loved this solution.,p | |
| I thought it was easy to follow and simple.,p | |
| Thanks.,o | |
| @Kelly: You're welcome :).,p | |
| "You should delete the file in the folder first , then the folder.This way you will recursively call the method.",o | |
| I found this piece of code more understadable and working: CODESNIPPET_JAVA1 .,p | |
| I wrote a method for this sometime back.,o | |
| It deletes the specified directory and returns true if the directory deletion was successful.,p | |
| CODESNIPPET_JAVA1 .,o | |
| Using the URL_http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileU tils.html#deleteDirectory%28java.io.File%29 [FileUtils.deleteDirectory()] method can help to simplify the process of deleting directory and everything below it recursively.,o | |
| Check URL_http://stackoverflow.com/questions/779519/delete-files-recursively- in-java [this] question .,o | |
| It will delete a folder recurcively public static void folderdel(String path) CODESNIPPET_JAVA1 .,o | |
| Please add an explanation rather than just dumping code as your answer.,o | |
| Read large files in Java.,o | |
| "I need the advice from someone who knows very well java and the memory issues.I have a large file (something like 1.5GB) and I need to cut this file in many(100 small files for example) smaller files.I Know generally how to do it (using a BufferedReader), but I would like to know if you have any advice regarding the memory, or tips how to do it faster.My file containt text, it is not binary and I have about 20 character per line.",n | |
| Use byte APIs (e.g.,o | |
| "FileInputStream, ByteChannel), rather than character APIs (BufferedReader, etc.).",o | |
| "Otherwise, you are encoding and decoding needlessly.",o | |
| Splitting a text file using bytes would be a bad idea.,n | |
| "To save memory, do not unnecessarily store/duplicate the data in memory (i.e.",n | |
| do not assign them to variables outside the loop).,o | |
| "Just process the output | |
| as soon as the input comes in.",o | |
| It really doesn't matter whether you're using CODETERM1 or not.,o | |
| It will not cost significantly much more memory as some implicitly seem to suggest.,n | |
| It will at highest only hit a few % from performance.,o | |
| The same applies on using NIO.,o | |
| "It will only improve scalability, not memory use.",p | |
| It will only become interesting when you've hundreds of threads running on the same file.,p | |
| "Just loop through the file, write every line immediately to other file as you read in, count the lines and if it reaches 100, then switch to next file, etcetera.",o | |
| Kickoff example: CODESNIPPET_JAVA1 .,o | |
| "Yes, just pipe it from the FileInputStream to the FilOutputStream using only a suitably sized byte buffer array.",o | |
| "It does not work for me to count the lines.The thing is: I have a file and I need to split it in 200 (this can change, it will come from the database) files for example.How do I do that?",o | |
| Just counting the line does not work.,o | |
| How else ?,o | |
| Then count the amount of bytes written instead of the amount of lines.,o | |
| You can know the file size in bytes beforehand.,o | |
| Using lineStr.getBytes().length ?,o | |
| For example.,o | |
| Don't forget the specify the proper encoding!,o | |
| E.g.,o | |
| line.getBytes(encoding).,o | |
| Else it will mess up.,n | |
| The byte length depends on the character encoding used.,o | |
| "If you actually don't worry about txt lines, then I would rather use InputStream/OutputStream instead and count the transferred bytes.",o | |
| "By the way, it's unclear whether you mean to say that the files are stored in the DB or that the file split parameters are stored in the DB.",o | |
| "If the files are actually also stored in the DB, then this may be memory hogging as wel.",n | |
| The exact solution will depend on the DB used.,o | |
| "You can consider using memory-mapped files, via URL_http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html [FileChannel] s .",n | |
| Generally _a lot_ faster for large files.,p | |
| "There are performance trade-offs that _could_ make it slower, so YMMV.",o | |
| Related answer: URL_http://stackoverflow.com/questions/1605332/java-nio- filechannel-versus-fileoutputstream-performance-usefulness [ URL_http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus - fileoutputstream-performance-usefulness] .,o | |
| "If you are just reading straight through a file, this will most likely not get you much of anything.",o | |
| Still worth mentioning :).,p | |
| "First, if your file contains binary data, then using CODETERM1 would be a big mistake (because you would be converting the data to String, which is unnecessary and could easily corrupt the data); you should use a CODETERM2 instead.",n | |
| "If it's text data and you need to split it along linebreaks, then using CODETERM3 is OK (assuming the file contains lines of a sensible lenght).",p | |
| "Regarding memory, there shouldn't be any problem if you use a decently sized buffer (I'd use at least 1MB to make sure the HD is doing mostly sequential reading and writing).",n | |
| "If speed turns out to be a problem, you could have a look at the CODETERM4 packages - those are supposedly faster than CODETERM5 , .",p | |
| "Yes, I will use BufferedReader because I have a text file and I need to read it line by line.Now I have another problem: I cannot detect the size of the new file when writing it.The idea is that when the size of the new file | |
| xx MB then generate a new file.",o | |
| @CC: you could simply keep adding up the String length of the lines you are copying.,o | |
| But it depends on the character encoding how that translates to file size (and doesn't work well at all with variable-length encodings such as UTF-8).,p | |
| i would suggest adding a custom FilterOutputStream between the FileOutputStream (on the bottom) and OutputStreamWriter.,o | |
| Implement this filter to just keep track of the number of bytes going through it (apache commons io may have such a utility in it already).,o | |
| "Also, a common mis-perception is that ""nio"" is _faster_ than ""io"".",p | |
| "This may be the case in certain situations, but generally ""nio"" was written to be more _scalable_ than ""io"", where ""scalable"" is not necessarily the same as ""faster"".",p | |
| "@james: the filter won't yield the correct result when there's a BufferedWriter above it, though the difference may not be large enough to matter.",p | |
| "It will be behind, yes, but the alternative is trying to approximate bytes from chars which, as you pointed out, is ugly.",n | |
| I am assuming there is a fudge factor anyway.,n | |
| "If the count needs to be _very_ accurate, you could flush after each line, but that will of course slow performance.",n | |
| It is highly unlikely that using a 1MiB buffer will be any faster than somewhere between 8 and 16 KiB.,p | |
| "@Software Monkey: Hm, wouldn't accessing the HD in 16 KiB chunks send it thrashing pretty badly?",o | |
| Perhaps the OS or hardware cache will alleviate that via prefetching.,o | |
| "In the end, the optimal buffer size is probably best determined via benchmarks based on the actual use case.",p | |
| "@Michael: In my testing, bulk reading/writing ceased to gain any meaningful throughput increase for buffers larger than this.",p | |
| YMMV.,o | |
| "At the time, circa early 2000's the sweet spot seemed to be about 10 K; it might be a little larger now, but probably not by much.",n | |
| "It's likely to be about X | |
| disk allocation unit, where X is quite small.",o | |
| "This is a very good article: URL_http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/ [ URL_http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/ ] In summary, for great performance, you should: 1.",p | |
| Avoid accessing the disk.,o | |
| 2.,o | |
| Avoid accessing the underlying operating system.,o | |
| 3.,o | |
| Avoid method calls.,o | |
| 4.,o | |
| Avoid processing bytes and characters individually.,o | |
| "For example, to reduce the access to disk, you can use a large buffer.",o | |
| The article describes various approaches.,o | |
| You can use java.nio which is faster than classical Input/Output stream: URL_http://java.sun.com/javase/6/docs/technotes/guides/io/index.html [ URL_http://java.sun.com/javase/6/docs/technotes/guides/io/index.html ] .,p | |
| See my comment on Michael Borgwardt's post.,o | |
| Don't use read without arguments.It's very slow.Better read it to buffer and move it to file quickly.,p | |
| Use bufferedInputStream because it supports binary reading.,o | |
| And it's all.,o | |
| Does it have to be done in Java?,o | |
| I.e.,o | |
| does it need to be platform independent?,o | |
| "If not, I'd suggest using the ' URL_http://unixhelp.ed.ac.uk/CGI/man-cgi?split [split] ' command in | |
| ",o | |
| "If you really wanted, you could execute this command via your java program.",o | |
| "While I haven't tested, I imagine it perform faster than whatever Java IO implementation you could come up with.",p | |
| "Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed.",o | |
| You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file.,o | |
| That program will be easily scalable to your situation.,p | |
| Yes.,o | |
| "I also think that using read() with arguments like read(Char[], int init, int end) is a better way to read a such a large file(Eg : read(buffer,0,buffer.length)) And I also experienced the problem of missing values of using the BufferedReader instead of BufferedInputStreamReader for a binary data input stream.",o | |
| "So, using the BufferedInputStreamReader is a much better in this like case.",o | |
| How to create a Java String from the contents of a file?,o | |
| I've been using this idiom for some time now.,o | |
| "And it seems to be the most wide-spread, at least in the sites I've visited.",p | |
| Does anyone have a better/different way to read a file into a string in Java?,o | |
| CODESNIPPET_JAVA1 .,o | |
| Can anyone explain me in a very simple way what's with the NIO?,o | |
| Each time I read about itI get lost in the nth mention of channel :(.,n | |
| do remember that it's not guaranteed that the line separator in the file isn't necessary the same as the system's line separator.,o | |
| Could you please insert a proper try finally that closes the reader?,o | |
| Someone might actually use this example and introduce a bug into his code.,n | |
| "Code above has a bug of adding extra new line char at the last line.It should be something like followingif(line | |
| reader.readLine() ) != null){ stringBuilder.append( line );}while (line | |
| reader.readLine() ) != null) { stringBuilder.append( ls ); stringBuilder.append( line );}.",n | |
| "Java 7 introduces byte[] Files.readAllBytes(file); To those, who suggest the 'one-line' Scanner solution: Don't yo need to close it?",o | |
| " | |
| Read text from a file Here's a compact, robust idiom for Java 7, wrapped up in a utility method: CODESNIPPET_JAVA1 .",p | |
| " | |
| Memory utilization This method can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), the decoded characters (a character buffer), and a copy of the character data (in the new CODETERM1 instance) all reside in memory at once.",n | |
| It is safest to apply to files that you know to be small relative to the available memory.,n | |
| "For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block.",n | |
| "Here, ""large"" depends on the computer specs.",o | |
| "Nowadays, this threshold might be many gigabytes of RAM.",o | |
| " | |
| Character encoding One thing that is missing from the sample in the original post is the character encoding.",o | |
| "There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.",p | |
| The URL_http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardChar sets.html [CODETERM2] class define some constants for the encodings required of all Java runtimes: CODESNIPPET_JAVA2 .,o | |
| The platform default is available from URL_http://docs.oracle.com/javase/7/doc s/api/java/nio/charset/Charset.html#defaultCharset%28%29 [the-CODETERM3-class] itself: CODESNIPPET_JAVA3 .,o | |
| " | |
| Note: This answer largely replaces my Java 6 version.",o | |
| "The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected.",p | |
| "You can view the old version via the ""edited"" link on this answer.",o | |
| Quite interesting.,p | |
| What does the channel means.,o | |
| "I know that is to avoid block the ""thread?",o | |
| """ They can be bidirectional ( or that's what I understood ) But, in more simple word, what are they?",o | |
| Can you elaborate further?,o | |
| "In many ways, a ReadableByteChannel is like an InputStream, and WritableByteChannel is like an OutputStream.",o | |
| "Many concrete Channels implement both of these interfaces, so one object is bi-directional.",o | |
| "Some channels (SocketChannel) support non-blocking IO, but this isn't true of all channels.",o | |
| "Do you know the time- and memory-efficiencies of this idiom, or can at least estimate?",o | |
| It's a beautiful idiom!.,p | |
| "Technically speaking, it's O(n) in time and space.",o | |
| "Qualitatively, due the immutability requirement of Strings, it's pretty hard on memory; temporarily there are two copies of the char data in memory, plus the room for the encoded bytes.",n | |
| "Assuming some single-byte encoding, it will (temporarily) require 5 bytes of memory for each character in the file.",n | |
| "Since the question asks specifically for a String, that's what I show, but if you can work with the CharBuffer returned by ""decode"", the memory requirement is much less.",n | |
| "Time- wise, I don't think you'll find anything faster in the core Java libs.",p | |
| Possible typo?,o | |
| NIO has a Charset (not CharSet) class called java.nio.charset.Charset.,o | |
| Is this what CharSet should have been?,o | |
| "Note : after exercising a bit that code, I found out that you can't reliably delete the file right after reading it with this method, which may be a non issue in some case, but not mine.May it be in relation with this issue : URL_http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154 ?I finally went with the proposition of Jon Skeet which doesn't suffer from this bug.Anyways, I just wanted to give the info, for other people, just in case...",o | |
| @Sbastien Nussbaumer: I also bumped on this problem.,o | |
| "Amazing that the bug has been marked ""Will Not Fix"".",n | |
| "This essentially means that FileChannel#map is, in general, unusable.",o | |
| "@Sbastien Nussbaumer: The bug has been deleted from the Oracle / Sun Bug Database: ""This bug is not available.",n | |
| """ Google cached the site at URL_http://webcac he.googleusercontent.com/search?q=cache:bugs.sun.com/bugdatabase/view_bug.do%3 Fbug_id%3D4715154.",o | |
| "I tried reading an exe file using this method with default charset, append some data in it and again make it an exe, But it corrupted the exe, Any thoughts ?",o | |
| @smilepleeeaz What you describe makes no sense.,o | |
| EXE files are not text.,o | |
| And they have a well-defined structure.,o | |
| "First you are destroying the content of the file by decoding it as text, then you are destroying the structure by appending text to it.",o | |
| How could this fail to corrupt the EXE?,o | |
| "I don't really care about encoding, could I just use Charset.defaultCharset() instead of having an argument accepting it?",o | |
| "@yannbane If you are sure that the file will always be encoded with the platform's default character set, yes, you could do that.",o | |
| "If there's a mismatch, then you'll care about encoding.",o | |
| "Commons URL_http://commons.apache.org/proper/commons-io/apidocs/org/apache/com mons/io/FileUtils.html#readFileToString%28java.io.File%29 [CODETERM1] : | |
| CODESNIPPET_JAVA1 .",o | |
| " | |
| Reads the contents of a file into a String using the default encoding for the VM.",o | |
| The file is always closed.,o | |
| " | |
| Parameters: | |
| CODETERM2 \- the file to read, must not be null | |
| Returns: the file contents, never null | |
| Throws: - CODETERM3 \- in case of an I/O error | |
| Since: Commons IO 1.3.1 | |
| by Oscar Reyes** I've found the code used ( indirectly ) by that class: URL_http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html [IOUtils.java] under URL_http://www.apache.org/licenses/LICENSE-2.0 [Apache- Licence-2.0] CODESNIPPET_JAVA2 .",o | |
| Very similar to the one use by Ritche_W .,o | |
| I don't find that method in the URL you provide.,o | |
| It's in the class org.apache.commons.io.FileUtils.,o | |
| "I'm using FileUtils too, but I'm wondering what is better betwwen using FileUtils or the accepted nio answer?",o | |
| @Guillaume: The biggest question is whether you're comfortable having a dependency on a 3rd party library.,o | |
| "If you do have Commons IO or [Guava]( URL_http://stackoverflow.com/a/2224519/56285 ) in your project, then use that (just for code simplicity; otherwise there likely won't be a noticeable difference).",o | |
| From URL_http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html [this-page] the one-line solution: CODESNIPPET_JAVA1 .,o | |
| or CODESNIPPET_JAVA2 .,o | |
| If you want to set the charset .,o | |
| +1 I thought the selimeter should be \\\Z.,o | |
| "\\\A works because there is no ""other beginning of file"", so you are in fact read the last token...which is also the first.",p | |
| Never tried with \\\Z.,o | |
| "Also note you can read anything that is Readable , like Files, InputStreams, channels...I sometimes use this code to read from the display window of eclipse, when I'm not sure if I'm reading one file or another...yes, classpath confuses me.",n | |
| "As the poster, I can say I really don't know if and when the file is properly close...I never write this one in production code, I use it only for tests or debug.",o | |
| It has a limit of 1024 chars I think.,o | |
| Scanner implements Closeable (it invokes close on the source) - so while elegant it shouldn't really be a one-liner.,p | |
| "The default size of the buffer is 1024, but Scanner will increase the size as necessary (see Scanner#makeSpace()).",o | |
| This one fails for empty files with a java.util.NoSuchElementException.,o | |
| If you're looking for an alternative that doesn't involve a 3rd party library (e.g.,o | |
| "commons IO), you can use the URL_http://java.sun.com/javase/6/docs/api/java/util/Scanner.html [Scanner] class CODESNIPPET_JAVA1 .",o | |
| I think this is the best way.,p | |
| Check out URL_http://java.sun.com/docs/books/tutorial/essential/io/scanning.html .,o | |
| "The Scanner constructor that accepts a String doesn't treat the string as the name of a file to read, but as the text to be scanned.",o | |
| I make that mistake all the time.,n | |
| :-/.,o | |
| "@Alan, good catch.",p | |
| I edited Don's answer slightly to fix that (I hope).,o | |
| fileContents.append(scanner.nextLine()).append(lineSeparator);.,o | |
| "Change the initialization statement to Scanner scanner | |
| new Scanner((Readable) new BufferedReader(new FileReader(file)));.",o | |
| Otherwise you may only capture part of the file.,o | |
| URL_http://code.google.com/p/guava-libraries/ [Guava] has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned: CODESNIPPET_JAVA1 .,o | |
| " | |
| by Oscar Reyes** This is the (simplified) underlying code on the cited library: CODESNIPPET_JAVA2 .",o | |
| " | |
| (by Jonik): The above doesn't match the source code of recent Guava versions.",o | |
| "For the current source, see the classes URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/Files.java [Files] , URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/CharStreams.java [CharStreams] , URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/ByteSource.java [ByteSource] and URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/CharSource.java [CharSource] in URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io [com.google.common.io] package.",o | |
| This code has casting from long to int which could pop up some crazy behaviour with big files.,n | |
| Has extra spaces and where do you close the inputstream?,o | |
| "@M-T-A: The stream | |
| closed, note the use of Closer in [CharSource]( URL_http://code.google.com/p/guava - libraries/source/browse/guava/src/com/google/common/io/CharSource.java).",o | |
| "The code in the answer isn't the actual, current Guava source.",o | |
| "That code will normalize line breaks, which may or may not be what you really want to do.",o | |
| "Here's an alternative which doesn't do that, and which is (IMO) simpler to understand than the NIO code (although it still uses java.nio.charset.Charset): CODESNIPPET_JAVA1 .",p | |
| "Which one is ""that"" code?",o | |
| The code in the question.,o | |
| No real need to close the BufferedReader/InputStreamReader as they're only wrapping the stream +1 !!,o | |
| !.,o | |
| "Forgive me for reviving a comment this old, but did you mean to pass in a String object called ""file"", or should that be a File object instead?",o | |
| @BryanLarson: Either's fine.,o | |
| CODESNIPPET_JAVA1 .,o | |
| ....... CODESNIPPET_JAVA2 .,o | |
| Or even more simple: new String(Files.readAllBytes(FileSystems.getDefault().getPath( filename)));.,p | |
| or new String(Files.readAllBytes(Paths.get(filename))); :-).,o | |
| "Well played, and to save the next guy the Googling, [Paths is apparently 1.7+]( URL_http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html ) as is [FileSystems]( URL_http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSys tems.html).",p | |
| (Dang it!,o | |
| ).,o | |
| It;s a shame this answer doesn't have more votes.,n | |
| I was looking for the quickest and simplest way to get a text file into a String.,p | |
| "This is it and if I didn't scroll down and down and down, I would have missed it.",o | |
| The OP should consider accepting this answer to move it to the top.,o | |
| If it's a text file why not use apache commons-io?,o | |
| URL_http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html [ URL_http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html ] It has the following method CODESNIPPET_JAVA1 .,o | |
| If you want the lines as a list use CODESNIPPET_JAVA2 .,o | |
| Java attempts to be extremely general and flexible in all it does.,p | |
| "As a result, something which is relatively simple in a scripting language (your code would be replaced with "" CODETERM1 "" in python) is a lot more complicated.",p | |
| "There doesn't seem to be any shorter way of doing it, except using an external library (like URL_http://stackoverflow.com/questions/326390 /is-there-an-alternative-to-this-way-of-read-file-to-a-string-in-java#326413 [Willi-aus-Rohr] mentioned).",o | |
| "Your options: | |
| Use an external library.",o | |
| " | |
| Copy this code into all your projects.",o | |
| " | |
| Create your own mini-library which contains functions you use often.",o | |
| "Your best bet is probably the 2nd one, as it has the least dependencies.",p | |
| Yeap.,o | |
| "It makes the ""high"" level language take a different meaning.",o | |
| Java is high level compared with C but low compared with Python or Ruby.,n | |
| Agree that Java is long on high-level abstractions but short on convenience methods.,n | |
| "True, Java has an insane number of ways of dealing with Files and many of them seem complicated.",n | |
| "But this is fairly close to what we have in higher level languages: byte[] bytes | |
| Files.readAllBytes(someFile.toPath());.",o | |
| CODESNIPPET_JAVA1 .,o | |
| I think this has the inconvenience os using the platform default encoding.,n | |
| +1 anyway :).,o | |
| I seems to me that the finally block does not know variables defined in the try block.,o | |
| javac 1.6.0_21 throws the error cannot find symbol.,o | |
| To read a File as binary and convert at the end CODESNIPPET_JAVA1 .,o | |
| "There is a variation on the same theme that uses a for loop, instead of a while loop, to limit the scope of the line variable.",o | |
| "Whether it's ""better"" is a matter of personal taste.",o | |
| CODESNIPPET_JAVA1 .,o | |
| This will change the newlines to the default newline choise.,o | |
| "This may be desirable, or unintended.",p | |
| Rolled back the edit to this answer because the point was to narrow the scope of the line variable.,o | |
| "The edit declared it twice, which would be a compile error.",o | |
| "Be aware when using CODETERM1 the returned integer does not have to represent the actual file size, but rather the guessed amount of bytes the system should be able to read from the stream without blocking IO.",o | |
| A safe and simple way could look like this CODESNIPPET_JAVA1 .,p | |
| "It should be considered that this approach is | |
| suitable for multi-byte character encodings like UTF-8.",o | |
| This code may give unpredictable results.,o | |
| "According to the [documentation](htt p://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#available%28%29 ) of the available() method, there is no guarantee that the end of file is reached in the event that the method returns 0.",o | |
| In that case you might end up with an incomplete file.,o | |
| "What's worse, the number of bytes actually read can be smaller than the value returned by available(), in which case you get corrupted output.",o | |
| A flexible solution using URL_http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html [IOUtils] from Apache URL_http://commons.apache.org/io/ [commons-io] in combination with URL_http://docs.oracle.com/javase/6/docs/api/java/io/StringWriter.html [StringWriter] : CODESNIPPET_JAVA1 .,p | |
| "It works with any reader or input stream (not just with files), for example when reading from a URL.",p | |
| One Line Solution CODESNIPPET_JAVA1 .,o | |
| "The original question was creating a single string, not a list of lines.",o | |
| This one uses the method CODETERM1 .,o | |
| CODESNIPPET_JAVA1 .,o | |
| "I cannot comment other entries yet, so I'll just leave it here.",o | |
| One of best answers here ( URL_http://stackoverflow.com/a/326448/1521167 [ URL_http://stackoverflow.com/a/326448/1521167 ] ): CODESNIPPET_JAVA1 .,p | |
| still has one flaw.,o | |
| "It always puts new line char in the end of string, which may cause some weirds bugs.",n | |
| My suggestion is to change it to: CODESNIPPET_JAVA2 .,o | |
| You could try: CODESNIPPET_JAVA1 .,o | |
| "I'm not sure what problems might occur with the bytes and character sets etc, but it works for me.",p | |
| "I have always wondered, is it possible that input.available() return less bytes count than those in the file; I guess with big files.",o | |
| Probably.,o | |
| "Like I said, it works for me.",p | |
| Perhaps there is a more suitable java.io.File method (something like getLength()?,o | |
| ) which could provide a more reliable value.,o | |
| Given the doco for read(byte[]) this is very risky code.,o | |
| What if the file is on a network share or SAN?,o | |
| Then you might get an available count of less than the file size.,o | |
| You need to use a readFull() method and File.length().,o | |
| "Like I said, it works for me and my purposes.",p | |
| It is concise and I've yet to encounter a problem with it.,o | |
| "That said, there are probably a hundred better ways to do it (just, this method has less code).",o | |
| Actually this is very similar the way the library posted by Willi aus Rohr.,o | |
| Don't see why the downvote.,n | |
| Problems with this code: 1) Stream is left open when there's an exception.,o | |
| 2) Use of available() to guess at file size (and assume it's constant).,o | |
| 3) Assumption that a single call to read() will read everything.,o | |
| 4) Use of platform-default character encoding.,o | |
| "In short, please don't do this :).",o | |
| I agree with Jon on all points.,o | |
| "No offense intended, but this is like a checklist of what NOT to do.",o | |
| "Cry me a river, I'll do it this way all the time just to spite you all.",n | |
| "Joking aside, I've NEVER had a problem with it so I'm just going to wave my hands like I just don't care (because I don't).",o | |
| Java GUI frameworks.,o | |
| What to choose?,o | |
| "Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?",o | |
| "There is quite a lot of gui frameworks out there for java, but what is recognized as today's framework of choice?",o | |
| "The following is my understanding of the different frameworks, please correct me if im wrong.",n | |
| "This is a very loosely defined set of questions, but i still think its valuable for anyone thinking of creating rich gui applications.",o | |
| " | |
| URL_http://en.wikipedia.org/wiki/Java_AWT [AWT] | |
| Is the very foundation of swing, it performs well but is lacking in advanced components.",n | |
| "If you intend to create rich applications, AWT is probably not the way to go.",o | |
| However for smaller gui applications that doesn't require rich user interfaces.,o | |
| This might suit perfectly as it's a tried and proven framework.,p | |
| " | |
| URL_http://en.wikipedia.org/wiki/Java_Swing [Swing] | |
| Based on AWT as previously stated.",o | |
| In its infancy it was regarded as slow and buggy and caused IBM to create SWT for Eclipse.,n | |
| However with Java 5 (or 6?,o | |
| ) Swing became the framework of choice for building new applications.,o | |
| Swing has a lot of rich components but are still lacking in some areas.,n | |
| One example being that there isn't a full featured TreeTable component which can do sorting and filtering/searching.,o | |
| " | |
| URL_http://en.wikipedia.org/wiki/Standard_Widget_Toolkit [SWT] | |
| Created by IBM for Eclipse, they seemed to think that Swing was not suited for Eclipse at the time.",o | |
| "By itself is pretty low-level, and it uses the platform's native widgets through JNI.",n | |
| It is not related to Swing and AWT at all.,o | |
| Their API is however somewhat clunky and not intuitive.,p | |
| They do have some advanced component's like a TreeTable.,o | |
| (but i don't think they support sorting and filtering out of the box).,o | |
| SWT uses some native bindings (through JNI?,o | |
| ) and the rant on the internet is that this framework should not be used in today's projects.,n | |
| (why not?,o | |
| ") | |
| URL_http://en.wikipedia.org/wiki/SwingX [SwingX] | |
| Based on Swing and it's mission is to create rich components for swing.",o | |
| Still under development.,o | |
| (not very active though.,o | |
| ") Have a very nice set of components, like for example TreeTable.",p | |
| But the TreeTable does not support filtering and sorting as far as i know.,o | |
| It does however support searching with highlighting.,p | |
| " | |
| Note that SwingX is components (AFAIU) that are extensions or compositions of existing Swing components | |
| A framework which i know nothing about... What is it's strengths and weaknesses?",o | |
| What set's Jgoodies apart from the rest?,o | |
| " | |
| JGoodies OTOH is about PLAFs and layouts.",o | |
| " | |
| URL_http://en.wikipedia.org/wiki/JavaFX [JavaFX] | |
| The latest flagship of Java/Oracle.",o | |
| promising to be the facto standard in developing rich desktop or web applications.,p | |
| " | |
| URL_http://en.wikipedia.org/wiki/Apache_Pivot [Apache-Pivot] | |
| It renders UI using Java2D, thus minimizing the impact of (IMO, bloated) legacies of Swing and AWT.",n | |
| "(@Augustus Thoo) It's main focus seems to be on RIA (Rich internet applications), but it seems it can also be applied to desktop applications.",o | |
| "And as a personal comment, Looks very interesting!",p | |
| I Especially like that it's an apache project.,o | |
| "URL_https://cwiki.apache.org/PIVOT/frequently-asked-questions-faq.html [ URL_https://cwiki.apache.org/PIVOT/frequently-asked-questions-faq.html ] | |
| URL_http://en.wikipedia.org/wiki/Qt_Jambi [Qt-Jambi] | |
| A java wrapper to the native qt library which is written in c/c++.",o | |
| "Very powerful, widely used and accepted.",p | |
| Has a lot of GUI components and a easy to use API.,p | |
| "URL_http://qt-jambi.org/ [ URL_http://qt-jambi.org/ ] | |
| So, to try to summarize a bit of what im asking: Say i wanted to create a desktop application today in Java which involves a lot of advanced components, what should i choose?",o | |
| And why?,o | |
| Which one of these frameworks should be recognized as deprecated and which should be recognized as the frameworks of the distant future?,o | |
| What is todays de-facto-standard framework and which tools do you utilize to create java gui applications?,o | |
| " | |
| I might regret asking this, but ill try it anyways: C#/.Net is said to have a very good set of easy to use components which can be flexed in every direction possible.",p | |
| And after investigating different java frameworks to some extent i can't seem to say the same about Java.,o | |
| Why is this?,o | |
| "_Why doesn't java (which is the most widely used programming language in the world) have the same set of GUI components?_ Is it just that java has based their gui components at a much lower level, and it is possible to write all these advanced components that im looking for, but you have to do much if not all of the work yourself?",o | |
| Hi.,o | |
| I am using JFace and RCP for rich clients.,o | |
| Both are SWT based and provide UI features and helpers that would be tedius to implement in native SWT.,o | |
| +1 for _Why doesn't java (which is the most widely used programming language in the world)_.,o | |
| "AWT | |
| might however look somewhat ugly on some operating systems.",n | |
| """* I disagree.",o | |
| "It uses native components, so it will only look as beautiful or ugly as the other components generally seen in that OS.",n | |
| "Or to put that another way, it would look much like the equivalent Swing components when they are set to the native PLAF.",o | |
| AWT's major failing is it's lack of components & functionality.,n | |
| E.G.,o | |
| "no tree, no table, no HTML rendering support..",o | |
| "@Andrew, thanks.",o | |
| ill update the text.,o | |
| "@netbrain Thanks back at you for asking an interesting, well researched question.",p | |
| "If it was rubbish, I would not have been motivated to correct one minor misunderstanding.",n | |
| "I wasn't aware that SWT was ""based on a combination of AWT and Swing"".",o | |
| Is that really the case?,o | |
| I thought it was pure JNI to invoke the OS's windowing system...,o | |
| "@Rich Oh, it was said in one of the answers comments.",o | |
| I just assumed they knew what they were talking about.,o | |
| "I think you confuse ""UI Toolkit"" and ""GUI framework"".",n | |
| "AWT, Swing and SWT are UI toolkits but I would certainly not call them ""frameworks"".",o | |
| Frameworks are based upon a given UI toolkit and provide the glue to build your application.,o | |
| "First, you should choose the UI toolkit and then choose a framework that works on that toolkit.",p | |
| "FWIW, I would choose Swing with my own home-made Guts-GUI framework :-).",o | |
| "It's almost always Swing vs. SWT (for me at least), for small comparison you could check [What are the main things that an experienced Java SWT programmer should be aware of when moving to Swing?",o | |
| ]( URL_http://stackoverflow.com/questions/6659413/what-are-the-main-things - that-an-experienced-java-swt-programmer-should-be-aware/6661296)..,o | |
| " | |
| is no more part of preview SDK and it is available for Production use.",o | |
| please update this post.,o | |
| "I just use AWT and Swing and I can do almost everythig, so thumbs up for them :).",o | |
| "Can we downvote all the people who voted this closed as ""not constructive""?",o | |
| The question close nannies strike again!.,o | |
| Close as not constructive is subjective at best.,p | |
| Why should some person that may have a grudge or having a bad day be able to remove content valuable to a community?,o | |
| Maybe we can get some votes to reopen this question?,o | |
| Decision tree: 1.,o | |
| Frameworks like Qt and SWT need native DLLs.,o | |
| So you have to ask yourself: Are all necessary platforms supported?,o | |
| Can you package the native DLLs with your app?,o | |
| "URL_http://stackoverflow.com/questions/2037220/how-can-i-creating-executable- jar-with-swt-that-runs-on-all-platforms [See-here,-how-to-do-this-for-SWT] .",o | |
| "If you have a choice here, you should prefer Qt over SWT.",p | |
| Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster.,p | |
| It's more a performance patch for Java 1.4 than a UI framework.,o | |
| "Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).",o | |
| "If SWT is missing a feature that you need, the framework is somewhat hostile to extending it.",o | |
| "For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of CODETERM1 isn't CODETERM2 and you can't add new classes in that package because it's signed).",n | |
| 2.,o | |
| "If you need a native, pure Java solution, that leaves you with the rest.",o | |
| "Let's start with AWT, Swing, SwingX - the Swing way.",o | |
| AWT is outdated.,o | |
| Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years).,o | |
| You could argue that Swing was good to begin with but we all know that code rots.,p | |
| And that's especially true for UIs today.,o | |
| That leaves you with SwingX.,o | |
| "After a longer period of slow progress, URL_http://java.net/projects/swingx/sources/svn/history?",o | |
| [development-has- picked-up-again] .,o | |
| "The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel ""clumsy"" today.",n | |
| "For example, the table views do support filtering and sorting but you still have to configure this.",o | |
| You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.,o | |
| Another weak area is theming.,o | |
| "As of today, there are a lot of themes around.",o | |
| URL_http://geeknizer.com/best-java-swing-look-and-feel-themes-professional- casual-top-10/ [See-here-for-a-top-10] .,o | |
| "But some are slow, some are buggy, some are incomplete.",n | |
| I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.,n | |
| 3.,o | |
| "JGoodies is another layer on top of Swing, like SwingX.",o | |
| It tries to make Swing more pleasant to use.,p | |
| The web site looks great.,p | |
| Let's have a look at the tutorial ... hm ... still searching ... hang on.,n | |
| It seems that there is no documentation on the web site at all.,o | |
| URL_https://www.google.ch/webhp?sourceid=chrome-instant&ie=UTF-8#hl=en&output=search&sclient=psy-ab&q=jgoodies%20tutorial [Google-to-the-rescue] .,o | |
| "Nope, no useful tutorials at all.",o | |
| I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans.,n | |
| That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.,p | |
| 4.,o | |
| JavaFX.,o | |
| "Great, stylish.",p | |
| Support is there but I feel it's more of a shiny toy than a serious UI framework.,o | |
| This feeling roots in the lack of complex UI components like tree tables.,n | |
| There is a URL_http://docs.oracle.com/javafx/2/webview/jfxpub-webview.htm [webkit-based-component-to-display-HTML] .,o | |
| "When it was introduced, my first thought was ""five years too late.",o | |
| """ If your aim is a nice app for phones or web sites, good.",p | |
| "If your aim is professional desktop application, make sure it delivers what you need.",o | |
| 5.,o | |
| Pivot.,o | |
| First time I heard about it.,o | |
| It's basically a new UI framework based on Java2D.,o | |
| So I gave it a try yesterday.,o | |
| "No Swing, just tiny bit of AWT ( CODETERM3 ).",o | |
| My first impression was a nice one.,p | |
| There is an extensive documentation that helps you getting started.,o | |
| "Most of the URL_http://pivot.apache.org/tutorials /push-buttons.html [examples-come-with-live-demos] (Note: You must have Java enabled in your web browser; _this is a security risk_) in the web page, so you can see the code and the resulting application side by side.",n | |
| "In my experience, more effort goes into code than into documentation.",o | |
| "By looking at the Pivot docs, a lot of effort must have went into the code.",o | |
| Note that there is currently a bug which prevents some of the examples to work ( URL_https://issues.apache.org/jira/browse/PIVOT-858 [PIVOT-858] ) in your browser.,n | |
| My second impression of Pivot is that it's easy to use.,p | |
| "When I ran into a problem, I could usually solve it quickly by looking at an example.",o | |
| "I'm missing a reference of all the styles which each component supports, though.",o | |
| "As with JavaFX, it's missing some higher level components like a tree table component ( URL_https://issues.apache.org/jira/browse/PIVOT-306 [PIVOT-306] ).",o | |
| I didn't try lazy loading with the table view.,o | |
| "My impression is that if the underlying model uses lazy loading, then that's enough.",p | |
| Promising.,p | |
| "If you can, give it a try.",o | |
| "With respect to JavaFXs webview, it's based on webkit URL_http://docs.oracle.com/javafx/2/webview/jfxpub-webview.htm and from a few short tests that i have done it seems to work fine with js in general (including jquery and jqueryui).",o | |
| "@nvrs: Thanks, updated my answer.",o | |
| "Not sure if this just wasn't true at the time of writing, but the JavaFX site states that it supports Linux.",o | |
| "Great answer, btw.",p | |
| JavaFX is bundled with Java 7 since u06.,o | |
| Updated my answer.,o | |
| "For number 1, the sentence ""you can add new classes in that package because it's signed"" has ambiguity.",o | |
| Do you mean cannot?,o | |
| @David: Good catch.,p | |
| Fixed.,o | |
| "Tried Pivot demo ""Kitchen sink"", after opening some groups it keeps eating whole CPU.",o | |
| "If it's because of Pivot design, then I definitely don't want it in my projects.",o | |
| Seems like I've found the source of problem and it's fixed in later versions: URL_http://apache-pivot-users.399431.n3.nabble.com/Expanders-Cause-Increased-CPU - and-Memory-Use-td4022102.html.,n | |
| JavaFX 8 (for Java 8 and above) has a TreeTableView widget.,o | |
| "However, JavaFX 2.2 (for Java 7) lacks this, and also lacks standard error and info dialgos: see URL_http://stackoverflow.com/a/12760202/105137 .",o | |
| Also the ControlsFX widget library is available for Java 8 only: URL_http://fxexperience.com/controlsfx/ .,o | |
| "URL_http://www.eclipse.org/swt/ [SWT] by itself is pretty low-level, and it uses the platform's native widgets through JNI.",n | |
| It is not related to Swing and AWT at all.,o | |
| "The URL_http://eclipse.org [Eclipse-IDE] and all Eclipse-based Rich Client Applications, like the URL_https://www.vuze.com/ [Vuze-BitTorrent- client] , are built using SWT.",o | |
| "Also, if you are developing Eclipse plugins, you will typically use SWT.",o | |
| "I have been developing Eclipse-based applications and plugins for almost 5 years now, so I'm clearly biased.",o | |
| "However, I also have extensive experience in working with SWT and the URL_http://wiki.eclipse.org/index.php/JFace [JFace- UI-toolkit] , which is built on top of it.",o | |
| I have found JFace to be very rich and powerful; in some cases it might even be the main reason for choosing SWT.,p | |
| "It enables you to whip up a working UI quite quickly, as long as it is IDE- like (with tables, trees, native controls, etc).",p | |
| "Of course you can integrate your custom controls as well, but that takes some extra effort.",p | |
| "In your opinion, would an advanced component like a TreeTable with column sorting and filtering be a big issue with SWT+JFace?",o | |
| "@netbrain: I have done that numerous times, it's fairly straightforward with JFace.",p | |
| "This is what I meant by an ""IDE-like"" interface, maybe not the best choice of words.",p | |
| I would like to suggest another framework: Apache Pivot URL_http://pivot.apache.org/ [ URL_http://pivot.apache.org/ ] .,o | |
| I tried it briefly and was impressed by what it can offer as an RIA (Rich Internet Application) framework _ala_ Flash.,o | |
| "It renders UI using Java2D, thus minimizing the impact of (IMO, bloated) legacies of Swing and AWT.",n | |
| I had the impression that netbrain was asking about desktop apps.,o | |
| "For RIA frameworks, consider also GWT and Vaadin.",o | |
| "These frameworks allow you to write in Java, compile and get JavaScript that runs very well on all common web browsers.",p | |
| can't pivot be applied for desktop applications?,o | |
| "Maybe it is a matter of definition, but RIA frameworks are basically designed to run in browsers.",o | |
| "@netbrain : Yes, you can run Pivot as desktop app (JFrame) or applet (JApplet).",o | |
| Swing + SwingX + URL_http://www.miglayout.com/ [Miglayout] is my combination of choice.,o | |
| Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful.,p | |
| "Also, it provides you with the ability to ""debug"" your layouts, which is especially handy when creating complex layouts.",n | |
| Miglayout reminds of the days where table tags in html were the standard for laying out elements on a page ;) Thanks for your contribution.,p | |
| Another option is to use URL_http://qt-jambi.org/ [Qt-Jambi] .,o | |
| "It has nearly all the greatness of Qt (many components, good documentation, easy to use), without the hassle of C++.",p | |
| "I used it 3-4 years ago for a small project, even then it was almost mature.",o | |
| You might want to see the discussion about Swing vs. Qt URL_http://stackoverflow.com/questions/422956/java-swing-or-java-qt [here] .,o | |
| My personal opinion: Go for Swing together with the NetBeans platform.,o | |
| If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.,o | |
| I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.,p | |
| "The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate ""pure"" Swing components into such an application.",n | |
| The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.,p | |
| Note that SwingX is components (AFAIU) that are extensions or compositions of existing Swing components.,o | |
| JGoodies OTOH is about PLAFs and layouts.,o | |
| "But as you said, either will integrate seamlessly with Swing.",o | |
| +1 Base your development on Swing.,o | |
| "Swing is built on top of AWT and includes light-weight components that look and behave the same on all platforms, so you never should use AWT components directly.",p | |
| There is a large number of excellent Beans you could easily add to your development GUI like i.e.,p | |
| toedter.com JCalendar.,o | |
| "@Andrew in addition to PLAF and layout, JGoodies offers more: beans binding (for presentation model pattern), validation and a ""JSR-296 like"" framework (that one is commercial).",o | |
| "you forgot for Java Desktop Aplication based on JSR296 as built-in Swing Framework in NetBeans excluding AWT and JavaFX are all of your desribed frameworks are based on Swing, if you'll start with Swing then you'd be understand (clearly) for all these Swing's (Based Frameworks) ATW, SWT (Eclipse), Java Desktop Aplication(Netbeans), SwingX, JGoodies all there frameworks (I don't know something more about JGoodies) incl.",o | |
| "JavaFX haven't long time any progress, lots of Swing's Based Frameworks are stoped, if not then without newest version just my view - best of them is SwingX, but required deepest knowledge about Swing, URL_http://stackoverflow.com/questions/3954616/look-and-feel-in-java [Look- and-Feel] for Swing's Based Frameworks .",n | |
| SWT isn't based on swing?,o | |
| "part of them on AWT Components, part on Swing JCompoentns, but between AWT and Swing is difference with implemented, accesible and inherits methods, for example Swing JComponents directly (API) implements lots of inherit or nested methods directly from AWT :-).",o | |
| The JSR296 is dead.,o | |
| "It is no longer ""maintained"" and the support for it has been removed from NetBeans.",o | |
| (And it never was a really good framework to start with).,p | |
| "@a_horse_with_no_name that right with same progress in SWT, SwingX, new owner, new maniers.",o | |
| "SWT, developed by IBM, is not based on Swing, it is/was a competing technology.",o | |
| Swing uses AWT.,o | |
| JavaFX isn't based on Swing either.,o | |
| It is an entirely new framework.,o | |
| "Some are calling it the successor to Swing, but it's still too immature to call that battle.",o | |
| "I am making the exact same decision at the moment, and Swing is my candidate, simply for the fact that it is the most mature, yet realistic option available.",o | |
| "SwingX is extensions to Swing (which is why it requires Swing knowledge), in fact, some of SwingX's features have been rolled into Swing itself.",o | |
| I've been quite happy with Swing for the desktop applications I've been involved in.,p | |
| "However, I do share your view on Swing not offering advanced components.",o | |
| What I've done in these cases is to go for JIDE.,o | |
| "It's not free, but not that pricey either and it gives you a whole lot more tools under your belt.",n | |
| "Specifically, they do offer a filterable TreeTable.",o | |
| Good to know!,p | |
| So JIDE has created their own components based on Swing...,o | |
| "Yes, JIDE has made quite a few components covering grids, trees, tables, graphs and the like.",o | |
| "Like I said, it's not free but given the time it would take to make these things yourself your'e probably better off using something that is already made.",p | |
| "Furthermore, as far as I understand, JIDE is flexible with regards to letting open source projects use their components in exchange for a link to their website or a logo in the 'About' dialog.",p | |
| I would go with Swing.,o | |
| For layout I would use JGoodies form layout.,o | |
| "Its worth studying the white paper on the Form Layout here - URL_http://www.jgoodies.com/freeware/forms/ [ URL_http://www.jgoodies.com/freeware/forms/ ] Also if you are going to start developing a huge desktop application, you will definitely need a framework.",p | |
| Others have pointed out the netbeans framework.,o | |
| I didnt like it much so wrote a new one that we now use in my company.,o | |
| "I have put it onto sourceforge, but didnt find the time to document it much.",o | |
| Here's the link to browse the code: URL_http://swingobj.svn.sourceforge.net/viewvc/swingobj/ [ URL_http://swingobj.svn.sourceforge.net/viewvc/swingobj/ ] The showcase should show you how to do a simple logon actually.. Let me know if you have any questions on it I could help.,p | |
| Is this GUI threadsafe (Using Swing)?,o | |
| I have the following code in my constructor for my GUI CODESNIPPET_JAVA1 .,o | |
| "The problem was that when I the ""//do stuff"" runs, it takes a while, and it doesn't let me do anything else.",o | |
| "So I made ""//do stuff"" into a thread, and it runs, and I can do other stuff in the GUI at the same time.",o | |
| "I wasn't sure if this was threadsafe or not, and if not, how to fix the problem.",p | |
| The problem is that you were probably blocking the main Swing event thread (the thread that handles things like button clicks).,o | |
| You can read up about it (and one possible solution) on URL_http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html [Swing-Worker-Threads] .,o | |
| I discovered them recently and this is really it.,o | |
| You should check it out.,o | |
| IDE for Swing.,o | |
| Is there any IDE that simplifies creating Swing applications (ideally something along the lines of Visual Studio) .,o | |
| "@Thorbjrn Ravn Andersen news only all answers about Netbeans and Framework based on JSR296 are outdated because this Swing Framework was refused by Oracle, and later was depreciated in the Netbeans Platform.",n | |
| "@mKorbel SAF is deprecated, Swing is not.",n | |
| @Thorbjrn Ravn Andersen huuuh sorry???,o | |
| "when, where, ...",o | |
| "I talked about Swing :-), only about Swing Framework or Framework based on JSR296.",o | |
| "@mKorbel Netbeans editor works just fine with ""plain Swing"" applications.",p | |
| "@Will - If this question is closed, what happens to the bounty?",o | |
| @Rothschilde should be refunded.,o | |
| "Like others have mentioned, Netbeans' visual editor is pretty good, but its based pretty heavily on the URL_https://java.net/projects/appframework/ [Swing-Application-Framework] so you'd need to get an understanding of how it works to properly use it (although you don't need to dig in to just test things).",p | |
| "Other than that there's also: | |
| the URL_http://www.jetbrains.com/idea/ [IntelliJ-IDEA] visual editor ( URL_http://www.jetbrains.com/idea/features/gui_builder.html [flash-demo-of-the-features] ) | |
| and Eclipse's URL_http://www.eclipse.org/vep/WebContent/main.php [Visual-Editor] Personally I've used Netbeans' and IDEA's visual editors.",o | |
| Both are nice but I thought Netbeans had a leg up because it doesn't use any proprietary way of saving the GUI structure and instead does something similar to what Visual Studio does - auto-generating the code that you can then add to.,p | |
| IDEA stores the information in a separate file which means you have to use IDEA to edit the layout visually later.,o | |
| I have not used Eclipse's Visual Editor.,o | |
| My vote is for Netbeans' visual editor.,o | |
| I think it satisfies what most people are looking for in a visual editor and leaves it flexible enough to plug the holes manually through code without affecting the visual editor (so you can switch back and forth between code and design views without breaking either).,p | |
| That is not true.,o | |
| Netbeans' visual editor is not heavily based on Swing Application Framework at all unless you opt-in to use the framework in the beginning.,n | |
| Matisse did use to have an extra dependency on GroupLayout but now it's included in jre so there is no dependency on SAF.,o | |
| An example of that dependency is the storing of string literals used for display (like label text).,o | |
| "Those are stored in properties files that are automatically managed (loading, structure) by the SAF.",o | |
| "It's all built-in to the latest JREs so you don't need extra jars, but you do need to understand the architecture of the SAF in order to use it effectively.",o | |
| Yeah that is not true.,o | |
| It does not depend on the Swing Application Framework at all.,o | |
| You do not have to know anything about the SAF.,o | |
| I have done multiple projects in Swing on NetBeans and I know absolutely nothing about the SAF.,o | |
| "Based on my experience, my comment above applied in 2008.",o | |
| But that was 2+ years ago and I haven't really used Netbeans heavily since so I do not know how things have changed with the latest releases.,n | |
| I like the URL_http://www.netbeans.org/features/java/swing.html [Swing-GUI- Builder] from the URL_http://www.netbeans.org/ [NetBeans-IDE] .,o | |
| "There are 2 that you can use (I've used them both, and they are both very powerful, and easy to use): | |
| URL_http://netbeans.org/ [Netbeans] which has a built in URL_http://netbeans.org/features/java/swing.html [Gui-Builder] .",p | |
| "or you can use: | |
| URL_http://www.eclipse.org/ [Eclipse] with the URL_http://www.eclipse.org/windowbuilder/ [Windowbuilder] URL_http://marketplace.eclipse.org/content/windowbuilder-pro-gui-designer [plugin] | |
| (it can be downloaded URL_http://marketplace.eclipse.org/content/windowbuilder-pro-gui-designer [here] and URL_http://www.eclipse.org/windowbuilder/download.php [here] ) Personally, I prefer eclipse with URL_http://marketplace.eclipse.org/content /windowbuilder-pro-gui-designer [Windowbuilder] , but that's just me.",p | |
| You can use either one.,o | |
| " | |
| is a picture of the URL_http://www.eclipse.org/windowbuilder/ [Windowbuilder] plugin:**!",o | |
| "[enter image description here]( URL_http://i.stack.imgur.com/HRrVE.gif ) | |
| here is a picture URL_http://netbeans.org/ [netbeans'] built in URL_http://netbeans.org/features/java/swing.html [Gui-Builder] :** !",o | |
| [enter image description here]( URL_http://i.stack.imgur.com/uBnha.png ) .,o | |
| "For me, the best visual swing editor is URL_http://www.jformdesigner.com [JFormDesigner] , which you can run standalone or as a plugin for Intellij and Eclipse.",p | |
| "It generates proper (actually readable) source code, it's very ergonomic and intuitive and, above all, very extensible.",p | |
| "That last point is really important, because if you want to build a decent swing application, you'll have to extend the base components or use some third-party libraries and it | |
| be easy** to integrate those in the visual editor.",p | |
| It's not free but it's a bargain for the power you get (129 EUR / 159 USD).,n | |
| I've been using it for a few years and love it.,p | |
| +1.,o | |
| JFormDesinger is the most polished GUI Builder I've ever seen.,o | |
| You just have to try it to see how it works - no screenshot can show how good it works.,p | |
| "I've worked with JFD for quite a while, and I can definitively say that it's miles ahead of other options I know.",o | |
| Try URL_http://www.instantiations.com/index.html [Instantiations] ' URL_http://www.instantiations.com/windowbuilder/index.html [Windows-Builder- Pro] .,o | |
| "It includes URL_http://www.instantiations.com/windowbuilder/swingdesigner/index.html [Swing-Designer] , which is a Swing UI builder.",o | |
| It is based on Eclipse.,o | |
| This is now part of [Google's Web Toolkit]( URL_http://code.google.com/intl/sv - SE/javadevtools/wbpro/).,o | |
| I think this is the superior option.,o | |
| It has a lot of detail and if you start hand-coding (you will) it offers a lot of flexibility.,o | |
| "Also, the code it generates is easily readable.",p | |
| It handles internationalization schemes and dynamic calls without breaking.,o | |
| I also like the lack of meta-data.,n | |
| It simply drops a little piece of information into your Javadoc marking it as an entry point.,n | |
| "Netbeans has some GUI-building support, and it's one of the most popular Java IDEs on the market.",p | |
| Give it a look.,o | |
| "URL_http://code.google.com/javadevtools/wbpro/ [WindowBuilder-Pro] for Eclipse | |
| Free!",p | |
| " | |
| Works with existing code and doesn't lock you in (as opposed to Netbeans) | |
| Works with MiGLayout | |
| It does have some conventions that your view classes have to follow though Installing in Eclipse (Juno): 1.",n | |
| "Goto - Menu | |
| Help | |
| Install New Software... 2.",o | |
| Select - Work With: Juno - URL_http://download.eclipse.org/releases/juno [ URL_http://download.eclipse.org/releases/juno ] 3.,o | |
| "The WindowBuilder items are under ""General Purpose Tools"" (or use the filter) Older versions and zips are available at URL_http://www.eclipse.org/windowbuilder/download.php [ URL_http://www.eclipse.org/windowbuilder/download.php ] .",o | |
| URL_https://java.net/projects/abeille/ [Abeille] is very good and is based on the JGoodies FormLayout.,p | |
| "Unlike almost every other Java GUI builder, Abeille does not generate code by default.",o | |
| "In the project I used it on, it was wonderful to avoid reading or scrolling through the layout code (because that code no longer existed).",p | |
| "Most of our hand-written code concerned itself with connecting events to actions, simply asking the layout for the relevant controls.",o | |
| It's a crime that code generation is the default way to layout code in Java because better ways of doing GUIs have been around for decades.,o | |
| "I have used Matisse, the NetBeans GUI code generator.",o | |
| "While Matisse (now known as "" URL_http://netbeans.org/features/java/swing.html [Swing-GUI-Builder] "") makes it pleasant to layout components, it is similar to all other code generation tools because when you use Matisse you must live in constant fear that someone else edited the ""you cannot edit this in NetBeans"" GUI sections outside of NetBeans.",n | |
| As soon as you touch the layout builder again it could destroy their work and then you have a broken GUI.,n | |
| There might be some simple task like re- ordering a variable initialization and its use or re-naming a variable (this was especially a problem when using Matisse's database feature).,p | |
| You know how to do this by editing the un-editable source code but may waste time trying to figure out how to do the same thing in the GUI builder.,o | |
| "Like most code generation tools, it might get you started, but eventually you will have to maintain the generated code yourself.",o | |
| Layout as code is the only approach that allows you to decouple from that particular designer you are using after you have finished.,o | |
| "In other words, no vendor lock-in.",o | |
| "I have very good experience with | |
| ",p | |
| It's so easy if you know every minor parts of this applications.,p | |
| "The most complicated part is using, for example, the layouts (If you can not handle complicated parts), but everything is almost plug & play.",o | |
| "And in addition, you can put CODETERM1 into other frames without creating another frame class for this.",o | |
| I think that will be good.,p | |
| The latest version of NetBeans include a very nice and simple visual editor for Swing called Matisse URL_http://www.netbeans.org/kb/articles/matisse.html [Matisse] .,p | |
| Netbeans is the simplest to use ( URL_http://netbeans.org/ [ URL_http://netbeans.org/ ] ).,p | |
| "However, it does not allow you to edit (fine tune) the generated code.",o | |
| "JDeveloper ( URL_http://www.oracle.com/technetwork /developer-tools/jdev/overview/index.html [ URL_http://www.oracle.com/technetwork /developer-tools/jdev/overview/index.html] ) is another solution, and does allow you to edit the code... but I feel netbeans more intuitive.",p | |
| I always thought that JDeveloper's generated code is more understandable.,p | |
| I recommend WindowBuilder plugin for Eclipse IDE 3.7.2 Indigo / 24 February 2012.,p | |
| Here's for the step-by-step installation: URL_https://sites.google.com/site/teachmemrxymon/java/create-java-gui-as-easy- as-visual-basic [Create-Java-GUI-as-Easy-as-Visual-Basic] !,o | |
| [enter image description here]( URL_http://i.stack.imgur.com/f6bUp.jpg ) .,o | |
| Eclipse Visual Editor is pretty dull in my experience.,n | |
| "I had more luck with | |
| which is also based on Eclipse, simply adding a few plugins to it as many other commercial products do.",o | |
| "It is still not able to parse any Swing code (I doubt any Swing WISIWYG editor does), but if you start with it, it gives you relatively seamless experience.You need to pay for it though.",p | |
| "At the end of the day, I have worked with different similar UI tools, Flash Builder, Delphi etc., but unless you do some relatively trivial UI design, not including much business logic and communication with other layers, you'll have to accept that what you are capable of creating in code once you learn to do it properly is much more powerful than what any editor is capable of providing you with.",n | |
| The Eclipse Visual Editor project is also pretty inactive.,o | |
| It is archived at this point and was pretty frustrating to use in anything past 3.4.,n | |
| WindowBuilderPro is really the viable (free) alternative for Eclipse.,p | |
| "Frankly, I've never seen an editor which comes even close to what I can do manually in a text editor.",o | |
| All the visual editors are nice if you only have very simple needs like putting a few buttons in a window.,p | |
| "When things become more complex, visual editors quickly loose their competitive edge.",o | |
| I usually use a bunch of high-level classes built from more basic widgets and wire my UI from that.,o | |
| This also allows me to easily test my UI with automated JUnit tests (because I can control what the source looks like).,p | |
| "Lastly, changes to the UI won't generate unnecessary noise in the version control system.",o | |
| I have tried a few and the closest I have found that comes close to Visual Studio is Netbeans.,o | |
| V6.5 is excellent and realy improved over v5.,p | |
| "I'm a big fan of JetBrains, and when it comes to Java, URL_http://www.jetbrains.com/idea/index.html [IntelliJ] is the best IDE I have used.",p | |
| "For Swing, they have a fully interactive UI builder.",o | |
| "And, for actual coding, their intellisense can't be beat.",o | |
| I have switched between several IDEs and the one that I believe has the best GUI builder in terms of use and performance would have to be Netbeans.,p | |
| JFormDesigner.,o | |
| "I used NetBeans extensively in the past for GUI design, but I am now using IntelliJ with the JFormDesigner plugin.",o | |
| "I have tried several other solutions, and this is the one I am sticking with.",o | |
| "JFormDesigner also works with JBuilder and Eclipse, so you are not locking your projects to one particular IDE.",p | |
| Of course you should use Netbeans for building Java Swing GUI.,o | |
| The drag and drop features and auto-code generation are quite mature.,o | |
| "For Eclipse, I am not sure.",o | |
| "But because IBM has its own SWT package for GUI, I am not sure whether it support Swing.",o | |
| "As I'm using eclipse, I use the Visual Editor plugin.",o | |
| "It generates clean source code, with good patterns and easy to patch/modify/extend.Unfortunately, it is not very stable.",p | |
| But it's worth trying.,p | |
| "I personally will suggest _Netbeans Swing Builder_, yet if you want total control and to gain depth understanding of the Swing framework, I have noticed doing it free hand is the ultimate choice.",p | |
| "I like Eclipse's VisualEditor, sometime ago I've tried to switch toanother editor, but found it impossible.",o | |
| "Visual editor has thisfeature that it generates manageable, readable, editable, and easy tounderstand code.",p | |
| Unlike both mentioned earlier NetBeans editor andWidnowBuilder it uses lazy initialization pattern to separateinitialization of components.,o | |
| "Also it does not need to lock down partsof code that you cant edit, you may edit code by hand, and VE is stillable to work with your changes.",o | |
| "Only disadvantage of VE is that it uses eclipse callisto (there is noofficial build for ganymede, or europa), so effectively you have touse two eclipses one for VE and one for rest of developement.",n | |
| "I took it from recent discussion on comp.lang.java.gui (I was the autor of this post so I could do it rightfully), URL_http://groups.google.com/group/com p.lang.java.gui/browse_thread/thread/3722f92594039d24/1f0b605efebb1b39#1f0b605 efebb1b39 [here] is the link to whole discussion.",p | |
| We are doing Swing development since nearly 10 years.,o | |
| There are some nice GUI builders available (e.g.,p | |
| "URL_http://www.jformdesigner.com [JFormDesigner] ), but | |
| restrict us too much** in different kinds.",o | |
| "For example, we have a lot of components without public no-arg constructor (e.g.",o | |
| a JTable subclass which requires the model in the constructor) or we have component factories.,o | |
| Desktop applications usually have to be obfuscated.,n | |
| Obfuscation very easily breaks user interfaces created with a GUI designer or requires much work to avoid obfuscating such classes.,o | |
| "Another often happening case is that, for example, a panel should only contain some components depending on some condition.",o | |
| Simply hiding them would make the GUI look bad; they rather should not be added instead.,n | |
| "I never found a GUI editor which provides this flexibility and even if there would be one, it would be so hard to use, that I definitely would be faster with good old Java code.",p | |
| I think the best editor that can exist is Visual editor for eclipse.The only drawback is the fact that we can't re-edit the visual part when we modified the source code.,p | |
| I hope one day we will have a tool that rivals Visual Studio on this aspect.,o | |
| I will prefer the NETBEANS .,p | |
| "it have following feature | |
| Swing GUI Building**Design Swing GUIs by dragging and positioning GUI components from a palette onto a canvas.",o | |
| The GUI builder automatically takes care of the correct spacing and alignment.,p | |
| "Click into JLabels, JButtons, ButtonGroups, JTrees, JTextFields, ComboBoxes and edit their properties directly in place.",o | |
| You can use the GUI builder to prototype GUIs right in front of customers.,o | |
| " | |
| and Customizable**You can choose whether the GUI code should be generated with fully qualified or simple class names.",p | |
| The helpbar displays context-sensitive hints about what can be done with the selected component and suggests shortcuts that can speed up your work in the future.,o | |
| The NetBeans IDE also comes with built-in support for GUI localization and accessibility.,o | |
| " | |
| and Custom GUI Components**The extensible Component Palette comes with pre-installed Swing and AWT components and includes a visual menu designer.",p | |
| Use the Component Inspector to view a component's tree and properties.,o | |
| " | |
| Binding technology (JSR 295) Support**Take advantage of Beans Binding technology and the Java Persistence API to create Swing applications more easily.",p | |
| "Using the Bind dialog box, you can quickly generate bindings for JavaBeans components.",p | |
| " | |
| Debugger**Debug a Swing GUI application without looking into the source code and control the execution flow in terms of high-level structures.",o | |
| Choose Take GUI Snapshot to make a screenshot of the application GUI that serves as a basis of the Visual Debugger functionality.!,o | |
| [enter image description here]( URL_http://i.stack.imgur.com/h8VtN.png ) .,o | |
| "I not used anything other than NetBeans for Swing, but have been extremely happy with it.",p | |
| I used for 18 months on a $25M app and to develop an prototype application to replace a winforms app.,o | |
| "Up and until Microsoft came out with WPF, in my opinion, there was not a better tool kit for traditional desktop apps.",o | |
| (I always found winforms too limiting).,o | |
| I used to use MyEclipse quite a bit.,o | |
| It had a decent IDE for making Swing forms and such.,o | |
| "I assume it has improved in the past year - they seem to add features in gobs and heaps, quite often.",o | |
| URL_http://www.myeclipseide.com / .,o | |
| That is the netbeans one which has been ported.,o | |
| "Use NetBeans, I have also successfully developed one application using NetBeans.",p | |
| "It is realy awesome, it helps you while writing the code.",p | |
| Since Swing generates some code on its own so it is really helpful to use Netbeans.,p | |
| Go through it and you can always ask question and problems.,o | |
| It will be good if you go for latest version release.,p | |
| I have always coded my UIs by hand.,o | |
| The frustration of dealing with screen builders and filling out all those property sheets is too much for me.,o | |
| After a couple of screens and a little research I am just as productive.,n | |
| "As others have mentioned, my best experience with Java SWING applications is with NetBeans.",p | |
| "NetBeans has a WYSIWYG editor, and the code is automatically generated for you, which is then protected, however you can add custom code to add listeners and other events that the end user may be interested in using, such as buttons, text forms and areas, and other nice GUI tools.",p | |
| "When I use swing, I usually use the NetBeans.",o | |
| "If you prefer the Eclipse IDE, there are the Visual Editor plugin.",p | |
| URL_https://developers.google.com/java-dev-tools/download [window-builder-pro] is good option and it is free also.,p | |
| Is Java Swing still in use?,o | |
| I am planning on making a Java Swing application and was wondering if Swing is still used or if it has been replaced with something else.,o | |
| Thanks in advance!,o | |
| Related: URL_http://stackoverflow.com/questions/407343/where-are-swing - applications-used.,o | |
| Related: URL_http://stackoverflow.com/questions/408820/what-is-the-difference - between-swing-and-awt.,o | |
| Related: URL_http://stackoverflow.com/questions/2377467/if-swing-has-more - features-to-design-a-form-then-what-is-the-use-of-awt-in-java.,o | |
| _**Swing is still in use.... but there is AWT!!,o | |
| " | |
| AWT: | |
| Speed: use of native peers speeds component performance.",o | |
| " | |
| Look and Feel: AWT components more closely reflect the look and feel of the OS they run on.",o | |
| " | |
| Portability: use of native peers creates platform specific limitations.",o | |
| Some components may not function at all on some platforms.,o | |
| " | |
| Third Party Development: the majority of component makers, including Borland and Sun, base new component development on Swing components.",o | |
| "There is a much smaller set of AWT components available, thus placing the burden on the programmer to create his or her own AWT-based components.",n | |
| " | |
| Features: AWT components do not support features like icons and tool-tips.",o | |
| " | |
| Swing: | |
| Portability: Pure Java design provides for fewer platform specific limitations.",o | |
| " | |
| Behavior: Pure Java design allows for a greater range of behavior for Swing components since they are not limited by the native peers that AWT uses.",p | |
| " | |
| Features: Swing supports a wider range of features like icons and pop-up tool-tips for components.",o | |
| " | |
| Vendor Support: Swing development is more active.",o | |
| Sun puts much more energy into making Swing robust.,p | |
| " | |
| Look and Feel: The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, Solaris, Macintosh, etc.).",o | |
| "It also makes it easier to make global changes to your Java programs that provide greater accessibility (like picking a hi-contrast color scheme or changing all the fonts in all dialogs, etc.).",p | |
| " | |
| Performance: Swing components are generally slower and buggier than AWT, due to both the fact that they are pure Java and to video issues on various platforms.",n | |
| Since Swing components handle their own painting (rather than using native API's like DirectX on Windows) you may run into graphical glitches.,o | |
| " | |
| Look and Feel: Even when Swing components are set to use the look and feel of the OS they are run on, they may not look like their native counterparts.",o | |
| " | |
| URL_http://edn.embarcadero.com/article/26970 [More-Reading.",o | |
| "] | |
| .",o | |
| """Applet Portability: most Web browsers support AWT classes so AWT applets can run without the Java plugin.",o | |
| """This is patently false.",n | |
| ugh?,o | |
| "I guess this is 1990s and you are still using Netscape 4.0, right?",o | |
| Edited it..........,o | |
| "I wouldn't recommend AWT, it gets very little love these days (other than the bits that are needed for Swing).",n | |
| Better to use SWT if you want to go down the native path.,o | |
| """Most Web browsers do not include the Swing classes, so the Java plugin must be used.",o | |
| """ What?",o | |
| "The Swing classes are part of the JRE, not the browser.",o | |
| I don't recall this being a problem in 2003.,o | |
| "For all these negatives, I have edited the question.....",o | |
| "they | |
| not look like their native counterparts that one made me giggle.",o | |
| At least on Windows I have yet to see a single control (apart from JLabel maybe) that looks and feels like its native counterpart with the native LAF :-).,o | |
| """rather than using native API's like DirectX on Windows"": false, Swing uses Java2D, which may use DirectX when supported.",n | |
| """Swing components are generally buggier than AWT"": this is false as well.",n | |
| Swing is still there and well supported.,p | |
| "Most of the reasons why people hated swing when it first came out are no longer valid simply because of Moores Law, along with improved JVMs.",o | |
| Swing apps no loger feel jerky and unrepsonsive and an accumulation of minor improvements result in a more professional looking GUI.,o | |
| "Its also worth looking at the ""groovy/swing"" combination for rapid development and prototyping.",p | |
| "Docs for Swing, on the other hand, are dire to nonexistent.",n | |
| "Aggree that the docs are lacking somewhat, but, IDE support is pretty good, and, googling usually gets you some decent usage examples.",n | |
| Real programmers don't read documentation.,o | |
| There is a lot of tuning in Swing that cannot be attributed to Moores law.,o | |
| @JMcO For documentation -> URL_http://download - llnw.oracle.com/javase/tutorial/uiswing/.,o | |
| Yes it is still in use.,o | |
| short and to the point.,o | |
| We still use it.,o | |
| "Not everything is a web app, so far there have been some tentative replacements (such as SWT, which eclipse is written in) SWT has a native layer that wraps the underlying calls to the native windowing layer.",o | |
| It only works for a limited set of platforms and of course requires some third party shared libraries.,p | |
| I would venture to say that there are far fewer SWT apps than Swing apps.,o | |
| "Although swing is still in use, I would rather chose URL_http://wiki.eclipse.org/index.php/Rich_Client_Platform [Eclipse-RCP] as a platform for desktop applications, since it also provides a huge amount of plugins.",o | |
| "Eclipse RCP uses Eclipse's own SWT, which means you need the native SWT libraries.",o | |
| "You can also build on the NetBeans Platform, which is built on Swing: URL_http://platform.netbeans.org/ .",o | |
| "Yes, it still is in use.",o | |
| "The library is still part of the JRE, and will probably be that way for the future.",o | |
| There are other options though.,o | |
| "For instance, you may want to look at JavaFX if you need a rich UI; or using SWT in your application.",o | |
| "Maybe you want some kind of 3D effects, and you need to look into a 3D engine like jpct or the jmonkeyengine.",o | |
| Java has progressed somewhat since the software Swing world.,o | |
| jmonkeyengine is only for games.,o | |
| Yes.,o | |
| Roughly URL_http://hewgill.com/~greg/stackoverflow/stack_overflow/tags/#!,o | |
| swing+javafx+wpf+qml [1-out-of-120-questions] on StackOverflow is about Swing!,o | |
| [enter image description here]( URL_http://i.stack.imgur.com/OwRhP.png) .,o | |
| "Yes, it's still in use.",o | |
| "Takes while to get used to but once you have it, it's a pretty nice framework for writing applications.",o | |
| Have a look at Webstart for deploying your application.,o | |
| Also a bit of a clunker to start with but really handy when you're comfortable .,p | |
| "Swing is still the preferred way to build heavy-weight, e.g.",n | |
| """Desktop"" applications, in Java.",o | |
| "If your code is running in a web browser, you will likely use other things.",o | |
| "But for freestanding desktop apps, it is quite excellent and in wide use.",p | |
| "For desktop programs, yes, Swing is heavily in use.",n | |
| However there are many alternatives because alot of people think that Swing is heavily verbose and hard to work with.,o | |
| JavaFX is worth taking a look at .,p | |
| JavaFX is for web apps is it not?,o | |
| I am looking to make native Desktop apps.,o | |
| JavaFX 2.0 works well for desktop apps as well.,p | |
| concurrent log4j.,o | |
| I have my own logging engine which writes the logs on a separate thread with a blocking queue.,o | |
| "For the sake of using ""standard software"" I am thinking about switching to log4j.",p | |
| I don't want my highly concurrent software to be slowed down by log commands that write everything to disk as some as the command is called.,n | |
| Can log4j be used as a dumpster instead?,o | |
| "logj4 might not be your best bet, if you need highly concurrent logging you should go w/ just something like a concurrent linked queue (or blocking) and a dedicated polling thread.",p | |
| Logging by default blocks hard (if you need to log for real).,n | |
| If you need even higher concurrency you can use a queue per thread (and still poll each queue by a separate one).,o | |
| See URL_http://stackoverflow.com/a/13144054/603516 for some links to related log4j locking issues.,o | |
| "Log4j is the logging implementation on most JavaEE app-servers out there, so that's a good advert for its concurrency abilities.",p | |
| "Having said that, I have seen Log4j 1.2 deadlock under high load conditions.",n | |
| A bit of investigation highlighted some scarily bad synchronization in the source code.,n | |
| "Apparently, this was fixed in Log4j 1.3, although development on this has slowed or stopped altogether - I get the feeling much of the source was unsalvageable.",n | |
| "However, if you're free to choose, then you should consider URL_http://logback.qos.ch/ [Logback] instead, the spiritual successor to Log4j.",o | |
| "It's a ground-up redesign, and is probably a better option for you.",o | |
| "Most (all) EE servers are anything but heavily concurrent, simply they are not.",n | |
| Saying that after 2 days+night battles vs tomcat data races.,o | |
| Note.,o | |
| "as ""heavily concurrent"" I assume 32+ cores that don't get starved.",n | |
| "Check out log4j's URL_http://logging.apache.org/log4j/1.2/apidocs/org/apache/l og4j/AsyncAppender.html [asynchronous-appender] , it buffers log messages ad passes them on to appenders using a separate thread.",o | |
| "It might be that you decide the log4j async appender is not appropriate URL_http://glueclue.blogspot.com/2007/01/log4j-asyncappender-is-not- always_31.html [(here-are-some-complaints-about-it)] , you could always make your own appender.",o | |
| I'd not call the impl.,o | |
| highly concurrent at any rate.,o | |
| It's async but not highly concurrent.,o | |
| "Logging using SL4J, Jakarta Commons logging, log4j for third party libraries and my own code.",o | |
| "I have some questions about logging, more specifically about setting it up and making sure it works.",p | |
| "The project I'm doing will use URL_http://wicket.apache.org/ [Wicket] , URL_http://www.springsource.org/ [Spring] and URL_http://www.hibernate.org/ [Hibernate] .",o | |
| I know that Wicket and Hibernate uses Simple Logging Facade for Java ( URL_http://www.slf4j.org/ [SL4J] ) and that Spring is using the URL_http://commons.apache.org/logging/ [logging-component-from-Apache-Commons] .,p | |
| "Will they co-exist happily?I thought I would use URL_http://logging.apache.org/log4j/1.2/index.html [log4j] together with both SL4J and the logging component from Apache commons, do you think that's a good idea?",o | |
| Can I set up them all to output logging data into a common file?Or should I use separate files?Or should I store the logging messages in the database?,o | |
| "(I'd rather not, as I find grepping etc on text files quite convenient.",o | |
| ) For Spring I guess I need some kind of configuration file for the Apache Commons logging component as well where I direct it to use log4j?,o | |
| When I've set these up I guess to see that everything works I set the logging level to INFO as it's fairly certain that all three of the frameworks output some information in that mode?,o | |
| Or is there an even better way to make sure?,o | |
| And my last question.,o | |
| "In the project I'm starting, do you recommend that I use SL4J for my own logging purposes?",o | |
| "(I thought I would use log4j directly, but that was before I learned a little bit more about logging and a lot of respectable libraries seem to choose the path of a bridge/facade for their logging needs.",n | |
| And if it gets us flexibility without added cost there's no reason not to do it that way.,o | |
| ) I'm looking forward to hearing more from you about how you are doing your logging.,o | |
| It's a new area for me which I'm eager to improve myself in.,o | |
| "Well SLF4J is just a facade, like commons logging, which means they still need something else to work.",p | |
| They permit library authors to not force users into having multiple logging library and configuration.,o | |
| Log4j and logback are regular logging libs.,o | |
| See URL_http://stackoverflow.com/questions/354837/whats-up-with-logging-in- java [here] for more info.,o | |
| SLF4J has a URL_http://www.slf4j.org/legacy.html [commons-logging-bridge] that you can use to replace the commons logging library.,o | |
| I think the schema there explain the situation very well.,p | |
| "Now, you just need to use slf4j-logj12.jar to have commons logging and slf4j use log4j (or anything else you chose; btw, logback doesn't need an additional library to be used with slf4j) as a backing engine.",o | |
| "You application will thus have | |
| jcl104-over-slf4j.jar (to bridge jakarta commons logging to slf4j) | |
| slf4j.jar (for hibernate and others to use slf4j) | |
| slf4j-logj12.jar (for slf4j to use log4j as a backend) | |
| log4j.jar (for your application to use.",o | |
| all config will also be done here) .,o | |
| Remember to not confuse slf4j-xxxx.jar with xxxx-over-slf4j.jar.,p | |
| "The former is for funneling to your desired logging framework (log4j, logback, etc), the latter is to replace the used logging framework.",o | |
| And using both can create a breach in the space-time fabric!.,o | |
| Stop the madness.,o | |
| Does anybody else think that logging has become far too complex?,o | |
| "I thought log4j was a terrific thing, worthy of being made a standard.",p | |
| I didn't follow the JCP history closely enough to know why Sun decided to go their own way.,p | |
| This is ridiculous.,o | |
| I use ACL + log4j.,o | |
| "Here is how to redirect everything to SLF4J: | |
| remove CODETERM1 from your classpath.",o | |
| "If you are using Maven and have trouble getting rid of commons-logging, see URL_http://day-to-day-stuff.blogspot.com/2007/07/no-more-commons-logging.html [this] .",o | |
| " | |
| put CODETERM2 in your classpath (it comes in the SLF4J distribution).",o | |
| "This is a drop-in replacement that mimics JCL's classes, but calls SLF4J internally.",o | |
| "This will take care of Spring, and any other framework that uses JCL.",o | |
| "Connect SLF4J to your favorite backend (Log4J, Logback...) by putting CODETERM3 in the classpath.",p | |
| "Configure the backend to log all categories to one file, and you're done.",o | |
| "As for using SLF4J in your application, it is not strictly necessary.",o | |
| Libraries like JCL and SLF4J were originally designed for people who write libraries and do no want to lock their clients into a particular logging framework.,o | |
| "PS: by the way, JCL | |
| Jakarta Commons Logging .",o | |
| Thanks!,o | |
| I changed to JCL in the OP.,o | |
| "What do you mean by ""onfigure the backend to log all categories to one file""?",o | |
| Could you provide more details?,o | |
| In order to exclude commons-logging from your final build in maven use scope 'provided' instead of the 99.0-does-not-exist from Eric.,o | |
| Log4j 2.0 and SLF4J and the never ending future of java logging frameworks.,o | |
| "So I just found out today that Log4J 2.0 is now actively being developed, there is an alpha version and it is said to replace logback.",o | |
| "Right now in my app I have close to 4 maybe more logging frameworks: | |
| Java Util Logging | |
| log4j | |
| slf4j | |
| logback (ignored thanks to a maven provided hack) | |
| commons logging (ignored thanks to a maven provided hack) | |
| And tomcat has its own JULI adapter I have been using log4j (1.2.x) because frankly I just haven't needed the _features_ of the newer guys but I have been tempted lately to switch to SLF4J and mainly | |
| I don't want to have rewrite my complicated log4j configurations files to a new format** (logback).",o | |
| Now my question is in terms of what I should code against is SLF4J the right choice for the future given log4j 2.0.,o | |
| "_It seems like I should just stick with old log4j ( CODETERM1 ) as it is the lowest common denominator?_ | |
| on further examination of log4j 2.0 while very similar it appears the configuration is not backward compatible with log4j 1.2.",n | |
| Looks like logback is the best choice.,p | |
| "For some projects we put together, logging framework was more driven by the open source frameworks we were using.",p | |
| But it is a state of preference.,o | |
| Yes I have done similar likewise but good ole log4j is almost in every project except for really really new projects and its the only one I can remember how to configure.,p | |
| The big annoyance in switching is actually the configuration and supported appenders.,o | |
| "Code with SLF4J, and choose backend at runtime.",o | |
| Changing logging backend is not a problem if you are using SLF4J Api.,o | |
| " | |
| I am the founder of log4j, slf4j and logback projects but unaffiliated with log4j 2.0.",o | |
| "As I understand it, notwithstanding its name, log4j 2.0 is very different than log4j 1.x.",o | |
| "As far as the user API is concerned, log4j 2.0 is largely incompatible with log4j 1.x.",o | |
| Log4j 2.0 provides an adaptation layer for log4j 1.x which at present time (2012-08) is URL_http://logging.apache.org/log4j/2.x/log4j12-api/api.html [CODETERM1] .,o | |
| I guess I was hoping for a grand unification of logging (GUL) but I guess like physics (GUT) that isn't going to happen anytime soon :).,o | |
| BTW thanks for log4j (original).,o | |
| My interest in log4j 2.0 (over logback) is not having to switch configuration to the new logback style (IMHO its easier to refactor to SLF4J) than change the config of 10 or so projects.,p | |
| Are you familiar with the log4j.properties translator?,o | |
| It can greatly help in migrating log4j.properties to logback.xml.,o | |
| Try it out URL_http://logback.qos.ch/translator/ .,o | |
| I think I vaguely remember seeing that in the logback project but I need one for the XML format.,o | |
| I should enhance the translator to deal with log4j.xml as well.,p | |
| (I should probably ask this as a separate Q.,o | |
| ) but how can I programmatical-ly turn off or change the threshold of a specific appender during runtime?,o | |
| "My old code: AsyncAppender appender | |
| (AsyncAppender) LogManager.getRootLogger().getAppender(""async"");AppenderSkeleton mailAppender | |
| (AppenderSkeleton) appender.getAppender(""mail"");.",o | |
| NM I'll file separate question and for now look at: URL_http://mailman.qos.ch/pipermail/logback-user/2007-May/000209.html .,o | |
| I could whip up some XSLT to translate log4j.xml to logback.xml.,o | |
| "The Log4J2 website reports that there is an adapter for SLF4J, so if you write your code to SLF4J you can switch to Log4J, Log4J2, and Logback whenever you want.",o | |
| Here's the bridge: URL_http://logging.apache.org/log4j/2.x/log4j-slf4j - impl/.,o | |
| It's a subjective question.,o | |
| "I'd suggest using slf4j, since it can use log4j as a backend if that's what you need.",o | |
| You're likely to be using a number of components which may all use different logging APIs.,o | |
| It's good to be able to consolidate the output via those APIs into a single output route.,p | |
| Yes I think slf4j is what I'll go with.,o | |
| I got confused between facade and impl.,n | |
| Log4j 2.0 is not a facade and does not advertise to be one.,o | |
| I would also recommend to use [jcabi-log]( URL_http://www.jcabi.com/jcabi-log /) as a convenient static wrapper of slf4j.,p | |
| What's Up with Logging in Java?,o | |
| Why one would use one of the following packages instead of the other?,o | |
| " | |
| Java Logging | |
| Commons Logging | |
| Log4j | |
| SLF4j | |
| Logback .",o | |
| "You might want to URL_http://stackoverflow.com/questions/873051 /, which compares SLF4j to Commons Logging.",o | |
| Why the hell has Ceki created 3 logging frameworks!!!,o | |
| thats madness...,o | |
| @mP.,o | |
| "- log4j was the first, then disagreement arose, and slf4j+logback was written.",o | |
| slf4j is the _API_ and logback the implementation of the API.,o | |
| "Regardless of everything else, slf4j is extremely useful.",o | |
| For details on why Ceki Glc did create SLF4J+Logback see the following Devoxx talk: URL_http://www.parleys.com /#st=5&id=1701.,o | |
| "In chronological order of api apperance (as far as I know): | |
| Log4j because most everybody uses it (in my experience) | |
| Commons Logging because open source projects use it (so they can integrate with whatever logging framework is used in the integrated solution); especially valid if you're an API/Framework/OSS and you rely on other packages that use Commons Logging.",p | |
| " | |
| Commons Logging because you don't want to ""lock down"" to a particular logging framework (so instead you lock down to what Commons Logging gives you instead) - I don't think it is sensible to decide using this point as the reason.",p | |
| " | |
| Java logging because you don't want to add in an extra jar.",o | |
| " | |
| SLF4j because it's newer than Commons Logging and provides parameterized logging: | |
| CODESNIPPET_JAVA1 .",o | |
| " | |
| Logback because it's newer than log4j and again, supports parameterized logging, as it implements SLF4j directly | |
| SLF4j/Logback because it's written by the same guy who did log4j, so he's made it better (according to URL_http://stackoverflow.com/questions/354837/whats-up-with-logging-in-java#356038 [Ken-G] - thanks.",o | |
| "It seems to fit when looking at URL_http://www.slf4j.org/news.html [their-earlier-news-posts] ) | |
| SLF4j because they also publish a log4j adapter so you don't have to ""switch out"" log4j in older code - just make log4j.properties use SLF4j and it's configuration .",o | |
| As far as I can tell the idea behind commons logging is that it should be used in libraries.,o | |
| This way the library can always use the same logging framework (via commons logging) that the hosting application uses.,o | |
| Thanks heaps to Loki for the question.,o | |
| I now know that I'm not going to be using log4j as my default framework any more.,o | |
| SLF4j FTW!Also thanks to Ken G for pointing out that SLF4j is written by the same guy as log4j.,o | |
| "The comment in your code example isn't 100% correct.The actual formatting of the message is performed lazily by Logback so it will only happen if the event is really handled by an appender | |
| the appender requires the formatted message - which wouldn't happen in case of e.g.",o | |
| "an SocketAppender since the event is serialized using the unchanged message pattern + the arguments as Strings.I guess it just depends how you define ""effectively"" though.",o | |
| It would certainly emit the same message (at least if entry and object are the same ;)) so please forgive my nitpicking.,o | |
| SLF4J actually is just an API that sits on top of other logging frameworks.,o | |
| "Similar to the goal of Commons Logging, but more intuitive from my experience.",p | |
| "I find logging in Java to be confusing, inconsistent, poorly documented, and especially haphazard.",n | |
| "Moreover, there is a huge amount of similarity between these logging frameworks resulting in duplication of effort, and confusion as to what logging environment you are actually in.",n | |
| "In particular, if you are working in a serious Java web application stack, you are often in _multiple_ logging environments at one time; (e.g hibernate may use log4j, and tomcat java.util.logging).",p | |
| "Apache commons is meant to bridge different logging frameworks, but really just adds more complexity.",o | |
| "If you do not know this ahead of time, it is utterly bewildering.",n | |
| "Why are my log messages not printing out to the console, etc.?",o | |
| "Ohh because I am looking at the Tomcat logs, and not log4j.",o | |
| "Adding yet another layer of complexity, the application server may have global logging configurations that may not recognize local configurations for a particular web application.",o | |
| "Lastly, all these logging frameworks are WAY TOO COMPLICATED.",o | |
| Logging in Java has been a disorganized mess leaving developers like me frustrated and confused.,n | |
| Early versions of Java did not have a built-in logging framework leading to this scenario.,o | |
| Is this an answer?,o | |
| It looks more like a rant.,n | |
| I am sorry.,n | |
| "It | |
| a little bit of a rant.",n | |
| "But it is also a cogent response to ""Whats Up with Logging in Java?"".",p | |
| "The answer, in short, is it is deeply broken.",n | |
| well it's not worth a -1 vote ;P But something to ponder about.,p | |
| The problems started when Sun actually added java.util.logging to Java 1.4.,o | |
| Before that LOG4J was well established and in wide use.,p | |
| After that there was the necessity of wrappers to support both LOG4J and java.util.logging.,o | |
| "Also, since jul is contained in the java.",o | |
| " | |
| package, it can't be replaced by swapping a JAR - which is the way SLF4J bridges the other frameworks.",o | |
| "This was probably the worst Sun idea ever... and it ultimately led to the wrong assumption that a ""good Java citizen"" should use jul.",n | |
| "@Huxi, I maintain that the Calendar API was worse.",n | |
| "In defense of Sun it wasn't their code, but came from Taglient.",o | |
| "There's one important point that wasn't mentioned before: SLF4J (and both Logback and LOG4J as the logging backend) have support for a so called Mapped Diagnostic Context (MDC, see URL_http://slf4j.org/apidocs/org/slf4j/MDC.html [javadoc] and URL_http://logback.qos.ch/manual/mdc.html [documentation] ).",o | |
| "This is essentially a thread-local Map<String,Object> which you can use to add additional context information to your logging event.",o | |
| The current state of the MDC is attached to every event.,o | |
| This can be incredibly useful if you put stuff like the username and the URL of the request (in case of a webapp) into it.,o | |
| "This can be done automatically using a filter, for example.",o | |
| "Technically, it's a thread-local Map<string,string>.",o | |
| See also answers to the question URL_http://stackoverflow.com/questions/296150 /what-are-the-best-practices-to-log-an-error [What-are-the-best-practices-to- log-an-error?,o | |
| "] , especially: | |
| There are some potentialclassloading issues with CommonsLogging.",o | |
| " | |
| Log4J and SLF4J were developed by the same person, learning from issues found in practice with Log4J.",o | |
| "The URL_http://commons.apache.org/logging/ [Commons-Logging-overview] gives the reason for its existence: logging from library code, when you have no control over the underlying logging framework.",o | |
| "Very important for the various Apache projects, which will be linked into outside applications.",o | |
| "Perhaps not so important for internal IT projects, where you have complete control.",o | |
| "That said, I write to Commons Logging, as do many of the other developers I know.",o | |
| "The reason is to minimize mental baggage: you can change projects or jobs, and not have to learn a new framework (provided the new job/project also uses CL, and/or you can convince them to move to it).",o | |
| "Also, there is some value to creating your own wrappers around whatever framework you use.",o | |
| "As described URL_http://www.kdgregory.com/index.php?page=java.logging [here] , I like to use a LogWrapper object to provide custom stringification (important), and minimize the visual clutter of logging statements (less important).",o | |
| There's also a commons.logging=>SLF4J bridge which can be used to route all CL logging over SLF4J.,o | |
| "SLF4J supports bridging of commons.logging, LOG4J and (a bit cumbersome, but as good as possible) java.util.logging so all logs will end up in whatever SLF4J backend you'll use.",n | |
| "See URL_http://slf4j.org/legacy.html I'd use Logback, btw, but you could argue that I'm biased.",o | |
| In our company project we use LOG4j and it is very easy to use like Stephen showed in his example.We also have written our own pattern classes for LOG4j so you can create your own output file schemas.,p | |
| You can describe how your log file should look like.,o | |
| It is possible to enhance the original log4j classes.,o | |
| "All LOG4j properties you can change in a log4j.properties file, so you can use different files for different projects.",o | |
| "Java logging is not my favorit, but this could be because i use log4j from the beginning.",o | |
| Generally I would default to using Log4J.,o | |
| I would use Java Logging if I didn't mind a dependency on Java 1.4 but I would still use Log4J in preference.,o | |
| I would use Commons Logging if I was enhancing something that already used it.,o | |
| Didn't mind a dependency on 1.4??,o | |
| Even 1.4 has hit its end of service life.,o | |
| @TomHe means jdk1.4+ dont be silly.,n | |
| "Actually I've recently done some work in a system that was still running under jdk 1.3 :-(, and it was less than two years ago I was last maintaining a | |
| 1.2** system.",o | |
| "Too many places don't upgrade unless they absolutely have to, they just refuse to install the upgrades.",n | |
| "I would suggest creating a thin logging facade that can write to any of the logging frameworks, at which point the choice of backing engine become pretty much a moot point.",o | |
| That is what commons logging does so why reinvent the wheel?,o | |
| Also there are some issues that your facade would have to handle that commons logging already does.,o | |
| "+1 To counter commons logging argument, Some enterprise apps use custom logger.",o | |
| It always a good idea to hide underlying implementation.,p | |
| The 'thin' wrapper eliminates the need for another jar being packaged and is not as much as reinventing.,o | |
| "This approach is valid in many cases, especially when your code must run on an arbitrary platform.",o | |
| "The underlying logging API tends to be different on application servers compared to Eclipse, for example.",o | |
| About hiding the underlying implementation: All the logging APIs mentioned can do just that: They are interfaces to pluggable implementations.,o | |
| This saved me recently when we ported our framework to the Compact Framework (in .Net).,o | |
| "If we had hardcoded dependencies on nLog, we would have been screwed.",n | |
| "Because we used this approach, we were able to drop in a null logger and be happy.Someone vote me back up to 0 Please :-).",o | |
| One already exists - take a look at slf4j.,o | |
| It's an accepted thin wrapper that allows you to switch logging frameworks on application startup by switching jars on the runtime classpath.,o | |
| clogging has its own way of discovering what framework it will use - its not nice and rather convuluted.,o | |
| How many logging frameworks has Ceki created.,o | |
| One should always strive to slot a level of interdirection and hide an implementation even if it is clogging with your own logging.,o | |
| Behind the scenes you can then plugin whatever f/w you desire as mentioned by Travis.,o | |
| Java - Create a new String instance with specified length and filled with specific character.,o | |
| Best solution?,o | |
| I did check the other questions; this question has its focus on solving this particular question the most efficient way.,o | |
| "Sometimes you want to create a new string with a specified length, and with a default character filling the entire string.",o | |
| "ie, it would be cool if you could do CODETERM1 and create a new String from there, with a length of 10 characters all having a . | |
| ",p | |
| "Because such a constructor does not exist, and you cannot extend from String, you have either to create a wrapper class or a method to do this for you.",o | |
| At this moment I am using this: CODESNIPPET_JAVA1 .,o | |
| "It still lacks any checking (ie, when length is 0 it will not work).",n | |
| I am constructing the array first because I believe it is faster than using string concatination or using a StringBuffer to do so.,p | |
| Anyone else has a better sollution?,o | |
| Simply use the StringUtils class from URL_http://commons.apache.org/lang [apache-commons-lang] project.,o | |
| "You have a URL_http://commons.apache.org/lang// api-2.4/org/apache/commons/lang/StringUtils.html#leftPad%28java.lang.String,%2 0int,%20char%29 [leftPad] method: CODESNIPPET_JAVA1 .",o | |
| +1 - that's exactly what he was looking for (aka 'cool').,o | |
| "For the exact same behaviour, but that's obvious, do: StringUtils.leftPad("""", 10, '*');.",o | |
| "+1 nice solution, though I wouldn't add a jar to my project just for that.",p | |
| Thanks.,o | |
| Yes that looks like a more suitable way to use it.,o | |
| "Luckily I am already using this jar, so i could use this straight away.",p | |
| "Or use repeat(), which doesn't require the empty string at the start and is arguably clearer in intent (see my answer).",p | |
| "@abyx> Yes, you will need to add a JAR, but commons lang offers so nice utils methods, so I don't think it is really a drawback!.",p | |
| Over 300kb for this jar??,o | |
| "Yuck, no thanks.",o | |
| Not for a mobile app.,o | |
| No need for bloatware.,o | |
| "No need to do the loop, and using just standard Java library classes: CODESNIPPET_JAVA1 .",p | |
| "As you can see, I also added suitable code for the CODETERM1 case.",o | |
| won't the code in Arrays.fill() contain a loop...,o | |
| "Maybe, but 1) it's likely to be faster and 2) that's code you don't need to write.",p | |
| Good find.,p | |
| Yes Arrays.fill does a for loop itself.,o | |
| But fundementally this is better.,o | |
| You should throw an IllegalArgumentException if (length < 0).,o | |
| (Even java.lang.NegativeArraySizeException is better.,o | |
| ).,o | |
| "Apache Commons Lang (probably useful enough to be on the classpath of any non- trivial project) has URL_http://commons.apache.org/lang//api-2.4/org/apache/co mmons/lang/StringUtils.html#repeat%28java.lang.String,%20int%29 [StringUtils.repeat()] : CODESNIPPET_JAVA1 .",n | |
| Easy!,p | |
| CODESNIPPET_JAVA1 .,o | |
| What is wrong?,o | |
| The above is fine.,o | |
| Do you mind if I ask you a question - Is this causing you a problem?,o | |
| It seams to me you are optimizing before you know if you need to.,o | |
| Now for my over engineered solution.,o | |
| In many (thou not all) cases you can use CharSequence instead of a String.,o | |
| CODESNIPPET_JAVA1 .,o | |
| CODESNIPPET_JAVA1 .,o | |
| "One extra note: it seems that all public ways of creating a new CODETERM1 instance involves necessarily the copy of whatever buffer you are working with, be it a CODETERM2 , a CODETERM3 or a CODETERM4 .",p | |
| "From the CODETERM5 javadoc (and is repeated in the respective CODETERM6 methods from the other classes): | |
| _The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string._ So you'll end up having a possibly big memory copy operation after the ""fast filling"" of the array.",n | |
| "The only solution that may avoid this issue is the one from @mlk, if you can manage working directly with the proposed CODETERM7 implementation (what may be the case).",p | |
| PS: I would post this as a comment but I don't have enough reputation to do that yet.,p | |
| using URL_http://bitbucket.org/dfa/dollar [Dollar] is simple: CODESNIPPET_JAVA1 .,p | |
| "There are 9 | |
| in the comment.",o | |
| "To improve performance you could have a single predefined sting if you know the max length like: | |
| String template | |
| ""####################################""; And then simply perform a substring once you know the length.",n | |
| Karl .,o | |
| +1: I just read on another post that substring creates a String that just uses the same char[] of the original String.,o | |
| So it's an O(1) operation (no loop) and it saves memory (if that is a real issue).,n | |
| "Try this Using the substring(int start, int end); method CODESNIPPET_JAVA1 .",o | |
| this will return abcde.,o | |
| C# equivalent to Java's charAt()?,o | |
| I know we can use the CODETERM1 method in Java get an individual character in a string by specifying its position.,o | |
| Is there an equivalent method in C#?,o | |
| "You can index into a string in C# like an array, and you get the character at that index.",o | |
| "Example: In Java, you would say str.charAt(8);In C#, you would say str[8]; .",o | |
| CODESNIPPET_JAVA1 .,o | |
| And <strike> CODETERM1 Reference: URL_http://msdn.microsoft.com/en- us/library/system.string.chars%28v=VS.71%29.aspx [ URL_http://msdn.microsoft.com /en-us/library/system.string.chars%28v=VS.71%29.aspx] </strike> The above is same as using indexers in c#.,o | |
| You beat me to it -- you get the upvote.,p | |
| I really don't know if it helps anything at all but I'll be damned if I don't try.,n | |
| "I had a similar problem when I required a specific position/index, and LINQ Saved the day actually, I just wish I remembered where I put that blasted code.",o | |
| "Sorry for the crappy answer, but it might be a good starting point if ALL ELSE fails.",n | |
| Console.WriteLine allows the user to specify a position in a string.,o | |
| "See sample: string str | |
| ""Tigger"";Console.WriteLine( str[0] ); //returns ""T"";Console.WriteLine( str[2] ); //returns ""g""; There you go!",o | |
| "this topic, and your answer, have nothing to do with WriteLine...",o | |
| "String, StringBuffer, and StringBuilder.",o | |
| "Please tell me a real time situation to compare CODETERM1 , CODETERM2 , and CODETERM3 ?",o | |
| " | |
| Difference:** CODETERM1 is | |
| if you try to alter their values, another object gets created, whereas CODETERM2 and CODETERM3 are | |
| so they can change their values.",o | |
| " | |
| Difference:** The difference between CODETERM4 and CODETERM5 is that CODETERM6 is thread-safe.",p | |
| So when the application needs to be run only in a single thread then it is better to use CODETERM7 .,o | |
| CODETERM8 is more efficient than CODETERM9 .,p | |
| " | |
| If your string is not going to change use a String class because a CODETERM10 object is immutable.",o | |
| " | |
| If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a CODETERM11 is good enough.",p | |
| " | |
| If your string can change, and will be accessed from multiple threads, use a CODETERM12 because CODETERM13 is synchronous so you have thread-safety.",p | |
| "Also, using String for logic operations is rather slow, and is not advised at all, since the JVM converts the String to a StringBuffer in the bytecode.",n | |
| A lot of overhead is wasted converting from String to StringBuffer and then back to String again.,o | |
| " | |
| You use URL_http://java.sun.com/javase/6/docs/api/java/lang/String.html [CODETERM1] when an immutable structure is appropriate; obtaining a new character sequence from a CODETERM2 may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).",n | |
| " | |
| You use URL_http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html [CODETERM3] when you need to create a mutable character sequence, usually to concatenate several character sequences together.",o | |
| " | |
| You use URL_http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html [CODETERM4] in the same circumstances you would use CODETERM5 , but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).",o | |
| See an example URL_http://java.sun.com/docs/books/tutorial/java/data/buffers.html [here] .,o | |
| "+1, concise answer.",o | |
| "concise, but incomplete, it misses the fundamental reason to use StringBuilder/Buffer and that is to reduce or eliminate the re-allocation and array copy of the regular String concatenation behavior.",o | |
| """You use String when you are dealing with immutable strings"" - doesn't make sense.",o | |
| "Instances of String ARE immutable, so maybe the comment should read ""Use String when the memory usage due to immutability doesn't matter"".",n | |
| The accepted answer covers it's bases pretty well.,p | |
| @fooMonster I've edited the answer.,o | |
| " | |
| Basics:** CODETERM1 is an immutable class, it can't be changed.",o | |
| "URL_http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html [CODETERM2] is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a CODETERM3 CODETERM4 is the original synchronized version of CODETERM5 You should prefer CODETERM6 in all cases where you have only a single thread accessing your object.",p | |
| " | |
| Details:** Also note that CODETERM7 aren't magic, they just use an Array as a backing object and that Array has to be re-allocated when ever it gets full.",o | |
| Be sure and create your CODETERM8 objects large enough originally where they don't have to be constantly re-sized every time CODETERM9 gets called.,p | |
| The re-sizing can get very degenerate.,n | |
| It basically re-sizes the backing Array to 2 times its current size every time it needs to be expanded.,o | |
| This can result in large amounts of RAM getting allocated and not used when CODETERM10 classes start to grow large.,o | |
| In Java CODETERM11 uses a CODETERM12 behind the scenes.,o | |
| So for simple cases there is no benefit of declaring your own.,p | |
| "But if you are building CODETERM13 objects that are large, say less than 4k, then declaring CODETERM14 is much more efficient than concatenation or using the URL_http:/ /java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html#StringBuilder%28% 29 [default] which is only 16 characters.",p | |
| If your CODETERM15 is going to be less than 10k then initialize it with the constructor to 10k to be safe.,o | |
| "But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array.",o | |
| So initializing high is better than to low.,n | |
| "In the auto re-size case, at the 17th character the backing Array gets re- allocated and copied to 32 characters, at the 33th character this happens again and you get to re-allocated and copy the Array into 64 characters.",o | |
| "You can see how this degenerates to | |
| of re-allocations and copies which is what you really are trying to avoid using CODETERM16 in the first place.",n | |
| This is from the JDK 6 Source code for AbstractStringBuilder CODESNIPPET_JAVA1 .,o | |
| A best practice is to initialize the CODETERM17 a little bit larger than you think you are going to need if you don't know right off hand how big the CODETERM18 will be but you can guess.,n | |
| One allocation of slightly more memory than you need is going to be better than lots of re-allocations and copies.,n | |
| "Also beware of initializing a CODETERM19 with a CODETERM20 as that will only allocated the size of the String + 16 characters, which in most cases will just start the degenerate re-allocation and copy cycle that you are trying to avoid.",n | |
| The following is straight from the Java 6 source code.,o | |
| CODESNIPPET_JAVA2 .,o | |
| "If you by chance do end up with an instance of CODETERM21 that you didn't create and can't control the constructor that is called, there is a way to avoid the degenerate re-allocate and copy behavior.",n | |
| Call URL_http://java.sun.c om/javase/6/docs/api/java/lang/StringBuilder.html#ensureCapacity%28int%29 [CODETERM22] with the size you want to ensure your resulting CODETERM23 will fit into.,o | |
| " | |
| Alternatives:** Just as a note, if you are doing really | |
| CODETERM24 building and manipulation, there is a much more performance oriented alternative called URL_http://ahmadsoft.org/ropes/ [Ropes] .",o | |
| "Another alternative, is to create a CODETERM25 implemenation by sub- classing CODETERM26 , and adding counters to track the number of characters on every CODETERM27 and other mutation operations of the list, then override CODETERM28 to create a CODETERM29 of the exact size you need and loop through the list and build the output, you can even make that CODETERM30 an instance variable and 'cache' the results of CODETERM31 and only have to re-generate it when something changes.",o | |
| "Also don't forget about CODETERM32 when building fixed formatted output, which can be optimized by the compiler as they make it better.",p | |
| "Does String x | |
| ""A"" + ""B""; really compile to be a StringBuilder?",o | |
| "Why wouldn't it just compile to String x | |
| ""AB"";, it should only use a StringBuilder if the components aren't known at compile time.",o | |
| "it might optimize the String constants out, I can't recall from the last time decompiled the byte code, but I do know that if there are any variables in there it will use a StringBuilder implementation for sure.",o | |
| You can download the JDK source code and find out yourself.,o | |
| """A"" + ""B"" is a contrived example for sure.",o | |
| I was wondering about String.format().,o | |
| I haven't ever really seen it being used in projects.,o | |
| Usually it's the StringBuilder.,o | |
| "Well, usually it's actually ""A"" + ""B"" + ""C"" because people are lazy ;) I tended to always use a StringBuilder, even if it was only two strings being concatenated, because in future, perhaps more strings would be appended.",p | |
| "I never used String.format() mainly because I never remembered what JDK it was introduced - I see it's JDK1.5, I'd use it in favour of the other options.",o | |
| This is a very good article URL_http://kaioa.com/node/59 [ URL_http://kaioa.com/node/59 ] .,p | |
| better article URL_http://java.sun.com/developer/technicalArticles/Interviews/comm unity/kabutz_qa.html.,o | |
| "Hi fuzzy lollipop,I do not understand your intension.",o | |
| If the article you have posted is better doesn't mean that my article is wrong.,n | |
| You should give -1 only if it is giving faulty info.,o | |
| @Sujee :Yours is better +1.,o | |
| "Do you mean, for concatenation?",o | |
| Real world example: _You want to create a new string out of many others_.,o | |
| For instance to send a message: String CODESNIPPET_JAVA1 .,o | |
| StringBuilder CODESNIPPET_JAVA2 .,o | |
| Or CODESNIPPET_JAVA3 .,o | |
| "StringBuffer ( the syntax is exactly as with StringBuilder, the effects differ ) About CODETERM1 vs. CODETERM2 The former is synchonized and later is not.",o | |
| "So, if you invoke it several times in a single thread ( which is 90% of the cases ), CODETERM3 will run | |
| faster because it won't stop to see if it owns the thread lock.",p | |
| "So, it is recommendable to use CODETERM4 ( unless of course you have more than one thread accessing to it at the same time, which is rare ) CODETERM5 concatenation ( _using the + operator_ ) may be optimized by the compiler to use CODETERM6 underneath, so, it not longer something to worry about, in the elder days of Java, this was something that everyone says should be avoided at all cost, because every concatenation created a new String object.",p | |
| "Modern compilers don't do this anymore, but still it is a good practice to use CODETERM7 instead just in case you use an ""old"" compiler.",p | |
| " | |
| Just for who is curious, this is what the compiler does for this class: CODESNIPPET_JAVA4 .",o | |
| javap -c StringConcatenation CODESNIPPET_JAVA5 .,o | |
| "Lines numbered 5 - 27 are for the String named ""literal"" Lines numbered 31-53 are for the String named ""builder"" Ther's no difference, exactly the | |
| code is executed for both strings.",o | |
| this is a really bad example.,n | |
| "Initializing the StringBuilder with "" Dear "" means the first .append() will cause a reallocation and copy.",p | |
| "Completely negating any efficiency that you are trying to gain over ""normal"" concatenation.",o | |
| A better example would to be to create it with a initial size that will hold the entire contents of the final String.,o | |
| It is NOT generally a good practice to use a StringBuilder to do String concatenation on the right-hand side of the assignment.,p | |
| Any good implementation will use a StringBuilder behind the scenes as you say.,p | |
| "Furthermore, your example of ""a"" + ""b"" would be compiled into a single literal ""ab"" but if you used StringBuilder it would result in two needless calls to append().",o | |
| "@Mark I didn't mean to use ""a""+""b"" but to say what was a | |
| concatenation* about I change it to be explicit.",o | |
| "What you don't say is, why is not a good practice to do it.",o | |
| That's exactly what ( a modern ) compiler does.,o | |
| "@fuzzy, I agree, specially when you know what the size of the final string would be ( aprox ) .",o | |
| "I don't think it's particularly | |
| practice, but I certainly wouldn't want any recommendation to do that in general.",o | |
| "It's clunky and hard to read, and overly verbose.",n | |
| "Plus, it encourages mistakes like yours where you are breaking up two literals that could otherwise be compiled as one.",n | |
| Only if profiling told me it made a difference would I do it your way.,o | |
| @Mark Got it.,o | |
| "I was thinking more in the | |
| chunk of code like a template""* and not really in every regular string literal.",o | |
| "But yes, I agree, since they do the same thing nowadays, it doesn't make sense ( 10 yrs ago was a reason to reject a change in a code revision ) :).",n | |
| "Personally, I don't think there is any real world use for CODETERM1 .",o | |
| When would I ever want to communicate between multiple threads by manipulating a character sequence?,o | |
| "That doesn't sound useful at all, but maybe I have yet to see the light :) .",o | |
| "Also, CODETERM1 is thread-safe, which CODETERM2 is not.",p | |
| "So in a real-time situation when different threads are accessing it, CODETERM3 could have an undeterministic result.",o | |
| "Note that if you are using Java 5 or newer, you should use CODETERM1 instead of CODETERM2 .",o | |
| "From the API documentation: | |
| As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, CODETERM3 .",o | |
| "The CODETERM4 class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.",p | |
| "In practice, you will almost never use this from multiple threads at the same time, so the synchronization that CODETERM5 does is almost always unnecessary overhead.",o | |
| "When you are using String, you are making a new String each time you are adding 2 of them.",o | |
| "When you are using StringBuilder, it uses a buffer to make less String addition and will therefore be more performant when you want to add a lot of string one after the other.",o | |
| StringBuffer is the exact same thing as of StringBuilder except that all his method are synchronized.,o | |
| The only use of that class is if you need to share the buffer with multiple thread (which rarely happends).,o | |
| Read/convert an InputStream to a String.,o | |
| "If you have CODETERM1 object, how should you process that object and produce a CODETERM2 ?",o | |
| " | |
| Suppose I have an CODETERM3 that contains text data, and I want to convert this to a CODETERM4 (for example, so I can write the contents of the stream to a log file).",o | |
| What is the easiest way to take the CODETERM5 and convert it to a CODETERM6 ?,o | |
| CODESNIPPET_JAVA1 .,o | |
| "Boy, I'm absolutely in love with Java, but this question comes up so often you'd think they'd just figure out that the chaining of streams is somewhat difficult and either make helpers to create various combinations or rethink the whole thing.",n | |
| You are right.,o | |
| "I tend to use a set of helper classes that do it once for me, so I don't need keep referring to Google or even StackOverflow for the answer.",o | |
| "In this case, I was away from my utility code and couldn't remember exactly how to do it.",o | |
| What better way to open my account on the site.,o | |
| "Yeah, it really shouldn't require so much boilerplate to do something as simple as read strings from a stream.",n | |
| "It's not that difficult, just annoying.",n | |
| @Adam: It really depends on what kind of Stream you're working with.,p | |
| "For instance, System.console().readLine() (new in Java 6) is pretty easy.",p | |
| Same with BufferedReader's readLine().,o | |
| The only hard part is when you don't know how many characters you need to read.,n | |
| The answers to this question only work if you want to read the stream's contents _fully_ (until it is closed).,o | |
| "Since that is not always intended (http requests with a keep-alive connection won't be closed), these method calls block (not giving you the contents).",o | |
| "You | |
| to know and specify the character encoding for the stream, or you | |
| have character encoding bugs, since you will be using a randomly chosen encoding depending on which machine/operating system/platform or version thereof your code is run on.",n | |
| "That is, do | |
| use methods that depend on the platform default encoding.",o | |
| "I don't really know Java, but ""InputStream | |
| "" seems wrong.",n | |
| "@Hello71: It is ok in Java, since the instanceof operator is spelled differently.",o | |
| @Ronald: Erm... never mind that.,o | |
| I must have been partially asleep while writing that.,o | |
| "Here's a way using only standard Java library (note that the stream is not closed, YMMV).",o | |
| CODESNIPPET_JAVA1 .,o | |
| "I learned this trick from URL_http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html [""Stupid-Scanner-tricks""] article.",o | |
| "The reason it works is because URL_http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html [Scanner] iterates over tokens in the stream, and in this case we separate tokens using ""beginning of the input boundary"" (\A) thus giving us only one token for the entire contents of the stream.",p | |
| " | |
| if you need to be specific about the input stream's encoding, you can provide the second argument to CODETERM1 constructor that indicates what charset to use (e.g.",o | |
| """UTF-8"").",o | |
| " | |
| Hat tip goes also to URL_http://stackoverflow.com/users/68127/jacob-gabrielson [Jacob,] who once pointed me to the said article.",o | |
| " | |
| Thanks to a suggestion from URL_http://stackoverflow.com/users/101272/patrick [Patrick] , made the function more robust when handling an empty input stream.",p | |
| " | |
| more edit:** nixed try/catch, Patrick's way is more laconic.",n | |
| "Thanks, for my version of this I added a finally block that closes the input stream, so the user doesn't have to since you've finished reading the input.",o | |
| Simplifies the caller code considerably.,o | |
| "I think this should be public | |
| String convertStreamToString .",o | |
| "@PavelRepin @Patrick in my case, an empty inputStream caused a NPE during Scanner construction.",o | |
| "I had to add if (is | |
| null) return """"; right at the beginning of the method; I believe this answer needs to be updated to better handle null inputStreams.",o | |
| The problem with this approach I find is it does not handle CR/LF translations too well.,p | |
| So you have to make sure your line endings are consistent.,o | |
| "@ArchimedesTrajano does IOUtils.copy(inputStream, writer, encoding) deal with CR/LF translations better?",o | |
| I think CR/LF consistency is entirely unrelated issue.,o | |
| Not saying it isn't an issue.,o | |
| "For Java 7 you can close in a try-with: try(java.util.Scanner s | |
| new java.util.Scanner(is)) { return s.useDelimiter(""\\\A"").hasNext() ?",o | |
| "s.next() : """"; }.",o | |
| Unfortunately this solution seems to go and lose the exceptions thrown in my underlying stream implementation.,o | |
| excellent trick!,p | |
| any ideas about performance of Scanner vs reading the stream in a more verbose way?,o | |
| @Igal I didn't measure it.,o | |
| "If you do, gist it and I'll append your results to the answer.",o | |
| A nice way to do this is using URL_http://commons.apache.org/ [Apache-commons] URL_http://commons.apache.org/proper/commons- io/apidocs/org/apache/commons/io/IOUtils.html [IOUtils] to copy the CODETERM1 into a CODETERM2 ... something like CODESNIPPET_JAVA1 .,p | |
| "Alternatively, you could use CODETERM3 if you don't want to mix your Streams and Writers .",o | |
| I hope IOUtils takes an optional Charset (or at least the name of the encodding to use).,o | |
| Best not to leave this kind of thing to chance :).,p | |
| Haha - of course it does!,o | |
| "URL_http://commons.apache.org/io/apidocs/org/apache/comm ons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.Writer,%20java.lang.St ring).",o | |
| Why copy the inputstream to a writer?,o | |
| Why not just use a reader?,o | |
| "Or read all bytes and use new String(bytes, charset)?",o | |
| "You really, | |
| should be using IOUtils.copy(inputStream, writer, encoding); unless you really, | |
| know what you're doing, which people never do with character encoding related programming.",o | |
| "Or in this case, IOUtils.toString(inputStream, encoding).",o | |
| "Methods that use the platform default encoding are almost never correct to use, like every other method that gives different results depending on which machine/operating system/platform or version thereof it is run on.",n | |
| I think the below answer (IOUtils.toString()) is simpler since there is no need for a StringWriter.,p | |
| A quick but not clean solution.,p | |
| I would rather prefer a solution without adding additional libraries as mentioned in the post below: URL_http://stackoverflow.com/a/6938341/411951 .,p | |
| "Only works for closes streams, I believe.",p | |
| Apache Commons allows: CODESNIPPET_JAVA1 .,o | |
| "Of course, you could choose other character encodings besides UTF-8.",o | |
| "Also see: ( URL_http://commons.apache.org/proper/commons-io/javadocs/api-2.4/o rg/apache/commons/io/IOUtils.html#toString%28java.io.InputStream,%20java.lang.",o | |
| String [Docs] ) .,o | |
| IOUtils.toString is deprecated.,n | |
| No it isn't.,o | |
| Only the version that takes a byte[] parameter is.,o | |
| "Also, there is a method that only take a inputStream argument, if you are find with the default encoding.",o | |
| "@Guillaume Cot I guess the message here is that you never should be ""fine with the default encoding"", since you cannot be sure of what it is, depending on the platform the java code is run on.",o | |
| @Per Wiklander I disagree with you.,o | |
| Code that is going to work on a single could be quite sure that default encoding will be fine.,o | |
| "For code that only open local file, it is a reasonable option to ask them to be encoded in the platform default encoding.",o | |
| This function is corrupting my input stream.,n | |
| To save anyone the hassle of Googling - org.apache.commons commons-io 1.3.2 .,o | |
| I don't know that I'd say the default encoding is NEVER fine.,o | |
| "On the other hand, I disagree with Guillaume also.",o | |
| "In fact, it's not a matter of fine or not; it's a matter of which is CORRECT.",p | |
| "In the situation where you want to take something that you know is encoded in the default encoding for the platform, then the default version is correct.",p | |
| "However, I believe this is a very rare use case.",o | |
| "The more normal case is that you need to specify what the encoding is, so specifying the encoding is correct.",p | |
| There is no optional case: either one or (more likely) the other is correct.,p | |
| "Also little improvement would be to use apache io (or other) constant for character encoding instead of using plain string literal - eg: IOUtils.toString(myInputStream, Charsets.UTF_8);.",n | |
| Taking into account file one should first get a CODETERM1 instance.,o | |
| "This can then be read and added to a CODETERM2 (we don't need CODETERM3 if we are not accessing it in multiple threads, and CODETERM4 is faster).",p | |
| "The trick here is that we work in blocks, and as such don't need other buffering streams.",o | |
| The block size is parameterized for run-time performance optimization.,o | |
| CODESNIPPET_JAVA1 .,o | |
| I like how this works without adding more libraries to your project.,p | |
| is there a chance to broke multi-bytes character in this solution?,o | |
| This solution uses multibyte characters.,o | |
| The example uses the UTF-8 encoding that allows expression of the full unicode range (Including Chinese).,o | |
| "Replacing ""UTF-8"" with another encoding would allow that encoding to be used.",o | |
| @User1 - I like using libraries in my code so I can get my job done faster.,p | |
| "It's awesome when your managers say ""Wow James!",p | |
| "How did you get that done so fast?!"".",o | |
| "But when we have to spend time reinventing the wheel just because we have misplaced ideas about including a common, reusable, tried and tested utility, we're giving up time we could be spending furthering our project's goals.",p | |
| "When we reinvent the wheel, we work twice as hard yet get to the finish line much later.",o | |
| "Once we're at the finish line, there is no one there to congratulate us.",p | |
| "When building a house, don't build the hammer too.",o | |
| "Sorry, after re-reading my comment, it comes off a little arrogant.",n | |
| "I just think it's important to have a good reason to avoid libraries and that the reason is a valid one, which there very well could be :).",p | |
| isn't it better to close stream/streamreader ?,o | |
| "Yes, I guess the reader should be closed at the end.",o | |
| "@jmort253 Many libraries are large, slow but powerful.",n | |
| "However there are many chances that we need a small, fast one.",o | |
| "In our product, I even replaced many JDK classes with our own implement.",o | |
| @coolcfan - I do agree with you on that point.,o | |
| Sometimes speed is of the utmost importance and is a hard requirement.,n | |
| "Many times, good enough is good enough.",p | |
| I question how often we put effort into optimizing something that no one notices.,o | |
| The answer of whether the reward is greater than the cost is a decision not to be taken lightly.,p | |
| Thank you for indicating that there are times when this is necessary.,p | |
| @jmort253 We noticed performance regression after updating some library in our product for several times.,o | |
| Luckily we are building and selling our own product so we don't really have the so called deadlines.,p | |
| "Unfortunately we are building a product that is available on many JVMs, databases and app servers on many operation systems so we have to think for the users using poor machines... And a string operation optimizing can improve the perf by 30~40%.",n | |
| "And a fix: In our product, I even replaced should be 'we even replaced'.",o | |
| "@jmort253 If you would already use apache commons I would say, go for it.",o | |
| "At the same time, there is a real cost to using libraries (as the dependency proliferation in many apache java libraries shows).",o | |
| "If this would be the only use of the library, it would be overkill to use the library.",o | |
| "On the other hand, determining your own buffer size(s) you can tune your memory/processor usage balance.",n | |
| How about this?,o | |
| "InputStream in | |
| _/* your InputStream | |
| is | |
| new InputStreamReader(in);StringBuilder sb=new StringBuilder();BufferedReader br | |
| new BufferedReader(is);String read | |
| br.readLine();while(read != null) { //System.out.println(read); sb.append(read); read | |
| sb.toString(); .",o | |
| Doesn't answer the question.,o | |
| "This shows how to iterate over the lines in a stream, not how to read the entire stream into a string.",o | |
| you can concat all string in to one String.that is simple.....,p | |
| "The thing is, you're first splitting into lines, and then undoing that.",o | |
| It's easier and faster to just read arbitrary buffers.,p | |
| "Also, readLine does not distinguish between \n and \r, so you cannot reproduce the exact stream again.",o | |
| "@PauldeVrieze how many lines, and how quickly do you need to process them!?",o | |
| "I would hazard a guess that any performance loss would be small, or could be handled by every once in a while logging them to a file and destroying the old String obj's.",o | |
| If you are using Google-Collections/Guava you could do the following: CODESNIPPET_JAVA1 .,o | |
| Note that the second parameter (i.e.,o | |
| "Charsets.UTF_8) for the CODETERM1 isn't necessary, but it is generally a good idea to specify the encoding if you know it (which you should!",p | |
| ) .,o | |
| "@harschware: Given the question was: ""If you have java.io.InputStream object how should you process that object and produce a String?",o | |
| """ I assumed that a stream is already present in the situation.",o | |
| "You didn't explain your answer very well, and had extraneous variables; user359996 said the same thing as you, but much more clearly.",p | |
| it returns to me boxes instead of actual text characters.,o | |
| plz advise.,o | |
| "+1 for guava, -1 for not specifying the encoding of the input stream.",o | |
| eg.,o | |
| "new InputStreamReader(stream, ""UTF-8"").",o | |
| Downvoting as doesn't close inputstream.,n | |
| "@plasma147 Instead of downvoting, consider editing the example (I just submitted that, adding Closeables.closeQuietly(stream);).",n | |
| "@Chris Noldus On the other hand, some people already have guava in their project, like me, and think this solution is more elegant than the sdk-only version.",p | |
| CODESNIPPET_JAVA1 .,o | |
| Works well on Android in comparison with other answers which work only in enterprise java.,p | |
| That's where it came from... My Android tools library :).,o | |
| "Crashed in Android with OutOfMemory error on the "".write"" line, every time, for short strings.",n | |
| What on earth do you copy...???,o | |
| I copy 5 - 10 mb files easy...,p | |
| Please specify the encoding - it's a very common bug.,n | |
| I've added the encoding.,o | |
| "just as a side note, the original readFully method I have in my code does not return String, it returns byte[] for a more general purpose functionality.",o | |
| Implementing the new String(...) with encoding is the responsibility of the on that uses the API!.,o | |
| "Here's the most elegant, pure-Java (no library) solution I came up with after some experimentation: CODESNIPPET_JAVA1 .",p | |
| Isn't there a reader.close() missing?,o | |
| Ideally with try/finally...,o | |
| "@TorbenKohlmeier, readers and buffers don't need to be closed.",o | |
| The provided InputStream should be closed by the caller.,o | |
| Don't forget to mention that there's a more preferable constructor in InputStreamReader that takes a CharSet.,p | |
| newlines are gone after this.,o | |
| How about: CODESNIPPET_JAVA1 .,o | |
| "As an alternative to the Commons libraries, Google's excellent URL_http://code.google.com/p/guava-libraries/ [guava-libraries] let you do this fairly concisely; given an _InputStream_ named _inputStream_: CODESNIPPET_JAVA1 .",p | |
| "Note this method is particularly convenient if, instead of an | |
| you have a | |
| ",o | |
| "For example, if you're getting the body of an HTTP request via | |
| it's just | |
| request.getReader() )**.",o | |
| "Here's more-or-less sampath's answer, cleaned up a bit and represented as a function: CODESNIPPET_JAVA1 .",p | |
| use a StringBuilder.,o | |
| Changed to use StringBuilder.,o | |
| Thanks @trnl.,o | |
| again no encoding.,o | |
| "I ran some timing tests because time matters, always.",o | |
| I attempted to get the response into a String 3 different ways.,o | |
| (shown below) I left out try/catch blocks for the sake readability.,o | |
| "To give context, this is the preceding code for all 3 approaches: CODETERM1 CODETERM2 CODETERM3 CODETERM4 1) CODETERM5 2) CODETERM6 CODETERM7 CODETERM8 CODETERM9 CODETERM10 CODETERM11 CODETERM12 CODETERM13 CODETERM14 3) CODETERM15 CODETERM16 CODETERM17 CODETERM18 So, after running 500 tests on each approach with the same request/response data, here are the numbers.",o | |
| "Once again, these are my findings and your findings may not be exactly the same, but I wrote this to give some indication to others of the efficiency differences of these approaches.",o | |
| "Ranks: Approach | |
| Approach | |
| - 2.6% slower than | |
| Approach | |
| - 4.3% slower than | |
| Any of these approaches is an appropriate solution for grabbing a response and creating a String from it.",n | |
| "2) contains an error, it adds always ""null"" at the end of the string as you are always makeing one more step then necessary.",o | |
| Performance will be the same anyway I think.,o | |
| "This should work:String read | |
| null; StringBuffer sb | |
| new StringBuffer();while((read | |
| br.readLine()) != null) { sb.append(read);}.",o | |
| If you can't use Commons IO (FileUtils/IOUtils/CopyUtils) here's an example using a BufferedReader to read the file line by line: CODESNIPPET_JAVA1 .,o | |
| or if you want raw speed I'd propose a variation on what Paul de Vrieze suggested (which avoids using a StringWriter (which uses a StringBuffer internally) : CODESNIPPET_JAVA2 .,o | |
| "In order to make your code work, I had to use this.getClass().getClassLoader().getResourceAsStream() (using Eclipse with a maven project).",o | |
| "If you were feeling adventurous, you could mix Scala and Java and end up with this: CODESNIPPET_JAVA1 .",o | |
| Mixing Java and Scala code and libraries has it's benefits.,o | |
| See full description here: URL_http://stackoverflow.com/q/5221524/828757 [Idiomatic-way-to-convert-an-InputStream-to-a-String-in-Scala] .,o | |
| CODESNIPPET_JAVA1 .,o | |
| Please give a description on what you are trying to accomplish.,o | |
| CODESNIPPET_JAVA1 .,o | |
| here s is your InputStream object which will get convert into String :) .,o | |
| make sure to close the streams at end if you use Stream Readers CODESNIPPET_JAVA1 .,o | |
| Well you can program it for yourself.. it's not complicated.. CODESNIPPET_JAVA1 .,o | |
| "Since you're using buffer variable locally with no chance of being shared across multiple threads you should consider changing its type to StringBuilder, to avoid the overhead of (useless) synchronization.",o | |
| That's a good point alex!.,p | |
| I thing that we both agree that this method isn't thread-safe in many ways.,n | |
| Even the input stream operations aren't thread-safe.,n | |
| The below code worked for me.,o | |
| CODESNIPPET_JAVA1 .,o | |
| "Please note, according to Java docs, the available() method might not work with InputStream but always works with BufferedInputStream.In case you don't want to use available() method we can always use the below code CODESNIPPET_JAVA2 .",p | |
| I am not sure if there will be any encoding issues.,o | |
| "Please comment, if there will be any issues with the code .",o | |
| "The whole point of using InputStream is, that a) you don't know the length of the _complete_ stream (which bails out anything depending on available) and b) the stream can be anything - a file, a socket, something internal (which bails out anything based on File.size()).",o | |
| Regarding available: This will cut off data if the stream is longer than the buffer size.,o | |
| You can use apache commons.In the IOUtils you can find the toString metod with 3 helpfull implementations.,p | |
| CODESNIPPET_JAVA1 .,o | |
| JDK 7/8 answer that closes the stream and still throws an IOException: CODESNIPPET_JAVA1 .,o | |
| CODESNIPPET_JAVA1 .,o | |
| See the commet by ChristofferHammarstrm in the answer by HarryLime.,o | |
| "First ,you have to know the encoding of string that you want to convert.Because the java.io.InputStream operates an underlying array of bytes,however,a string is composed by a array of character that needs an encoding, e,g.",o | |
| "UTF-8,the JDK will take the default encoding that is taken from System.getProperty(""file.encoding"",""UTF-8""); CODESNIPPET_JAVA1 .",o | |
| "If inputStream's byte array is very big, you could do it in loop.",o | |
| :EOF .,o | |
| "From the javadocs: Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not.",o | |
| It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.,n | |
| This is a bad idea!,n | |
| Don't be burnt by misunderstanding what available() gives you.,n | |
| "As mentioned above, available() is not the way to go.",o | |
| It's highly recommended to ignore this method so much so that you could treat this to be a restricted API.,p | |
| Quick and easy: CODESNIPPET_JAVA1 .,p | |
| I get java.io.StreamCorruptedException: invalid stream header.,n | |
| "ObjectInputStream is about deserialization, and the stream have to respect the serialization protocol to work, which may not always true in the context of this question.",o | |