jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
        StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
        if (startTlsFeature != null) {
            if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
                notifyConnectionError(new SecurityRequiredByServerException());
                return;
            }

            if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
                sendNonza(new StartTls());
            }
        }
        // If TLS is required but the server doesn't offer it, disconnect
        // from the server and throw an error. First check if we've already negotiated TLS
        // and are secure, however (features get parsed a second time after TLS is established).
        if (!isSecureConnection() && startTlsFeature == null
                        && getConfiguration().getSecurityMode() == SecurityMode.required) {
            throw new SecurityRequiredByClientException();
        }

        if (getSASLAuthentication().authenticationSuccessful()) {
            // If we have received features after the SASL has been successfully completed, then we
            // have also *maybe* received, as it is an optional feature, the compression feature
            // from the server.
            maybeCompressFeaturesReceived.reportSuccess();
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerWindowItemsPacket packet) {
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        inventory.setStateId(packet.getStateId());

        for (int i = 0; i < packet.getItems().length; i++) {
            GeyserItemStack newItem = GeyserItemStack.from(packet.getItems()[i]);
            inventory.setItem(i, newItem, session);
        }

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            translator.updateInventory(session, inventory);
        }

        session.getPlayerInventory().setCursor(GeyserItemStack.from(packet.getCarriedItem()), session);
        InventoryUtils.updateCursor(session);
    }
//  [java]
    public void translate(ServerWindowItemsPacket packet, GeyserSession session) {
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        inventory.setStateId(packet.getStateId());

        for (int i = 0; i < packet.getItems().length; i++) {
            GeyserItemStack newItem = GeyserItemStack.from(packet.getItems()[i]);
            inventory.setItem(i, newItem, session);
        }

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            translator.updateInventory(session, inventory);
        }

        session.getPlayerInventory().setCursor(GeyserItemStack.from(packet.getCarriedItem()), session);
        InventoryUtils.updateCursor(session);
    }
//  [java]
    public int validateUser(boolean withConfirmEmail, XWikiContext context) throws XWikiException
    {
        try {
            XWikiRequest request = context.getRequest();
            // Get the user document
            String username = convertUsername(request.getParameter("xwikiname"), context);
            if (username.indexOf('.') == -1) {
                username = "XWiki." + username;
            }
            XWikiDocument userDocument = getDocument(username, context);

            // Get the stored validation key
            BaseObject userObject = userDocument.getObject("XWiki.XWikiUsers", 0);
            String storedKey = userObject.getStringValue("validkey");

            // Get the validation key from the URL
            String validationKey = request.getParameter("validkey");
            PropertyInterface validationKeyClass = getClass("XWiki.XWikiUsers", context).get("validkey");
            if (validationKeyClass instanceof PasswordClass) {
                validationKey = ((PasswordClass) validationKeyClass).getEquivalentPassword(storedKey, validationKey);
            }

            // Compare the two keys
            if ((!storedKey.equals("") && (storedKey.equals(validationKey)))) {
                // Ensure to remove the validation key value, so it cannot be used afterwards to enable back
                // a disabled user.
                userObject.setStringValue("validkey", "");
                saveDocument(userDocument, context);

                XWikiUser xWikiUser = new XWikiUser(userDocument.getDocumentReference());
                xWikiUser.setDisabled(false, context);
                xWikiUser.setEmailChecked(true, context);

                if (withConfirmEmail) {
                    String email = userObject.getStringValue("email");
                    String password = userObject.getStringValue("password");
                    sendValidationEmail(username, password, email, request.getParameter("validkey"),
                        "confirmation_email_content", context);
                }

                return 0;
            } else {
                return -1;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);

            throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_VALIDATE_USER,
                "Exception while validating user", e, null);
        }
    }
//  [java]
    public int validateUser(boolean withConfirmEmail, XWikiContext context) throws XWikiException
    {
        try {
            XWikiRequest request = context.getRequest();
            // Get the user document
            String username = convertUsername(request.getParameter("xwikiname"), context);
            if (username.indexOf('.') == -1) {
                username = "XWiki." + username;
            }
            XWikiDocument userDocument = getDocument(username, context);

            // Get the stored validation key
            BaseObject userObject = userDocument.getObject("XWiki.XWikiUsers", 0);
            String storedKey = userObject.getStringValue("validkey");

            // Get the validation key from the URL
            String validationKey = request.getParameter("validkey");
            PropertyInterface validationKeyClass = getClass("XWiki.XWikiUsers", context).get("validkey");
            if (validationKeyClass instanceof PasswordClass) {
                validationKey = ((PasswordClass) validationKeyClass).getEquivalentPassword(storedKey, validationKey);
            }

            // Compare the two keys
            if ((!storedKey.equals("") && (storedKey.equals(validationKey)))) {
                XWikiUser xWikiUser = new XWikiUser(userDocument.getDocumentReference());
                xWikiUser.setDisabled(false, context);
                xWikiUser.setEmailChecked(true, context);
                saveDocument(userDocument, context);

                if (withConfirmEmail) {
                    String email = userObject.getStringValue("email");
                    String password = userObject.getStringValue("password");
                    sendValidationEmail(username, password, email, request.getParameter("validkey"),
                        "confirmation_email_content", context);
                }

                return 0;
            } else {
                return -1;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);

            throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_VALIDATE_USER,
                "Exception while validating user", e, null);
        }
    }
//  [java]
    private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        String oldName = request.getParameter("groupName");
        String newName = request.getParameter("newName");

        if (newName != null && newName.matches(".*[&<>\"`']+.*")) {
            throw new ServletException("Group ID must not contain any HTML markup.");
        }

        if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
            m_groupRepository.renameGroup(oldName, newName);
        }
        
        return listGroups(request, response);
    }
//  [java]
    private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        String oldName = request.getParameter("groupName");
        String newName = request.getParameter("newName");
        
        if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
            m_groupRepository.renameGroup(oldName, newName);
        }
        
        return listGroups(request, response);
    }
//  [java]
    public void translate(GeyserSession session, ServerPlayerSetExperiencePacket packet) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        AttributeData experience = GeyserAttributeType.EXPERIENCE.getAttribute(packet.getExperience());
        entity.getAttributes().put(GeyserAttributeType.EXPERIENCE, experience);
        AttributeData experienceLevel = GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(packet.getLevel());
        entity.getAttributes().put(GeyserAttributeType.EXPERIENCE_LEVEL, experienceLevel);

        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());
        attributesPacket.setAttributes(Arrays.asList(experience, experienceLevel));
        session.sendUpstreamPacket(attributesPacket);
    }
//  [java]
    public void translate(ServerPlayerSetExperiencePacket packet, GeyserSession session) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        AttributeData experience = GeyserAttributeType.EXPERIENCE.getAttribute(packet.getExperience());
        entity.getAttributes().put(GeyserAttributeType.EXPERIENCE, experience);
        AttributeData experienceLevel = GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(packet.getLevel());
        entity.getAttributes().put(GeyserAttributeType.EXPERIENCE_LEVEL, experienceLevel);

        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());
        attributesPacket.setAttributes(Arrays.asList(experience, experienceLevel));
        session.sendUpstreamPacket(attributesPacket);
    }
//  [java]
    public RedirectView callback(@RequestParam(defaultValue = "/") String redirect,
                                 @PathVariable String serverId,
                                 @RequestParam String code,
                                 @RequestParam String state,
                                 HttpServletRequest request,
                                 HttpSession session) throws UnsupportedEncodingException {
        try {
            String cachedState = (String) session.getAttribute(STATE_SESSION_KEY);
            if (!state.equals(cachedState)) {
                throw new BusinessException(ErrorType.STATE_ERROR.name());
            }
            oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter));
            return new RedirectView(URLDecoder.decode(redirect, "UTF-8"));
        } finally {
            session.removeAttribute(STATE_SESSION_KEY);
        }
    }
//  [java]
    public RedirectView callback(@RequestParam(defaultValue = "/") String redirect,
                                 @PathVariable String serverId,
                                 @RequestParam String code,
                                 @RequestParam String state,
                                 HttpServletRequest request,
                                 HttpSession session) throws UnsupportedEncodingException {
        try {
            String cachedState = (String) session.getAttribute(STATE_SESSION_KEY);
            //  if (!state.equals(cachedState)) throw new BusinessException("state error");
            oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter));
            return new RedirectView(URLDecoder.decode(redirect, "UTF-8"));
        } finally {
            session.removeAttribute(STATE_SESSION_KEY);
        }
    }
//  [java]
    public void translate(GeyserSession session, AdventureSettingsPacket packet) {
        boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);
        if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) {
            // We should always be flying in spectator mode
            session.sendAdventureSettings();
            return;
        }

        session.setFlying(isFlying);
        ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying);
        session.sendDownstreamPacket(abilitiesPacket);

        if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {
            // Bedrock can fly and swim at the same time? Make sure that can't happen
            session.setSwimming(false);
        }
    }
//  [java]
    public void translate(AdventureSettingsPacket packet, GeyserSession session) {
        boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);
        if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) {
            // We should always be flying in spectator mode
            session.sendAdventureSettings();
            return;
        }

        session.setFlying(isFlying);
        ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying);
        session.sendDownstreamPacket(abilitiesPacket);

        if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {
            // Bedrock can fly and swim at the same time? Make sure that can't happen
            session.setSwimming(false);
        }
    }
//  [java]
	private void processReturnFiles(VFSLeaf target, List<BulkAssessmentRow> rows) {
		Map<String, BulkAssessmentRow> assessedIdToRow = new HashMap<>();
		for(BulkAssessmentRow row:rows) {
			assessedIdToRow.put(row.getAssessedId(), row);
		}

		if(target.exists()) {
			File parentTarget = ((LocalImpl)target).getBasefile().getParentFile();

			ZipEntry entry;
			try(InputStream is = target.getInputStream();
					ZipInputStream zis = new ZipInputStream(is)) {
				byte[] b = new byte[FileUtils.BSIZE];
				while ((entry = zis.getNextEntry()) != null) {//TODO zip
					if(!entry.isDirectory()) {
						while (zis.read(b) > 0) {
							//continue
						}

						Path op = new File(parentTarget, entry.getName()).toPath();
						if(!Files.isHidden(op) && !op.toFile().isDirectory()) {
							Path parentDir = op.getParent();
							String assessedId = parentDir.getFileName().toString();
							String filename = op.getFileName().toString();

							BulkAssessmentRow row;
							if(assessedIdToRow.containsKey(assessedId)) {
								row = assessedIdToRow.get(assessedId);
							} else {
								row = new BulkAssessmentRow();
								row.setAssessedId(assessedId);
								assessedIdToRow.put(assessedId, row);
								rows.add(row);
							}

							if(row.getReturnFiles() == null) {
								row.setReturnFiles(new ArrayList<String>(2));
							}
							row.getReturnFiles().add(filename);
						}
					}
				}
			} catch(Exception e) {
				logError("", e);
			}
		}
	}
//  [java]
	private void processReturnFiles(VFSLeaf target, List<BulkAssessmentRow> rows) {
		Map<String, BulkAssessmentRow> assessedIdToRow = new HashMap<>();
		for(BulkAssessmentRow row:rows) {
			assessedIdToRow.put(row.getAssessedId(), row);
		}

		if(target.exists()) {
			File parentTarget = ((LocalImpl)target).getBasefile().getParentFile();

			ZipEntry entry;
			try(InputStream is = target.getInputStream();
					ZipInputStream zis = new ZipInputStream(is)) {
				byte[] b = new byte[FileUtils.BSIZE];
				while ((entry = zis.getNextEntry()) != null) {
					if(!entry.isDirectory()) {
						while (zis.read(b) > 0) {
							//continue
						}

						Path op = new File(parentTarget, entry.getName()).toPath();
						if(!Files.isHidden(op) && !op.toFile().isDirectory()) {
							Path parentDir = op.getParent();
							String assessedId = parentDir.getFileName().toString();
							String filename = op.getFileName().toString();

							BulkAssessmentRow row;
							if(assessedIdToRow.containsKey(assessedId)) {
								row = assessedIdToRow.get(assessedId);
							} else {
								row = new BulkAssessmentRow();
								row.setAssessedId(assessedId);
								assessedIdToRow.put(assessedId, row);
								rows.add(row);
							}

							if(row.getReturnFiles() == null) {
								row.setReturnFiles(new ArrayList<String>(2));
							}
							row.getReturnFiles().add(filename);
						}
					}
				}
			} catch(Exception e) {
				logError("", e);
			}
		}
	}
//  [java]
    protected List<String> getRawCommandLine( String executable, String[] arguments )
    {
        List<String> commandLine = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();

        if ( executable != null )
        {
            String preamble = getExecutionPreamble();
            if ( preamble != null )
            {
                sb.append( preamble );
            }

            if ( isQuotedExecutableEnabled() )
            {
                sb.append( quoteOneItem( getOriginalExecutable(), true ) );
            }
            else
            {
                sb.append( getExecutable() );
            }
        }
        for ( int i = 0; i < arguments.length; i++ )
        {
            if ( sb.length() > 0 )
            {
                sb.append( " " );
            }

            if ( isQuotedArgumentsEnabled() )
            {
                sb.append( quoteOneItem( arguments[i], false ) );
            }
            else
            {
                sb.append( arguments[i] );
            }
        }

        commandLine.add( sb.toString() );

        return commandLine;
    }
//  [java]
    protected List<String> getRawCommandLine( String executable, String[] arguments )
    {
        List<String> commandLine = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();

        if ( executable != null )
        {
            String preamble = getExecutionPreamble();
            if ( preamble != null )
            {
                sb.append( preamble );
            }

            if ( isQuotedExecutableEnabled() )
            {
                char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() );

                sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false ) );
            }
            else
            {
                sb.append( getExecutable() );
            }
        }
        for ( int i = 0; i < arguments.length; i++ )
        {
            if ( sb.length() > 0 )
            {
                sb.append( " " );
            }

            if ( isQuotedArgumentsEnabled() )
            {
                char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() );

                sb.append( StringUtils.quoteAndEscape( arguments[i], getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), getArgumentEscapePattern(), false ) );
            }
            else
            {
                sb.append( arguments[i] );
            }
        }

        commandLine.add( sb.toString() );

        return commandLine;
    }
//  [java]
        public String getShortDescription() {
            if(note != null) {
                try {
                    return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, Jenkins.getInstance().getMarkupFormatter().translate(note));
                } catch (IOException x) {
                    // ignore
                }
            }
            return Messages.Cause_RemoteCause_ShortDescription(addr);
        }
//  [java]
        public String getShortDescription() {
            if(note != null) {
                return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note);
            } else {
                return Messages.Cause_RemoteCause_ShortDescription(addr);
            }
        }
//  [java]
    public void translate(GeyserSession session, ServerSetTitlesAnimationPacket packet) {
        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.TIMES);
        titlePacket.setText("");
        titlePacket.setFadeInTime(packet.getFadeIn());
        titlePacket.setFadeOutTime(packet.getFadeOut());
        titlePacket.setStayTime(packet.getStay());
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public void translate(ServerSetTitlesAnimationPacket packet, GeyserSession session) {
        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.TIMES);
        titlePacket.setText("");
        titlePacket.setFadeInTime(packet.getFadeIn());
        titlePacket.setFadeOutTime(packet.getFadeOut());
        titlePacket.setStayTime(packet.getStay());
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
    {
        super("文件[" + filename + "]后缀[" + extension + "]不正确，请上传 [" + Arrays.toString(allowedExtension) + "]格式文件");
        this.allowedExtension = allowedExtension;
        this.extension = extension;
        this.filename = filename;
    }
//  [java]
    public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
    {
        super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
        this.allowedExtension = allowedExtension;
        this.extension = extension;
        this.filename = filename;
    }
//  [java]
    public List<String> getShellCommandLine( String[] arguments )
    {

        List<String> commandLine = new ArrayList<String>();

        if ( getShellCommand() != null )
        {
            commandLine.add( getShellCommand() );
        }

        if ( getShellArgs() != null )
        {
            commandLine.addAll( getShellArgsList() );
        }

        commandLine.addAll( getCommandLine( getOriginalExecutable(), arguments ) );

        return commandLine;

    }
//  [java]
    public List<String> getShellCommandLine( String[] arguments )
    {

        List<String> commandLine = new ArrayList<String>();

        if ( getShellCommand() != null )
        {
            commandLine.add( getShellCommand() );
        }

        if ( getShellArgs() != null )
        {
            commandLine.addAll( getShellArgsList() );
        }

        commandLine.addAll( getCommandLine( getExecutable(), arguments ) );

        return commandLine;

    }
//  [java]
    private JsonNode yamlPathToJson(Path path) throws IOException {
        Yaml reader = new Yaml(new SafeConstructor());
        ObjectMapper mapper = new ObjectMapper();
        try (InputStream in = Files.newInputStream(path)) {
        	return mapper.valueToTree(reader.load(in));
        }
    }
//  [java]
    private JsonNode yamlPathToJson(Path path) throws IOException {
        Yaml reader = new Yaml();
        ObjectMapper mapper = new ObjectMapper();
        Path p;
        
        try (InputStream in = Files.newInputStream(path)) {
        	return mapper.valueToTree(reader.load(in));
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityEffectPacket packet) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
            session.getEffectCache().setEffect(packet.getEffect(), packet.getAmplifier());
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        MobEffectPacket mobEffectPacket = new MobEffectPacket();
        mobEffectPacket.setAmplifier(packet.getAmplifier());
        mobEffectPacket.setDuration(packet.getDuration());
        mobEffectPacket.setEvent(MobEffectPacket.Event.ADD);
        mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
        mobEffectPacket.setParticles(packet.isShowParticles());
        mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
        session.sendUpstreamPacket(mobEffectPacket);
    }
//  [java]
    public void translate(ServerEntityEffectPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
            session.getEffectCache().setEffect(packet.getEffect(), packet.getAmplifier());
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        MobEffectPacket mobEffectPacket = new MobEffectPacket();
        mobEffectPacket.setAmplifier(packet.getAmplifier());
        mobEffectPacket.setDuration(packet.getDuration());
        mobEffectPacket.setEvent(MobEffectPacket.Event.ADD);
        mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
        mobEffectPacket.setParticles(packet.isShowParticles());
        mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
        session.sendUpstreamPacket(mobEffectPacket);
    }
//  [java]
	private final void servlet31(HttpServletRequest request) {
		try {
			for(Part part:request.getParts()) {
				if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) {
					contentType = part.getContentType();
					filename = part.getSubmittedFileName();
					if(filename != null && !filename.contains("..")) {
						filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
					} else {
						filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
					}
					file = new File(WebappHelper.getTmpDir(), filename);
					part.write(file.getAbsolutePath());
					file = new File(WebappHelper.getTmpDir(), filename);
				} else {
					String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding());
					fields.put(part.getName(), value);
				}
				
				try {
					part.delete();
				} catch (Exception e) {
					//we try (tomcat doesn't send exception but undertow)
				}
			}
		} catch (IOException | ServletException e) {
			log.error("", e);
		}
	}
//  [java]
	private final void servlet31(HttpServletRequest request) {
		try {
			for(Part part:request.getParts()) {
				if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) {
					contentType = part.getContentType();
					filename = part.getSubmittedFileName();
					if(filename != null) {
						filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
					} else {
						filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
					}
					file = new File(WebappHelper.getTmpDir(), filename);
					part.write(file.getAbsolutePath());
					file = new File(WebappHelper.getTmpDir(), filename);
				} else {
					String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding());
					fields.put(part.getName(), value);
				}
				
				try {
					part.delete();
				} catch (Exception e) {
					//we try (tomcat doesn't send exception but undertow)
				}
			}
		} catch (IOException | ServletException e) {
			log.error("", e);
		}
	}
//  [java]
    public static void endRequest() {
        final List<RequestScopedItem> result = CACHE.get();
        if (result != null) {
            CACHE.remove();
            for (final RequestScopedItem item : result) {
                item.invalidate();
            }
        }
    }
//  [java]
    public static void endRequest() {
        final List<RequestScopedItem> result = CACHE.get();
        CACHE.remove();
        if (result != null) {
            for (final RequestScopedItem item : result) {
                item.invalidate();
            }
        }
    }
//  [java]
    private JsonNode yamlStreamToJson(InputStream yamlStream) {
        Yaml reader = new Yaml(new SafeConstructor());
        ObjectMapper mapper = new ObjectMapper();
		return mapper.valueToTree(reader.load(yamlStream));
    }
//  [java]
    private JsonNode yamlStreamToJson(InputStream yamlStream) {
        Yaml reader = new Yaml();
        ObjectMapper mapper = new ObjectMapper();
		return mapper.valueToTree(reader.load(yamlStream));
    }
//  [java]
  public void refreshRow() throws SQLException {
    checkUpdateable();
    if (onInsertRow) {
      throw new PSQLException(GT.tr("Can''t refresh the insert row."),
          PSQLState.INVALID_CURSOR_STATE);
    }

    if (isBeforeFirst() || isAfterLast() || castNonNull(rows, "rows").isEmpty()) {
      return;
    }

    StringBuilder selectSQL = new StringBuilder("select ");

    ResultSetMetaData rsmd = getMetaData();
    PGResultSetMetaData pgmd = (PGResultSetMetaData) rsmd;
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
      if (i > 1) {
        selectSQL.append(", ");
      }
      Utils.escapeIdentifier(selectSQL, pgmd.getBaseColumnName(i));
    }
    selectSQL.append(" from ").append(onlyTable).append(tableName).append(" where ");

    List<PrimaryKey> primaryKeys = castNonNull(this.primaryKeys, "primaryKeys");
    int numKeys = primaryKeys.size();

    for (int i = 0; i < numKeys; i++) {

      PrimaryKey primaryKey = primaryKeys.get(i);
      Utils.escapeIdentifier(selectSQL, primaryKey.name);
      selectSQL.append(" = ?");

      if (i < numKeys - 1) {
        selectSQL.append(" and ");
      }
    }
    String sqlText = selectSQL.toString();
    if (connection.getLogger().isLoggable(Level.FINE)) {
      connection.getLogger().log(Level.FINE, "selecting {0}", sqlText);
    }
    // because updateable result sets do not yet support binary transfers we must request refresh
    // with updateable result set to get field data in correct format
    PreparedStatement selectStatement = null;
    try {
      selectStatement = connection.prepareStatement(sqlText,
          ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

      for (int i = 0; i < numKeys; i++) {
        selectStatement.setObject(i + 1, primaryKeys.get(i).getValue());
      }

      PgResultSet rs = (PgResultSet) selectStatement.executeQuery();

      if (rs.next()) {
        // we know that the row is updatable as it was tested above.
        if ( rs.thisRow == null ) {
          rowBuffer = null;
        } else {
          rowBuffer = castNonNull(rs.thisRow).updateableCopy();
        }
      }

      castNonNull(rows).set(currentRow, castNonNull(rowBuffer));
      thisRow = rowBuffer;

      connection.getLogger().log(Level.FINE, "done updates");

      rs.close();
    } finally {
      JdbcBlackHole.close(selectStatement);
    }
  }
//  [java]
  public void refreshRow() throws SQLException {
    checkUpdateable();
    if (onInsertRow) {
      throw new PSQLException(GT.tr("Can''t refresh the insert row."),
          PSQLState.INVALID_CURSOR_STATE);
    }

    if (isBeforeFirst() || isAfterLast() || castNonNull(rows, "rows").isEmpty()) {
      return;
    }

    StringBuilder selectSQL = new StringBuilder("select ");

    ResultSetMetaData rsmd = getMetaData();
    PGResultSetMetaData pgmd = (PGResultSetMetaData) rsmd;
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
      if (i > 1) {
        selectSQL.append(", ");
      }
      selectSQL.append(pgmd.getBaseColumnName(i));
    }
    selectSQL.append(" from ").append(onlyTable).append(tableName).append(" where ");

    List<PrimaryKey> primaryKeys = castNonNull(this.primaryKeys, "primaryKeys");
    int numKeys = primaryKeys.size();

    for (int i = 0; i < numKeys; i++) {

      PrimaryKey primaryKey = primaryKeys.get(i);
      selectSQL.append(primaryKey.name).append(" = ?");

      if (i < numKeys - 1) {
        selectSQL.append(" and ");
      }
    }
    String sqlText = selectSQL.toString();
    if (connection.getLogger().isLoggable(Level.FINE)) {
      connection.getLogger().log(Level.FINE, "selecting {0}", sqlText);
    }
    // because updateable result sets do not yet support binary transfers we must request refresh
    // with updateable result set to get field data in correct format
    PreparedStatement selectStatement = null;
    try {
      selectStatement = connection.prepareStatement(sqlText,
          ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

      for (int i = 0; i < numKeys; i++) {
        selectStatement.setObject(i + 1, primaryKeys.get(i).getValue());
      }

      PgResultSet rs = (PgResultSet) selectStatement.executeQuery();

      if (rs.next()) {
        // we know that the row is updatable as it was tested above.
        if ( rs.thisRow == null ) {
          rowBuffer = null;
        } else {
          rowBuffer = castNonNull(rs.thisRow).updateableCopy();
        }
      }

      castNonNull(rows).set(currentRow, castNonNull(rowBuffer));
      thisRow = rowBuffer;

      connection.getLogger().log(Level.FINE, "done updates");

      rs.close();
    } finally {
      JdbcBlackHole.close(selectStatement);
    }
  }
//  [java]
	public String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {

		return this.displayCategory(friendlyUrl,ref,model,request,response,locale);
	}
//  [java]
	public String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
		
		
		
		return this.displayCategory(friendlyUrl,ref,model,request,response,locale);
	}
//  [java]
	public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
			byte[] ciphertext, int ciphertextOffset, int length)
			throws ShortBufferException {
		int space;
		if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)
			throw new IllegalArgumentException();
		if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)
			throw new IllegalArgumentException();
		space = ciphertext.length - ciphertextOffset;
		if (!haskey) {
			// The key is not set yet - return the plaintext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
			return length;
		}
		if (space < 16 || length > (space - 16))
			throw new ShortBufferException();
		setup(ad);
		encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
		ghash.update(ciphertext, ciphertextOffset, length);
		ghash.pad(ad != null ? ad.length : 0, length);
		ghash.finish(ciphertext, ciphertextOffset + length, 16);
		for (int index = 0; index < 16; ++index)
			ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
		return length + 16;
	}
//  [java]
	public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
			byte[] ciphertext, int ciphertextOffset, int length)
			throws ShortBufferException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (!haskey) {
			// The key is not set yet - return the plaintext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
			return length;
		}
		if (space < 16 || length > (space - 16))
			throw new ShortBufferException();
		setup(ad);
		encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
		ghash.update(ciphertext, ciphertextOffset, length);
		ghash.pad(ad != null ? ad.length : 0, length);
		ghash.finish(ciphertext, ciphertextOffset + length, 16);
		for (int index = 0; index < 16; ++index)
			ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
		return length + 16;
	}
//  [java]
	public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) {
		this.folderComponent = fc;
		this.translator = trans;
		this.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath());
				
		VelocityContainer main = new VelocityContainer("mc", VELOCITY_ROOT + "/movecopy.html", translator, this);
		main.contextPut("fileselection", fileSelection);
		
		//check if command is executed on a file list containing invalid filenames or paths
		if(!fileSelection.getInvalidFileNames().isEmpty()) {		
			main.contextPut("invalidFileNames", fileSelection.getInvalidFileNames());
		}		

		selTree = new MenuTree(null, "seltree", this);
		FolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(),
				true, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter());
		selTree.setTreeModel(ftm);
		selectButton = LinkFactory.createButton(move ? "move" : "copy", main, this);
		cancelButton = LinkFactory.createButton("cancel", main, this);

		main.put("seltree", selTree);
		if (move) {
			main.contextPut("move", Boolean.TRUE);
		}

		setInitialComponent(main);
		return this;
	}
//  [java]
	public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) {
		this.folderComponent = fc;
		this.translator = trans;
		this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());
				
		VelocityContainer main = new VelocityContainer("mc", VELOCITY_ROOT + "/movecopy.html", translator, this);
		main.contextPut("fileselection", fileSelection);
		
		//check if command is executed on a file list containing invalid filenames or paths
		if(!fileSelection.getInvalidFileNames().isEmpty()) {		
			main.contextPut("invalidFileNames", fileSelection.getInvalidFileNames());
		}		

		selTree = new MenuTree(null, "seltree", this);
		FolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(),
				true, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter());
		selTree.setTreeModel(ftm);
		selectButton = LinkFactory.createButton(move ? "move" : "copy", main, this);
		cancelButton = LinkFactory.createButton("cancel", main, this);

		main.put("seltree", selTree);
		if (move) {
			main.contextPut("move", Boolean.TRUE);
		}

		setInitialComponent(main);
		return this;
	}
//  [java]
	public int decryptWithAd(byte[] ad, byte[] ciphertext,
			int ciphertextOffset, byte[] plaintext, int plaintextOffset,
			int length) throws ShortBufferException, BadPaddingException {
		int space;
		if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)
			throw new IllegalArgumentException();
		else
			space = ciphertext.length - ciphertextOffset;
		if (length > space)
			throw new ShortBufferException();
		if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)
			throw new IllegalArgumentException();
		space = plaintext.length - plaintextOffset;
		if (!haskey) {
			// The key is not set yet - return the ciphertext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
			return length;
		}
		if (length < 16)
			Noise.throwBadTagException();
		int dataLen = length - 16;
		if (dataLen > space)
			throw new ShortBufferException();
		setup(ad);
		ghash.update(ciphertext, ciphertextOffset, dataLen);
		ghash.pad(ad != null ? ad.length : 0, dataLen);
		ghash.finish(enciv, 0, 16);
		int temp = 0;
		for (int index = 0; index < 16; ++index)
			temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
		if ((temp & 0xFF) != 0)
			Noise.throwBadTagException();
		encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
		return dataLen;
	}
//  [java]
	public int decryptWithAd(byte[] ad, byte[] ciphertext,
			int ciphertextOffset, byte[] plaintext, int plaintextOffset,
			int length) throws ShortBufferException, BadPaddingException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (length > space)
			throw new ShortBufferException();
		if (plaintextOffset > plaintext.length)
			space = 0;
		else
			space = plaintext.length - plaintextOffset;
		if (!haskey) {
			// The key is not set yet - return the ciphertext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
			return length;
		}
		if (length < 16)
			Noise.throwBadTagException();
		int dataLen = length - 16;
		if (dataLen > space)
			throw new ShortBufferException();
		setup(ad);
		ghash.update(ciphertext, ciphertextOffset, dataLen);
		ghash.pad(ad != null ? ad.length : 0, dataLen);
		ghash.finish(enciv, 0, 16);
		int temp = 0;
		for (int index = 0; index < 16; ++index)
			temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
		if ((temp & 0xFF) != 0)
			Noise.throwBadTagException();
		encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
		return dataLen;
	}
//  [java]
    private void visitorPermission(Invocation ai) {
        ai.invoke();
        String templateName = ai.getReturnValue();
        if (templateName == null) {
            return;
        }
        GlobalResourceHandler.printUserTime("Template before");
        String templatePath = TemplateHelper.fullTemplateInfo(ai.getController(), true);
        GlobalResourceHandler.printUserTime("Template after");
        TemplateVO templateVO = new TemplateService().getTemplateVO(JFinal.me().getContextPath(), new File(PathKit.getWebRootPath() + templatePath));
        String ext = ZrLogUtil.getViewExt(templateVO.getViewType());
        if (ai.getController().getAttr("log") != null) {
            ai.getController().setAttr("pageLevel", 1);
        } else if (ai.getController().getAttr("data") != null) {
            if ("/".equals(ai.getActionKey()) && new File(PathKit.getWebRootPath() + templatePath + "/" + templateName + ext).exists()) {
                ai.getController().setAttr("pageLevel", 2);
            } else {
                templateName = "page";
                ai.getController().setAttr("pageLevel", 1);
            }
        } else {
            ai.getController().setAttr("pageLevel", 2);
        }
        fullDevData(ai.getController());
        String viewPath = templatePath + "/" + templateName + ext;
        if (ext.equals(".ftl")) {
            BlogFrontendFreeMarkerRender render = new BlogFrontendFreeMarkerRender(viewPath);
            render.setContext(ai.getController().getRequest(), ai.getController().getResponse());
            ai.getController().render(render);
        } else {
            ai.getController().render(viewPath);
        }

    }
//  [java]
    private void visitorPermission(Invocation ai) {
        ai.invoke();
        String templateName = ai.getReturnValue();
        if (templateName == null) {
            return;
        }
        GlobalResourceHandler.printUserTime("Template before");
        String templatePath = TemplateHelper.fullTemplateInfo(ai.getController(), true);
        GlobalResourceHandler.printUserTime("Template after");
        TemplateVO templateVO = new TemplateService().getTemplateVO(JFinal.me().getContextPath(), new File(PathKit.getWebRootPath() + templatePath));
        String ext = ZrLogUtil.getViewExt(templateVO.getViewType());
        if (ai.getController().getAttr("log") != null) {
            ai.getController().setAttr("pageLevel", 1);
        } else if (ai.getController().getAttr("data") != null) {
            if ("/".equals(ai.getActionKey()) && new File(PathKit.getWebRootPath() + templatePath + "/" + templateName + ext).exists()) {
                ai.getController().setAttr("pageLevel", 2);
            } else {
                templateName = "page";
                ai.getController().setAttr("pageLevel", 1);
            }
        } else {
            ai.getController().setAttr("pageLevel", 2);
        }
        fullDevData(ai.getController());
        ai.getController().render(templatePath + "/" + templateName + ext);
    }
//  [java]
    private boolean processStyleTag(Element ele, Node parentNode) {
        /*
         * Invoke the css parser on this element.
         */
        CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets());

        try {
            int childNodesCount = ele.getChildNodes().getLength();
            if (childNodesCount > 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.
                 * Starting from the end due to list updating on the fly.
                 */
                for (int i = childNodesCount - 1; i >= 1; 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;
    }