/* (non-Javadoc)
@see org.apereo.portal.rendering.xslt.TransformerConfigurationSource#getTransformerOutputProperties(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
162992
@Override
    public Properties getOutputProperties(
            HttpServletRequest request, HttpServletResponse response) {
        final Properties mergedProperties = new Properties();

        for (final TransformerConfigurationSource source : this.sources) {
            final Properties properties = source.getOutputProperties(request, response);
            if (properties != null) {
                mergedProperties.putAll(properties);
            }
        }

        return mergedProperties;
    }
713254
public ResourceTransformerEntry resolveResourceTransformer(final PathAddress address, final PlaceholderResolver placeholderResolver) {
        return resolveResourceTransformer(address.iterator(), null, placeholderResolver);
    }
165541
@Override
	public ResultTransformer createMapping(final App app, final String sourceType, final String targetType, final Map<String, String> propertyMappings, final Map<String, String> transforms) throws FrameworkException {

		try (final Tx tx = app.tx()) {

			final VirtualType type = app.create(VirtualType.class,
				new NodeAttribute<>(StructrApp.key(VirtualType.class, "sourceType"), sourceType),
				new NodeAttribute<>(StructrApp.key(VirtualType.class, "name"),       targetType)
			);

			int i = 0;

			for (final Entry<String, String> entry : propertyMappings.entrySet()) {

				final String sourceProperty = entry.getKey();
				final String targetProperty = entry.getValue();

				app.create(VirtualProperty.class,
					new NodeAttribute<>(StructrApp.key(VirtualProperty.class, "virtualType"),   type),
					new NodeAttribute<>(StructrApp.key(VirtualProperty.class, "sourceName"),    sourceProperty),
					new NodeAttribute<>(StructrApp.key(VirtualProperty.class, "targetName"),    targetProperty),
					new NodeAttribute<>(StructrApp.key(VirtualProperty.class, "position"),      i++),
					new NodeAttribute<>(StructrApp.key(VirtualProperty.class, "inputFunction"), transforms.get(sourceProperty))
				);
			}

			tx.success();

			return type;
		}
	}
274181
private Transformer createTransformer(boolean indent) {

    try {
      Transformer result = this.transformerFactory.newTransformer();
      if (indent) {
        result.setOutputProperty(OutputKeys.INDENT, "yes");
      }
      return result;
    } catch (TransformerConfigurationException e) {
      throw new IllegalStateException("XML Transformer misconfigured!" + " Probably your JVM does not support the required JAXP version!", e);
    }
  }
526364
private <IN, OUT> Collection<Integer> transformOneInputTransform(OneInputTransformation<IN, OUT> transform) {

		Collection<Integer> inputIds = transform(transform.getInput());

		// the recursive call might have already transformed this
		if (alreadyTransformed.containsKey(transform)) {
			return alreadyTransformed.get(transform);
		}

		String slotSharingGroup = determineSlotSharingGroup(transform.getSlotSharingGroup(), inputIds);

		streamGraph.addOperator(transform.getId(),
				slotSharingGroup,
				transform.getCoLocationGroupKey(),
				transform.getOperator(),
				transform.getInputType(),
				transform.getOutputType(),
				transform.getName());

		if (transform.getStateKeySelector() != null) {
			TypeSerializer<?> keySerializer = transform.getStateKeyType().createSerializer(env.getConfig());
			streamGraph.setOneInputStateKey(transform.getId(), transform.getStateKeySelector(), keySerializer);
		}

		streamGraph.setParallelism(transform.getId(), transform.getParallelism());
		streamGraph.setMaxParallelism(transform.getId(), transform.getMaxParallelism());

		for (Integer inputId: inputIds) {
			streamGraph.addEdge(inputId, transform.getId(), 0);
		}

		return Collections.singleton(transform.getId());
	}
803777
public List<MutableInputColumn<?>> getOutputColumns() {
        final Component component = getComponentInstanceForQuestioning();
        if (component == null) {
            // as long as the transformer is not configured, just return an
            // empty list
            return Collections.emptyList();
        }

        final Transformer transformer = (Transformer) component;
        
        final OutputColumns outputColumns;
        try {
            outputColumns = transformer.getOutputColumns();
        } catch (final Exception e) {
            logger.error("getOutputColumn() threw unexpected exception on transformer: " + transformer, e);
            return Collections.emptyList();
        }
        if (outputColumns == null) {
            logger.error("getOutputColumns() returned null on transformer: " + transformer);
            return Collections.emptyList();
        }
        boolean changed = false;

        // adjust the amount of output columns
        final int expectedCols = outputColumns.getColumnCount();
        final int existingCols = _outputColumns.size();
        if (expectedCols != existingCols) {
            changed = true;
            final int colDiff = expectedCols - existingCols;
            if (colDiff > 0) {
                for (int i = 0; i < colDiff; i++) {
                    final int nextIndex = _outputColumns.size();
                    final String name = getColumnName(outputColumns, nextIndex);
                    final String id = _id + "-" + _idGenerator.nextId();
                    final TransformedInputColumn<Object> column = new TransformedInputColumn<>(name, id);
                    /*
                     * If the transformer has the annotation
                     * "HideOutputColumns", the output columns are hidden in
                     * other components as input columns. If the user wants to
                     * use them, he can select them in the transformer.
                     */
                    final HideOutputColumns hideOutputColumnsAnnotation =
                            this.getDescriptor().getAnnotation(HideOutputColumns.class);
                    if (hideOutputColumnsAnnotation != null && hideOutputColumnsAnnotation.isHidden()) {
                        column.setHidden(true);
                    }

                    _outputColumns.add(column);
                    _automaticOutputColumnNames.add(name);
                }
            } else if (colDiff < 0) {
                for (int i = 0; i < Math.abs(colDiff); i++) {
                    // remove from the tail
                    _outputColumns.remove(_outputColumns.size() - 1);
                    _automaticOutputColumnNames.remove(_automaticOutputColumnNames.size() - 1);
                }
            }

            // reset the names when the number of output columns change and the
            // initial name has changed
            for (int i = 0; i < expectedCols; i++) {
                final MutableInputColumn<?> column = _outputColumns.get(i);
                final String previousProposedName = column.getInitialName();
                final String newProposedName = outputColumns.getColumnName(i);
                if (newProposedName != null && !newProposedName.equals(previousProposedName)) {
                    column.setName(newProposedName);
                }
            }
        }

        // automatically update names and types of columns if they have not been
        // manually set
        for (int i = 0; i < expectedCols; i++) {
            final String proposedName = getColumnName(outputColumns, i);
            final Class<?> dataType = outputColumns.getColumnType(i);

            final TransformedInputColumn<?> col = (TransformedInputColumn<?>) _outputColumns.get(i);
            col.setInitialName(proposedName);
            if (dataType != col.getDataType()) {
                col.setDataType(dataType);
                changed = true;
            }

            final String automaticName = _automaticOutputColumnNames.get(i);
            final String columnName = col.getName();
            if (StringUtils.isNullOrEmpty(columnName) || automaticName.equals(columnName)) {
                if (proposedName != null) {
                    col.setName(proposedName);
                    _automaticOutputColumnNames.set(i, proposedName);
                }
            }
        }

        if (changed) {
            // notify listeners
            onOutputChanged();
        }

        return Collections.unmodifiableList(_outputColumns);
    }
497007
public static XslTransformer getTransformer(File xslFile) throws TransformerConfigurationException {
    	if (xslFile == null) {
    		throw new IllegalArgumentException("xslFile is null");
    	}
        return getTransformer(new StreamSource(xslFile));
    }
1175367
protected String getParameterOrDefault(Map<String, String> parameters, String paramName, String defaultValue)
        throws TransformationOperationException {
        return getParameter(parameters, paramName, false, defaultValue);
    }
1089679
protected Transformer getTransformer() {
    TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory();
    try {
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      return transformer;
    }
    catch (TransformerConfigurationException e) {
      throw LOG.unableToCreateTransformer(e);
    }
  }
421856
@Override
    public void registerTransformers(SubsystemTransformerRegistration subsystemRegistration) {
        ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance();
        builder.addChildResource(DeploymentPermissionsResourceDefinition.DEPLOYMENT_PERMISSIONS_PATH).
                getAttributeBuilder().addRejectCheck(new RejectAttributeChecker.DefaultRejectAttributeChecker() {

            @Override
            protected boolean rejectAttribute(PathAddress address, String attributeName, ModelNode value, TransformationContext context) {
                // reject the maximum set if it is defined and empty as that would result in complete incompatible policies
                // being used in nodes running earlier versions of the subsystem.
                if (value.isDefined() && value.asList().isEmpty()) { return true; }
                return false;
            }

            @Override
            public String getRejectionLogMessage(Map<String, ModelNode> attributes) {
                return SecurityManagerLogger.ROOT_LOGGER.rejectedEmptyMaximumSet();
            }
        }, DeploymentPermissionsResourceDefinition.MAXIMUM_PERMISSIONS);
        TransformationDescription.Tools.register(builder.build(), subsystemRegistration, EAP_7_0_0_MODEL_VERSION);
    }
1007951
private static void generateParserOnXmlStartElement(BindTypeContext context, MethodSpec.Builder methodBuilder,
			String instanceName, String parserName, BindEntity entity) {
		BindTransform bindTransform;
		// start and inner bean
		methodBuilder.addStatement("currentTag = xmlParser.getName().toString()");

		int count = 0;
		// count property to manage
		{
			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.TAG)
					continue;

				bindTransform = BindTransformer.lookup(property);

				// here we manage only property of bean type
				if (bindTransform != null) {
					count++;
				}
			}
		}

		if (count > 0) {
			// switch for tag elements
			// @formatter:off
			methodBuilder.beginControlFlow("switch(currentTag)$>");

			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.TAG)
					continue;

				bindTransform = BindTransformer.lookup(property);

				// here we manage only property of bean type
				if (bindTransform != null) {
					methodBuilder.addCode("case $S:\n$>", BindProperty.xmlName(property));
					methodBuilder.addCode("// property $L (mapped on $S)\n", property.getName(),
							BindProperty.xmlName(property));

					// methodBuilder.beginControlFlow("if
					// (!xmlParser.isEmptyElement())");
					bindTransform.generateParseOnXml(context, methodBuilder, "xmlParser",
							property.getPropertyType().getTypeName(), "instance", property);
					// methodBuilder.endControlFlow();

					methodBuilder.addStatement("$<break");
				}
			}

			methodBuilder.addCode("default:\n$>");
			// methodBuilder.addStatement("$L.skipElement()", parserName);

			methodBuilder.addStatement("$<break");
			methodBuilder.endControlFlow();
		} else {
			methodBuilder.addCode("// No property to manage here\n");
		}
		// @formatter:on

	}
1011249
private void performTransform(String xslt, Document document,
                                  Result result)
        throws TransformerException, ConfigurationException, XpathException {
        try {
            StreamSource source = new StreamSource(new StringReader(xslt));
            TransformerFactory tf = XMLUnit.newTransformerFactory();
            ErrorListener el = new ErrorListener() {
                    public void error(TransformerException ex)
                        throws TransformerException {
                        // any error in our simple stylesheet must be fatal
                        throw ex;
                    }
                    public void fatalError(TransformerException ex)
                        throws TransformerException {
                        throw ex;
                    }
                    public void warning(TransformerException ex) {
                        // there shouldn't be any warning
                        ex.printStackTrace();
                    }
                };
            tf.setErrorListener(el);
            Transformer transformer = tf.newTransformer(source);
            // Issue 1985229 says Xalan-J 2.7.0 may return null for
            // illegal input
            if (transformer == null) {
                throw new XpathException("failed to obtain an XSLT transformer"
                                         + " for XPath expression.");
            }
            transformer.setErrorListener(el);
            transformer.transform(new DOMSource(document), result);
        } catch (javax.xml.transform.TransformerConfigurationException ex) {
            throw new ConfigurationException(ex);
        }
    }
1004754
public List<LayoutProperty> getDataProperties() throws FetchException {
        List<LayoutProperty> all = getAllProperties();
        List<LayoutProperty> data = new ArrayList<LayoutProperty>(all.size() - 1);
        for (LayoutProperty property : all) {
            if (!property.isPrimaryKeyMember()) {
                data.add(property);
            }
        }
        return Collections.unmodifiableList(data);
    }
1288145
protected final <T> T __getRenderPropertyAs(String name, T def) {
        Object o = __getRenderProperty(name, def);
        return null == o ? def : (T) o;
    }
1316527
protected void transformTo(final Result result) throws TransformerException {
        withExceptionHandling(new Trans<Object>() {
                public Object transform() {
                    transformation.transformTo(result);
                    return null;
                }
            });
    }
322507
protected final MapfishMapContext getLayerTransformer(final MapfishMapContext transformer) {
        MapfishMapContext layerTransformer = transformer;

        if (!FloatingPointUtil.equals(transformer.getRotation(), 0.0) && !this.supportsNativeRotation()) {
            // if a rotation is set and the rotation can not be handled natively
            // by the layer, we have to adjust the bounds and map size
            layerTransformer = new MapfishMapContext(
                    transformer,
                    transformer.getRotatedBoundsAdjustedForPreciseRotatedMapSize(),
                    transformer.getRotatedMapSize(),
                    0,
                    transformer.getDPI(),
                    transformer.isForceLongitudeFirst(),
                    transformer.isDpiSensitiveStyle());
        }

        return layerTransformer;
    }
834736
@Override
    public Object getProperty(String name)
    {
        /* 18-Nov-2008, TSa: As per [WSTX-50], should report the
         *   actual Base URL. It can be overridden by matching
         *   setProperty, but if not, is set to actual source
         *   of content being parsed.
         */
        if (WstxInputProperties.P_BASE_URL.equals(name)) {
        	try {
        		return mInput.getSource();
        	} catch (IOException e) { // not optimal but...
        		throw new IllegalStateException(e);
        	}
        }
        /* 23-Apr-2008, TSa: Let's NOT throw IllegalArgumentException
         *   for unknown property; JavaDocs do not suggest it needs
         *   to be done (different from that of XMLInputFactory
         *   and XMLStreamWriter specification)
         */
        return mConfig.safeGetProperty(name);
    }