Css file in java

CSS Parser in Java [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Is there anything like Jsoup but instead of parsing HTML, I need to parse CSS, is there a parser similar to that that will create a Document model of a CSS? That perhaps can be used to iterate to nodes? What I need to do is to find and replace «url» in the CSS file. And with html this is quite easy with Jsoup. However I am not sure if this will be possible with CSS. If there are no such parser exist what are the options?

4 Answers 4

I’m getting java.lang.NoClassDefFoundError: org/w3c/css/sac/DocumentHandler when using this CSS parser, do I need to include additional jar apart from the cssparser-0.9.6.jar?

I just rolled out my own CSS Stream Parser for Java, available on github. What sets this parser apart includes:

  • It is a stream parser, so the parser handler will receive notification of all new content immediately after each item has been parsed
  • Full support for all currently-documented At-Rules
  • Custom classes TokenSequence and Token simplify processes for handling selectors, etc.
  • Easy to use and to understand
  • Useful for validation or for more advanced applications
  • Scalable: designed to be able to handle changes to CSS definitions.
Читайте также:  Simple android apps in java

For your problem, just use the basic parsing technique:

but override some methods in DefaultCSSHandler to look for the identifier you need.

@xybrek yes, I am currently using this parser to develop CSS support for droidQuery. I stumbled upon the linked CSS parser before, and found it confusing. It also uses a lot of libraries that if I remember are not easy to find. My Parser does not use SAC, it is standalone, so once you download it, it is easy to run. Furthermore, I made sure to document well and, because it is intended to be used for more than a validator, it is should be easy to understand how to handle parsed data in a similar way as xml parsing.

A CSS library for reading and writing CSS2 and CSS3 files in Java is ph-css from https://github.com/phax/ph-css It is based on a JavaCC grammar and supports both CSS2 as well as CSS3 and additionally lets you parse HTML style attributes.

It supports the most common hacks "*", "_" and "$" which are not spec compliant It supports CSS math - the calc() expression It supports the @page rule It supports the CSS3 media queries It supports @viewport rules It supports @keyframes rules It supports @supports rules - quite new It supports the @namespace rules You can get source location information for the different elements (line + column number for start and end - both for the tag as well as for the complete construct) 

Источник

Looking for a CSS Parser in java [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

I’m looking for a CSS Parser in java. In particular my requirement is, for a given node/element in an HTML document, to be able to ask/get the css styles for that element from the Parser. I know there is the W3C SAC interface and one or 2 implementations based on this — but turorials/examples appear non-existant. Any help/points in right direction much appreciated. Thanks

8 Answers 8

I’ve used CSSParser and I like it- it gives good feedback on errors as well.

Here’s some sample code I’ve found and modified:

package com.dlogic; import com.steadystate.css.parser.CSSOMParser; import org.w3c.css.sac.InputSource; import org.w3c.dom.css.CSSStyleSheet; import org.w3c.dom.css.CSSRuleList; import org.w3c.dom.css.CSSRule; import org.w3c.dom.css.CSSStyleRule; import org.w3c.dom.css.CSSStyleDeclaration; import java.io.*; public class CSSParserTest < protected static CSSParserTest oParser; public static void main(String[] args) < oParser = new CSSParserTest(); if (oParser.Parse("design.css")) < System.out.println("Parsing completed OK"); >else < System.out.println("Unable to parse CSS"); >> public boolean Parse(String cssfile) < FileOutputStream out = null; PrintStream ps = null; boolean rtn = false; try < // cssfile accessed as a resource, so must be in the pkg (in src dir). InputStream stream = oParser.getClass().getResourceAsStream(cssfile); // overwrites and existing file contents out = new FileOutputStream("log.txt"); if (out != null) < //log file ps = new PrintStream( out ); System.setErr(ps); //redirects stderr to the log file as well >else < return rtn; >InputSource source = new InputSource(new InputStreamReader(stream)); CSSOMParser parser = new CSSOMParser(); // parse and create a stylesheet composition CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null); //ANY ERRORS IN THE DOM WILL BE SENT TO STDERR HERE!! // now iterate through the dom and inspect. CSSRuleList ruleList = stylesheet.getCssRules(); ps.println("Number of rules: " + ruleList.getLength()); for (int i = 0; i < ruleList.getLength(); i++) < CSSRule rule = ruleList.item(i); if (rule instanceof CSSStyleRule) < CSSStyleRule styleRule=(CSSStyleRule)rule; ps.println("selector:" + i + ": " + styleRule.getSelectorText()); CSSStyleDeclaration styleDeclaration = styleRule.getStyle(); for (int j = 0; j < styleDeclaration.getLength(); j++) < String property = styleDeclaration.item(j); ps.println("property: " + property); ps.println("value: " + styleDeclaration.getPropertyCSSValue(property).getCssText()); ps.println("priority: " + styleDeclaration.getPropertyPriority(property)); >>// end of StyleRule instance test > // end of ruleList loop if (out != null) out.close(); if (stream != null) stream.close(); rtn = true; > catch (IOException ioe) < System.err.println ("IO Error: " + ioe); >catch (Exception e) < System.err.println ("Error: " + e); >finally < if (ps != null) ps.close(); >return rtn; > > 

Источник

Reading the content of a css file using Java

I am trying to read a css file, find out the css classes and their definition and then save it in a csv file with its class name and description. Using Java, the following I have css file, common.css.

/* CSS Document */ .Page < background-color: #F4EEE0; background-image: none; margin: 0px 0px 0px 0px; scrollbar-face-color: #DEAC64; scrollbar-highlight-color: #FFFFFF; scrollbar-shadow-color: #805822; scrollbar-3dlight-color: #B47F36; scrollbar-arrow-color: #805822; scrollbar-darkshadow-color: #7188AA; scrollbar-base-color: #F4EEE0; scrollbar-track-color: #E8C490; >a.PageLinkTrail < font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; font-style: normal; font-weight: bold; color: #805822; text-decoration:none; >a.PageLinkTrail:hover < font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; font-style: normal; font-weight: bold; color: #805822; text-decoration:underline; >.IconSpacing a:hover
.Page a.PageLinkTrail a.PageLinkTrail:hover 

I want to save it on a csv file. How should I use Java to get the CSS content such as name and definition? This is the part of the solution I am having most trouble completing at the moment. I have written a flowing code

package com.tufan.digite.Count; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GetAllCssFiles < public static void main(String args[]) throws IOException < try < FileInputStream fstream = new FileInputStream("D:/digite/work/digite/WEBUI/common/theme1/common.css"); DataInputStream dis = new DataInputStream(fstream); FileChannel fc = fstream.getChannel(); ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,(int) fc.size()); Charset cs = Charset.forName("8859_1"); CharsetDecoder cd = cs.newDecoder(); CharBuffer cb = cd.decode(bb); String strLine; String content = ".MainNav a:hover< float:left; width:70px; height:65px; border-top: 2px Solid #F4E6CC; border-bottom: 2px Solid #805822; border-left: 2px Solid #F4E6CC; border-right: 2px Solid #805822; margin: 0px 0px 0px 0px; align:center; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: bold; color: #FFFFFF; text-decoration: none; text-align: center; background:#C99349; background-image: url(../../images/hor_nav_bg.gif); background-repeat: repeat-X; padding:4px; clear:left; >"; Pattern p = Pattern.compile("([a-zA-Z_0-9 | -|:|;|\n\t]*)(\\<[\n\t]*[a-zA-Z_0-9 | -|:|;|\n\t]*\\>)"); Matcher matcher = p.matcher(cb); while (matcher.find()) < String selector = matcher.group(1); String definition = matcher.group(2); System.out.println("selector:" + selector + "Definition" + definition); >> catch (Exception e) < e.printStackTrace(); >>> 

Источник

How to Use External CSS Files in a JavaFX Application

In JavaFX, there are many ways to skin a application, I’ll take a look at three methods of dynamically loading a css file into your JavaFX application.

There are a many advantages to placing your style rules inside of a CSS file; It keeps your style rules in one central location, allows the application’s logic and design to be seperated from each other, as well as allowing for the look of the application to be changed on the fly without needing to recompile the jar each time. You can of course set the style of an individual Node using Node.setStyle(), but as we’ve found in our combined Swing and JavaFX Viewer, this can start to get out of hand and at some point you need to reign it in.

The example application I’m using can be found on my Github.

nocss

1. From Compiled Jar

fromjar

This stylesheet is the one included in the compiled jar for this project. The code to load it is as follows:

String css = DynamicCSS.class.getResource("/jarcss.css").toExternalForm(); scene.getStylesheets().clear(); scene.getStylesheets().add(css);

The last two lines are fairly straightforward: Remove all current stylesheets in use and use our one. The first line gets the absolute path on disk to the file inside of the jar file with a string representation with a form similar to “jar:path/to/application.jar!/stylesheet.css” which tells the application that the file is located inside of a compiled java application.

2. From File

fromfile

You can also load a stylesheet for your application from your file system. This can be done by changing:

File f = new File("filecss.css"); scene.getStylesheets().clear(); scene.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));

There are two things to be aware of when loading from disk; First of all, JavaFX uses URLs to resolve the file location, so the prefix “file:///” is needed when loading from disk. Secondly, you can’t mix and match your slashes, so backslashes have to be converted to forward slashes.

3. From the Web

fromweb

As we can add CSS via URLs, we can also load in CSS files from the internet. To do this, we simply provide the location of the file:

scene.getStylesheets().clear(); scene.getStylesheets().add("http://www.jpedal.org/simon/dynamiccss/webcss.css");

Conclusion

There are multiple ways of setting a personalised style in JavaFX using CSS. There are no wrong answers to which one you want to use, but ultimately it comes down to where you want control to lie. If you want control over the style then options 1 and 3 would be the best depending on the context – Option 1 if you want the CSS to be updated with every build or 3 if you want the CSS to be consistent across all versions. If you want the user to have more control over the CSS, then option 2 is the best solution.

Are you a Developer working with PDF files?

Simon Lissack Simon Lissack is a developer at IDR Solutions, working on JavaFX, Android and the Cloud Conversion service.

Источник

Оцените статью