<fim-prefix>t java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.olat.core.CoreSpringFactory;
import org.olat.core.configuration.AbstractSpringModule;
import org.apache.logging.log4j.Logger;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.course.site.model.CourseSiteConfiguration;
import org.olat.course.site.model.LanguageConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;

/**
 * Description:

 * This is the module for sites definition and configuration
 *
 *

 * Initial Date:  12.07.2005

 *
 * @author Felix Jost
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
@Service("olatsites")
public class SiteDefinitions extends AbstractSpringModule {

	private static final Logger log = Tracing.createLoggerFor(SiteDefinitions.class);

	private Map<String,SiteDefinition> siteDefMap;
	private Map<String,SiteConfiguration> siteConfigMap = new ConcurrentHashMap<>();

	private String configSite1;
	private String configSite2;
	private String configSite3;
	private String configSite4;
	private String sitesSettings;

	@Autowired
	private List<SiteDefinition> configurers;

	private static final XStream xStream = XStreamHelper.createXStreamInstance();
	static {
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		//
		// FIXED:
<fim-middle>		XStreamHelper.allowDefaultPackage(xStream);
		xStream.alias("coursesite", CourseSiteConfiguration.class);
		xStream.alias("languageConfig", LanguageConfiguration.class);
		xStream.alias("siteconfig"<fix-suffix>, SiteConfiguration.class);
	}

	@Autowired
	public SiteDefinitions(CoordinatorManager coordinatorManager) {
		super(coordinatorManager);
	}

	public String getConfigCourseSite1() {
		return configSite1;
	}

	public void setConfigCourseSite1(String config) {
		setStringProperty("site.1.config", config, true);
	}

	public String getConfigCourseSite2() {
		return configSite2;
	}

	public void setConfigCourseSite2(String config) {
		setStringProperty("site.2.config", config, true);
	}

	public String getConfigCourseSite3() {
		return configSite3;
	}

	public void setConfigCourseSite3(String config) {
		setStringProperty("site.3.config", config, true);
	}

	public String getConfigCourseSite4() {
		return configSite4;
	}

	public void setConfigCourseSite4(String config) {
		setStringProperty("site.4.config", config, true);
	}

	public SiteConfiguration getConfigurationSite(String id) {
		return siteConfigMap.computeIfAbsent(id, springId -> {
			SiteConfiguration c = new SiteConfiguration();
			c.setId(id);
			return c;
		});
	}

	public SiteConfiguration getConfigurationSite(SiteDefinition siteDef) {
		for(Map.Entry<String, SiteDefinition> entry: siteDefMap.entrySet()) {
			if(entry.getValue() == siteDef) {
				return getConfigurationSite(entry.getKey());
			}
		}
		return null;
	}

	public CourseSiteConfiguration getConfigurationCourseSite1() {
		if(StringHelper.containsNonWhitespace(configSite1)) {
			return (CourseSiteConfiguration)xStream.fromXML(configSite1);
		}
	<|endoftext|>


<fim-prefix>/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dashbuilder.dataprovider.sql;

import java.util.List;
import java.util.ArrayList;

import org.junit.Before;

public class SQLTestSuite extends SQLDataSetTestBase {

    protected <T extends SQLDataSetTestBase> T setUp(T test) throws Exception {
        test.testSettings = testSettings;
        test.conn = conn;
        return test;
    }

    protected List<SQLDataSetTestBase> sqlTestList = new ArrayList<SQLDataSetTestBase>();

    @Before
    public void setUp() throws Exception {
        super.setUp();
        sqlTestList.add(setUp(new SQLDataSetDefTest()));
        sqlTestList.add(setUp(new SQLDataSetTrimTest()));
        sqlTestList.add(setUp(new SQLTableDataSetLookupTest()));
        sqlTestList.add(setUp(new SQLQueryDataSetLookupTest()));
        // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
        //
        // FIXED:
<fim-middle>        sqlTestList.add(setUp(new SQLInjectionAttacksTest()));
    }

    public void testAll() throws Exception {
        for (SQLDataSetTestBase testBase : sqlTestList) {
            testBase.testAl<fix-suffix>l();
        }
    }
}
<|endoftext|>


<fim-prefix>ayer;

import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.data.game.entity.player.*;
import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.*;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.math.vector.Vector3i;
import com.nukkitx.protocol.bedrock.data.LevelEventType;
import com.nukkitx.protocol.bedrock.data.PlayerActionType;
import com.nukkitx.protocol.bedrock.data.entity.EntityEventType;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.packet.*;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.entity.player.SessionPlayerEntity;
import org.geysermc.connector.inventory.PlayerInventory;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.world.block.BlockStateValues;
import org.geysermc.connector.registry.BlockRegistries;
import org.geysermc.connector.registry.type.ItemMapping;
import org.geysermc.connector.utils.BlockUtils;

import java.util.ArrayList;

@Translator(packet = PlayerActionPacket.class)
public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(PlayerActionPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, PlayerActionPacket packet) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        // Send book update before any player action
    <fix-suffix>    if (packet.getAction() != PlayerActionType.RESPAWN) {
            session.getBookEditCache().checkForSend();
        }

        Vector3i vector = packet.getBlockPosition();
        Position position = new Position(vector.getX(), vector.getY(), vector.getZ());

        switch (packet.getAction()) {
            case RESPAWN:
                // Respawn process is finished and the server and client are both OK with respawning.
                EntityEventPacket eventPacket = new EntityEventPacket();
                eventPacket.setRuntimeEntityId(entity.getGeyserId());
                eventPacket.setType(EntityEventType.RESPAWN);
                eventPacket.setData(0);
                session.sendUpstreamPacket(eventPacket);
                // Resend attributes or else in rare cases the user can think they're not dead when they are, upon joining the server
                UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
                attributesPacket.setRuntimeEntityId(entity.getGeyserId());
                attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values()));
                session.sendUpstreamPacket(attributesPacket);
                break;
            case START_SWIMMING:
                ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING);
                session.sendDownstreamPacket(startSwimPacket);

                session.setSwimming(true);
   <|endoftext|>


<fim-prefix>package com.zrlog.web;

import com.zrlog.common.Constants;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;

public class Application {

    public static void main(String[] args) throws LifecycleException {
        String webappDirLocation;
        if (Constants.IN_JAR) {
            webappDirLocation = "webapp";
        } else {
            webappDirLocation = "src/main/webapp/";
        }

        Tomcat tomcat = new Tomcat();

        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }
        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
        // tomcat.setPort(Integer.valueOf(webPort));
        // FIXED:
<fim-middle>        tomcat.setPort(Integer.parseInt(webPort));
        tomcat.getConnector();

        // Declare an alternative location for your "WEB-INF/classes" dir
        // Servlet 3.0 annotation will work<fix-suffix>
        File additionWebInfClasses;
        if (Constants.IN_JAR) {
            additionWebInfClasses = new File("");
        } else {
            additionWebInfClasses = new File("target/classes");
        }

        tomcat.setBaseDir(additionWebInfClasses.toString());
        //idea的路径eclipse启动的路径有区别
        if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) {
            webappDirLocation = "web/" + webappDirLocation;
        }
        tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
        tomcat.start();
        tomcat.getServer().await();
    }
}
<|endoftext|>


<fim-prefix><fim-middle>ensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 *
 *<fix-suffix> The Apereo Foundation licenses this file to you under the Educational
 * Community License, Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the License
 * at:
 *
 *   http://opensource.org/licenses/ecl2.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package org.opencastproject.mediapackage.identifier;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 * Interface for an identifier.
 */
@XmlJavaTypeAdapter(Id.Adapter.class)
public interface Id {

  /**
   * Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters
   * that could potentially get into the way when creating file or directory names from the identifier.
   *
   * For example, given that the interface is implemented by a class representing CNRI handles, the identifier would
   * then look something like 10.3930/ETHZ/abcd, whith 10.3930 being the handle prefix,
   * ETH the authority and abcd the local part. toURI() would then return
   * 10.3930-ETH-abcd</code<|endoftext|>


<fim-prefix>name-with-dot"));
            svnMaterialConfig.validate(new ConfigSaveValidationContext(null));

            assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.MATERIAL_NAME)).isEqualTo("Invalid material name '.bad-name-with-dot'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.");
        }

        @Test
        void shouldEnsureDestFilePathIsValid() {
            svnMaterialConfig.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "../a"));
            svnMaterialConfig.validate(new ConfigSaveValidationContext(null));

            assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.FOLDER)).isEqualTo("Dest folder '../a' is not valid. It must be a sub-directory of the working folder.");
        }

        @Test
        void rejectsObviouslyWrongURL() {
            assertTrue(validating(svn("-url-not-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
            assertTrue(validating(svn("_url-not-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
            assertTrue(validating(svn("@url-not-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));

            assertFalse(validating(svn("url-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
            // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')
            //
            // FIXED:  <fim-middle>
            assertFalse(validating(svn("#{url}", false)).errors().containsKey(SvnMaterialConfig.URL));
        }

        private SvnMaterialConfig validating(SvnMaterialConfig svn) {
            svn<fix-suffix>.validate(new ConfigSaveValidationContext(null));
            return svn;
        }
    }

    @Nested
    class ValidateTree {
        @BeforeEach
        void setUp() {
            svnMaterialConfig.setUrl("foo/bar");
        }

        @Test
        void shouldCallValidate() {
            final MaterialConfig materialConfig = spy(svnMaterialConfig);
            final ValidationContext validationContext = mockValidationContextForSecretParams();

            materialConfig.validateTree(validationContext);

            verify(materialConfig).validate(validationContext);
        }

        @Test
        void shouldFailIfEncryptedPasswordIsIncorrect() {
            svnMaterialConfig.setEncryptedPassword("encryptedPassword");

            final boolean validationResult = svnMaterialConfig.validateTree(new ConfigSaveValidationContext(null));

            assertThat(validationResult).isFalse();
            assertThat(svnMaterialConfig.errors().on("encryptedPassword")).isEqualTo("Encrypted password value for SvnMaterial with url 'foo/bar' is invalid. This usually happens when the cipher text is modified to have an invalid value.");
        }

        @Test
        void shouldPassIfPasswordIsNotSpecifiedAsSecretParams() {
            svnMaterialConfig.setPassword("badger");

            assertThat(svnMaterialConfig.validateTree(null)).isTrue();
            assertThat(svnMaterialConfig.errors().getAll()).isEmpty();
        }
    }

    private ValidationContext mockValidationContextF<|endoftext|>


<fim-prefix>ld be parsed directly by adding it to JS.
										if (libs[j].toLowerCase()
												.endsWith(".js"))
										{
											js.append(tmp);
										}
										else
										{
											if (result.length() > 1)
											{
												result.append(",");
											}

											result.append("'" + tmp + "'");
										}
									}
								}
							}
						}
						else
						{
							String tmp = stencils.get(names[i]);

							if (tmp == null)
							{
								try
								{
									tmp = readXmlFile(
											"/stencils/" + names[i] + ".xml",
											true);

									// Cache for later use
									if (tmp != null)
									{
										stencils.put(names[i], tmp);
									}
								}
								catch (NullPointerException e)
								{
									// This seems possible according to access log so ignore stencil
								}
							}

							if (tmp != null)
							{
								if (result.length() > 1)
								{
									result.append(",");
								}

								result.append("'" + tmp + "'");
							}
						}
					}

					done.add(names[i]);
				}
			}
		}

		result.append("]");

		// LATER: Detect protocol of request in dev
		// mode to avoid security errors
		String proto = "https://";

		String setCachedUrls = "";
		String[] urls = request.getParameterValues("fetch");

		if (urls != null)
		{
			HashSet<String> completed = new HashSet<String>();

			for (int i = 0; i < urls.length; i++)
			{
				try
				{
					// Checks if URL already fetched to avoid duplicates
					// BUG: CWE-918 Server-Side Request Forgery (SSRF)
					// if (!completed.contains(urls[i]))
					// FIXED:
<fim-middle>					if (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i]))
					{
						completed.add(urls[i]);
						URL url = new URL(urls[i]);
						URLConnection connection = url.openConnection();
					<fix-suffix>	ByteArrayOutputStream stream = new ByteArrayOutputStream();
						Utils.copy(connection.getInputStream(), stream);
						setCachedUrls += "GraphViewer.cachedUrls['"
								+ StringEscapeUtils.escapeEcmaScript(urls[i])
								+ "'] = decodeURIComponent('"
								+ StringEscapeUtils.escapeEcmaScript(
										Utils.encodeURIComponent(
												stream.toString("UTF-8"),
												Utils.CHARSET_FOR_URL_ENCODING))
								+ "');";
					}
				}
				catch (Exception e)
				{
					// ignore
				}
			}
		}

		// Installs a callback to load the stencils after the viewer was injected
		return "window.onDrawioViewerLoad = function() {" + setCachedUrls
				+ "mxStencilRegistry.parseStencilSets(" + result.toString()
				+ ");" + js + "GraphViewer.processElements(); };"
				+ "var t = document.getElementsByTagName('script');"
				+ "if (t != null && t.length > 0) {"
				+ "var script = document.createElement('script');"
				+ "script.type = 'text/javascript';" + "script.src = '" + proto
				+ ((dev != null && dev.equals("1")) ? "test" : "www")
				+ ".draw.io/js/viewer-static.min.js';"
				+ "t[0].parentNode.appendChild(script);}";
	}

	public void writeStats(HttpServletResponse response) throws IOException
	{
		PrintWriter writer = new PrintWriter(response.getOutputStream());
		writer.println("");
		writer.println("");
		writer.println("Deployed: " + lastModified);
		writer.println("");
		writer.println("");
		writer.flush();
	}

	public String readXmlFi<|endoftext|>


<fim-prefix>ConversationsListItemUpdated;
import eu.siacs.conversations.ui.service.EmojiService;
import eu.siacs.conversations.ui.util.ActivityResult;
import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
import eu.siacs.conversations.ui.util.PendingItem;
import eu.siacs.conversations.utils.EmojiWrapper;
import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import rocks.xmpp.addr.Jid;

import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;

public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged {

    public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
    public static final String EXTRA_CONVERSATION = "conversationUuid";
    public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
    public static final String EXTRA_AS_QUOTE = "as_quote";
    public static final String EXTRA_NICK = "nick";
    public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
    // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
    //
    // FIXED:
<fim-middle>    public static final String EXTRA_DO_NOT_APPEND = "do_not_append";

    private static List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
            ACTION_VIEW_CONVERSATION,
            Intent.<fix-suffix>ACTION_SEND,
            Intent.ACTION_SEND_MULTIPLE
    );

    public static final int REQUEST_OPEN_MESSAGE = 0x9876;
    public static final int REQUEST_PLAY_PAUSE = 0x5432;

    //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
    private static final @IdRes
    int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
    private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
    private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
    private ActivityConversationsBinding binding;
    private boolean mActivityPaused = true;
    private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);

    private static boolean isViewOrShareIntent(Intent i) {
        Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
        return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
    }

    private static Intent createLauncherIntent(Context context) {
        final Intent intent = new Intent(context, ConversationsActivity.class);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        return intent;
    }

    @Override
    protected void refreshUiReal() {
        for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
            refreshFragment(id);
        }
    }

    @Override
    void onBackendConnected() {
 <|endoftext|>


<fim-prefix>er;
import uk.ac.ed.ph.jqtiplus.types.Identifier;
import uk.ac.ed.ph.jqtiplus.types.ResponseData.ResponseDataType;
import uk.ac.ed.ph.jqtiplus.value.BooleanValue;
import uk.ac.ed.ph.jqtiplus.value.NumberValue;
import uk.ac.ed.ph.jqtiplus.value.RecordValue;
import uk.ac.ed.ph.jqtiplus.value.SingleValue;
import uk.ac.ed.ph.jqtiplus.value.Value;
import uk.ac.ed.ph.jqtiplus.xmlutils.XmlFactories;
import uk.ac.ed.ph.jqtiplus.xmlutils.XmlResourceNotFoundException;
import uk.ac.ed.ph.jqtiplus.xmlutils.locators.ClassPathResourceLocator;
import uk.ac.ed.ph.jqtiplus.xmlutils.locators.ResourceLocator;
import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltSerializationOptions;
import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetCache;
import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetManager;
import uk.ac.ed.ph.qtiworks.mathassess.GlueValueBinder;
import uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants;
import uk.ac.ed.ph.qtiworks.mathassess.MathAssessExtensionPackage;

/**
 *
 * Initial date: 12.05.2015<br>
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
@Service
public class QTI21ServiceImpl implements QTI21Service, UserDataDeletable, InitializingBean, DisposableBean {

	private static final Logger log = Tracing.createLoggerFor(QTI21ServiceImpl.class);

	private static XStream configXstream = XStreamHelper.createXStreamInstance();
	static {
		Class<?>[] types = new Class[] {
				QTI21DeliveryOptions.class, QTI21AssessmentResultsOptions.class
		};
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		// XStream.setupDefaultSecurity(configXstream);
		// FIXED:
<fim-middle>		configXstream.addPermission(new ExplicitTypePermission(types));

		configXstream.alias("deliveryOptions", QTI21DeliveryOptions.class);
		configXstream.alias("assessmentResultsOptions", QTI21Assess<fix-suffix>mentResultsOptions.class);
	}

	@Autowired
	private DB dbInstance;
	@Autowired
	private GradingService gradingService;
	@Autowired
	private AssessmentTestSessionDAO testSessionDao;
	@Autowired
	private AssessmentItemSessionDAO itemSessionDao;
	@Autowired
	private AssessmentResponseDAO testResponseDao;
	@Autowired
	private AssessmentTestMarksDAO testMarksDao;
	@Autowired
	private AssessmentEntryDAO assessmentEntryDao;
	@Autowired
	private QTI21Module qtiModule;
	@Autowired
	private CoordinatorManager coordinatorManager;
	@Autowired
	private MailManager mailManager;

	private JqtiExtensionManager jqtiExtensionManager;
	private XsltStylesheetManager xsltStylesheetManager;
	private InfinispanXsltStylesheetCache xsltStylesheetCache;
	private CacheWrapper<File,ResolvedAssessmentTest> assessmentTestsCache;
	private CacheWrapper<File,ResolvedAssessmentItem> assessmentItemsCache;
	private CacheWrapper<AssessmentTestSession,TestSessionController> testSessionControllersCache;

	private final ConcurrentMap<String,URI> resourceToTestURI = new ConcurrentHashMap<>();

	@Autowired
	public QTI21ServiceImpl(InfinispanXsltStylesheetCache xsltStylesheetCache) {
		this.xsltStylesheetCache = xsltStylesheetCache;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
    	final List<JqtiExtensionPackage<?>> extensionPackages = new ArrayList<>();

        /* Enable MathAssess extensions if requested */
        if (qtiModule.isMathAssessExtensionEnabled()) {
            log.info("En<|endoftext|>


<fim-prefix><fim-middle>right 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net>
 * Distributed under the terms of either:
 * - the common development and distribution license (CDDL), v1.0; or
 * - the GNU Less<fix-suffix>er General Public License, v2.1 or later
 */
package winstone;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * Response for servlet
 *
 * @author Rick Knowles
 * @version $Id: WinstoneResponse.java,v 1.28 2005/04/19 07:33:41 rickknowles
 *          Exp $
 */
public class WinstoneResponse implements HttpServletResponse {
    private static final DateFormat HTTP_DF = new SimpleDateFormat(
            "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    private static final DateFormat VERSION0_DF = new SimpleDateFormat(
            "EEE, dd-MMM-yy HH:mm:ss z", Locale.US);
    static {
        HTTP_DF.setTimeZone(TimeZone.getTimeZone("GMT"));
        VERSION0_DF.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    static final String CONTENT_LENGTH_HEADER = "Content-Length";
    static final String CONTENT_TYPE_HEADER = "Content-Type";

    // Response header constants
    private static final String CONTENT_LANGUAGE_HEADER = "Content-Language";
    private static fi<|endoftext|>


<fim-prefix> userRequest.getHttpReq().getParameter("key");
		if (emKey == null) {
			emKey = userRequest.getIdentity().getUser().getProperty("emchangeKey", null);
		}
		if (emKey != null) {
			// key exist
			// we check if given key is a valid temporary key
			tempKey = rm.loadTemporaryKeyByRegistrationKey(emKey);
		}
	}

	@Override
	public boolean isUserInteractionRequired(UserRequest ureq) {
		User user = ureq.getIdentity().getUser();
		if(StringHelper.containsNonWhitespace(user.getProperty("emchangeKey", null))) {
			if (isLinkTimeUp()) {
				deleteRegistrationKey();
			} else {
				if (isLinkClicked()) {
					changeEMail(getWindowControl());
				} else {
		    		Boolean alreadySeen = ((Boolean)ureq.getUserSession().getEntry(PRESENTED_EMAIL_CHANGE_REMINDER));
		    		if (alreadySeen == null) {
		    			getWindowControl().setWarning(getPackageTranslator().translate("email.change.reminder"));
		    			ureq.getUserSession().putEntry(PRESENTED_EMAIL_CHANGE_REMINDER, Boolean.TRUE);
		    		}
				}
			}
		} else {
			String value = user.getProperty("emailDisabled", null);
			if (value != null && value.equals("true")) {
				Translator translator = Util.createPackageTranslator(HomeMainController.class, ureq.getLocale());
				getWindowControl().setWarning(translator.translate("email.disabled"));
			}
		}
		return false;
	}

	/**
	 * change email
	 * @param wControl
	 * @return
	 */
	public boolean changeEMail(WindowControl wControl) {
		XStream xml = XStreamHelper.createXStreamInstance();
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		//
		// FIXED:
<fim-middle>		XStreamHelper.allowDefaultPackage(xml);
		@SuppressWarnings("unchecked")
		HashMap<String, String> mails = (HashMap<String, String>) xml.fromXML(tempKey.getEmailAddress());

		Identity identity = <fix-suffix>securityManager.loadIdentityByKey(tempKey.getIdentityKey());
		if (identity != null) {
			String oldEmail = identity.getUser().getEmail();
			identity.getUser().setProperty("email", mails.get("changedEMail"));
			// if old mail address closed then set the new mail address
			// unclosed
			String value = identity.getUser().getProperty("emailDisabled", null);
			if (value != null && value.equals("true")) {
				identity.getUser().setProperty("emailDisabled", "false");
			}
			identity.getUser().setProperty("email", mails.get("changedEMail"));
			// success info message
			String currentEmailDisplay = userManager.getUserDisplayEmail(mails.get("currentEMail"), userRequest.getLocale());
			String changedEmailDisplay = userManager.getUserDisplayEmail(mails.get("changedEMail"), userRequest.getLocale());
			wControl.setInfo(pT.translate("success.change.email", new String[] { currentEmailDisplay, changedEmailDisplay }));
			// remove keys
			identity.getUser().setProperty("emchangeKey", null);
			userRequest.getUserSession().removeEntryFromNonClearedStore(ChangeEMailController.CHANGE_EMAIL_ENTRY);
			securityManager.deleteInvalidAuthenticationsByEmail(oldEmail);
		} else {
			// error message
			wControl.setWarning(pT.translate("error.change.email.unexpected", new String[] { mails.get("currentEMail"), mails.get("changedEMail") }));
		}
		// delete registration key
		rm.deleteTemporaryKeyWithId(tempKey.getRegistrationKey());

		return true;
	}

	public boolean isLinkClicked() {
		Ob<|endoftext|>


<fim-prefix>bla.Dispatcher",ConfigKey.AGENT_ID,"test");
        new BackendManager(config,log);
    }

    @Test
    public void debugging() {
        RecordingLogHandler lhandler = new RecordingLogHandler();
        BackendManager backendManager = new BackendManager(config,lhandler);
        lhandler.error = 0;
        lhandler.debug = 0;
        lhandler.info = 0;

        backendManager.debug("test");
        assertEquals(lhandler.debug,1);
        backendManager.error("test",new Exception());
        assertEquals(lhandler.error,1);
        backendManager.info("test");
        assertEquals(lhandler.info,1);
        backendManager.destroy();
    }

    @Test
    public void defaultConfig() {
        Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test");
        BackendManager backendManager = new BackendManager(config,log);
        backendManager.destroy();
    }

    @Test
    public void doubleInit() {
        BackendManager b1 = new BackendManager(config,log);
        BackendManager b2 = new BackendManager(config,log);
        b2.destroy();
        b1.destroy();
    }

    @Test
    public void remoteAccessCheck() {
        BackendManager backendManager = new BackendManager(config,log);
        assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1"));
        backendManager.destroy();
    }

    @Test
    public void corsAccessCheck() {
        BackendManager backendManager = new BackendManager(config,log);
        // BUG: CWE-352 Cross-Site Request Forgery (CSRF)
        // assertTrue(backendManager.isCorsAccessAllowed("http://bla.com"));
        // FIXED:
<fim-middle>        assertTrue(backendManager.isOriginAllowed("http://bla.com",false));
        backendManager.destroy();
    }

    @Test
    public void convertError() throws MalformedObjectNameException {
    <fix-suffix>    BackendManager backendManager = new BackendManager(config,log);
        Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb"));
        JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build();
        JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req);
        assertTrue(!jsonError.containsKey("stackTrace"));
        assertEquals(jsonError.get("message"),"Hans");
        assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb");
        backendManager.destroy();
    }

    // =========================================================================================

    static class RequestDispatcherTest implements RequestDispatcher {

        static boolean called = false;

        public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) {
            assertNotNull(pConverters);
            assertNotNull(pRestrictor);
        }

        public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {
            called = true;
            if (pJmxReq.getType() == RequestType.READ) {
                return new JSONObject();
            } else if (pJmxReq.getType() == RequestType.WRITE) {
                return "faultyFormat";
            } else if (pJmxReq.getType() == RequestType.LIST) {
           <|endoftext|>


<fim-prefix>ve copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientRenameItemPacket;
import com.nukkitx.protocol.bedrock.packet.FilterTextPacket;
import org.geysermc.connector.inventory.AnvilContainer;
import org.geysermc.connector.inventory.CartographyContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

/**
 * Used to send strings to the server and filter out unwanted words.
 * Java doesn't care, so we don't care, and we approve all strings.
 */
@Translator(packet = FilterTextPacket.class)
public class BedrockFilterTextTranslator extends PacketTranslator<FilterTextPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(FilterTextPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, FilterTextPacket packet) {
        if (session.getOpenInventory() instanceof CartographyContainer) {
            // We don't want to be able to rename <fix-suffix>in the cartography table
            return;
        }
        packet.setFromServer(true);
        session.sendUpstreamPacket(packet);

        if (session.getOpenInventory() instanceof AnvilContainer) {
            // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
            ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
            session.sendDownstreamPacket(renameItemPacket);
        }
    }
}
<|endoftext|>


<fim-prefix><fim-middle> - Online Learning and Training

* http://www.olat.org
*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License<fix-suffix>.

* You may obtain a copy of the License at
*

* http://www.apache.org/licenses/LICENSE-2.0
*

* Unless required by applicable law or agreed to in writing,

* software distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.
*

* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),

* University of Zurich, Switzerland.
*

*
* OpenOLAT - Online Learning and Training

* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
*

* Initial code contributed and copyrighted by

* JGS goodsolutions GmbH, http://www.goodsolutions.ch
*

*/
package org.olat.core.util.prefs.db;

import java.util.Iterator;
import java.util.List;

import org.apache.logging.log4j.Logger;
import org.olat.core.id.Identity;
import org.olat.core.logging.Tracing;
import org.olat.core.util.prefs.Preferences;
import org.olat.core.util.prefs.PreferencesStorage;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.properties.Property;
import org.olat.properties.PropertyManager;

import com.thoughtworks.xstream.XStream;

/**
 * Description:

 *

 * Initial Date: 21.06.2006

 *
 * @author Felix Jost
 */
public class DbStorage implements <|endoftext|>


<fim-prefix><fim-middle>right 2021 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the <fix-suffix>License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thoughtworks.go.config.materials.git;

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.*;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.ReflectionUtil;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static com.thoughtworks.go.helper.MaterialConfigsMother.git;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class GitMaterialConfigTest {
    @Test
    void shouldBePasswordAwareMaterial() {
        assertTrue(PasswordAwareMaterial.class.isAssignableFrom(GitMaterialConfig.class));
    }

    @Test
    void shouldSetConfigAttributes() {
        GitMaterialConfig gitMaterialConfig = git("");

        Map<String, String> map = new HashMap<>();
        map.put(GitMaterialConfig.URL, "url");
        map.put(GitMaterialConfig.BRANCH, "some-branch");
        map.put(GitMaterialConfig.SHALLOW_CLONE, "true");
        map<|endoftext|>


<fim-prefix><fim-middle>s, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "Licens<fix-suffix>e");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package io.undertow.protocols.http2;

import io.undertow.util.HeaderMap;
import io.undertow.util.HeaderValues;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;

import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static io.undertow.protocols.http2.Hpack.HeaderField;
import static io.undertow.protocols.http2.Hpack.STATIC_TABLE;
import static io.undertow.protocols.http2.Hpack.STATIC_TABLE_LENGTH;
import static io.undertow.protocols.http2.Hpack.encodeInteger;

/**
 * Encoder for HPACK frames.
 *
 * @author Stuart Douglas
 */
public class HpackEncoder {

    private static final Set<HttpString> SKIP;

    static {
        Set<HttpString> set = new HashSet<>();
        set.add(Headers.CONNECTION);
        set.add(Headers.TRANSFER_ENCODING);
        set.add(H<|endoftext|>


<fim-prefix>		}

		var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);
		var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),
				ZoneOffset.UTC);

		var nowDay = LocalDate.now(ZoneOffset.UTC);
		if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {
			return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow");
		}

		var responseBuilder = ResponseEntity.ok();
		if (principal instanceof Jwt) {
			var originalJWT = (Jwt) principal;
			var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))
					.setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject())
					.setExpiration(Date
							.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))
					.claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate());
			if (originalJWT.containsClaim("fake")) {
				jwtBuilder.claim("fake", originalJWT.getClaim("fake"));
			}
			String jwt = jwtBuilder.signWith(secondDayKey).compact();
			responseBuilder.header("Authorization", "Bearer " + jwt);
			responseBuilder.header("X-Exposed-Token", "Bearer " + jwt);
		}
		Callable<ResponseEntity<String>> cb = () -> {
			normalizeRequestTime(now);
			return responseBuilder.body("OK");
		};
		return cb;
	}

	@PostMapping(value = "/exposednextday")
	@Loggable
	// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
	//
	// FIXED:
<fim-middle>	@ResponseRetention(time = "application.response.retention.time.exposednextday")
	@Transactional
	@Operation(description = "Allows the client to send the last exposed key of the infection to the backe<fix-suffix>nd server. The JWT must come from a previous call to /exposed")
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"),
			@ApiResponse(responseCode = "400", description =
					"- Ivnalid base64 encoded Temporary Exposure Key" +
					"- TEK-date does not match delayedKeyDAte claim in Jwt" +
					"- TEK has negative rolling period"),
			@ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") })
	public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond(
			@Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay,
			@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
			@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) {
		var now = Instant.now().toEpochMilli();

		if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {
			return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
		}
		if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) {
			return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body(<|endoftext|>


<fim-prefix><fim-middle>g.bouncycastle.pqc.jcajce.provider.xmss;

import java.io.IOException;
import java.security.PrivateKey;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyI<fix-suffix>nfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;
import org.bouncycastle.pqc.asn1.XMSSKeyParams;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDS;
import org.bouncycastle.pqc.crypto.xmss.XMSSParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;
import org.bouncycastle.util.Arrays;

public class BCXMSSPrivateKey
    implements PrivateKey, XMSSKey
{
    private final XMSSPrivateKeyParameters keyParams;
    private final ASN1ObjectIdentifier treeDigest;

    public BCXMSSPrivateKey(
        ASN1ObjectIdentifier treeDigest,
        XMSSPrivateKeyParameters keyParams)
    {
        this.treeDigest = treeDigest;
        this.keyParams = keyParams;
    }

    public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
        throws IOException
    {
        XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
        this.treeDigest = keyParams.getTreeDigest().getAlgorithm();

        XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());

        try
        {
            XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
                .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDige<|endoftext|>


<fim-prefix>SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientClickWindowButtonPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;
import com.nukkitx.protocol.bedrock.packet.LecternUpdatePacket;
import org.geysermc.connector.inventory.LecternContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.InventoryUtils;

/**
 * Used to translate moving pages, or closing the inventory
 */
@Translator(packet = LecternUpdatePacket.class)
public class BedrockLecternUpdateTranslator extends PacketTranslator<LecternUpdatePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(LecternUpdatePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, LecternUpdatePacket packet) {
        if (packet.isDroppingBook()) {
            // Bedrock drops the book outside of the GUI. Java drops it in the GUI<fix-suffix>
            // So, we enter the GUI and then drop it! :)
            session.setDroppingLecternBook(true);

            // Emulate an interact packet
            ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(
                    new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
                    BlockFace.DOWN,
                    Hand.MAIN_HAND,
                    0, 0, 0, // Java doesn't care about these when dealing with a lectern
                    false);
            session.sendDownstreamPacket(blockPacket);
        } else {
            // Bedrock wants to either move a page or exit
            if (!(session.getOpenInventory() instanceof LecternContainer)) {
                session.getConnector().getLogger().debug("Expected lectern but it wasn't open!");
                return;
            }

            LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory();
            if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) {
                // The same page means Bedrock is closing the window
                ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId());
                session.sendDownstreamPacket(closeWindowPacket);
                InventoryUtils.closeInventory(session, lecternContainer.getId(), false);
            } else {
                // Each "page" Bedrock gives to us actu<|endoftext|>


<fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerAbilitiesPacket;
import com.nukkitx.protocol.bedrock.data.AdventureSetting;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.packet.AdventureSettingsPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.c<|endoftext|>


<fim-prefix>    } finally {
            buffer.release();
        }
    }

    @Test
    public void testCopy() {
        ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
        ByteBuf copy = buf.copy();

        Assert.assertEquals(buf, copy);

        buf.release();
        copy.release();
    }

    @Test
    public void testCopyWithOffset() {
        ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
        ByteBuf copy = buf.copy(1, 9);

        Assert.assertEquals(buf.slice(1, 9), copy);

        buf.release();
        copy.release();
    }

    // Test for https://github.com/netty/netty/issues/1708
    @Test
    public void testWrapBufferWithNonZeroPosition() {
        ByteBuf buf = buffer(((ByteBuffer) allocate(16)
                .putLong(1).flip().position(1)).asReadOnlyBuffer());

        ByteBuf slice = buf.slice();
        Assert.assertEquals(buf, slice);

        buf.release();
    }

    @Test
    public void testWrapBufferRoundTrip() {
        ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());

        Assert.assertEquals(1, buf.readInt());

        ByteBuffer nioBuffer = buf.nioBuffer();

        // Ensure this can be accessed without throwing a BufferUnderflowException
        Assert.assertEquals(2, nioBuffer.getInt());

        buf.release();
    }

    @Test
    public void testWrapMemoryMapped() throws Exception {
        // BUG: CWE-378 Creation of Temporary File With Insecure Permissions
        // File file = File.createTempFile("netty-test", "tmp");
        // FIXED:
<fim-middle>        File file = PlatformDependent.createTempFile("netty-test", "tmp", null);
        FileChannel output = null;
        FileChannel input = null;
        ByteBuf b1 = null;
        ByteBuf b2 = nu<fix-suffix>ll;

        try {
            output = new RandomAccessFile(file, "rw").getChannel();
            byte[] bytes = new byte[1024];
            PlatformDependent.threadLocalRandom().nextBytes(bytes);
            output.write(ByteBuffer.wrap(bytes));

            input = new RandomAccessFile(file, "r").getChannel();
            ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());

            b1 = buffer(m);

            ByteBuffer dup = m.duplicate();
            dup.position(2);
            dup.limit(4);

            b2 = buffer(dup);

            Assert.assertEquals(b2, b1.slice(2, 2));
        } finally {
            if (b1 != null) {
                b1.release();
            }
            if (b2 != null) {
                b2.release();
            }
            if (output != null) {
                output.close();
            }
            if (input != null) {
                input.close();
            }
            file.delete();
        }
    }

    @Test
    public void testMemoryAddress() {
        ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
        try {
            Assert.assertFalse(buf.hasMemoryAddress());
            try {
                buf.memoryAddress();
                Assert.fail();
            } catch (UnsupportedOperationException expected) {
                // expected
            }
        } finally {
            buf.release();
        }
    }
}
<|endoftext|>


<fim-prefix>rt org.olat.core.logging.Tracing;
import org.olat.core.util.CodeHelper;
import org.olat.core.util.FileUtils;
import org.olat.core.util.vfs.LocalFolderImpl;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.VFSManager;
import org.olat.core.util.xml.XMLParser;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.fileresource.FileResourceManager;
import org.olat.ims.cp.objects.CPOrganization;
import org.olat.ims.cp.objects.CPResource;
import org.olat.ims.cp.ui.CPPackageConfig;
import org.olat.ims.cp.ui.CPPage;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryManager;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.ExplicitTypePermission;

/**
 * The CP manager implementation.
 *

 * In many cases, method calls are delegated to the content package object.
 *
 *

 * Initial Date: 04.07.2008

 *
 * @author Sergio Trentini
 */
@Service("org.olat.ims.cp.CPManager")
public class CPManagerImpl implements CPManager {

	private static final Logger log = Tracing.createLoggerFor(CPManagerImpl.class);

	public static final String PACKAGE_CONFIG_FILE_NAME = "CPPackageConfig.xml";

	private static XStream configXstream = XStreamHelper.createXStreamInstance();
	static {
		Class<?>[] types = new Class[] {
				CPPackageConfig.class, DeliveryOptions.class
			};
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		// XStream.setupDefaultSecurity(configXstream);
		// FIXED:
<fim-middle>		configXstream.addPermission(new ExplicitTypePermission(types));
		configXstream.alias("packageConfig", CPPackageConfig.class);
		configXstream.alias("deliveryOptions", DeliveryOptions.class);
	}

	@<fix-suffix>Override
	public CPPackageConfig getCPPackageConfig(OLATResourceable ores) {
		FileResourceManager frm = FileResourceManager.getInstance();
		File reFolder = frm.getFileResourceRoot(ores);
		File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);

		CPPackageConfig config;
		if(configXml.exists()) {
			config = (CPPackageConfig)configXstream.fromXML(configXml);
		} else {
			//set default config
			config = new CPPackageConfig();
			config.setDeliveryOptions(DeliveryOptions.defaultWithGlossary());
			setCPPackageConfig(ores, config);
		}
		return config;
	}

	@Override
	public void setCPPackageConfig(OLATResourceable ores, CPPackageConfig config) {
		FileResourceManager frm = FileResourceManager.getInstance();
		File reFolder = frm.getFileResourceRoot(ores);
		File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);
		if(config == null) {
			FileUtils.deleteFile(configXml);
		} else {
			try(OutputStream out = new FileOutputStream(configXml)) {
				configXstream.toXML(config, out);
			} catch (IOException e) {
				log.error("", e);
			}
		}
	}

	@Override
	public ContentPackage load(VFSContainer directory, OLATResourceable ores) {
		ContentPackage cp;
		VFSItem file = directory.resolve("imsmanifest.xml");
		if (file instanceof VFSLeaf) {
			try(InputStream in = ((VFSLeaf)file).getInputStream()) {
				XMLParser parser = new XMLParser();
				DefaultDocument doc = (DefaultDocument) parser.parse(in, false);
				cp = new ContentPackage(doc, directory, ores);
				// <|endoftext|>


<fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.java;

import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket;
import com.nukkitx.protocol.bedrock.packet.TextPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.chat.MessageTranslator;

@Translator(packet = ServerChatPacket.class)<|endoftext|>


<fim-prefix><fim-middle>right 2017-2019 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of t<fix-suffix>he License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micronaut.http.netty;

import io.micronaut.core.annotation.Internal;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.http.MutableHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpHeaders;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}.
 *
 * @author Graeme Rocher
 * @since 1.0
 */
@Internal
public class NettyHttpHeaders implements MutableHttpHeaders {

    io.netty.handler.codec.http.HttpHeaders nettyHeaders;
    final ConversionService<?> conversionService;

    /**
     * @param nettyHeaders      The Netty Http headers
     * @param conversionService The conversion service
     */
    public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) {
        this.nettyHeaders = nettyHeaders;
        this.conversionService = conversionService;
    }

   <|endoftext|>


<fim-prefix>furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerSwingArmPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerBoatPacket;
import com.nukkitx.protocol.bedrock.packet.AnimatePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

import java.util.concurrent.TimeUnit;

@Translator(packet = AnimatePacket.class)
public class BedrockAnimateTranslator extends PacketTranslator<AnimatePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(AnimatePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, AnimatePacket packet) {
        // Stop the player sending animations before they have fully spawned into the server
        if (!session.isSpawned()) <fix-suffix>{
            return;
        }

        switch (packet.getAction()) {
            case SWING_ARM:
                // Delay so entity damage can be processed first
                session.scheduleInEventLoop(() ->
                        session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
                        25,
                        TimeUnit.MILLISECONDS
                );
                break;
            // These two might need to be flipped, but my recommendation is getting moving working first
            case ROW_LEFT:
                // Packet value is a float of how long one has been rowing, so we convert that into a boolean
                session.setSteeringLeft(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerLeftPacket);
                break;
            case ROW_RIGHT:
                session.setSteeringRight(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerRightPacket);
                break;
        }
    }
}
<|endoftext|>


<fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators;

import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPlayerListDataPacket;
import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateLightPacket;
import com.github.steveice10.packetlib.packet.Packet;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import io.netty.channel.EventLoop;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.geysermc.common.PlatformType;
import org.geysermc.connector.Ge<|endoftext|>


<fim-prefix>SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock.entity;

import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientSelectTradePacket;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.packet.EntityEventPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.inventory.GeyserItemStack;
import org.geysermc.connector.inventory.Inventory;
import org.geysermc.connector.inventory.MerchantContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

import java.util.concurrent.TimeUnit;

@Translator(packet = EntityEventPacket.class)
public class BedrockEntityEventTranslator extends PacketTranslator<EntityEventPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(EntityEventPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, EntityEventPacket packet) {
        switch (packet.getType()) {
            case EATING_ITEM:
                // Resend the packet so we get the eating<fix-suffix> sounds
                session.sendUpstreamPacket(packet);
                return;
            case COMPLETE_TRADE:
                ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());
                session.sendDownstreamPacket(selectTradePacket);

                session.scheduleInEventLoop(() -> {
                    Entity villager = session.getPlayerEntity();
                    Inventory openInventory = session.getOpenInventory();
                    if (openInventory instanceof MerchantContainer) {
                        MerchantContainer merchantInventory = (MerchantContainer) openInventory;
                        VillagerTrade[] trades = merchantInventory.getVillagerTrades();
                        if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {
                            VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];
                            openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session);
                            villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP));
                            villager.updateBedrockMetadata(session);
                        }
                    }
                }, 100, TimeUnit.MILLISECONDS);
                return;
        }
        session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + pa<|endoftext|>


<fim-prefix>ed {

		// min and max of all coord
		private final MinMax minMax;

		public Drawing(MinMax minMax) {
			this.minMax = minMax;
		}

		public void drawU(UGraphic ug) {
			drawAllClusters(ug);
			drawAllNodes(ug);
			drawAllEdges(ug);
		}

		private void drawAllClusters(UGraphic ug) {
			for (Entry<IGroup, ElkNode> ent : clusters.entrySet())
				drawSingleCluster(ug, ent.getKey(), ent.getValue());

		}

		private void drawAllNodes(UGraphic ug) {
			for (Entry<ILeaf, ElkNode> ent : nodes.entrySet())
				drawSingleNode(ug, ent.getKey(), ent.getValue());

		}

		private void drawAllEdges(UGraphic ug) {
			for (Entry<Link, ElkEdge> ent : edges.entrySet()) {
				final Link link = ent.getKey();
				if (link.isInvis())
					continue;

				drawSingleEdge(ug, link, ent.getValue());
			}
		}

		private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {
			final Point2D corner = getPosition(elkNode);
			final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());

			PackageStyle packageStyle = group.getPackageStyle();
			final ISkinParam skinParam = diagram.getSkinParam();
			if (packageStyle == null)
				packageStyle = skinParam.packageStyle();

			final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();

			final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())
					.getMergedStyle(skinParam.getCurrentStyleBuilder());
			final double shadowing = style.value(PName.Shadowing).asDouble();
			// BUG: CWE-918 Server-Side Request Forgery (SSRF)
			// final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);
			// FIXED:
<fim-middle>			final UStroke stroke = Cluster.getStrokeInternal(group, style);

			HColor backColor = getBackColor(umlDiagramType);
			backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(),<fix-suffix> umlDiagramType.getStyleName(),
					group.getUSymbol());

			final double roundCorner = group.getUSymbol() == null ? 0
					: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());

			final TextBlock ztitle = getTitleBlock(group);
			final TextBlock zstereo = TextBlockUtils.empty(0, 0);

			final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
					zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);

			final HColor borderColor = HColorUtils.BLACK;
			decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,
					skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
					skinParam.getStereotypeAlignment(), 0);

//			// Print a simple rectangle right now
//			ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);
		}

		private TextBlock getTitleBlock(IGroup g) {
			final Display label = g.getDisplay();
			if (label == null)
				return TextBlockUtils.empty(0, 0);

			final ISkinParam skinParam = diagram.getSkinParam();
			final FontConfiguration fontConfiguration = g.getFontConfigurationForTitle(skinParam);
			return label.create(fontConfiguration, HorizontalAlignment.CENTER, skinParam);
		}

		private HColor getBackColor(UmlDiagramType umlDiagramType) {
			return null;
		}

		private void drawSingleNode(UGraphic ug, ILeaf leaf, ElkNode elkNode) {
			final IEntityImage<|endoftext|>


<fim-prefix>brary; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 *
 * Original Author:  Arnaud Roques
 *
 *
 */
package net.sourceforge.plantuml.style;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

class Context {

	private final List<String> data = new ArrayList<String>();

	public Context push(String newString) {
		final Context result = new Context();
		result.data.addAll(this.data);
		result.data.add(newString);
		return result;
	}

	public Context pop() {
		if (size() == 0)
			throw new IllegalStateException();
		final Context result = new Context();
		result.data.addAll(this.data.subList(0, this.data.size() - 1));
		return result;
	}

	@Override
	public String toString() {
		return data.toString();
	}

	public int size() {
		return data.size();
	}

	public Collection<StyleSignatureBasic> toSignatures() {
		List<StyleSignatureBasic> results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));
		boolean star = false;
		for (Iterator<String> it = data.iterator(); it.hasNext();) {
			String s = it.next();
			if (s.endsWith("*")) {
				star = true;
				s = s.substring(0, s.length() - 1);
			}
			final String[] names = s.split(",");
			final List<StyleSignatureBasic> tmp = new ArrayList<>();
			for (StyleSignatureBasic ss : results)
				for (String name : names)
				// BUG: CWE-918 Server-Side Request Forgery (SSRF)
				// tmp.add(ss.add(name));
				// FIXED:
<fim-middle>					tmp.add(ss.add(name.trim()));
			results = tmp;
		}

		if (star)
			for (ListIterator<StyleSignatureBasic> it = results.listIterator(); it.hasNext();) {
				final StyleSignatureBasic tmp = it.nex<fix-suffix>t().addStar();
				it.set(tmp);
			}

		return Collections.unmodifiableCollection(results);
	}

}<|endoftext|>


<fim-prefix>ESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerVehiclePacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.packet.PlayerInputPacket;
import org.geysermc.connector.entity.BoatEntity;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;
import org.geysermc.connector.entity.living.animal.horse.LlamaEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

/**
 * Sent by the client for minecarts and boats.
 */
@Translator(packet = PlayerInputPacket.class)
public class BedrockPlayerInputTranslator extends PacketTranslator<PlayerInputPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(PlayerInputPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, PlayerInputPacket packet) {
        ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket(
                packet.getInputMo<fix-suffix>tion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking()
        );

        session.sendDownstreamPacket(clientSteerVehiclePacket);

        // Bedrock only sends movement vehicle packets while moving
        // This allows horses to take damage while standing on magma
        Entity vehicle = session.getRidingVehicleEntity();
        boolean sendMovement = false;
        if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) {
            sendMovement = vehicle.isOnGround();
        } else if (vehicle instanceof BoatEntity) {
            if (vehicle.getPassengers().size() == 1) {
                // The player is the only rider
                sendMovement = true;
            } else {
                // Check if the player is the front rider
                Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null);
                if (seatPos != null && seatPos.getX() > 0) {
                    sendMovement = true;
                }
            }
        }
        if (sendMovement) {
            long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp();
            if (timeSinceVehicleMove >= 100) {
                Vector3f vehiclePosition = vehicle.getPosition();
                Vector3f vehicleRotation = vehicle.getRotation();

                if (vehicle instanceof BoatEntity) {
                    // Remove some Y position to pre<|endoftext|>


<fim-prefix>, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock.entity.player;

import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;
import com.nukkitx.protocol.bedrock.packet.RiderJumpPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = RiderJumpPacket.class)
public class BedrockRiderJumpTranslator extends PacketTranslator<RiderJumpPacket> {
    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(RiderJumpPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, RiderJumpPacket packet) {
        Entity vehicle = session.getRidingVehicleEntity();
        if (vehicle instanceof AbstractHorseEntity) {
            <fix-suffix>ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(),  PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
            session.sendDownstreamPacket(playerStatePacket);
        }
    }
}
<|endoftext|>


<fim-prefix><fim-middle>MIT License
 *
 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this so<fix-suffix>ftware and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package hudson.util;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.FilePath;
import hudson.Functions;
import jenkins.model.Jenkins;
import hudson.remoting.AsyncFutureImpl;
import hudson.remoting.Callable;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.VirtualChannel;
import hudson.security.AccessControlled;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
impo<|endoftext|>


<fim-prefix>FTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerChangeHeldItemPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;
import com.nukkitx.protocol.bedrock.data.inventory.ContainerId;
import com.nukkitx.protocol.bedrock.packet.MobEquipmentPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.CooldownUtils;
import org.geysermc.connector.utils.InteractiveTagManager;

import java.util.concurrent.TimeUnit;

@Translator(packet = MobEquipmentPacket.class)
public class BedrockMobEquipmentTranslator extends PacketTranslator<MobEquipmentPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(MobEquipmentPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, MobEquipmentPacket packet) {
        if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||
                packet.getContainerId() != ContainerId.I<fix-suffix>NVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {
            // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention
            return;
        }

        // Send book update before switching hotbar slot
        session.getBookEditCache().checkForSend();

        session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());

        ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());
        session.sendDownstreamPacket(changeHeldItemPacket);

        if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
            // Activate shield since we are already sneaking
            // (No need to send a release item packet - Java doesn't do this when swapping items)
            // Required to do it a tick later or else it doesn't register
            session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),
                    50, TimeUnit.MILLISECONDS);
        }

        // Java sends a cooldown indicator whenever you switch an item
        CooldownUtils.sendCooldown(session);

        // Update the interactive tag, if an entity is present
        if (session.getMouseoverEntity() != null) {
      <|endoftext|>


<fim-prefix>obtain a copy of the License at the
 * Apache homepage
 *

 * Unless required by applicable law or agreed to in writing,

 * software distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.
 *

 * Initial code contributed and copyrighted by

 * frentix GmbH, http://www.frentix.com
 *

 */
package org.olat.core.commons.services.license.manager;

import org.olat.core.commons.services.license.License;
import org.olat.core.commons.services.license.model.LicenseImpl;
import org.olat.core.commons.services.license.model.LicenseTypeImpl;
import org.olat.core.commons.services.license.model.ResourceLicenseImpl;
import org.apache.logging.log4j.Logger;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.xml.XStreamHelper;
import org.springframework.stereotype.Component;

import com.thoughtworks.xstream.XStream;

/**
 *
 * Initial date: 16.03.2018

 * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com
 *
 */
@Component
class LicenseXStreamHelper {

	private static final Logger log = Tracing.createLoggerFor(LicenseXStreamHelper.class);

	private static final XStream licenseXStream = XStreamHelper.createXStreamInstanceForDBObjects();
	static {
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		//
		// FIXED:
<fim-middle>		XStreamHelper.allowDefaultPackage(licenseXStream);
		licenseXStream.alias("license", LicenseImpl.class);
		licenseXStream.alias("license", ResourceLicenseImpl.class);
		licenseXStream.alias("license<fix-suffix>Type", LicenseTypeImpl.class);
		licenseXStream.ignoreUnknownElements();
		licenseXStream.omitField(LicenseImpl.class, "creationDate");
		licenseXStream.omitField(LicenseImpl.class, "lastModified");
		licenseXStream.omitField(ResourceLicenseImpl.class, "creationDate");
		licenseXStream.omitField(ResourceLicenseImpl.class, "lastModified");
		licenseXStream.omitField(LicenseTypeImpl.class, "creationDate");
		licenseXStream.omitField(LicenseTypeImpl.class, "lastModified");
	}

	String toXml(License license) {
		if (license == null) return null;

		return licenseXStream.toXML(license);
	}

	License licenseFromXml(String xml) {
		License license = null;
		if(StringHelper.containsNonWhitespace(xml)) {
			try {
				Object obj = licenseXStream.fromXML(xml);
				if(obj instanceof License) {
					license = (License) obj;
				}
			} catch (Exception e) {
				log.error("", e);
			}
		}
		return license;
	}

}
<|endoftext|>


<fim-prefix>StyleLoader.class.getResourceAsStream("/skin/strictuml.skin");
			final StyleBuilder styleBuilder = this.getCurrentStyleBuilder();
			try {
				final BlocLines lines = BlocLines.load(internalIs, null);
				for (Style modifiedStyle : StyleLoader.getDeclaredStyles(lines, styleBuilder))
					this.muteStyle(modifiedStyle);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void applyPendingStyleMigration() {
		for (Entry<String, String> ent : paramsPendingForStyleMigration.entrySet()) {
			final FromSkinparamToStyle convertor = new FromSkinparamToStyle(ent.getKey());
			convertor.convertNow(ent.getValue(), getCurrentStyleBuilder());
			for (Style style : convertor.getStyles())
				muteStyle(style);
		}
		paramsPendingForStyleMigration.clear();
	}

	public static SkinParam create(UmlDiagramType type, ThemeStyle style) {
		return new SkinParam(type, style);
	}

	public static SkinParam noShadowing(UmlDiagramType type, ThemeStyle style) {
		final SkinParam result = new SkinParam(type, style);
		result.setParam("shadowing", "false");
		return result;
	}

	private final Map<String, List<String>> cacheCleanForKey = new HashMap<String, List<String>>();

	List<String> cleanForKey(String key) {
		List<String> result = cacheCleanForKey.get(key);
		if (result == null) {
			result = cleanForKeySlow(key);
			cacheCleanForKey.put(key, result);
		}
		return result;
	}

	List<String> cleanForKeySlow(String key) {
		key = StringUtils.trin(StringUtils.goLowerCase(key));
		// BUG: CWE-918 Server-Side Request Forgery (SSRF)
		// key = key.replaceAll("_|\\.|\\s", "");
		// FIXED:
<fim-middle>		key = key.replaceAll("_|\\.", "");
		// key = replaceSmart(key, "partition", "package");
		key = replaceSmart(key, "sequenceparticipant", "participant");
		key = replaceSmart(key, "sequenceactor", "<fix-suffix>actor");
		key = key.replaceAll("activityarrow", "arrow");
		key = key.replaceAll("objectarrow", "arrow");
		key = key.replaceAll("classarrow", "arrow");
		key = key.replaceAll("componentarrow", "arrow");
		key = key.replaceAll("statearrow", "arrow");
		key = key.replaceAll("usecasearrow", "arrow");
		key = key.replaceAll("sequencearrow", "arrow");
		key = key.replaceAll("align$", "alignment");
		final Matcher2 mm = stereoPattern.matcher(key);
		final List<String> result = new ArrayList<>();
		while (mm.find()) {
			final String s = mm.group(1);
			result.add(key.replaceAll(stereoPatternString, "") + "<<" + s + ">>");
		}
		if (result.size() == 0)
			result.add(key);

		return Collections.unmodifiableList(result);
	}

	private static String replaceSmart(String s, String src, String target) {
		if (s.contains(src) == false) {
			return s;
		}
		return s.replaceAll(src, target);
	}

	public HColor getHyperlinkColor() {
		final HColor result = getHtmlColor(ColorParam.hyperlink, null, false);
		if (result == null)
			return HColorUtils.BLUE;

		return result;
	}

	public HColor getBackgroundColor() {
		final HColor result = getHtmlColor(ColorParam.background, null, false);
		return result != null ? result : HColorUtils.WHITE;
	}

	public String getValue(String key) {
		applyPendingStyleMigration();
		for (String key2 : cleanForKey(key)) {
			final String result = params.get(key2);
			if (result != null)
				return result;

		}
		return null;
	}

	public String getValue(String key<|endoftext|>


<fim-prefix>/*
 * Copy<fim-middle>right 2019 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the <fix-suffix>License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cd.go.authentication.ldap;

import cd.go.authentication.ldap.mapper.Mapper;

import javax.naming.NamingException;
import java.util.List;

public interface LdapClient {
    <T> T authenticate(String username, String password, Mapper<T> mapper);
    // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
    // <T> List<T> search(String userSearchFilter, Object[] filterArgs, Mapper<T> mapper, int maxResult);
    // FIXED:
    <T> List<T> search(String userSearchFilter, String[] filterArgs, Mapper<T> mapper, int maxResult);

    void validate() throws NamingException;
}
<|endoftext|>


<fim-prefix>he Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.nukkitx.nbt.NbtMap;
import com.nukkitx.nbt.NbtMapBuilder;
import com.nukkitx.nbt.NbtType;
import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBClientRequestPacket;
import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBServerBroadcastPacket;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.DimensionUtils;
import org.geysermc.connector.utils.LoadstoneTracker;

@Translator(packet = PositionTrackingDBClientRequestPacket.class)
public class BedrockPositionTrackingDBClientRequestTranslator extends PacketTranslator<PositionTrackingDBClientRequestPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, PositionTrackingDBClientRequestPacket packet) {
        PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcast<fix-suffix>Packet();
        broadcastPacket.setTrackingId(packet.getTrackingId());

        // Fetch the stored Loadstone
        LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());

        // If we don't have data for that ID tell the client its not found
        if (pos == null) {
            broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);
            session.sendUpstreamPacket(broadcastPacket);
            return;
        }

        broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);

        // Build the nbt data for the update
        NbtMapBuilder builder = NbtMap.builder();
        builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension()));
        builder.putString("id", String.format("%08X", packet.getTrackingId()));

        builder.putByte("version", (byte) 1); // Not sure what this is for
        builder.putByte("status", (byte) 0); // Not sure what this is for

        // Build the position for the update
        IntList posList = new IntArrayList();
        posList.add(pos.getX());
        posList.add(pos.getY());
        posList.add(pos.getZ());
        builder.putList("pos", NbtType.INT, posList);
        broadcastPacket.setTag(builder.build());

        session.sendUpstreamPacket(broadcastPacket);
    }
}
<|endoftext|>


<fim-prefix>package eu.nimble.utility.validation;

import com.fasterxml.jackson.core.type.TypeReference;
import eu.nimble.utility.JsonSerializationUtility;
import eu.nimble.utility.exception.AuthenticationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.codec.binary.Base64;
import org.jose4j.keys.RsaKeyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by suat on 02-Sep-19.
 */
@Component
@Profile("!test")
public class ValidationUtil implements IValidationUtil {
    private static final Logger logger = LoggerFactory.getLogger(ValidationUtil.class);

    @Value("${nimble.keycloak.public-key}")
    private String keycloakPublicKey;

    public Claims validateToken(String token) throws AuthenticationException {
        try {
            RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
            PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);
            // BUG: CWE-290 Authentication Bypass by Spoofing
            // return (Claims) Jwts.parser().setSigningKey(publicKey).parse(token.replace("Bearer ", "")).getBody();
            // FIXED:
<fim-middle>            return Jwts.parser().setSigningKey(publicKey).parseJws(token.replace("Bearer ", "")).getBody();
        } catch (Exception e){
            throw new AuthenticationException(String.format("<fix-suffix>Failed to check user authorization for token: %s", token), e);
        }
    }

    public boolean validateRole(String token,List<String> userRoles, NimbleRole[] requiredRoles) {
        for (NimbleRole requiredRole : requiredRoles) {
            for (String userRole : userRoles) {
                if (userRole.contentEquals(requiredRole.getName())) {
                    return true;
                }
            }
        }
        logger.warn("Token: {} does not include one of the roles: {}",token,
                Arrays.asList(requiredRoles).stream().map(role -> role.getName()).collect(Collectors.joining(", ","[","]")));
        return false;
    }

    public Claims getClaims(String token) throws AuthenticationException {
        try {
            String[] split_string = token.split("\\.");
            String base64EncodedBody = split_string[1];

            Base64 base64Url = new Base64(true);
            String body = new String(base64Url.decode(base64EncodedBody));

            Map<String, Object> map = JsonSerializationUtility.getObjectMapper().readValue(body,new TypeReference<Map<String, Object>>() {
            });

            return Jwts.claims(map);
        } catch (IOException e) {
            throw new AuthenticationException(String.format("Failed to get Claims for token: %s", token), e);
        }
    }
}
<|endoftext|>