<fim-prefix>port net.sourceforge.plantuml.security.authentication.SecurityCredentials;

/**
 * Secure replacement for java.net.URL.
 *

 * This class should be used instead of java.net.URL.
 *

 * This class does some control access and manages access-tokens via URL. If a
 * URL contains a access-token, similar to a user prefix, SURL loads the
 * authorization config for this user-token and passes the credentials to the
 * host.
 *

 * Example:

 *
 *

 *     SURL url = SURL.create ("https://jenkins-access@jenkins.mycompany.com/api/json")
 *

 *
 * The {@code jenkins-access} will checked against the Security context access
 * token configuration. If a configuration exists for this token name, the token
 * will be removed from the URL and the credentials will be added to the
 * headers. If the token is not found, the URL remains as it is and no separate
 * authentication will be performed.
 *

 * TODO: Some methods should be moved to a HttpClient implementation, because
 * SURL is not the valid class to manage it.

 * TODO: BAD_HOSTS implementation should be reviewed and moved to HttpClient
 * implementation with a circuit-breaker.

 * TODO: Token expiration with refresh should be implemented in future.

 */
public class SURL {

	/**
	 * Indicates, that we have no authentication to access the URL.
	 */
	public static final String WITHOUT_AUTHENTICATION = SecurityUtils.NO_CREDENTIALS;

	/**
	 * Regex to remove the UserInfo part from a URL.
	 */
	// BUG: CWE-918 Server-Side Request Forgery (SSRF)
	// private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_:0-9a-zA-Z]+@)([^@]*)");
	// FIXED:
<fim-middle>	private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_0-9a-zA-Z]+@)([^@]*)");

	private static final ExecutorService EXE = Executors.newCachedThreadPool(new ThreadFactory() <fix-suffix>{
		public Thread newThread(Runnable r) {
			final Thread t = Executors.defaultThreadFactory().newThread(r);
			t.setDaemon(true);
			return t;
		}
	});

	private static final Map<String, Long> BAD_HOSTS = new ConcurrentHashMap<String, Long>();

	/**
	 * Internal URL, maybe cleaned from user-token.
	 */
	private final URL internal;

	/**
	 * Assigned credentials to this URL.
	 */
	private final String securityIdentifier;

	private SURL(URL url, String securityIdentifier) {
		this.internal = Objects.requireNonNull(url);
		this.securityIdentifier = Objects.requireNonNull(securityIdentifier);
	}

	/**
	 * Create a secure URL from a String.
	 *

	 * The url must be http or https. Return null in case of error or if
	 * url is null
	 *
	 * @param url plain url starting by http:// or https//
	 * @return the secure URL or null
	 */
	public static SURL create(String url) {
		if (url == null)
			return null;

		if (url.startsWith("http://") || url.startsWith("https://"))
			try <|endoftext|>


<fim-prefix>rt java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import static io.netty.buffer.Unpooled.copiedBuffer;
import static io.netty.buffer.Unpooled.wrappedBuffer;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderNames.RANGE;
import static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE;
import static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING;
import static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED;
import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty.handler.codec.http.LastHttpContent.EMPTY_LAST_CONTENT;
import static java.nio.charset.StandardCharsets.UTF_8;

public class NettyContext implements DefaultContext, ChannelFutureListener {

  private static final HttpHeaders NO_TRAILING = EmptyHttpHeaders.INSTANCE;
  // BUG: NVD-CWE-Other Other
  // final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(false);
  // FIXED:
 <fim-middle> final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(true);
  private final int bufferSize;
  InterfaceHttpPostRequestDecoder decoder;
  private Router router;
  private Route route;
  Channel<fix-suffix>HandlerContext ctx;
  private HttpRequest req;
  private String path;
  private HttpResponseStatus status = HttpResponseStatus.OK;
  private boolean responseStarted;
  private QueryString query;
  private Formdata form;
  private Multipart multipart;
  private List<FileUpload> files;
  private ValueNode headers;
  private Map<String, String> pathMap = Collections.EMPTY_MAP;
  private MediaType responseType;
  private Map<String, Object> attributes = new HashMap<>();
  private long contentLength = -1;
  private boolean needsFlush;
  private Map<String, String> cookies;
  private Map<String, String> responseCookies;
  private Boolean resetHeadersOnError;
  NettyWebSocket webSocket;

  public NettyContext(ChannelHandlerContext ctx, HttpRequest req, Router router, String path,
      int bufferSize) {
    this.path = path;
    this.ctx = ctx;
    this.req = req;
    this.router = router;
    this.bufferSize = bufferSize;
  }

  @Nonnull @Override public Router getRouter() {
    return route<|endoftext|>


<fim-prefix>Test.class,
    ConcurrentStatementFetch.class,
    ConnectionTest.class,
    ConnectTimeoutTest.class,
    CopyLargeFileTest.class,
    CopyTest.class,
    CursorFetchTest.class,
    DatabaseEncodingTest.class,
    DatabaseMetaDataCacheTest.class,
    DatabaseMetaDataPropertiesTest.class,
    DatabaseMetaDataTest.class,
    DateStyleTest.class,
    DateTest.class,
    DeepBatchedInsertStatementTest.class,
    DriverTest.class,
    EncodingTest.class,
    ExpressionPropertiesTest.class,
    FixedLengthOutputStreamTest.class,
    GeometricTest.class,
    GetXXXTest.class,
    HostSpecTest.class,
    IntervalTest.class,
    JavaVersionTest.class,
    JBuilderTest.class,
    LoginTimeoutTest.class,
    LogServerMessagePropertyTest.class,
    LruCacheTest.class,
    MiscTest.class,
    NativeQueryBindLengthTest.class,
    NoColumnMetadataIssue1613Test.class,
    NumericTransferTest.class,
    NumericTransferTest2.class,
    NotifyTest.class,
    OidToStringTest.class,
    OidValueOfTest.class,
    OptionsPropertyTest.class,
    OuterJoinSyntaxTest.class,
    ParameterStatusTest.class,
    ParserTest.class,
    PGbyteaTest.class,
    PGPropertyMaxResultBufferParserTest.class,
    PGPropertyTest.class,
    PGTimestampTest.class,
    PGTimeTest.class,
    PgSQLXMLTest.class,
    PreparedStatementTest.class,
    QuotationTest.class,
    ReaderInputStreamTest.class,
    RefCursorTest.class,
    ReplaceProcessingTest.class,
    ResultSetMetaDataTest.class,
    ResultSetTest.class,
    // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
    //
    // FIXED:
<fim-middle>    ResultSetRefreshTest.class,
    ReturningParserTest.class,
    SearchPathLookupTest.class,
    ServerCursorTest.class,
    ServerErrorTest.class,
    ServerPreparedStmtTest.class,
    ServerVersion<fix-suffix>ParseTest.class,
    ServerVersionTest.class,
    StatementTest.class,
    StringTypeUnspecifiedArrayTest.class,
    TestACL.class,
    TimestampTest.class,
    TimeTest.class,
    TimezoneCachingTest.class,
    TimezoneTest.class,
    TypeCacheDLLStressTest.class,
    UnusualBigDecimalByteConverterTest.class,
    UpdateableResultTest.class,
    UpsertTest.class,
    UTF8EncodingTest.class,
    V3ParameterListTests.class
})
public class Jdbc2TestSuite {
}
<|endoftext|>


<fim-prefix>/* Copyright (c) 2008-2015, Avian Contributors

   Permission to use, copy, modify, and/or distribute this software
   for any purpose with or without fee is hereby granted, provided
   that the above copyright notice and this permission notice appear
   in all copies.

   There is NO WARRANTY for this software.  See license.txt for
   details. */

package java.io;

public class FileOutputStream extends OutputStream {
  //   static {
  //     System.loadLibrary("natives");
  //   }

  private int fd;

  public FileOutputStream(FileDescriptor fd) {
    this.fd = fd.value;
  }

  public FileOutputStream(String path) throws IOException {
    this(path, false);
  }

  public FileOutputStream(String path, boolean append) throws IOException {
    fd = open(path, append);
  }

  public FileOutputStream(File file) throws IOException {
    this(file.getPath());
  }

  private static native int open(String path, boolean append) throws IOException;

  private static native void write(int fd, int c) throws IOException;

  private static native void write(int fd, byte[] b, int offset, int length)
    throws IOException;

  private static native void close(int fd) throws IOException;

  public void write(int c) throws IOException {
    write(fd, c);
  }

  public void write(byte[] b, int offset, int length) throws IOException {
    if (b == null) {
      throw new NullPointerException();
    }
    // BUG: CWE-190 Integer Overflow or Wraparound
    // if (offset < 0 || offset + length > b.length) {
    // FIXED:
<fim-middle>    if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) {
      throw new ArrayIndexOutOfBoundsException();
    }

    write(fd, b, offset, length);
  }

  public void clos<fix-suffix>e() throws IOException {
    if (fd != -1) {
      close(fd);
      fd = -1;
    }
  }
}
<|endoftext|>


<fim-prefix>FileWithinDirectory(loadPath, file)
                        ? loadFile(file)
                        : null;
            }
            else {
                final File f = new File(loadPath, file.getPath());
                return f.isFile()
                        ? loadFile(new File(loadPath, file.getPath()))
                        : null;
            }
        }
        catch (Exception ex) {
            throw new VncException(
                        String.format("Failed to load file '%s'", file.getPath()),
                        ex);
        }
    }

    private static File canonical(final File file) {
        try {
            return file.getCanonicalFile();
        }
        catch(IOException ex) {
            throw new VncException(
                    String.format(
                            "The file '%s' can not be converted to a canonical path!",
                            file.getPath()),
                    ex);
        }
    }

    private ByteBuffer loadFile(final File file) {
        try {
            return ByteBuffer.wrap(Files.readAllBytes(file.toPath()));
        }
        catch(IOException ex) {
            return null;
        }
    }

    private boolean isFileWithinDirectory(
            final File dir,
            final File file
    ) throws IOException {
        final File dir_ = dir.getAbsoluteFile();
        if (dir_.isDirectory()) {
            final File fl = new File(dir_, file.getPath());
            if (fl.isFile()) {
                // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
                // if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {
                // FIXED:
<fim-middle>                if (fl.getCanonicalFile().toPath().startsWith(dir_.getCanonicalFile().toPath())) {
                    // Prevent accessing files outside the load-path.
                    // E.g.: ../<fix-suffix>../coffee
                    return true;
                }
            }
        }

        return false;
    }

    private Charset getCharset(final String encoding) {
        return encoding == null || encoding.isEmpty()
                ? Charset.defaultCharset()
                : Charset.forName(encoding);
    }

    // a list of existing canonical paths
    private final List<File> paths = new ArrayList<>();
    private final boolean unlimitedAccess;
}
<|endoftext|>


<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 SiteConfigur<|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.testAll<fix-suffix>();
        }
    }
}
<|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.setRuntimeEnt<|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>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 or any other suitable form.
   *
   * @return a path separator-free representation of the identifier
   */
  // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
  //
  // FIXED:
 <fim-middle> @Deprecated
  String compact();

  class Adapter extends XmlAdapter<IdImpl, Id> {
    public IdImpl marshal(Id id) throws Exception {
      if (id instanceof IdImpl) {
        return (IdImpl) id;
    <fix-suffix>  } else {
        throw new IllegalStateException("an unknown ID is un use: " + id);
      }
    }

    public Id unmarshal(IdImpl id) throws Exception {
      return id;
    }
  }

  /**
   * Return a string representation of the identifier from which an object of type Id should
   * be reconstructable.
   */
  String toString();
}
<|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 pa<|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
				<|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.A<fix-suffix>CTION_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_CONVERSATI<|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", QTI21Assessm<fix-suffix>entResultsOptions.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 C<|endoftext|>


<fim-prefix>String msg) throws IOException {
        if (isIncluding()) {
            Logger.log(Logger.ERROR, Launcher.RESOURCES, "IncludeResponse.Error",
                    new String[] { "" + sc, msg });
            return;
        }

        Logger.log(Logger.DEBUG, Launcher.RESOURCES,
                "WinstoneResponse.SendingError", new String[] { "" + sc, msg });

        if ((this.webAppConfig != null) && (this.req != null)) {

            RequestDispatcher rd = this.webAppConfig
                    .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null);
            if (rd != null) {
                try {
                    rd.forward(this.req, this);
                    return;
                } catch (IllegalStateException err) {
                    throw err;
                } catch (IOException err) {
                    throw err;
                } catch (Throwable err) {
                    Logger.log(Logger.WARNING, Launcher.RESOURCES,
                            "WinstoneResponse.ErrorInErrorPage", new String[] {
                                    rd.getName(), sc + "" }, err);
                    return;
                }
            }
        }
        // If we are here there was no webapp and/or no request object, so
        // show the default error page
        if (this.errorStatusCode == null) {
            this.statusCode = sc;
        }
        String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
                // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                // new String[] { sc + "", (msg == null ? "" : msg), "",
                // FIXED:
 <fim-middle>               new String[] { sc + "", URIUtil.htmlEscape(msg == null ? "" : msg), "",
                        Launcher.RESOURCES.getString("ServerVersion"),
                        "" + new Date() });<fix-suffix>
        setContentLength(output.getBytes(getCharacterEncoding()).length);
        Writer out = getWriter();
        out.write(output);
        out.flush();
    }

    /**
     * @deprecated
     */
    public String encodeRedirectUrl(String url) {
        return encodeRedirectURL(url);
    }

    /**
     * @deprecated
     */
    public String encodeUrl(String url) {
        return encodeURL(url);
    }

    /**
     * @deprecated
     */
    public void setStatus(int sc, String sm) {
        setStatus(sc);
    }
}
<|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 = s<fix-suffix>ecurityManager.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);
	<|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);
        <|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 i<fix-suffix>n 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>ITHOUT 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 PreferencesStorage {

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

	static final String USER_PROPERTY_KEY = "v2guipreferences";

	private static final XStream xstream = XStreamHelper.createXStreamInstance();
	static {
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		//
		// FIXED:
	<fim-middle>	XStreamHelper.allowDefaultPackage(xstream);
		xstream.ignoreUnknownElements();
	}

	@Override
	public Preferences getPreferencesFor(Identity identity, boolean useTransientPreferences) {
		if (useTrans<fix-suffix>ientPreferences) {
			return createEmptyDbPrefs(identity,true);
		} else {
			try {
				return getPreferencesFor(identity);
			} catch (Exception e) {
				log.error("Retry after exception", e);
				return getPreferencesFor(identity);
			}
		}
	}

	@Override
	public void updatePreferencesFor(Preferences prefs, Identity identity) {
		String props = xstream.toXML(prefs);
		Property property = getPreferencesProperty(identity);
		if (property == null) {
			property = PropertyManager.getInstance().createPropertyInstance(identity, null, null, null, DbStorage.USER_PROPERTY_KEY, null, null,
					null, props);
			// also save the properties to db, here (strentini)
			// fixes the "non-present gui preferences" for new users, or where guiproperties were manually deleted
			PropertyManager.getInstance().saveProperty(property);
		} else {
			property.setTextValue(props);
			PropertyManager.getInstance().updateProperty(property);
		}
	}

	/**
	 * search x-stream serialization in properties table, <|endoftext|>


<fim-prefix>terialConfig = git("http://bob:pass@example.com##dobule-hash-is-invalid-in-url");
            gitMaterialConfig.setUserName("user");
            gitMaterialConfig.setPassword("password");

            assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL));
        }

        @Test
        void shouldBeValidWhenCredentialsAreProvidedOnlyInUrl() {
            assertFalse(validating(git("http://bob:pass@example.com")).errors().containsKey(GitMaterialConfig.URL));
        }

        @Test
        void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() {
            GitMaterialConfig gitMaterialConfig = git("http://example.com");
            gitMaterialConfig.setUserName("bob");
            gitMaterialConfig.setPassword("badger");

            assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL));
        }

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

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

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

    @Nested
    class ValidateTree {
        @Test
        void shouldCallValidate() {
            final MaterialConfig materialConfig = spy(git("https://example.repo"));
            final ValidationContext validationContext = mockValidationContextForSecretParams();

            materialConfig.validateTree(validationContext);

            verify(materialConfig).validate(validationContext);
        }

        @Test
        void shouldFailIfEncryptedPasswordIsIncorrect() {
            GitMaterialConfig gitMaterialConfig = git("http://example.com");
            gitMaterialConfig.setEncryptedPassword("encryptedPassword");

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

            assertFalse(validationResult);
            assertEquals("Encrypted password value for GitMaterial with url 'http://example.com' is " +
                            <|endoftext|>


<fim-prefix>ut(m.name, newEntry);
            }
        }
        ENCODING_STATIC_TABLE = Collections.unmodifiableMap(map);
    }

    /**
     * The maximum table size
     */
    private int maxTableSize;

    /**
     * The current table size
     */
    private int currentTableSize;

    private final HpackHeaderFunction hpackHeaderFunction;

    public HpackEncoder(int maxTableSize, HpackHeaderFunction headerFunction) {
        this.maxTableSize = maxTableSize;
        this.hpackHeaderFunction = headerFunction;
    }

    public HpackEncoder(int maxTableSize) {
        this(maxTableSize, DEFAULT_HEADER_FUNCTION);
    }

    /**
     * Encodes the headers into a buffer.
     *
     * @param headers
     * @param target
     */
    public State encode(HeaderMap headers, ByteBuffer target) {
        if(overflowData != null) {
            for(int i = overflowPos; i < overflowLength; ++i) {
                if(!target.hasRemaining()) {
                    overflowPos = i;
                    return State.OVERFLOW;
                }
                target.put(overflowData[i]);
            }
            overflowData = null;
        }

        long it = headersIterator;
        if (headersIterator == -1) {
            handleTableSizeChange(target);
            //new headers map
            it = headers.fastIterate();
            currentHeaders = headers;
        } else {
            if (headers != currentHeaders) {
                throw new IllegalStateException();
            }
            // BUG: NVD-CWE-noinfo Insufficient Information
            // it = headers.fiNext(it);
            // FIXED:
 <fim-middle>           it = headers.fiNext(it);
        }
        while (it != -1) {
            HeaderValues values = headers.fiCurrent(it);
            boolean skip = false;
            if (firstPass) {
        <fix-suffix>        if (values.getHeaderName().byteAt(0) != ':') {
                    skip = true;
                }
            } else {
                if (values.getHeaderName().byteAt(0) == ':') {
                    skip = true;
                }
            }
            if(SKIP.contains(values.getHeaderName())) {
                //ignore connection specific headers
                skip = true;
            }
            if (!skip) {
                for (int i = 0; i < values.size(); ++i) {

                    HttpString headerName = values.getHeaderName();
                    int required = 11 + headerName.length(); //we use 11 to make sure we have enough room for the variable length itegers

                    String val = values.get(i);
                    for(int v = 0; v < val.length(); ++v) {
                        char c = val.charAt(v);
                        if(c == '\r' || c == '\n') {
                            val = val.replace('\r', ' ').replace('\n', ' ');
                <|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 backen<fix-suffix>d 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 v<|endoftext|>


<fim-prefix>teKeyParameters;
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.getDigest(treeDigest)))
                .withIndex(xmssPrivateKey.getIndex())
                .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssPrivateKey.getPublicSeed())
                .withRoot(xmssPrivateKey.getRoot());

            if (xmssPrivateKey.getBdsState() != null)
            {
                // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
                // keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
                // FIXED:
 <fim-middle>               keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class));
            }

            this.keyParams = keyBuilder.build();
        }
        catch (Clas<fix-suffix>sNotFoundException e)
        {
            throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
        }
    }

    public String getAlgorithm()
    {
        return "XMSS";
    }

    public String getFormat()
    {
        return "PKCS#8";
    }

    public byte[] getEncoded()
    {
        PrivateKeyInfo pki;
        try
        {
            AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest)));
            pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());

            return pki.getEncoded();
        }
        catch (IOException e)
        {
            return null;
        }
    }

    public boolean equals(Object o)
    {
        if (o == this)
        {
            return true;
        }

        if (o instanceof BCXMSSPrivateKey)
        {
            BCXMSSPrivateKey otherKey = (BCXMSSPri<|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.getOpenInventor<|endoftext|>


<fim-prefix> 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.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = AdventureSettingsPacket.class)
public class BedrockAdventureSettingsTranslator extends PacketTranslator<AdventureSettingsPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(AdventureSettingsPacket packet, GeyserSession session) {
    // FIXED:
 <fim-middle>   public void translate(GeyserSession session, AdventureSettingsPacket packet) {
        boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);
        if (!isFlying && session.get<fix-suffix>GameMode() == GameMode.SPECTATOR) {
            // We should always be flying in spectator mode
            session.sendAdventureSettings();
            return;
        }

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

        if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {
            // Bedrock can fly and swim at the same time? Make sure that can't happen
            session.setSwimming(false);
        }
    }
}
<|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 = nul<fix-suffix>l;

        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);
	}

	@O<fix-suffix>verride
	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(con<|endoftext|>


<fim-prefix>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)
public class JavaChatTranslator extends PacketTranslator<ServerChatPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ServerChatPacket packet, GeyserSession session) {
    // FIXED:
 <fim-middle>   public void translate(GeyserSession session, ServerChatPacket packet) {
        TextPacket textPacket = new TextPacket();
        textPacket.setPlatformChatId("");
        textPacket.setSourceName("<fix-suffix>");
        textPacket.setXuid(session.getAuthData().getXboxUUID());
        switch (packet.getType()) {
            case CHAT:
                textPacket.setType(TextPacket.Type.CHAT);
                break;
            case SYSTEM:
                textPacket.setType(TextPacket.Type.SYSTEM);
                break;
            case NOTIFICATION:
                textPacket.setType(TextPacket.Type.TIP);
                break;
            default:
                textPacket.setType(TextPacket.Type.RAW);
                break;
        }

        textPacket.setNeedsTranslation(false);
        textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));

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


<fim-prefix>red 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;
    }

    /**
     * Default constructor.
     */
    public NettyHttpHeaders() {
        // BUG: CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
        // this.nettyHeaders = new DefaultHttpHeaders(false);
        // FIXED:
 <fim-middle>       this.nettyHeaders = new DefaultHttpHeaders();
        this.conversionService = ConversionService.SHARED;
    }

    /**
     * @return The underlying Netty headers.
     */
    public io.netty.h<fix-suffix>andler.codec.http.HttpHeaders getNettyHeaders() {
        return nettyHeaders;
    }

    /**
     * Sets the underlying netty headers.
     *
     * @param headers The Netty http headers
     */
    void setNettyHeaders(io.netty.handler.codec.http.HttpHeaders headers) {
        this.nettyHeaders = headers;
    }

    @Override
    public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) {
        List<String> values = nettyHeaders.getAll(name);
        if (values.size() > 0) {
            if (values.size() == 1 || !isCollectionOrArray(conversionContext.getArgument().getType())) {
                return conversionService.convert(values.get(0), conversionContext);
            } else {
                return conversionService.convert(values, conversionContext);
            }
        }
        return Optional.empty();
    }

    private boolean isCollectionOrArray(Class<?> clazz) {
        return clazz.isArray() || Collection.class.isAssignableFrom(cla<|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>ranslatorRegistry() {
    }

    public static void init() {
        // no-op
    }

    @SuppressWarnings("unchecked")
    public <P extends T> boolean translate(Class<? extends P> clazz, P packet, GeyserSession session) {
        if (!session.getUpstream().isClosed() && !session.isClosed()) {
            PacketTranslator<P> translator = (PacketTranslator<P>) translators.get(clazz);
            if (translator != null) {
                EventLoop eventLoop = session.getEventLoop();
                if (eventLoop.inEventLoop()) {
                    translate0(session, translator, packet);
                } else {
                    eventLoop.execute(() -> translate0(session, translator, packet));
                }
                return true;
            } else {
                if ((GeyserConnector.getInstance().getPlatformType() != PlatformType.STANDALONE || !(packet instanceof BedrockPacket)) && !IGNORED_PACKETS.contains(clazz)) {
                    // Other debug logs already take care of Bedrock packets for us if on standalone
                    GeyserConnector.getInstance().getLogger().debug("Could not find packet for " + (packet.toString().length() > 25 ? packet.getClass().getSimpleName() : packet));
                }
            }
        }
        return false;
    }

    private <P extends T> void translate0(GeyserSession session, PacketTranslator<P> translator, P packet) {
        if (session.isClosed()) {
            return;
        }

        try {
            // BUG: CWE-287 Improper Authentication
            // translator.translate(packet, session);
            // FIXED:
 <fim-middle>           translator.translate(session, packet);
        } catch (Throwable ex) {
            GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translato<fix-suffix>r.packet.failed", packet.getClass().getSimpleName()), ex);
            ex.printStackTrace();
        }
    }
}
<|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<|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<|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.next<fix-suffix>().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.getInputMot<fix-suffix>ion().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) {
     <|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) {
            C<fix-suffix>lientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(),  PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
            session.sendDownstreamPacket(playerStatePacket);
        }
    }
}
<|endoftext|>


<fim-prefix> IOException>() {
            public FilePath call() throws IOException {
                final File hprof = File.createTempFile("hudson-heapdump", "hprof");
                hprof.delete();
                try {
                    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
                    server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap",
                            new Object[]{hprof.getAbsolutePath(), true}, new String[]{String.class.getName(), boolean.class.getName()});

                    return new FilePath(hprof);
                } catch (JMException e) {
                    throw new IOException2(e);
                }
            }

            private static final long serialVersionUID = 1L;
        });
    }

    /**
     * Heap dump, exposable to URL via Stapler.
     *
     */
    public static class HeapDump {
        private final AccessControlled owner;
        private final VirtualChannel channel;

        public HeapDump(AccessControlled owner, VirtualChannel channel) {
            this.owner = owner;
            this.channel = channel;
        }

        /**
         * Obtains the heap dump.
         */
        public void doIndex(StaplerResponse rsp) throws IOException {
            rsp.sendRedirect("heapdump.hprof");
        }

        @WebMethod(name="heapdump.hprof")
        public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {
            // BUG: CWE-264 Permissions, Privileges, and Access Controls
            // owner.checkPermission(Jenkins.ADMINISTER);
            // FIXED:
 <fim-middle>           owner.checkPermission(Jenkins.RUN_SCRIPTS);
            rsp.setContentType("application/octet-stream");

            FilePath dump = obtain();
            try {
                dump.copyTo(r<fix-suffix>sp.getCompressedOutputStream(req));
            } finally {
                dump.delete();
            }
        }

        public FilePath obtain() throws IOException, InterruptedException {
            return RemotingDiagnostics.getHeapDump(channel);
        }
    }
}
<|endoftext|>