jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    private boolean processStyleTag(Element ele, Node parentNode) {
        /*
         * Invoke the css parser on this element.
         */
        CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets());

        try {
            if (ele.getChildNodes().getLength() > 0) {
                StringBuffer toScan = new StringBuffer();

                for (int i = 0; i < ele.getChildNodes().getLength(); i++) {
                    Node childNode = ele.getChildNodes().item(i);
                    if (toScan.length() > 0) {
                        toScan.append("\n");
                    }
                    toScan.append(childNode.getTextContent());
                }

                CleanResults cr = styleScanner.scanStyleSheet(toScan.toString(), policy.getMaxInputSize());
                errorMessages.addAll(cr.getErrorMessages());

                /*
                 * If IE gets an empty style tag, i.e. <style/> it will
                 * break all CSS on the page. I wish I was kidding. So,
                 * if after validation no CSS properties are left, we
                 * would normally be left with an empty style tag and
                 * break all CSS. To prevent that, we have this check.
                 */

                String cleanHTML = cr.getCleanHTML();
                cleanHTML = cleanHTML == null || cleanHTML.equals("") ? "/* */" : cleanHTML;

                ele.getFirstChild().setNodeValue(cleanHTML);
                /*
                 * Remove every other node after cleaning CSS, there will
                 * be only one node in the end, as it always should have.
                 */
                for (int i = 1; i < ele.getChildNodes().getLength(); i++) {
                    Node childNode = ele.getChildNodes().item(i);
                    ele.removeChild(childNode);
                }
            }

        } catch (DOMException | ScanException | ParseException | NumberFormatException e) {

            /*
             * ParseException shouldn't be possible anymore, but we'll leave it
             * here because I (Arshan) am hilariously dumb sometimes.
             * Batik can throw NumberFormatExceptions (see bug #48).
             */

            addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(ele.getFirstChild().getNodeValue())});
            parentNode.removeChild(ele);
            return true;
        }
        return false;
    }
//  [java]
  public User getUser() throws IllegalStateException {
    Organization org = getOrganization();
    if (org == null)
      throw new IllegalStateException("No organization is set in security context");

    User delegatedUser = delegatedUserHolder.get();

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof AnonymousAuthenticationToken) {
      return SecurityUtil.createAnonymousUser(org);
    }

    if (delegatedUser != null) {
      return delegatedUser;
    }

    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(org);
    if (auth != null) {
      Object principal = auth.getPrincipal();
      if ((principal instanceof UserDetails)) {
        UserDetails userDetails = (UserDetails) principal;

        User user = null;

        // If user exists, fetch it from the userDirectory
        if (userDirectory != null) {
          user = userDirectory.loadUser(userDetails.getUsername());
          if (user == null) {
            logger.debug("Authenticated user '{}' could not be found in any of the current UserProviders. "
                + "Continuing anyway...", userDetails.getUsername());
          }
        } else {
          logger.debug("No UserDirectory was found when trying to search for user '{}'", userDetails.getUsername());
        }

        // Add the roles (authorities) in the security context
        Set<JaxbRole> roles = new HashSet<>();
        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        if (authorities != null) {
          for (GrantedAuthority ga : authorities) {
            roles.add(new JaxbRole(ga.getAuthority(), jaxbOrganization));
          }
        }

        if (user == null) {
          // No user was found. Create one to hold the auth information from the security context
          user = new JaxbUser(userDetails.getUsername(), null, jaxbOrganization, roles);
        } else {
          // Combine the existing user with the roles in the security context
          user = JaxbUser.fromUser(user, roles);
        }

        // Save the user to retrieve it quicker the next time(s) this method is called (by this thread)
        delegatedUserHolder.set(user);

        return user;
      }
    }

    // Return the anonymous user by default
    return SecurityUtil.createAnonymousUser(jaxbOrganization);
  }
//  [java]
  public User getUser() throws IllegalStateException {
    Organization org = getOrganization();
    if (org == null)
      throw new IllegalStateException("No organization is set in security context");

    User delegatedUser = delegatedUserHolder.get();

    if (delegatedUser != null) {
      return delegatedUser;
    }

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(org);
    if (auth != null) {
      Object principal = auth.getPrincipal();
      if ((principal != null) && (principal instanceof UserDetails)) {
        UserDetails userDetails = (UserDetails) principal;

        User user = null;

        // If user exists, fetch it from the userDirectory
        if (userDirectory != null) {
          user = userDirectory.loadUser(userDetails.getUsername());
          if (user == null) {
            logger.debug(
                    "Authenticated user '{}' could not be found in any of the current UserProviders. Continuing anyway...",
                    userDetails.getUsername());
          }
        } else {
          logger.debug("No UserDirectory was found when trying to search for user '{}'", userDetails.getUsername());
        }

        // Add the roles (authorities) in the security context
        Set<JaxbRole> roles = new HashSet<JaxbRole>();
        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        if (authorities != null) {
          for (GrantedAuthority ga : authorities) {
            roles.add(new JaxbRole(ga.getAuthority(), jaxbOrganization));
          }
        }

        if (user == null) {
          // No user was found. Create one to hold the auth information from the security context
          user = new JaxbUser(userDetails.getUsername(), null, jaxbOrganization, roles);
        } else {
          // Combine the existing user with the roles in the security context
          user = JaxbUser.fromUser(user, roles);
        }

        // Save the user to retrieve it quicker the next time(s) this method is called (by this thread)
        delegatedUserHolder.set(user);

        return user;
      }
    }

    // Return the anonymous user by default
    return SecurityUtil.createAnonymousUser(jaxbOrganization);
  }
//  [java]
    public void translate(GeyserSession session, ServerDisconnectPacket packet) {
        session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale()));
    }
//  [java]
    public void translate(ServerDisconnectPacket packet, GeyserSession session) {
        session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale()));
    }
//  [java]
    public static void encryptPlayerConnection(GeyserSession session, LoginPacket loginPacket) {
        JsonNode certData;
        try {
            certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());
        } catch (IOException ex) {
            throw new RuntimeException("Certificate JSON can not be read.");
        }

        JsonNode certChainData = certData.get("chain");
        if (certChainData.getNodeType() != JsonNodeType.ARRAY) {
            throw new RuntimeException("Certificate data is not valid");
        }

        encryptConnectionWithCert(session, loginPacket.getSkinData().toString(), certChainData);
    }
//  [java]
    public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {
        JsonNode certData;
        try {
            certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());
        } catch (IOException ex) {
            throw new RuntimeException("Certificate JSON can not be read.");
        }

        JsonNode certChainData = certData.get("chain");
        if (certChainData.getNodeType() != JsonNodeType.ARRAY) {
            throw new RuntimeException("Certificate data is not valid");
        }

        encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);
    }
//  [java]
  public AuthorizationCodeRequestUrl newAuthorizationUrl() {
    AuthorizationCodeRequestUrl url = new  AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId);
    url.setScopes(scopes);
    if (pkce != null) {
      url.setCodeChallenge(pkce.getChallenge());
      url.setCodeChallengeMethod(pkce.getChallengeMethod());
    }
    return url;
  }
//  [java]
  public AuthorizationCodeRequestUrl newAuthorizationUrl() {
    return new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId).setScopes(
        scopes);
  }
//  [java]
  public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
    HttpExecuteInterceptor pkceClientAuthenticationWrapper = new HttpExecuteInterceptor() {
      @Override
      public void intercept(HttpRequest request) throws IOException {
        clientAuthentication.intercept(request);
        if (pkce != null) {
          Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
          data.put("code_verifier", pkce.getVerifier());
        }
      }
    };

    return new AuthorizationCodeTokenRequest(transport, jsonFactory,
        new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
        pkceClientAuthenticationWrapper).setRequestInitializer(requestInitializer).setScopes(scopes);
  }
//  [java]
  public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
    return new AuthorizationCodeTokenRequest(transport, jsonFactory,
        new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
        clientAuthentication).setRequestInitializer(requestInitializer).setScopes(scopes);
  }
//  [java]
    private static boolean validateChainData(JsonNode data) throws Exception {
        if (data.size() != 3) {
            return false;
        }

        ECPublicKey lastKey = null;
        boolean validChain = false;
        for (JsonNode node : data) {
            JWSObject jwt = JWSObject.parse(node.asText());

            // x509 cert is expected in every claim
            URI x5u = jwt.getHeader().getX509CertURL();
            if (x5u == null) {
                return false;
            }

            ECPublicKey expectedKey = EncryptionUtils.generateKey(jwt.getHeader().getX509CertURL().toString());
            // First key is self-signed
            if (lastKey == null) {
                lastKey = expectedKey;
            } else if (!lastKey.equals(expectedKey)) {
                return false;
            }

            if (!EncryptionUtils.verifyJwt(jwt, lastKey)) {
                return false;
            }

            if (lastKey.equals(EncryptionUtils.getMojangPublicKey())) {
                validChain = true;
            }

            Object payload = JSONValue.parse(jwt.getPayload().toString());
            Preconditions.checkArgument(payload instanceof JSONObject, "Payload is not an object");

            Object identityPublicKey = ((JSONObject) payload).get("identityPublicKey");
            Preconditions.checkArgument(identityPublicKey instanceof String, "identityPublicKey node is missing in chain");
            lastKey = EncryptionUtils.generateKey((String) identityPublicKey);
        }

        return validChain;
    }
//  [java]
    private static boolean validateChainData(JsonNode data) throws Exception {
        ECPublicKey lastKey = null;
        boolean validChain = false;
        for (JsonNode node : data) {
            JWSObject jwt = JWSObject.parse(node.asText());

            if (!validChain) {
                validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
            }

            if (lastKey != null) {
                if (!EncryptionUtils.verifyJwt(jwt, lastKey)) return false;
            }

            JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());
            JsonNode ipkNode = payloadNode.get("identityPublicKey");
            Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
            lastKey = EncryptionUtils.generateKey(ipkNode.asText());
        }
        return validChain;
    }
//  [java]
    private static void encryptConnectionWithCert(GeyserSession session, String clientData, JsonNode certChainData) {
        try {
            GeyserConnector connector = session.getConnector();

            boolean validChain = validateChainData(certChainData);

            connector.getLogger().debug(String.format("Is player data valid? %s", validChain));

            if (!validChain && !session.getConnector().getConfig().isEnableProxyConnections()) {
                session.disconnect(LanguageUtils.getLocaleStringLog("geyser.network.remote.invalid_xbox_account"));
                return;
            }
            JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText());
            JsonNode payload = JSON_MAPPER.readTree(jwt.getPayload().toBytes());

            if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) {
                throw new RuntimeException("AuthData was not found!");
            }

            JsonNode extraData = payload.get("extraData");
            session.setAuthenticationData(new AuthData(
                    extraData.get("displayName").asText(),
                    UUID.fromString(extraData.get("identity").asText()),
                    extraData.get("XUID").asText(),
                    certChainData, clientData
            ));

            if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
                throw new RuntimeException("Identity Public Key was not found!");
            }

            ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
            JWSObject clientJwt = JWSObject.parse(clientData);
            EncryptionUtils.verifyJwt(clientJwt, identityPublicKey);

            JsonNode clientDataJson = JSON_MAPPER.readTree(clientJwt.getPayload().toBytes());
            BedrockClientData data = JSON_MAPPER.convertValue(clientDataJson, BedrockClientData.class);
            session.setClientData(data);

            if (EncryptionUtils.canUseEncryption()) {
                try {
                    LoginEncryptionUtils.startEncryptionHandshake(session, identityPublicKey);
                } catch (Throwable e) {
                    // An error can be thrown on older Java 8 versions about an invalid key
                    if (connector.getConfig().isDebugMode()) {
                        e.printStackTrace();
                    }

                    sendEncryptionFailedMessage(connector);
                }
            } else {
                sendEncryptionFailedMessage(connector);
            }
        } catch (Exception ex) {
            session.disconnect("disconnectionScreen.internalError.cantConnect");
            throw new RuntimeException("Unable to complete login", ex);
        }
    }
//  [java]
    private static void encryptConnectionWithCert(GeyserConnector connector, GeyserSession session, String clientData, JsonNode certChainData) {
        try {
            boolean validChain = validateChainData(certChainData);

            connector.getLogger().debug(String.format("Is player data valid? %s", validChain));

            if (!validChain && !session.getConnector().getConfig().isEnableProxyConnections()) {
                session.disconnect(LanguageUtils.getLocaleStringLog("geyser.network.remote.invalid_xbox_account"));
                return;
            }
            JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText());
            JsonNode payload = JSON_MAPPER.readTree(jwt.getPayload().toBytes());

            if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) {
                throw new RuntimeException("AuthData was not found!");
            }

            JsonNode extraData = payload.get("extraData");
            session.setAuthenticationData(new AuthData(
                    extraData.get("displayName").asText(),
                    UUID.fromString(extraData.get("identity").asText()),
                    extraData.get("XUID").asText(),
                    certChainData, clientData
            ));

            if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
                throw new RuntimeException("Identity Public Key was not found!");
            }

            ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
            JWSObject clientJwt = JWSObject.parse(clientData);
            EncryptionUtils.verifyJwt(clientJwt, identityPublicKey);

            JsonNode clientDataJson = JSON_MAPPER.readTree(clientJwt.getPayload().toBytes());
            BedrockClientData data = JSON_MAPPER.convertValue(clientDataJson, BedrockClientData.class);
            session.setClientData(data);

            if (EncryptionUtils.canUseEncryption()) {
                try {
                    LoginEncryptionUtils.startEncryptionHandshake(session, identityPublicKey);
                } catch (Throwable e) {
                    // An error can be thrown on older Java 8 versions about an invalid key
                    if (connector.getConfig().isDebugMode()) {
                        e.printStackTrace();
                    }

                    sendEncryptionFailedMessage(connector);
                }
            } else {
                sendEncryptionFailedMessage(connector);
            }
        } catch (Exception ex) {
            session.disconnect("disconnectionScreen.internalError.cantConnect");
            throw new RuntimeException("Unable to complete login", ex);
        }
    }
//  [java]
	public String getOrderBy() {
		return SQLUtil.sanitizeSortBy(orderBy);
	}
//  [java]
	public String getOrderBy() {
		return orderBy;
	}
//  [java]
  public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, AccessControlList seriesAcl, Date now)
      throws SolrServerException, UnauthorizedException {
    try {
      SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl);
      Schema.setOcModified(episodeDocument, now);

      SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), seriesAcl);
      if (seriesDocument != null)
        Schema.enrich(episodeDocument, seriesDocument);

      // Post everything to the search index
      solrServer.add(episodeDocument);
      if (seriesDocument != null)
        solrServer.add(seriesDocument);
      solrServer.commit();
      return true;
    } catch (Exception e) {
      throw new SolrServerException(
          String.format("Unable to add media package %s to index", sourceMediaPackage.getIdentifier()), e);
    }
  }
//  [java]
  public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date now) throws SolrServerException,
          UnauthorizedException {
    try {
      SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl);
      Schema.setOcModified(episodeDocument, now);

      SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl);
      if (seriesDocument != null)
        Schema.enrich(episodeDocument, seriesDocument);

      // If neither an episode nor a series was contained, there is no point in trying to update
      if (episodeDocument == null && seriesDocument == null) {
        logger.warn("Neither episode nor series metadata found");
        return false;
      }

      // Post everything to the search index
      if (episodeDocument != null)
        solrServer.add(episodeDocument);
      if (seriesDocument != null)
        solrServer.add(seriesDocument);
      solrServer.commit();
      return true;
    } catch (Exception e) {
      logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier());
      throw new SolrServerException(e);
    }
  }
//  [java]
    public void translate(GeyserSession session, ServerEntityTeleportPacket packet) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.teleport(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }
//  [java]
    public void translate(ServerEntityTeleportPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.teleport(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }
//  [java]
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
        if(qs==null)
            throw new ServletException();
        Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
    }
//  [java]
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
        if(qs==null || !ICON_SIZE.matcher(qs).matches())
            throw new ServletException();
        Cookie cookie = new Cookie("iconSize", qs);
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityRotationPacket packet) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.updateRotation(session, packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }
//  [java]
    public void translate(ServerEntityRotationPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.updateRotation(session, packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }
//  [java]
	private final HColor getBackColor(UmlDiagramType umlDiagramType, Style style) {
		if (EntityUtils.groupRoot(group))
			return null;

		final HColor result = group.getColors().getColor(ColorType.BACK);
		if (result != null)
			return result;

		final Stereotype stereo = group.getStereotype();

		return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());

//		final USymbol sym = group.getUSymbol() == null ? USymbols.PACKAGE : group.getUSymbol();
//		final ColorParam backparam = umlDiagramType == UmlDiagramType.ACTIVITY ? ColorParam.partitionBackground
//				: sym.getColorParamBack();
//		final HColor c1 = skinParam.getHtmlColor(backparam, stereo, false);
//		if (c1 != null)
//			return c1;
//
//		if (parentCluster == null)
//			return null;
//
//		return parentCluster.getBackColor(umlDiagramType, style);
	}
//  [java]
	private final HColor getBackColor(UmlDiagramType umlDiagramType, Style style) {
		if (EntityUtils.groupRoot(group))
			return null;

		final HColor result = group.getColors().getColor(ColorType.BACK);
		if (result != null)
			return result;

		final Stereotype stereo = group.getStereotype();

		if (UseStyle.useBetaStyle())
			return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());

		final USymbol sym = group.getUSymbol() == null ? USymbols.PACKAGE : group.getUSymbol();
		final ColorParam backparam = umlDiagramType == UmlDiagramType.ACTIVITY ? ColorParam.partitionBackground
				: sym.getColorParamBack();
		final HColor c1 = skinParam.getHtmlColor(backparam, stereo, false);
		if (c1 != null)
			return c1;

		if (parentCluster == null)
			return null;

		return parentCluster.getBackColor(umlDiagramType, style);
	}
//  [java]
	public void drawU(UGraphic ug, UmlDiagramType umlDiagramType, ISkinParam skinParam2unused) {
		if (group.isHidden())
			return;

		final String fullName = group.getCodeGetName();
		if (fullName.startsWith("##") == false)
			ug.draw(new UComment("cluster " + fullName));

		final USymbol uSymbol = group.getUSymbol() == null ? USymbols.PACKAGE : group.getUSymbol();
		Style style = getDefaultStyleDefinition(umlDiagramType.getStyleName(), uSymbol)
				.withTOBECHANGED(group.getStereotype()).getMergedStyle(skinParam.getCurrentStyleBuilder());
		final double shadowing = style.value(PName.Shadowing).asDouble();
		HColor borderColor;
		if (group.getColors().getColor(ColorType.LINE) != null)
			borderColor = group.getColors().getColor(ColorType.LINE);
		else
			borderColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
		final double rounded = style.value(PName.RoundCorner).asDouble();
		final double diagonalCorner = style.value(PName.DiagonalCorner).asDouble();

		ug.startGroup(Collections.singletonMap(UGroupType.ID, "cluster_" + fullName));

		final Url url = group.getUrl99();
		if (url != null)
			ug.startUrl(url);

		try {
			if (entityPositionsExceptNormal().size() > 0)
				manageEntryExitPoint(ug.getStringBounder());

			if (skinParam.useSwimlanes(umlDiagramType)) {
				drawSwinLinesState(ug, borderColor);
				return;
			}
			final boolean isState = umlDiagramType == UmlDiagramType.STATE;

			if (isState && group.getUSymbol() == null) {
				drawUState(ug, umlDiagramType, rounded, shadowing);
				return;
			}
			PackageStyle packageStyle = group.getPackageStyle();
			if (packageStyle == null)
				packageStyle = skinParam.packageStyle();

			if (border != null) {
				final HColor tmp = skinParam.getHtmlColor(border, group.getStereotype(), false);
				if (tmp != null)
					borderColor = tmp;
			}

			final UStroke stroke = getStrokeInternal(group, style);

			HColor backColor = getBackColor(umlDiagramType, style);
			backColor = getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),
					group.getUSymbol());
			if (ztitle != null || zstereo != null) {
				final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
						zstereo, minX, minY, maxX, maxY, stroke);
				decoration.drawU(ug, backColor, borderColor, shadowing, rounded,
						skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
						skinParam.getStereotypeAlignment(), diagonalCorner);
				return;
			}
			final URectangle rect = new URectangle(maxX - minX, maxY - minY);
			rect.setDeltaShadow(shadowing);
			ug = ug.apply(backColor.bg()).apply(borderColor);
			ug.apply(new UStroke(2)).apply(new UTranslate(minX, minY)).draw(rect);

		} finally {
			if (url != null)
				ug.closeUrl();
			ug.closeGroup();
		}
	}
//  [java]
	private void drawUState(UGraphic ug, UmlDiagramType umlDiagramType, double rounded, double shadowing) {
		final Dimension2D total = new Dimension2DDouble(maxX - minX, maxY - minY);
		final double suppY;
		if (ztitle == null)
			suppY = 0;
		else
			suppY = ztitle.calculateDimension(ug.getStringBounder()).getHeight() + IEntityImage.MARGIN
					+ IEntityImage.MARGIN_LINE;

		final Style styleGroup = getDefaultStyleDefinitionStateGroup(group.getStereotype())
				.getMergedStyle(skinParam.getCurrentStyleBuilder());

		HColor borderColor = group.getColors().getColor(ColorType.LINE);
		if (borderColor == null)
			borderColor = getStyleState().value(PName.LineColor).asColor(skinParam.getThemeStyle(),
					skinParam.getIHtmlColorSet());

		HColor backColor = group.getColors().getColor(ColorType.BACK);
		if (backColor == null)
			backColor = getStyleState().value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(),
					skinParam.getIHtmlColorSet());

		final HColor imgBackcolor = getBackColor(umlDiagramType, styleGroup);

		// final Style style = getStyle(FontParam.STATE_ATTRIBUTE, skinParam2);

		final TextBlock attribute = GeneralImageBuilder.stateHeader(group, styleGroup, skinParam);
		final double attributeHeight = attribute.calculateDimension(ug.getStringBounder()).getHeight();
		if (total.getWidth() == 0) {
			System.err.println("Cluster::drawUState issue");
			return;
		}

		UStroke stroke = group.getColors().getSpecificLineStroke();
		if (stroke == null)
			stroke = getStyleState().getStroke();

		final RoundedContainer r = new RoundedContainer(total, suppY,
				attributeHeight + (attributeHeight > 0 ? IEntityImage.MARGIN : 0), borderColor, backColor, imgBackcolor,
				stroke, rounded, shadowing);
		r.drawU(ug.apply(new UTranslate(minX, minY)));

		if (ztitle != null)
			ztitle.drawU(ug.apply(new UTranslate(xTitle, yTitle)));

		if (attributeHeight > 0)
			attribute.drawU(
					ug.apply(new UTranslate(minX + IEntityImage.MARGIN, minY + suppY + IEntityImage.MARGIN / 2.0)));

		final Stereotype stereotype = group.getStereotype();
		final boolean withSymbol = stereotype != null && stereotype.isWithOOSymbol();
		if (withSymbol)
			EntityImageState.drawSymbol(ug.apply(borderColor), maxX, maxY);

	}
//  [java]
	private void drawUState(UGraphic ug, HColor borderColor, ISkinParam skinParam2, UStroke stroke,
			UmlDiagramType umlDiagramType, double rounded, double shadowing) {
		final Dimension2D total = new Dimension2DDouble(maxX - minX, maxY - minY);
		final double suppY;
		if (ztitle == null)
			suppY = 0;
		else
			suppY = ztitle.calculateDimension(ug.getStringBounder()).getHeight() + IEntityImage.MARGIN
					+ IEntityImage.MARGIN_LINE;

		final Style styleGroup = getDefaultStyleDefinitionStateGroup(group.getStereotype())
				.getMergedStyle(skinParam.getCurrentStyleBuilder());

		HColor stateBack = getBackColor(umlDiagramType, styleGroup);
		if (UseStyle.useBetaStyle() == false && stateBack == null)
			stateBack = getColorLegacy(skinParam2, ColorParam.stateBackground, group.getStereotype());

		final HColor background;
		if (UseStyle.useBetaStyle() == false)
			background = getColorLegacy(skinParam2, ColorParam.background, null);
		else
			background = stateBack;

		// final Style style = getStyle(FontParam.STATE_ATTRIBUTE, skinParam2);

		final TextBlock attribute = GeneralImageBuilder.stateHeader(group, styleGroup, skinParam2);
		final double attributeHeight = attribute.calculateDimension(ug.getStringBounder()).getHeight();
		if (total.getWidth() == 0) {
			System.err.println("Cluster::drawUState issue");
			return;
		}
		final RoundedContainer r = new RoundedContainer(total, suppY,
				attributeHeight + (attributeHeight > 0 ? IEntityImage.MARGIN : 0), borderColor, stateBack, background,
				stroke, rounded, shadowing);
		r.drawU(ug.apply(new UTranslate(minX, minY)));

		if (ztitle != null)
			ztitle.drawU(ug.apply(new UTranslate(xTitle, yTitle)));

		if (attributeHeight > 0)
			attribute.drawU(
					ug.apply(new UTranslate(minX + IEntityImage.MARGIN, minY + suppY + IEntityImage.MARGIN / 2.0)));

		final Stereotype stereotype = group.getStereotype();
		final boolean withSymbol = stereotype != null && stereotype.isWithOOSymbol();
		if (withSymbol)
			EntityImageState.drawSymbol(ug.apply(borderColor), maxX, maxY);

	}
//  [java]
	static public UStroke getStrokeInternal(IGroup group, Style style) {
		final Colors colors = group.getColors();
		if (colors.getSpecificLineStroke() != null)
			return colors.getSpecificLineStroke();

		return style.getStroke();
	}
//  [java]
	static public UStroke getStrokeInternal(IGroup group, ISkinParam skinParam, Style style) {
		final Colors colors = group.getColors();
		if (colors.getSpecificLineStroke() != null)
			return colors.getSpecificLineStroke();

		if (style != null)
			return style.getStroke();

		if (group.getUSymbol() != null && group.getUSymbol() != USymbols.PACKAGE)
			return group.getUSymbol().getSkinParameter().getStroke(skinParam, group.getStereotype());

		return GeneralImageBuilder.getForcedStroke(group.getStereotype(), skinParam);
	}
//  [java]
	public RefUpdated uploadFiles(Collection<FileUpload> uploads, String directory, String commitMessage) {
		Map<String, BlobContent> newBlobs = new HashMap<>();
		
		String parentPath = getDirectory();
		
		if (directory != null) { 
			if (parentPath != null)
				parentPath += "/" + directory;
			else
				parentPath = directory;
		}
		
		User user = Preconditions.checkNotNull(SecurityUtils.getUser());
		BlobIdent blobIdent = getBlobIdent();
		
		for (FileUpload upload: uploads) {
			String blobPath = FilenameUtils.sanitizeFilename(upload.getClientFileName());
			if (parentPath != null)
				blobPath = parentPath + "/" + blobPath;
			
			if (getProject().isReviewRequiredForModification(user, blobIdent.revision, blobPath)) 
				throw new BlobEditException("Review required for this change. Please submit pull request instead");
			else if (getProject().isBuildRequiredForModification(user, blobIdent.revision, blobPath)) 
				throw new BlobEditException("Build required for this change. Please submit pull request instead");
			
			BlobContent blobContent = new BlobContent.Immutable(upload.getBytes(), FileMode.REGULAR_FILE);
			newBlobs.put(blobPath, blobContent);
		}

		BlobEdits blobEdits = new BlobEdits(Sets.newHashSet(), newBlobs);
		String refName = blobIdent.revision!=null?GitUtils.branch2ref(blobIdent.revision):"refs/heads/master";

		ObjectId prevCommitId;
		if (blobIdent.revision != null)
			prevCommitId = getProject().getRevCommit(blobIdent.revision, true).copy();
		else
			prevCommitId = ObjectId.zeroId();

		while (true) {
			try {
				ObjectId newCommitId = blobEdits.commit(getProject().getRepository(), refName, prevCommitId, 
						prevCommitId, user.asPerson(), commitMessage);
				return new RefUpdated(getProject(), refName, prevCommitId, newCommitId);
			} catch (ObjectAlreadyExistsException|NotTreeException e) {
				throw new BlobEditException(e.getMessage());
			} catch (ObsoleteCommitException e) {
				prevCommitId = e.getOldCommitId();
			}
		}
	}
//  [java]
	public RefUpdated uploadFiles(Collection<FileUpload> uploads, String directory, String commitMessage) {
		Map<String, BlobContent> newBlobs = new HashMap<>();
		
		String parentPath = getDirectory();
		
		if (directory != null) { 
			if (parentPath != null)
				parentPath += "/" + directory;
			else
				parentPath = directory;
		}
		
		User user = Preconditions.checkNotNull(SecurityUtils.getUser());
		BlobIdent blobIdent = getBlobIdent();
		
		for (FileUpload upload: uploads) {
			String blobPath = upload.getClientFileName();
			if (parentPath != null)
				blobPath = parentPath + "/" + blobPath;
			
			if (getProject().isReviewRequiredForModification(user, blobIdent.revision, blobPath)) 
				throw new BlobEditException("Review required for this change. Please submit pull request instead");
			else if (getProject().isBuildRequiredForModification(user, blobIdent.revision, blobPath)) 
				throw new BlobEditException("Build required for this change. Please submit pull request instead");
			
			BlobContent blobContent = new BlobContent.Immutable(upload.getBytes(), FileMode.REGULAR_FILE);
			newBlobs.put(blobPath, blobContent);
		}

		BlobEdits blobEdits = new BlobEdits(Sets.newHashSet(), newBlobs);
		String refName = blobIdent.revision!=null?GitUtils.branch2ref(blobIdent.revision):"refs/heads/master";

		ObjectId prevCommitId;
		if (blobIdent.revision != null)
			prevCommitId = getProject().getRevCommit(blobIdent.revision, true).copy();
		else
			prevCommitId = ObjectId.zeroId();

		while (true) {
			try {
				ObjectId newCommitId = blobEdits.commit(getProject().getRepository(), refName, prevCommitId, 
						prevCommitId, user.asPerson(), commitMessage);
				return new RefUpdated(getProject(), refName, prevCommitId, newCommitId);
			} catch (ObjectAlreadyExistsException|NotTreeException e) {
				throw new BlobEditException(e.getMessage());
			} catch (ObsoleteCommitException e) {
				prevCommitId = e.getOldCommitId();
			}
		}
	}
//  [java]
	public static boolean isAbsolute(String url)
	{
		if (url.startsWith("//"))  // //www.domain.com/start
		{
			return true;
		}
	
		try 
		{
			URI uri = new URI(url);
			return uri.isAbsolute();
		}
		catch (URISyntaxException e) 
		{
			return true; // Block malformed URLs also
		}
	}
//  [java]
	public static boolean isAbsolute(String url)
	{
		if (url.startsWith("//"))  // //www.domain.com/start
		{
			return true;
		}
	
		if (url.startsWith("/")) // /somePage.html
		{
			return false;
		}
	
		boolean result = false;
	
		try 
		{
			URI uri = new URI(url);
			result = uri.isAbsolute();
		}
		catch (URISyntaxException e) {} //Ignore
	
		return result;
	}
//  [java]
    public void translate(GeyserSession session, ServerEntityHeadLookPacket packet) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }

        if (entity == null) return;

        entity.updateHeadLookRotation(session, packet.getHeadYaw());
    }
//  [java]
    public void translate(ServerEntityHeadLookPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }

        if (entity == null) return;

        entity.updateHeadLookRotation(session, packet.getHeadYaw());
    }
//  [java]
    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        Assert.isTrue(isValid(path), "Path is not valid");

        String pathToUse = StringUtils.cleanPath(path);

        if (pathToUse.startsWith("/")) {
            pathToUse = pathToUse.substring(1);
        }

        this.path = pathToUse;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    }
//  [java]
    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'");

        String pathToUse = StringUtils.cleanPath(path);

        if (pathToUse.startsWith("/")) {
            pathToUse = pathToUse.substring(1);
        }

        this.path = pathToUse;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    }
//  [java]
    public void render(HtmlRenderer renderer) {
        if (isArtifactsDeleted || isEmpty()) {
            HtmlElement element = p().unsafecontent("Artifacts for this job instance are unavailable as they may have been <a href='" +
                    CurrentGoCDVersion.docsUrl("configuration/delete_artifacts.html") +
                    "' target='blank'>purged by Go</a> or deleted externally. "
                    + "Re-run the stage or job to generate them again.");
            element.render(renderer);
        }
        for (DirectoryEntry entry : this) {
            entry.toHtml().render(renderer);
        }
    }
//  [java]
    public void render(HtmlRenderer renderer) {
        if (isArtifactsDeleted || isEmpty()) {
            HtmlElement element = p().content("Artifacts for this job instance are unavailable as they may have been <a href='" +
                    CurrentGoCDVersion.docsUrl("configuration/delete_artifacts.html") +
                    "' target='blank'>purged by Go</a> or deleted externally. "
                    + "Re-run the stage or job to generate them again.");
            element.render(renderer);
        }
        for (DirectoryEntry entry : this) {
            entry.toHtml().render(renderer);
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityAnimationPacket packet) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        AnimatePacket animatePacket = new AnimatePacket();
        animatePacket.setRuntimeEntityId(entity.getGeyserId());
        switch (packet.getAnimation()) {
            case SWING_ARM:
                animatePacket.setAction(AnimatePacket.Action.SWING_ARM);
                break;
            case EAT_FOOD: // ACTUALLY SWING OFF HAND
                // Use the OptionalPack to trigger the animation
                AnimateEntityPacket offHandPacket = new AnimateEntityPacket();
                offHandPacket.setAnimation("animation.player.attack.rotations.offhand");
                offHandPacket.setNextState("default");
                offHandPacket.setBlendOutTime(0.0f);
                offHandPacket.setStopExpression("query.any_animation_finished");
                offHandPacket.setController("__runtime_controller");
                offHandPacket.getRuntimeEntityIds().add(entity.getGeyserId());

                session.sendUpstreamPacket(offHandPacket);
                return;
            case CRITICAL_HIT:
                animatePacket.setAction(AnimatePacket.Action.CRITICAL_HIT);
                break;
            case ENCHANTMENT_CRITICAL_HIT:
                animatePacket.setAction(AnimatePacket.Action.MAGIC_CRITICAL_HIT); // Unsure if this does anything
                // Spawn custom particle
                SpawnParticleEffectPacket stringPacket = new SpawnParticleEffectPacket();
                stringPacket.setIdentifier("geyseropt:enchanted_hit_multiple");
                stringPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));
                stringPacket.setPosition(Vector3f.ZERO);
                stringPacket.setUniqueEntityId(entity.getGeyserId());
                session.sendUpstreamPacket(stringPacket);
                break;
            case LEAVE_BED:
                animatePacket.setAction(AnimatePacket.Action.WAKE_UP);
                break;
            default:
                // Unknown Animation
                return;
        }

        session.sendUpstreamPacket(animatePacket);
    }
//  [java]
    public void translate(ServerEntityAnimationPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        AnimatePacket animatePacket = new AnimatePacket();
        animatePacket.setRuntimeEntityId(entity.getGeyserId());
        switch (packet.getAnimation()) {
            case SWING_ARM:
                animatePacket.setAction(AnimatePacket.Action.SWING_ARM);
                break;
            case EAT_FOOD: // ACTUALLY SWING OFF HAND
                // Use the OptionalPack to trigger the animation
                AnimateEntityPacket offHandPacket = new AnimateEntityPacket();
                offHandPacket.setAnimation("animation.player.attack.rotations.offhand");
                offHandPacket.setNextState("default");
                offHandPacket.setBlendOutTime(0.0f);
                offHandPacket.setStopExpression("query.any_animation_finished");
                offHandPacket.setController("__runtime_controller");
                offHandPacket.getRuntimeEntityIds().add(entity.getGeyserId());

                session.sendUpstreamPacket(offHandPacket);
                return;
            case CRITICAL_HIT:
                animatePacket.setAction(AnimatePacket.Action.CRITICAL_HIT);
                break;
            case ENCHANTMENT_CRITICAL_HIT:
                animatePacket.setAction(AnimatePacket.Action.MAGIC_CRITICAL_HIT); // Unsure if this does anything
                // Spawn custom particle
                SpawnParticleEffectPacket stringPacket = new SpawnParticleEffectPacket();
                stringPacket.setIdentifier("geyseropt:enchanted_hit_multiple");
                stringPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));
                stringPacket.setPosition(Vector3f.ZERO);
                stringPacket.setUniqueEntityId(entity.getGeyserId());
                session.sendUpstreamPacket(stringPacket);
                break;
            case LEAVE_BED:
                animatePacket.setAction(AnimatePacket.Action.WAKE_UP);
                break;
            default:
                // Unknown Animation
                return;
        }

        session.sendUpstreamPacket(animatePacket);
    }
//  [java]
    private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
        String parent) throws XWikiException
    {
        XWiki xwiki = context.getWiki();

        // Set the locale and default locale, considering that we're creating the original version of the document
        // (not a translation).
        newDocument.setLocale(Locale.ROOT);
        if (newDocument.getDefaultLocale() == Locale.ROOT) {
            newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
        }

        // Copy the template.
        readFromTemplate(newDocument, template, context);

        // Set the parent field.
        if (!StringUtils.isEmpty(parent)) {
            DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);
            newDocument.setParentReference(parentReference);
        }

        // Set the document title
        if (title != null) {
            newDocument.setTitle(title);
        }

        // Set the author and creator.
        DocumentReference currentUserReference = context.getUserReference();
        newDocument.setAuthorReference(currentUserReference);
        newDocument.setCreatorReference(currentUserReference);

        // Make sure the user is allowed to make this modification
        xwiki.checkSavingDocument(currentUserReference, newDocument, context);

        xwiki.saveDocument(newDocument, context);
    }