List of usage examples for org.jdom2 Element getAttributeValue
public String getAttributeValue(final String attname)
This returns the attribute value for the attribute with the given name and within no namespace, null if there is no such attribute, and the empty string if the attribute value is empty.
From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java
private BufferedImage processTextElement(BufferedImage image, Element textElement) throws IOException, IM4JavaException, InterruptedException { int x = Integer.valueOf(textElement.getAttributeValue("X")); int y = Integer.valueOf(textElement.getAttributeValue("Y")); int width = Integer.valueOf(textElement.getAttributeValue("Width")); int height = Integer.valueOf(textElement.getAttributeValue("Height")); String alignment = textElement.getAttributeValue("TextAlignment"); boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase()); boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias"); String textColor = "#" + Integer.toHexString(Integer.valueOf(textElement.getAttributeValue("ForeColor"))).substring(2); // now get the text String text = textElement.getAttributeValue("Text"); // if text matches pattern of %VARIABLE%{MODIFIER} logger.info("parsing token {}", text); Matcher matcher = pattern.matcher(text); int start = 0; while (matcher.find(start)) { // apply modification text = text.replace(matcher.group(), applyModifier(matcher.group())); start = matcher.end();/*from www.ja v a 2 s .c om*/ } Stream2BufferedImage s2b = new Stream2BufferedImage(); convert.setOutputConsumer(s2b); IMOperation op = new IMOperation(); op.background("none"); op.size(width, height); op = parseText(op, text, textElement.getAttributeValue("Font"), textColor); op.gravity(gravityMap.get(alignment)); op.addImage("png:-"); convert.createScript("/tmp/images/myscript.sh", op); convert.run(op); BufferedImage tmpImage = s2b.getImage(); // compose over current image CompositeCmd command = new CompositeCmd(); op = new IMOperation(); // the image is alrready resized, so we have to fill only x and y op.geometry(null, null, x, y); // compose putting source image over destination image op.compose("Src_Over"); op.addImage(2); op.addImage("png:-"); s2b = new Stream2BufferedImage(); command.setOutputConsumer(s2b); command.run(op, tmpImage, image); // retrieve image image = s2b.getImage(); // logger.info("Saving image..."); // ScreenImage.writeImage(image, "/tmp/images/image" + textElement.getAttributeValue("Name") + ".png"); // // BufferedImage tmpImage; // if (width > 0 && height > 0) { // // create a transparent tmpImage // tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // } else { //// FontMetrics fm = g2.getFontMetrics(font); //// Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds(); //// we need to create a transparent image to paint //// tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_RGB); // } //// Graphics2D g2d = tmpImage.createGraphics(); //// g2d.setFont(font); // //// g2d.setColor(textColor); //// drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline); //// tmpImage = processActions(textElement, tmpImage); ////// Graphics2D g2d = tmpImage.createGraphics(); //// // set current font //// g2.setFont(font); ////// g2d.setComposite(AlphaComposite.Clear); ////// g2d.fillRect(0, 0, width, height); ////// g2d.setComposite(AlphaComposite.Src); //// // TODO: we have to parse it //// int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth")); //// // the color of the outline //// if (strokeWidth > 0) { ////// Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor"))); ////// AffineTransform affineTransform; ////// affineTransform = g2d.getTransform(); ////// affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2 ////// + (outlineBounds.height / 2)); ////// g2d.transform(affineTransform); ////// // backup stroke width and color ////// Stroke originalStroke = g2d.getStroke(); ////// Color originalColor = g2d.getColor(); ////// g2d.setColor(strokeColor); ////// g2d.setStroke(new BasicStroke(strokeWidth)); ////// g2d.draw(shape); ////// g2d.setClip(shape); ////// // restore stroke width and color ////// g2d.setStroke(originalStroke); ////// g2d.setColor(originalColor); //// } ////// // get the text color //// Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); //// g2.setColor(textColor); ////// g2d.setBackground(Color.BLACK); ////// g2d.setStroke(new BasicStroke(2)); ////// g2d.setColor(Color.WHITE); //// // draw the text //// //// drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline); //// g2.drawString(text, x, y); //// Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position //// FontMetrics fm = g2.getFontMetrics(); //// FontRenderContext frc = g2.getFontRenderContext(); //// TextLayout tl = new TextLayout(text, g2.getFont(), frc); //// AffineTransform transform = new AffineTransform(); //// transform.setToTranslation(rect.getX(), rect.getY()); //// if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) { //// double scaleY //// = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY() //// - tl.getOutline(null).getBounds().getMinY()); //// transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY); //// } //// Shape shape = tl.getOutline(transform); //// g2.setClip(shape); //// g2.fill(shape.getBounds()); // if (antiAlias) { // // we need to restore antialias to none //// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // } //// g2.drawString(text, x, y); // // // alway resize //// BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height); //// tmpImage = scaleFilter.filter(tmpImage, null); // // draw the image to the source //// g2.drawImage(tmpImage, x, y, width, height, null); //// try { //// ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png"); //// } catch (IOException ex) { //// //// } logger.info("{} processed...", textElement.getAttributeValue("Name")); // return processed image return image; }
From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java
private BufferedImage processActions(Element imageElement, BufferedImage tmpImage) throws IM4JavaException, InterruptedException, IOException { BufferedImage result = tmpImage; // verify if there are filters Element actions = imageElement.getChild("Actions"); if (actions != null) { List<Element> filters = actions.getChildren(); for (Element filter : filters) { Stream2BufferedImage s2b = new Stream2BufferedImage(); // TODO: implement filters switch (filter.getName()) { // Crop case "Crop": break; // GlassTable case "GlassTable": break; // Glow case "Glow": break; // GaussianBlur case "GaussianBlur": double sigma = Double.valueOf(filter.getAttributeValue("Radius")); double radius = sigma * 3; convert.setOutputConsumer(s2b); IMOperation op = new IMOperation(); op.addImage();/*from ww w. java2s. c om*/ op.blur(sigma, radius); op.addImage("png:-"); convert.run(op, tmpImage); result = s2b.getImage(); break; // AdjustHue case "AdjustHue": break; // AdjustGamma case "AdjustGamma": break; // RoundCorners case "RoundCorners": break; // AdjustSaturation case "AdjustSaturation": break; // AdjustBrightness case "AdjustBrightness": break; // AdjustOpacity case "AdjustOpacity": int opacity = Integer.valueOf(filter.getAttributeValue("Opacity")) * 255 / 100; OpacityFilter opacityFilter = new OpacityFilter(opacity); result = opacityFilter.filter(tmpImage, null); break; // PerspectiveView case "PerspectiveView": break; // Rotate case "Rotate": break; // DropShadow case "DropShadow": break; // Skew case "Skew": break; // Flip case "Flip": break; } } } return result; }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private ImagePanel drawTemplate(Element drawImageTemplateElement) throws Exception { // OutputImageSettings logger.info("reading ImageDrawTemlate attributes..."); Element outputImageSettingsElement = drawImageTemplateElement.getChild(OUTPUT_IMAGE_SETTINGS); String colorDepth = outputImageSettingsElement.getAttributeValue("ColorDepth"); String imageForat = outputImageSettingsElement.getAttributeValue("ImageFormat"); String jpegCompressionLevel = outputImageSettingsElement.getAttributeValue("JpegCompressionLevel"); String dpi = outputImageSettingsElement.getAttributeValue("Dpi"); logger.info("Reading Canvas attributes..."); // Canvas/*from w w w. j av a 2 s .c om*/ Element canvasElement = drawImageTemplateElement.getChild(CANVAS); String autoSize = canvasElement.getAttributeValue("AutoSize"); String centerElements = canvasElement.getAttributeValue("CenterElements"); int width = Integer.valueOf(canvasElement.getAttributeValue("Width")); int height = Integer.valueOf(canvasElement.getAttributeValue("Height")); String fill = canvasElement.getAttributeValue("Fill"); // create image of specified dimensions logger.info("Creating working image..."); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // Elements logger.info("Processing elements..."); Element elementsElement = drawImageTemplateElement.getChild("Elements"); for (Element element : elementsElement.getChildren()) { switch (element.getName()) { case "ImageElement": processImageElement(g2, element); break; case "TextElement": processTextElement(g2, element); break; } } return new ImagePanel(image); }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private void processImageElement(Graphics2D g2, Element imageElement) throws Exception { logger.info("Processing {}...", imageElement.getAttributeValue("Name")); int x = Integer.valueOf(imageElement.getAttributeValue("X")); int y = Integer.valueOf(imageElement.getAttributeValue("Y")); int width = Integer.valueOf(imageElement.getAttributeValue("Width")); int height = Integer.valueOf(imageElement.getAttributeValue("Height")); // File or Base64String String sourceType = imageElement.getAttributeValue("Source"); String sourceData = imageElement.getAttributeValue("SourceData"); String nullImageUrl = imageElement.getAttributeValue("NullImageUrl"); // String sourceDpi = imageElement.getAttributeValue("SourceDpi"); // boolean useSourceDpi = Boolean.valueOf(imageElement.getAttributeValue("UseSourceDpi")); BufferedImage tmpImage = null; switch (sourceType) { case "File": // load image from file if (StringUtils.isEmpty(sourceData)) { tmpImage = ImageIO.read(new File(nullImageUrl.replaceAll("\\\\", "/"))); } else {//from w w w .j a v a 2 s. c om // tmpImage = ImageIO.read(new File(sourceData.replaceAll("\\\\", "/"))); tmpImage = ImageIO.read(new File(sourceData.replaceAll("\\\\", "/"))); } break; case "Base64String": // use substitution to retrieve fileName // RATINGSTARS if (sourceData.equalsIgnoreCase("%RATINGSTARS%")) { // // BufferedImage stars = ImageIO.read(new FileInputStream(settings.getStarsRating().replaceAll("\\\\", "/"))); // // // create stars // float starsNumber = Float.valueOf(tokenMap.get("%RATINGPERCENT%")) / 10F; // int fullStarsNumber = (int) Math.floor(starsNumber); // float starFraction = starsNumber - fullStarsNumber; // // // 1 star -> 24px, so 7.4 stars are 24x7.4 -> 178px // BufferedImage singleStar = stars.getSubimage(0, 0, 24, 24); // // //Initializing the final image // tmpImage = new BufferedImage(width, height, singleStar.getType()); // Graphics2D g2i = tmpImage.createGraphics(); // for (int i = 0; i < fullStarsNumber; i++) { // g2i.drawImage(singleStar, 24 * i, 0, null); // } // // crop the last star // BufferedImage croppedStar = singleStar.getSubimage(0, 0, Math.round(24 * starFraction), 24); // g2i.drawImage(croppedStar, 24 * fullStarsNumber, 0, null); } else { String imageUrl = tokenMap.get(sourceData); if (imageUrl != null) { tmpImage = ImageIO.read(new File(imageUrl.replaceAll("\\\\", "/"))); } } break; } if (tmpImage != null) { // process actions tmpImage = processActions(imageElement, tmpImage); // alway resize Scalr.resize(tmpImage, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_TO_WIDTH, width, height, Scalr.OP_ANTIALIAS); // BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height); // tmpImage = scaleFilter.filter(tmpImage, null); g2.drawImage(tmpImage, x, y, width, height, null); } logger.info("{} processed...", imageElement.getAttributeValue("Name")); }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private void processTextElement(Graphics2D g2, Element textElement) { int x = Integer.valueOf(textElement.getAttributeValue("X")); int y = Integer.valueOf(textElement.getAttributeValue("Y")); int width = Integer.valueOf(textElement.getAttributeValue("Width")); int height = Integer.valueOf(textElement.getAttributeValue("Height")); String alignment = textElement.getAttributeValue("TextAlignment"); boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase()); boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias"); Font font = parseFont(textElement.getAttributeValue("Font")); logger.info("Using font " + font); // now get the textim4java performance String text = textElement.getAttributeValue("Text"); // if text matches pattern of %VARIABLE%{MODIFIER} logger.info("parsing token {}", text); Matcher matcher = pattern.matcher(text); int start = 0; while (matcher.find(start)) { // apply modification text = text.replace(matcher.group(), applyModifier(matcher.group())); start = matcher.end();/*from ww w .ja va 2 s . c o m*/ } BufferedImage tmpImage; if (width > 0 && height > 0) { // create a transparent tmpImage tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { FontMetrics fm = g2.getFontMetrics(font); Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds(); // we need to create a transparent image to paint tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_ARGB); } Graphics2D g2d = tmpImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); // } g2d.setFont(font); Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); g2d.setColor(textColor); Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f); g2d.setComposite(comp); drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); tmpImage = processActions(textElement, tmpImage); //// Graphics2D g2d = tmpImage.createGraphics(); // // set current font // g2.setFont(font); //// g2d.setComposite(AlphaComposite.Clear); //// g2d.fillRect(0, 0, width, height); //// g2d.setComposite(AlphaComposite.Src); // // TODO: we have to parse it // int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth")); // // the color of the outline // if (strokeWidth > 0) { //// Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor"))); //// AffineTransform affineTransform; //// affineTransform = g2d.getTransform(); //// affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2 //// + (outlineBounds.height / 2)); //// g2d.transform(affineTransform); //// // backup stroke width and color //// Stroke originalStroke = g2d.getStroke(); //// Color originalColor = g2d.getColor(); //// g2d.setColor(strokeColor); //// g2d.setStroke(new BasicStroke(strokeWidth)); //// g2d.draw(shape); //// g2d.setClip(shape); //// // restore stroke width and color //// g2d.setStroke(originalStroke); //// g2d.setColor(originalColor); // } //// // get the text color // Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); // g2.setColor(textColor); //// g2d.setBackground(Color.BLACK); //// g2d.setStroke(new BasicStroke(2)); //// g2d.setColor(Color.WHITE); // // draw the text // // drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline); // g2.drawString(text, x, y); // Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position // FontMetrics fm = g2.getFontMetrics(); // FontRenderContext frc = g2.getFontRenderContext(); // TextLayout tl = new TextLayout(text, g2.getFont(), frc); // AffineTransform transform = new AffineTransform(); // transform.setToTranslation(rect.getX(), rect.getY()); // if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) { // double scaleY // = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY() // - tl.getOutline(null).getBounds().getMinY()); // transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY); // } // Shape shape = tl.getOutline(transform); // g2.setClip(shape); // g2.fill(shape.getBounds()); // if (antiAlias) { // we need to restore antialias to none // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // } // g2.drawString(text, x, y); // alway resize // BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height); // tmpImage = scaleFilter.filter(tmpImage, null); // draw the image to the source g2.drawImage(tmpImage, x, y, width, height, null); try { ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png"); } catch (IOException ex) { } }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private BufferedImage processActions(Element imageElement, BufferedImage tmpImage) { // verify if there are filters Element actions = imageElement.getChild("Actions"); if (actions != null) { List<Element> filters = actions.getChildren(); for (Element filter : filters) { logger.info("Processing action {}", filter.getName()); // TODO: implement filters switch (filter.getName()) { // Crop case "Crop": break; // GlassTable case "GlassTable": MirrorFilter mirrorFilter = new MirrorFilter(); float reflectionOpacity = Float.valueOf(filter.getAttributeValue("ReflectionOpacity")); mirrorFilter.setOpacity(reflectionOpacity / 100); mirrorFilter.setCentreY(1f); mirrorFilter.setGap(0f); tmpImage = mirrorFilter.filter(tmpImage, null); break; // Glow case "Glow": GlowFilter glowFilter = new GlowFilter(); float amount = Float.valueOf(filter.getAttributeValue("Amount")); glowFilter.setAmount(amount); tmpImage = glowFilter.filter(tmpImage, null); break; // GaussianBlur case "GaussianBlur": GaussianFilter gaussianFilter = new GaussianFilter(); gaussianFilter.setRadius(Float.valueOf(filter.getAttributeValue("Radius"))); tmpImage = gaussianFilter.filter(tmpImage, null); break; // AdjustHue case "AdjustHue": break; // AdjustGamma case "AdjustGamma": break; // RoundCorners case "RoundCorners": break; // AdjustSaturation case "AdjustSaturation": break; // AdjustBrightness case "AdjustBrightness": break; // AdjustOpacity case "AdjustOpacity": // int opacity = (int) (Float.valueOf(filter.getAttributeValue("Opacity")) * 255 / 100); // OpacityFilter opacityFilter = new OpacityFilter(opacity); // tmpImage = opacityFilter.filter(tmpImage, null); break; // PerspectiveView case "PerspectiveView": break; // Rotate case "Rotate": RotateFilter rotateFilter = new RotateFilter(); float rotateAngle = Float.valueOf(filter.getAttributeValue("Angle")); rotateFilter.setAngle(rotateAngle); tmpImage = rotateFilter.filter(tmpImage, null); break; // DropShadow case "DropShadow": logger.info("Dropping shadow..."); ShadowFilter shadow = new ShadowFilter(); float angle = Float.valueOf(filter.getAttributeValue("Angle")); shadow.setAngle(angle);/*w w w . ja va 2 s . c om*/ float distance = Float.valueOf(filter.getAttributeValue("Distance")); shadow.setDistance(distance); // shadow.setRadius(3.0f); float opacity = Float.valueOf(filter.getAttributeValue("Opacity")); shadow.setOpacity(opacity / 100); tmpImage = shadow.filter(tmpImage, null); break; // Skew case "Skew": break; // Flip case "Flip": FlipFilter flipFilter = new FlipFilter(); // Type can be "Horizontal" or "Vertical" String type = filter.getAttributeValue("Type"); switch (type.toLowerCase()) { case "horizontal": flipFilter.setOperation(FlipFilter.FLIP_H); break; case "vertical": flipFilter.setOperation(FlipFilter.FLIP_V); break; } tmpImage = flipFilter.filter(tmpImage, null); break; } } } return tmpImage; }
From source file:com.github.lucapino.sheetmaker.renderer.SettingsElement.java
public SettingsElement(Element settingsElement) { this.name = settingsElement.getName(); this.separator = settingsElement.getAttributeValue(SEPARATOR); this.maximumValues = settingsElement.getAttributeValue(MAXIMUM_VALUES); }
From source file:com.github.lucapino.sheetmaker.renderer.TemplateElement.java
TemplateElement(Element child) { this.name = child.getAttributeValue(NAME); this.text = child.getAttributeValue(TEXT); this.image = child.getAttributeValue(IMAGE); }
From source file:com.github.zdsiyan.maven.plugin.smartconfig.SmartconfigMojo.java
License:Apache License
private Smartconfig buildFastconfig() throws Exception { PluginParameterExpressionEvaluator pel = new PluginParameterExpressionEvaluator(session, execution); Smartconfig fastconfig = new Smartconfig(); SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(config); Element root = doc.getRootElement(); // use scriptEngine, maybe we can extend it, not only javascript ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); // load profile List<Profile> profiles = session.getCurrentProject().getActiveProfiles(); profiles.forEach(profile -> profile.getProperties().keySet().forEach(key -> { Object value = profile.getProperties().get(key); engine.put(key.toString(), value); //getLog().warn("profile:"+key); }));/*from w w w. j a v a2s .com*/ // load user properties session.getUserProperties().keySet().forEach(key -> { Object value = session.getUserProperties().get(key); engine.put(key.toString(), value); //getLog().warn("user:"+key); }); /* load sys properties session.getSystemProperties().keySet().forEach(key->{ Object value = session.getSystemProperties().get(key); engine.put(key.toString(), value); getLog().warn("sys:"+key); }); */ session.getCurrentProject().getProperties().keySet().forEach(key -> { Object value = session.getCurrentProject().getProperties().get(key); engine.put(key.toString(), value); //getLog().warn("prop:"+key); }); // config-file for (Element cf : root.getChildren()) { String path = String.valueOf(pel.evaluate(cf.getAttributeValue("path"))); File file = new File(path); if (!file.isAbsolute()) { file = new File(outputDirectory, path); } boolean disable = false; //eval the script if (StringUtils.isNotEmpty(cf.getAttributeValue("disable"))) { Object result = engine.eval(cf.getAttributeValue("disable")); if (Boolean.TRUE.equals(result)) { disable = true; } } if (disable == true) { continue; } //rename to if (StringUtils.isNotEmpty(cf.getAttributeValue("replace"))) { String replace = String.valueOf(pel.evaluate(cf.getAttributeValue("replace"))); //getLog().warn("filepath:"+file.getPath()); File refile = new File(file.getParent() + File.separator + replace); //getLog().warn("refilepath:"+refile.getPath()); FileUtils.rename(file, refile); continue; } ConfigFile.Mode mode; if (StringUtils.isNotEmpty(cf.getAttributeValue("mode"))) { mode = ConfigFile.Mode.valueOf(cf.getAttributeValue("mode")); } else { mode = toConfigMode(path.substring(path.lastIndexOf(".") + 1)); } if (mode == null) { throw new SmartconfigException("Not found file[" + path + "] replace mode"); } ConfigFile configFile = new ConfigFile(file, mode); for (Element rt : cf.getChildren()) { String expression = rt.getAttributeValue("expression"); String value = String.valueOf(pel.evaluate(rt.getTextTrim())); PointHandle.Mode phMode; if (StringUtils.isNotEmpty(rt.getAttributeValue("mode"))) { phMode = PointHandle.Mode.valueOf(rt.getAttributeValue("mode")); } else { phMode = PointHandle.Mode.replace; } if (mode == null) { throw new SmartconfigException("Not found pointhandle mode"); } configFile.addPointHandle(new PointHandle(expression, value, phMode)); } fastconfig.addConfigFile(configFile); } return fastconfig; }
From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java
License:Apache License
private String parseXLF(JobBO p_job, File p_srcFile) { if (p_srcFile == null || !p_srcFile.exists()) return "File not exits."; String srcLang, trgLang;// w w w . ja v a 2 s. c o m List<String> srcSegments = new ArrayList<String>(); try { SAXBuilder builder = new SAXBuilder(); Document read_doc = builder.build(p_srcFile); // Get Root Element Element root = read_doc.getRootElement(); Namespace namespace = root.getNamespace(); Element fileElem = root.getChild("file", namespace); // Get Source/Target Language srcLang = fileElem.getAttributeValue(XLF_SOURCE_LANGUAGE); trgLang = fileElem.getAttributeValue(XLF_TARGET_LANGUAGE); XPathFactory xFactory = XPathFactory.instance(); XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace); List<Element> list = expr.evaluate(fileElem.getChild("body", namespace)); for (int i = 0; i < list.size(); i++) { Element tuElem = (Element) list.get(i); Element srcElem = tuElem.getChild("source", namespace); // Get Source Segment if (srcElem != null && srcElem.getContentSize() > 0) { String source = getInnerXMLString(srcElem); srcSegments.add(source); } } p_job.setSourceLanguage(srcLang); p_job.setTargetLanguage(trgLang); p_job.setSourceSegments(srcSegments); } catch (Exception e) { String msg = "Parse XLIFF file error."; logger.error(msg, e); return msg; } return null; }