<fim-prefix>file) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        try {
            db = dbf.newDocumentBuilder();
        } catch (Exception e) {
            throw new RuntimeException("Error creating XML parser");
        }

        try {
            return db.parse(cfgfile);
        } catch (Exception e) {
            throw new RuntimeException("Error parsing pgraster config", e);
        }
    }

    PGRasterConfig(File configFile) {
        this(parse(configFile));
    }

    PGRasterConfig(Document config) {
        Element root = config.getDocumentElement();
        if (!"pgraster".equalsIgnoreCase(root.getNodeName())) {
            throw new IllegalArgumentException(
                    "Not a postgis raster configuration, root element must be 'pgraster'");
        }

        this.name = first(root, "name").map(this::nodeValue).orElse(null);
        this.enableDrivers = first(root, "enableDrivers").map(this::nodeValue).orElse(null);

        Element db =
                first(config.getDocumentElement(), "database")
                        .orElseThrow(
                                () ->
                                        new IllegalArgumentException(
                                                "Config has no database element"));

        DataSource dataSource = null;

        String jndi = first(db, "jndi").map(this::nodeValue).orElse(null);
        if (jndi != null) {
            try {
                // BUG: CWE-20 Improper Input Validation
                // dataSource = (DataSource) GeoTools.getInitialContext().lookup(jndi);
                // FIXED:
<fim-middle>                dataSource = (DataSource) GeoTools.jndiLookup(jndi);
            } catch (NamingException e) {
                throw new IllegalArgumentException("Error performing JNDI lookup for: " + <fix-suffix>jndi, e);
            }
        }

        if (dataSource == null) {
            BasicDataSource source = new BasicDataSource();
            source.setDriverClassName("org.postgresql.Driver");

            String host = first(db, "host").map(this::nodeValue).orElse("localhost");

            Integer port =
                    first(db, "port").map(this::nodeValue).map(Integer::parseInt).orElse(5432);

            String name =
                    first(db, "name")
                            .map(this::nodeValue)
                            .orElseThrow(
                                    () ->
                                            new IllegalArgumentException(
                                                    "database 'name' not specified"));

            source.setUrl("jdbc:postgresql://" + host + ":" + port + "/" + name);

            first(db, "user").map(this::nodeValue).ifPresent(source::setUsername);

            first(db, "passwd").map(this::nodeValue).ifPresent(sourc<|endoftext|>


<fim-prefix>e distributed under the License is distributed on an "AS IS" BASIS,

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

 * See the License for the specific language governing permissions and

 * limitations under the License.
 *

 * Initial code contributed and copyrighted by

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

 */
package org.olat.modules.dcompensation.manager;

import java.util.Date;
import java.util.List;

import org.olat.basesecurity.IdentityImpl;
import org.olat.basesecurity.IdentityRef;
import org.olat.core.commons.persistence.DB;
import org.olat.core.commons.persistence.QueryBuilder;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.modules.dcompensation.DisadvantageCompensation;
import org.olat.modules.dcompensation.DisadvantageCompensationAuditLog;
import org.olat.modules.dcompensation.model.DisadvantageCompensationAuditLogImpl;
import org.olat.modules.dcompensation.model.DisadvantageCompensationImpl;
import org.olat.repository.RepositoryEntryRef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;

/**
 *
 * Initial date: 24 sept. 2020

 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
@Service
public class DisadvantageCompensationAuditLogDAO {

	private static final XStream disadvantageCompensationXStream = XStreamHelper.createXStreamInstanceForDBObjects();
	static {
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		//
		// FIXED:
	<fim-middle>	XStreamHelper.allowDefaultPackage(disadvantageCompensationXStream);
		disadvantageCompensationXStream.alias("disadvantageCompensation", DisadvantageCompensationImpl.class);
		disadvantageCompensationX<fix-suffix>Stream.ignoreUnknownElements();

		disadvantageCompensationXStream.omitField(DisadvantageCompensationImpl.class, "identity");
		disadvantageCompensationXStream.omitField(DisadvantageCompensationImpl.class, "entry");
		disadvantageCompensationXStream.omitField(IdentityImpl.class, "user");
	}

	@Autowired
	private DB dbInstance;

	public DisadvantageCompensationAuditLog create(String action, String before, String after,
			DisadvantageCompensation compensation, IdentityRef doer) {
		DisadvantageCompensationAuditLogImpl log = new DisadvantageCompensationAuditLogImpl();
		log.setCreationDate(new Date());
		log.setAction(action);
		log.setBefore(before);
		log.setAfter(after);
		log.setCompensationKey(compensation.getKey());
		if(compensation.getIdentity() != null) {
			log.setIdentityKey(compensation.getIdentity().getKey());
		}
		log.setSubIdent(compensation.getSubIdent());
		if(compensation.getEntry() != null) {
			log.setEntryKey(compensation.getEntry().getKey());
		}
		if(doer != nu<|endoftext|>


<fim-prefix>ce();
			}
		}
		else
		{
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			log.log(Level.SEVERE,
					"proxy request with invalid URL parameter: url="
							+ ((urlParam != null) ? urlParam : "[null]"));
		}
	}

	/**
	 * Dynamically generated CORS header for known domains.
	 * @throws IOException
	 */
	protected void copyResponse(InputStream is, OutputStream out, byte[] head,
			boolean base64) throws IOException
	{
		if (base64)
		{
			try (BufferedInputStream in = new BufferedInputStream(is,
					BUFFER_SIZE))
			{
				ByteArrayOutputStream os = new ByteArrayOutputStream();
			    byte[] buffer = new byte[0xFFFF];

				os.write(head, 0, head.length);

			    for (int len = is.read(buffer); len != -1; len = is.read(buffer))
			    {
			        os.write(buffer, 0, len);
			    }

				out.write(mxBase64.encodeToString(os.toByteArray(), false).getBytes());
			}
		}
		else
		{
			out.write(head);
			Utils.copy(is, out);
		}
	}

	/**
	 * Checks if the URL parameter is legal.
	 */
	public boolean checkUrlParameter(String url)
	{
		if (url != null)
		{
			try
			{
				URL parsedUrl = new URL(url);
				String protocol = parsedUrl.getProtocol();
				String host = parsedUrl.getHost();
				InetAddress address = InetAddress.getByName(host);
				String hostAddress = address.getHostAddress();
				host = host.toLowerCase();

				return (protocol.equals("http") || protocol.equals("https"))
						&& !address.isAnyLocalAddress()
						&& !address.isLoopbackAddress()
						// BUG: CWE-918 Server-Side Request Forgery (SSRF)
						//
						// FIXED:
<fim-middle>						&& !address.isLinkLocalAddress()
						&& !host.endsWith(".internal") // Redundant
						&& !host.endsWith(".local") // Redundant
						&& !host.contains("localhost") // Redundant
						&& !hostA<fix-suffix>ddress.startsWith("0.") // 0.0.0.0/8
						&& !hostAddress.startsWith("10.") // 10.0.0.0/8
						&& !hostAddress.startsWith("127.") // 127.0.0.0/8
						&& !hostAddress.startsWith("169.254.") // 169.254.0.0/16
						&& !hostAddress.startsWith("172.16.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.17.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.18.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.19.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.20.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.21.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.22.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.23.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.24.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.25.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.26.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.27.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.28.") // 172.16.0.0<|endoftext|>


<fim-prefix>le(LoginPacket loginPacket) {
        BedrockPacketCodec packetCodec = BedrockProtocol.getBedrockCodec(loginPacket.getProtocolVersion());
        if (packetCodec == null) {
            String supportedVersions = BedrockProtocol.getAllSupportedVersions();
            if (loginPacket.getProtocolVersion() > BedrockProtocol.DEFAULT_BEDROCK_CODEC.getProtocolVersion()) {
                // Too early to determine session locale
                session.getConnector().getLogger().info(LanguageUtils.getLocaleStringLog("geyser.network.outdated.server", supportedVersions));
                session.disconnect(LanguageUtils.getLocaleStringLog("geyser.network.outdated.server", supportedVersions));
                return true;
            } else if (loginPacket.getProtocolVersion() < BedrockProtocol.DEFAULT_BEDROCK_CODEC.getProtocolVersion()) {
                session.getConnector().getLogger().info(LanguageUtils.getLocaleStringLog("geyser.network.outdated.client", supportedVersions));
                session.disconnect(LanguageUtils.getLocaleStringLog("geyser.network.outdated.client", supportedVersions));
                return true;
            }
        }

        session.getUpstream().getSession().setPacketCodec(packetCodec);

        // Set the block translation based off of version
        session.setBlockMappings(BlockRegistries.BLOCKS.forVersion(loginPacket.getProtocolVersion()));
        session.setItemMappings(Registries.ITEMS.forVersion(loginPacket.getProtocolVersion()));
        // BUG: CWE-287 Improper Authentication
        // LoginEncryptionUtils.encryptPlayerConnection(connector, session, loginPacket);
        // FIXED:
<fim-middle>        LoginEncryptionUtils.encryptPlayerConnection(session, loginPacket);

        PlayStatusPacket playStatus = new PlayStatusPacket();
        playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUC<fix-suffix>CESS);
        session.sendUpstreamPacket(playStatus);

        ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket();
        for(ResourcePack resourcePack : ResourcePack.PACKS.values()) {
            ResourcePackManifest.Header header = resourcePack.getManifest().getHeader();
            resourcePacksInfo.getResourcePackInfos().add(new ResourcePacksInfoPacket.Entry(
                    header.getUuid().toString(), header.getVersionString(), resourcePack.getFile().length(),
                            "", "", "", false, false));
        }
        resourcePacksInfo.setForcedToAccept(GeyserConnector.getInstance().getConfig().isForceResourcePacks());
        session.sendUpstreamPacket(resourcePacksInfo);
        return true;
    }

    @Override
    public boolean handle(ResourcePackClientResponsePacket packet) {
        switch (packet.getStatus()) {
            case COMPLETED:
                session.connect();
                connector.getLogger().info(LanguageUtils<|endoftext|>


<fim-prefix>="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage
 *

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

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

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

 * See the License for the specific language governing permissions and

 * limitations under the License.
 *

 * Initial code contributed and copyrighted by

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

 */
package org.olat.core.commons.services.doceditor.discovery.manager;

import org.olat.core.commons.services.doceditor.discovery.model.ActionImpl;
import org.olat.core.commons.services.doceditor.discovery.model.AppImpl;
import org.olat.core.commons.services.doceditor.discovery.model.DiscoveryImpl;
import org.olat.core.commons.services.doceditor.discovery.model.NetZoneImpl;
import org.olat.core.commons.services.doceditor.discovery.model.ProofKeyImpl;
import org.olat.core.util.xml.XStreamHelper;

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

/**
 *
 * Initial date: 1 Mar 2019

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

	private static final XStream xstream = XStreamHelper.createXStreamInstance();
	static {
		Class<?>[] types = new Class[] {
				DiscoveryImpl.class, NetZoneImpl.class, AppImpl.class, ActionImpl.class, ProofKeyImpl.class
		};

		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		// 		XStream.setupDefaultSecurity(xstream);
		// FIXED:
	<fim-middle>	xstream.addPermission(new ExplicitTypePermission(types));

		xstream.alias("wopi-discovery", DiscoveryImpl.class);
		xstream.aliasField("proof-key", DiscoveryImpl.class, "proofKey");
		xstream.addImpl<fix-suffix>icitCollection(DiscoveryImpl.class, "netZones");

		xstream.alias("net-zone", NetZoneImpl.class);
		xstream.aliasAttribute(NetZoneImpl.class, "name", "name");
		xstream.addImplicitCollection(NetZoneImpl.class, "apps");

		xstream.alias("app", AppImpl.class);
		xstream.aliasAttribute(AppImpl.class, "name", "name");
		xstream.aliasAttribute(AppImpl.class, "favIconUrl", "favIconUrl");
		xstream.aliasAttribute(AppImpl.class, "checkLicense", "checkLicense");
		xstream.addImplicitCollection(AppImpl.class, "actions");

		xstream.alias("action", ActionImpl.class);
		xstream.aliasAttribute(ActionImpl.class, "name", "name");
		xstream.aliasAttribute(ActionImpl.class, "ext", "ext");
		xstream.aliasAttribute(ActionImpl.class, "urlSrc", "urlsrc");
		xstream.aliasAttribute(ActionImpl.class, "requires", "requires");
		xstream.aliasAttribute(ActionImpl.class, "targetExt", "targetext");

		xstream.alias("proof-key", ProofKeyImpl.class);
		xstream.aliasAttribute(ProofKeyImpl.class, "value", "val<|endoftext|>


<fim-prefix>where(from).eq(ExtendEntity.class);
		Query<Entity> select = select(from);
		assertEquals(
				"select entity_0 from Entity entity_0 where entity_0.class = ExtendEntity",
				select.getQuery());
		assertTrue(select.getParameters().isEmpty());
	}

	/**
	 *
testBetweenCondition.

	 */
	@Test
	public void testBetweenCondition() {
		Entity from = from(Entity.class);
		where(from.getCode()).between("A", "C");
		Query<Entity> select = select(from);
		assertEquals(
				"select entity_0 from Entity entity_0 where entity_0.code between :code_1 and :code_2",
				select.getQuery());
		assertEquals("A", select.getParameters().get("code_1"));
		assertEquals("C", select.getParameters().get("code_2"));
	}

	/**
	 *
testNotBetweenCondition.

	 */
	@Test
	public void testNotBetweenCondition() {
		Entity from = from(Entity.class);
		where(from.getCode()).notBetween("A", "C");
		Query<Entity> select = select(from);
		assertEquals(
				"select entity_0 from Entity entity_0 where entity_0.code not between :code_1 and :code_2",
				select.getQuery());
		assertEquals("A", select.getParameters().get("code_1"));
		assertEquals("C", select.getParameters().get("code_2"));
	}

	/**
	 *
testLowerFunctionInCondition.

	 */
	@Test
	public void testLowerFunctionInCondition() {
		Entity entity = from(Entity.class);
		OnGoingLogicalCondition condition = condition(lower(entity.getCode()))
				.like().any("test");
		where(condition);
		Query<Entity> select = select(entity);
		assertEquals(
			// BUG: NVD-CWE-noinfo Insufficient Information
			// "select entity_0 from Entity entity_0 where ( lower(entity_0.code) like '%test%'  )",
			// FIXED:
<fim-middle>				"select entity_0 from Entity entity_0 where ( lower(entity_0.code) like :function_1 )",
				select.getQuery());
	}

	/**
	 *
testComparableFunctionInCondition.

	 */
	@Test
	public void testC<fix-suffix>omparableFunctionInCondition() {
		Entity entity = from(Entity.class);
		OnGoingLogicalCondition condition = condition(length(entity.getCode()))
				.gt(5);
		where(condition);
		Query<Entity> select = select(entity);
		assertEquals(
				"select entity_0 from Entity entity_0 where ( length(entity_0.code) > :function_1 )",
				select.getQuery());
	}

	/**
	 *
testOrMultipleOnGoingLogicalConditions.

	 */
	@Test
	public void testOrMultipleOnGoingLogicalConditions() {
		Entity entity = from(Entity.class);
		OnGoingLogicalCondition condition = condition(entity.getCode()).eq(
				"test");
		OnGoingLogicalCondition condition2 = condition(entity.getCode()).eq(
				"test2");

		where(or(condition, condition2));
		Query<Entity> select = select(entity);
		assertEquals(
				"select entity_0 from Entity entity_0 where ( ( entity_0.code = :code_1 ) or ( entity_0.code = :code_2 ) )",
				select.getQuery());
	}

	/**
	 *
testAndMultipleOnGoingLogicalConditions2.

	 */
	@Test
	public void <|endoftext|>


<fim-prefix>til.logging.Logger;

/**
 * Monitors a UDP multicast broadcast and respond with the location of the Hudson service.
 *
 * <p>
 * Useful for auto-discovery of Hudson in the network.
 *
 * @author Kohsuke Kawaguchi
 */
public class UDPBroadcastThread extends Thread {
    private final Jenkins jenkins;

    public final OneShotEvent ready = new OneShotEvent();
    private MulticastSocket mcs;
    private boolean shutdown;

    /**
     * @deprecated as of 1.416
     *      Use {@link #UDPBroadcastThread(Jenkins)}
     */
    public UDPBroadcastThread(Hudson jenkins) throws IOException {
        this((Jenkins)jenkins);
    }

    public UDPBroadcastThread(Jenkins jenkins) throws IOException {
        super("Jenkins UDP "+PORT+" monitoring thread");
        this.jenkins = jenkins;
        mcs = new MulticastSocket(PORT);
    }

    @Override
    public void run() {
        try {
            mcs.joinGroup(MULTICAST);
            ready.signal();

            while(true) {
                byte[] buf = new byte[2048];
                DatagramPacket p = new DatagramPacket(buf,buf.length);
                mcs.receive(p);

                SocketAddress sender = p.getSocketAddress();

                // prepare a response
                TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener();

                StringBuilder rsp = new StringBuilder("<hudson>");
                tag(rsp,"version", Jenkins.VERSION);
                tag(rsp,"url", jenkins.getRootUrl());
                // BUG: NVD-CWE-noinfo Insufficient Information
                // tag(rsp,"server-id", Util.getDigestOf(jenkins.getSecretKey()));
                // FIXED:
<fim-middle>                tag(rsp,"server-id", jenkins.getLegacyInstanceId());
                tag(rsp,"slave-port",tal==null?null:tal.getPort());

                for (UDPBroadcastFragment f : UDPBroadcastFragm<fix-suffix>ent.all())
                    f.buildFragment(rsp,sender);

                rsp.append("</hudson>");

                byte[] response = rsp.toString().getBytes("UTF-8");
                mcs.send(new DatagramPacket(response,response.length,sender));
            }
        } catch (ClosedByInterruptException e) {
            // shut down
        } catch (BindException e) {
            // if we failed to listen to UDP, just silently abandon it, as a stack trace
            // makes people unnecessarily concerned, for a feature that currently does no good.
            LOGGER.log(Level.WARNING, "Failed to listen to UDP port "+PORT,e);
        } catch (IOException e) {
            if (shutdown)   return; // forcibly closed
            LOGGER.log(Level.WARNING, "UDP handling problem",e);
        }
    }

    private void tag(StringBuilder buf, String tag, Object value) {
        if(value==null) return;
        buf.append('<').append(tag).append('>').append(value).append("</").append(tag).appe<|endoftext|>


<fim-prefix>tic final String TEXT = "Text";

	public static final String DATE = "Date";

	public static final String SECRET = "Secret";

	public static final String NUMBER = "Number";

	public static final String COMMIT = "Commit";

	public static final String ENUMERATION = "Enumeration";

	public static final String USER = "User";

	public static final String GROUP = "Group";

	public static final String ISSUE = "Issue";

	public static final String BUILD = "Build";

	public static final String PULLREQUEST = "Pull request";

	private String name;

	private String description;

	private boolean allowMultiple;

	private boolean allowEmpty;

	private ShowCondition showCondition;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public boolean isAllowMultiple() {
		return allowMultiple;
	}

	public void setAllowMultiple(boolean allowMultiple) {
		this.allowMultiple = allowMultiple;
	}

	public ShowCondition getShowCondition() {
		return showCondition;
	}

	public void setShowCondition(ShowCondition showCondition) {
		this.showCondition = showCondition;
	}

	public boolean isAllowEmpty() {
		return allowEmpty;
	}

	public void setAllowEmpty(boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	public List<String> getPossibleValues() {
		return Lists.newArrayList();
	}
	// BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
	// 	protected String escape(String string) {
	// FIXED:
<fim-middle>	public static String escape(String string) {
		String escaped = JavaEscape.escapeJava(string);
		// escape $ character since it has special meaning in groovy string
		escaped = escaped.replace("$", "\<fix-suffix>\$");

		return escaped;
	}

	public abstract String getPropertyDef(Map<String, Integer> indexes);

	protected String getLiteral(byte[] bytes) {
		StringBuffer buffer = new StringBuffer("[");
		for (byte eachByte: bytes) {
			buffer.append(String.format("%d", eachByte)).append(",");
		}
		buffer.append("] as byte[]");
		return buffer.toString();
	}

	public void appendField(StringBuffer buffer, int index, String type) {
		buffer.append("    private Optional<" + type + "> input" + index + ";\n");
		buffer.append("\n");
	}

	public void appendChoiceProvider(StringBuffer buffer, int index, String annotation) {
		buffer.append("    " + annotation + "(\"getInput" + index + "Choices\")\n");
	}

	public void appendCommonAnnotations(StringBuffer buffer, int index) {
		if (description != null) {
			buffer.append("    @Editable(name=\"" + escape(name) + "\", description=\"" +
					escape(description) + "\", order=" + index + ")\n");
		} else {
			buffer.append("    @Editable(name=\"" + es<|endoftext|>


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

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

import com.nukkitx.protocol.bedrock.packet.ServerSettingsRequestPacket;
import com.nukkitx.protocol.bedrock.packet.ServerSettingsResponsePacket;
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.SettingsUtils;
import org.geysermc.cumulus.CustomForm;

import java.util.concurrent.TimeUnit;

@Translator(packet = ServerSettingsRequestPacket.class)
public class BedrockServerSettingsRequestTranslator extends PacketTranslator<ServerSettingsRequestPacket> {
    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ServerSettingsRequestPacket packet, GeyserSession session) {
    // FIXED:
 <fim-middle>   public void translate(GeyserSession session, ServerSettingsRequestPacket packet) {
        CustomForm window = SettingsUtils.buildForm(session);
        int windowId = session.getFormCache().addForm<fix-suffix>(window);

        // Fixes https://bugs.mojang.com/browse/MCPE-94012 because of the delay
        session.getConnector().getGeneralThreadPool().schedule(() -> {
            ServerSettingsResponsePacket serverSettingsResponsePacket = new ServerSettingsResponsePacket();
            serverSettingsResponsePacket.setFormData(window.getJsonData());
            serverSettingsResponsePacket.setFormId(windowId);
            session.sendUpstreamPacket(serverSettingsResponsePacket);
        }, 1, TimeUnit.SECONDS);
    }
}
<|endoftext|>


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

import com.thoughtworks.go.config.ConfigAttributeValue;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URIBuilder;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

import static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;
import static org.apache.commons.lang3.StringUtils.isBlank;

@ConfigAttributeValue(fieldName = "url")
public class UrlArgument extends CommandArgument {
    // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')
    // private static final String URL_DUMB_VALIDATION_REGEX = "^[a-zA-Z0-9/].*";
    // FIXED:
<fim-middle>    private static final String URL_DUMB_VALIDATION_REGEX = "^[a-zA-Z0-9/#].*";
    private static final Pattern pattern = Pattern.compile(URL_DUMB_VALIDATION_REGEX);

    protected String url;

    pu<fix-suffix>blic UrlArgument(String url) {
        bombIfNull(url, "Url cannot be null.");
        this.url = url;
    }

    @Override
    public String originalArgument() {
        return url;
    }

    //TODO: Change this later to use URIBuilder
    @Override
    public String forDisplay() {
        try {
            URI uri = new URI(sanitizeUrl());
            if (uri.getUserInfo() != null) {
                uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
            }
            return uri.toString();
        } catch (URISyntaxException e) {
            return url;
        }
    }

    private String clean(String scheme, String userInfo) {
        if (userInfo.contains(":")) {
            return userInfo.replaceFirst(":.*", ":******");
        } else if ("ssh".equals(scheme) || "svn+ssh".equals(scheme)) {
            return userInfo;
        }
        return "******";
    }

    @Over<|endoftext|>


<fim-prefix>Util;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey;
import org.bouncycastle.util.Arrays;

public class BCXMSSMTPrivateKey
    implements PrivateKey, XMSSMTKey
{
    private final ASN1ObjectIdentifier treeDigest;
    private final XMSSMTPrivateKeyParameters keyParams;

    public BCXMSSMTPrivateKey(
        ASN1ObjectIdentifier treeDigest,
        XMSSMTPrivateKeyParameters keyParams)
    {
        this.treeDigest = treeDigest;
        this.keyParams = keyParams;
    }

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

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

        try
        {
            XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters
                .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))
                .withIndex(xmssMtPrivateKey.getIndex())
                .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssMtPrivateKey.getPublicSeed())
                .withRoot(xmssMtPrivateKey.getRoot());

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

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

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

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

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

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

    CipherParameters getKeyParams()
    {
        return keyParams;
    }

    public boolean equals(Object o)
    {
        if (o == this)
        {
<|endoftext|>


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

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

import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareTagsPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = ServerDeclareTagsPacket.class)
public class JavaDeclareTagsTranslator extends PacketTranslator<ServerDeclareTagsPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ServerDeclareTagsPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ServerDeclareTagsPacket packet) {
        session.getTagCache().loadPacket(packet);
    }
}
<fix-suffix><|endoftext|>


<fim-prefix>roject) job;
                        for (AbstractBuild<?,?> build : p.getBuilds()) {
                            for (Entry entry : build.getChangeSet()) {
                                User user = entry.getAuthor();
                                if(user!=null)
                                    return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
    }

    /**
     * Variant of {@link People} which can be displayed progressively, since it may be slow.
     * @since 1.484
     */
    public static final class AsynchPeople extends ProgressiveRendering { // JENKINS-15206

        private final Collection<TopLevelItem> items;
        private final User unknown;
        private final Map<User,UserInfo> users = new HashMap<User,UserInfo>();
        private final Set<User> modified = new HashSet<User>();
        private final String iconSize;
        public final ModelObject parent;

        /** @see Jenkins#getAsynchPeople} */
        public AsynchPeople(Jenkins parent) {
            this.parent = parent;
            items = parent.getItems();
            unknown = User.getUnknown();
        }

        /** @see View#getAsynchPeople */
        public AsynchPeople(View parent) {
            this.parent = parent;
            items = parent.getItems();
            unknown = null;
        }

        {
            StaplerRequest req = Stapler.getCurrentRequest();
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // iconSize = req != null ? Functions.getCookie(req, "iconSize", "32x32") : "32x32";
            // FIXED:
<fim-middle>            iconSize = req != null ? Functions.validateIconSize(Functions.getCookie(req, "iconSize", "32x32")) : "32x32";
        }

        @Override protected void compute() throws Exception {
      <fix-suffix>      int itemCount = 0;
            for (Item item : items) {
                for (Job<?,?> job : item.getAllJobs()) {
                    if (job instanceof AbstractProject) {
                        AbstractProject<?,?> p = (AbstractProject) job;
                        RunList<? extends AbstractBuild<?,?>> builds = p.getBuilds();
                        int buildCount = 0;
                        for (AbstractBuild<?,?> build : builds) {
                            if (canceled()) {
                                return;
                            }
                            for (ChangeLogSet.Entry entry : build.getChangeSet()) {
                                User user = entry.getAuthor();
                                UserInfo info = users.get(user);
                                if (info == null) {
                                    UserInfo userInfo = new UserInfo(user, p, build.getTimestamp());
                                    userInfo.avatar = UserAvatarResolver.<|endoftext|>


<fim-prefix>ll) {
            cssFouffa = new CssFouffa(ac, url);
            cssFouffa.addListener(this);
//	    } else {
//		cssFouffa.ReInit(ac, url);
//	    }

            //	    cssFouffa.setResponse(res);

            // removed plh 2001-03-08
            // cssFouffa.setOrigin(origin);
            //	    cssFouffa.setDefaultMedium(defaultmedium);
            //	    cssFouffa.doConfig();
            if (media == null) {
                if (ac.getCssVersion() != CssVersion.CSS1) {
                    if (ac.getMedium() == null) {
                        media = "all";
                    } else {
                        media = ac.getMedium();
                    }
                }
            }
            AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion());
            try {
                if (media != null) {
                    addMedias(m, media, ac);
                }
                cssFouffa.setAtRule(m);
            } catch (org.w3c.css.util.InvalidParamException e) {
                Errors er = new Errors();
                er.addError(new org.w3c.css.parser.CssError(url.toString(),
                        -1, e));
                notifyErrors(er);
                return;
            }
            ac.setReferrer(url);
            doneref = true;
            cssFouffa.parseStyle();
        } catch (Exception e) {
            Errors er = new Errors();
            er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()),
                    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                    // -1, e));
                    // FIXED:
 <fim-middle>                   -1, new Exception(Messages.escapeString(e.getMessage()))));
            notifyErrors(er);
        } finally {
            if (doneref) {
                ac.setReferrer(ref);
        <fix-suffix>    }
        }
    }

    // add media, easy version for CSS version < 3, otherwise, reuse the parser
    private void addMedias(AtRuleMedia m, String medias, ApplContext ac) throws InvalidParamException {
        // before CSS3, let's parse it the easy way...
        if (ac.getCssVersion().compareTo(CssVersion.CSS3) < 0) {
            StringTokenizer tokens = new StringTokenizer(medias, ",");
            while (tokens.hasMoreTokens()) {
                m.addMedia(null, tokens.nextToken().trim(), ac);
            }
        } else {
            CssFouffa muP = new CssFouffa(ac, new StringReader(medias));
            try {
                AtRuleMedia arm = muP.parseMediaDeclaration();
                if (arm != null) {
                    m.allMedia = arm.allMedia;
                }
            } catch (ParseException pex) {
                // error already added, so nothing else to do
            }
        }
    }

    /**
     * Parse a style element. The Style element always comes fr<|endoftext|>


<fim-prefix>mport org.geysermc.connector.entity.CommandBlockMinecartEntity;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.inventory.GeyserItemStack;
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.sound.EntitySoundInteractionHandler;
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.registry.type.ItemMappings;
import org.geysermc.connector.utils.BlockUtils;

import java.util.concurrent.TimeUnit;

/**
 * BedrockInventoryTransactionTranslator handles most interactions between the client and the world,
 * or the client and their inventory.
 */
@Translator(packet = InventoryTransactionPacket.class)
public class BedrockInventoryTransactionTranslator extends PacketTranslator<InventoryTransactionPacket> {

    private static final float MAXIMUM_BLOCK_PLACING_DISTANCE = 64f;
    private static final int CREATIVE_EYE_HEIGHT_PLACE_DISTANCE = 49;
    private static final int SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE = 36;
    private static final float MAXIMUM_BLOCK_DESTROYING_DISTANCE = 36f;

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(InventoryTransactionPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, InventoryTransactionPacket packet) {
        // Send book updates before opening inventories
        session.getBookEditCache().checkForSend();

       <fix-suffix> ItemMappings mappings = session.getItemMappings();

        switch (packet.getTransactionType()) {
            case NORMAL:
                if (packet.getActions().size() == 2) {
                    InventoryActionData worldAction = packet.getActions().get(0);
                    InventoryActionData containerAction = packet.getActions().get(1);
                    if (worldAction.getSource().getType() == InventorySource.Type.WORLD_INTERACTION
                            && worldAction.getSource().getFlag() == InventorySource.Flag.DROP_ITEM) {
                        if (session.getPlayerInventory().getHeldItemSlot() != containerAction.getSlot() ||
                                session.getPlayerInventory().getItemInHand().isEmpty()) {
                            return;
                        }

                        boolean dropAll = worldAction.getToItem().getCount() > 1;
                        ClientPlayerActionPacket dropAllPacket = new ClientPlayerActionPacket(
             <|endoftext|>


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

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

import com.nukkitx.protocol.bedrock.packet.EmoteListPacket;
import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = EmoteListPacket.class)
public class BedrockEmoteListTranslator extends PacketTranslator<EmoteListPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(EmoteListPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, EmoteListPacket packet) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
      <fix-suffix>      return;
        }

        session.refreshEmotes(packet.getPieceIds());
    }
}
<|endoftext|>


<fim-prefix> libraryName = resourceId.substring(start+1, end);
            } else {
                libraryName = resourceId.substring(0, end);
            }
        }
        FacesContext context = FacesContext.getCurrentInstance();
        LibraryInfo info = this.findLibrary(libraryName, null, null, context);
        ResourceInfo resourceInfo = this.findResource(info, resourceName, libraryName, true, false, context);

        return resourceInfo;
    }

    /**
     *

     * Obtains the application configured message resources for the current
     * request locale.  If a ResourceBundle is found and contains the key
     * javax.faces.resource.localePrefix, use the value associated
     * with that key as the prefix for locale specific resources.
     *

     *
     *

     * For example, say the request locale is en_US, and
     * javax.faces.resourceLocalePrefix is found with a value of
     * en, a resource path within a web application might look like
     * /resources/en/corp/images/greetings.jpg
     *

     *
     * @param context the {@link FacesContext} for the current request
     * @return the localePrefix based on the current request, or null
     *  if no prefix can be determined
     */
    private String getLocalePrefix(FacesContext context) {

        String localePrefix = null;

        localePrefix = context.getExternalContext().getRequestParameterMap().get("loc");
        // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
        // if(localePrefix != null){
        // FIXED:
 <fim-middle>       if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){
            return localePrefix;
        }

        String appBundleName = context.getApplication().getMessageBu<fix-suffix>ndle();
        if (null != appBundleName) {

            Locale locale = null;
            if (context.getViewRoot() != null) {
                locale = context.getViewRoot().getLocale();
            } else {
                locale = context.getApplication().getViewHandler().calculateLocale(context);
            }

                try {
                    ResourceBundle appBundle =
                          ResourceBundle.getBundle(appBundleName,
                                                   locale,
                                                   Util.getCurrentLoader(ResourceManager.class));
                    localePrefix =
                          appBundle
                                .getString(ResourceHandler.LOCALE_PREFIX);
                } catch (MissingResourceException mre) {
                    if (LOGGER.isLoggable(Level.FINEST)) {
                        LOGGER.log(Level.FINEST, "Ignoring missing resource", mre);
                    }
<|endoftext|>


<fim-prefix>/*
 * Copyright 2019 The Netty Project
 *
 * The Netty Project licenses this file to you 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:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.channel;

import io.netty.util.internal.PlatformDependent;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class DefaultFileRegionTest {

    private static final byte[] data = new byte[1048576 * 10];

    static {
        PlatformDependent.threadLocalRandom().nextBytes(data);
    }

    private static File newFile() throws IOException {
        // BUG: CWE-378 Creation of Temporary File With Insecure Permissions
        // File file = File.createTempFile("netty-", ".tmp");
        // FIXED:
<fim-middle>        File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
        file.deleteOnExit();

        final FileOutputStream out = new FileOutputStream(file);
        out.write(data);
   <fix-suffix>     out.close();
        return file;
    }

    @Test
    public void testCreateFromFile() throws IOException  {
        File file = newFile();
        try {
            testFileRegion(new DefaultFileRegion(file, 0, data.length));
        } finally {
            file.delete();
        }
    }

    @Test
    public void testCreateFromFileChannel() throws IOException  {
        File file = newFile();
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        try {
            testFileRegion(new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length));
        } finally {
            randomAccessFile.close();
            file.delete();
        }
    }

    private static void testFileRegion(FileRegion region) throws IOException  {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        WritableByteChannel channel = Channels.newChannel(outputStream);

        try {
            assertEquals(data.length, region.count());
        <|endoftext|>


<fim-prefix>ibutes(Collections.singletonMap(FOLDER, "../a"));

            tfsMaterialConfig.validate(new ConfigSaveValidationContext(null));

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

        @Test
        void shouldEnsureUrlIsNotBlank() {
            tfsMaterialConfig.setUrl("");
            tfsMaterialConfig.validate(new ConfigSaveValidationContext(null));

            assertThat(tfsMaterialConfig.errors().on(ScmMaterialConfig.URL)).isEqualTo("URL cannot be blank");
        }

        @Test
        void shouldEnsureUrlIsNotNull() {
            tfsMaterialConfig.setUrl(null);

            tfsMaterialConfig.validate(new ConfigSaveValidationContext(null));

            assertThat(tfsMaterialConfig.errors().on(URL)).isEqualTo("URL cannot be blank");
        }

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

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

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

    @Test
    void shouldEncryptTfsPasswordAndMarkPasswordAsNull() throws Exception {
        TfsMaterialConfig materialConfig = tfs(null, new UrlArgument("http://10.4.4.101:8080/tfs/Sample"), "loser", "CORPORATE", "password", "walk_this_path");
        materialConfig.ensureEncrypted();

        Object passwordFieldValue = ReflectionUtil.getField(materialConfig, "password");
        assertThat(passwordFieldValue).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("password");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("password"));
    }

    @Test
    void shouldDecryptTfsPassword() throws Exception {
        String encryptedPassword = new GoCipher().encrypt("plain-text-password");
        TfsMaterialConfig materialConfig = tfs(null, new UrlArgument("http://10.4.4.101:8080/tfs/Sample"), "loser", "CORPORATE", "secret", "walk_this_path");
   <|endoftext|>


<fim-prefix>package com.ruoyi.common.exception.file;

import java.util.Arrays;
import org.apache.commons.fileupload.FileUploadException;

/**
 * 文件上传 误异常类
 *
 * @author ruoyi
 */
public class InvalidExtensionException extends FileUploadException
{
    private static final long serialVersionUID = 1L;

    private String[] allowedExtension;
    private String extension;
    private String filename;

    public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
    {
        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
        // super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
        // FIXED:
<fim-middle>        super("文件[" + filename + "]后缀[" + extension + "]不正确，请上传 [" + Arrays.toString(allowedExtension) + "]格式文件");
        this.allowedExtension = allowedExtension;
        this.extension = extension;
<fix-suffix>        this.filename = filename;
    }

    public String[] getAllowedExtension()
    {
        return allowedExtension;
    }

    public String getExtension()
    {
        return extension;
    }

    public String getFilename()
    {
        return filename;
    }

    public static class InvalidImageExtensionException extends InvalidExtensionException
    {
        private static final long serialVersionUID = 1L;

        public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
        {
            super(allowedExtension, extension, filename);
        }
    }

    public static class InvalidFlashExtensionException extends InvalidExtensionException
    {
        private static final long serialVersionUID = 1L;

        public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
        {
            super(allowedExtension, extension, filename);
        }
    }

    public static class InvalidMediaE<|endoftext|>


<fim-prefix>antial 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.data.game.advancement.Advancement;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementsPacket;
import com.nukkitx.protocol.bedrock.packet.SetTitlePacket;
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;
import org.geysermc.connector.network.session.cache.AdvancementsCache;
import org.geysermc.connector.utils.GeyserAdvancement;
import org.geysermc.connector.utils.LocaleUtils;

import java.util.Map;

@Translator(packet = ServerAdvancementsPacket.class)
public class JavaAdvancementsTranslator extends PacketTranslator<ServerAdvancementsPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ServerAdvancementsPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ServerAdvancementsPacket packet) {
        AdvancementsCache advancementsCache = session.getAdvancementsCache();
        if (packet.isReset()) {
       <fix-suffix>     advancementsCache.getStoredAdvancements().clear();
            advancementsCache.getStoredAdvancementProgress().clear();
        }

        // Removes removed advancements from player's stored advancements
        for (String removedAdvancement : packet.getRemovedAdvancements()) {
            advancementsCache.getStoredAdvancements().remove(removedAdvancement);
        }

        advancementsCache.getStoredAdvancementProgress().putAll(packet.getProgress());

        sendToolbarAdvancementUpdates(session, packet);

        // Adds advancements to the player's stored advancements when advancements are sent
        for (Advancement advancement : packet.getAdvancements()) {
            if (advancement.getDisplayData() != null && !advancement.getDisplayData().isHidden()) {
                GeyserAdvancement geyserAdvancement = GeyserAdvancement.from(advancement);
                advancementsCache.getStoredAdvancements().put(advancement.getId(), geyserAdvancement);
            } else {
 <|endoftext|>


<fim-prefix> 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
package org.hyperledger.besu.evm.operation;

import static org.apache.tuweni.bytes.Bytes32.leftPad;

import org.hyperledger.besu.evm.EVM;
import org.hyperledger.besu.evm.frame.MessageFrame;
import org.hyperledger.besu.evm.gascalculator.GasCalculator;

import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;

public class SarOperation extends AbstractFixedCostOperation {

  private static final UInt256 ALL_BITS = UInt256.MAX_VALUE;

  public SarOperation(final GasCalculator gasCalculator) {
    super(0x1d, "SAR", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());
  }

  @Override
  public Operation.OperationResult executeFixedCostOperation(
      final MessageFrame frame, final EVM evm) {

    Bytes shiftAmount = frame.popStackItem();
    final Bytes value = leftPad(frame.popStackItem());
    final boolean negativeNumber = value.get(0) < 0;
    if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
      frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO);
    } else {
      final int shiftAmountInt = shiftAmount.toInt();
      // BUG: CWE-681 Incorrect Conversion between Numeric Types
      // if (shiftAmountInt >= 256) {
      // FIXED:
 <fim-middle>     if (shiftAmountInt >= 256 || shiftAmountInt < 0) {
        frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO);
      } else {
        // first perform standard shift right.
        Byte<fix-suffix>s result = value.shiftRight(shiftAmountInt);

        // if a negative number, carry through the sign.
        if (negativeNumber) {
          final Bytes32 significantBits = ALL_BITS.shiftLeft(256 - shiftAmountInt);
          result = result.or(significantBits);
        }
        frame.pushStackItem(result);
      }
    }
    return successResponse;
  }
}
<|endoftext|>


<fim-prefix>r>
 * See the License for the specific language governing permissions and

 * limitations under the License.
 *

 * Initial code contributed and copyrighted by

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

 */
package org.olat.restapi.support;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Logger;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.WebappHelper;

/**
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
public class MultipartReader {

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

	private String filename;
	private String contentType;
	private File file;
	private Map<String, String> fields = new HashMap<>();

	public MultipartReader(HttpServletRequest request) {
		servlet31(request);
	}

	private final void servlet31(HttpServletRequest request) {
		try {
			for(Part part:request.getParts()) {
				if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) {
					contentType = part.getContentType();
					filename = part.getSubmittedFileName();
					// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
					// if(filename != null) {
					// FIXED:
<fim-middle>					if(filename != null && !filename.contains("..")) {
						filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
					} else {
						filename = "upload-" + UUID.randomUUID().toS<fix-suffix>tring().replace("-", "");
					}
					file = new File(WebappHelper.getTmpDir(), filename);
					part.write(file.getAbsolutePath());
					file = new File(WebappHelper.getTmpDir(), filename);
				} else {
					String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding());
					fields.put(part.getName(), value);
				}

				try {
					part.delete();
				} catch (Exception e) {
					//we try (tomcat doesn't send exception but undertow)
				}
			}
		} catch (IOException | ServletException e) {
			log.error("", e);
		}
	}

	public String getFilename() {
		return filename;
	}

	public String getContentType() {
		return contentType;
	}

	public String getText() {
		return fields.get("text");
	}

	public String getValue(String key) {
		return fields.get(key);
	}

	public String getValue(String key, String defaultValue) {
		String value = fields.get(key);
		if(StringHelper.containsNonWhitespace(key)) {
			return value;
		}
		return defaultValue;
	}

	public Long get<|endoftext|>


<fim-prefix>pyright 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.nukkitx.math.vector.Vector3i;
import com.nukkitx.protocol.bedrock.packet.BlockPickRequestPacket;
import org.geysermc.connector.entity.ItemFrameEntity;
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;
import org.geysermc.connector.network.translators.world.block.BlockStateValues;
import org.geysermc.connector.registry.BlockRegistries;
import org.geysermc.connector.utils.InventoryUtils;

@Translator(packet = BlockPickRequestPacket.class)
public class BedrockBlockPickRequestTranslator extends PacketTranslator<BlockPickRequestPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(BlockPickRequestPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, BlockPickRequestPacket packet) {
        Vector3i vector = packet.getBlockPosition();
        int blockToPick = session.getConnector().getWorldManager()<fix-suffix>.getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());

        // Block is air - chunk caching is probably off
        if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
            // Check for an item frame since the client thinks that's a block when it's an entity in Java
            ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
            if (entity != null) {
                // Check to see if the item frame has an item in it first
                if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
                    // Grab the item in the frame
                    InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
                } else {
                    // Grab the frame as the item
                    InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
                }
            }
            return;
        }

        InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
    }
}
<|endoftext|>


<fim-prefix>DED "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.data.game.entity.player.InteractAction;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;
import com.nukkitx.protocol.bedrock.packet.ItemFrameDropItemPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

/**
 * Pre-1.16.210: used for both survival and creative item frame item removal
 *
 * 1.16.210: only used in creative.
 */
@Translator(packet = ItemFrameDropItemPacket.class)
public class BedrockItemFrameDropItemTranslator extends PacketTranslator<ItemFrameDropItemPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ItemFrameDropItemPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ItemFrameDropItemPacket packet) {
        Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
        if (entity != <fix-suffix>null) {
            ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),
                    InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking());
            session.sendDownstreamPacket(interactPacket);
        }
    }
}
<|endoftext|>


<fim-prefix>ate;

import org.checkerframework.checker.initialization.qual.UnderInitialization;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.io.Console;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Properties;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

/**
 * Provide an SSLSocketFactory that is compatible with the libpq behaviour.
 */
public class LibPQFactory extends WrappedFactory {

  @Nullable KeyManager km;
  boolean defaultfile;

  private CallbackHandler getCallbackHandler(
      @UnderInitialization(WrappedFactory.class) LibPQFactory this,
      Properties info) throws PSQLException {
    // Determine the callback handler
    CallbackHandler cbh;
    String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info);
    if (sslpasswordcallback != null) {
      try {
        // BUG: CWE-665 Improper Initialization
        // cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null);
        // FIXED:
<fim-middle>        cbh = ObjectFactory.instantiate(CallbackHandler.class, sslpasswordcallback, info, false, null);
      } catch (Exception e) {
        throw new PSQLException(
          GT.tr("The password call<fix-suffix>back class provided {0} could not be instantiated.",
            sslpasswordcallback),
          PSQLState.CONNECTION_FAILURE, e);
      }
    } else {
      cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info));
    }
    return cbh;
  }

  private void initPk8(
      @UnderInitialization(WrappedFactory.class) LibPQFactory this,
      String sslkeyfile, String defaultdir, Properties info) throws  PSQLException {

    // Load the client's certificate and key
    String sslcertfile = PGProperty.SSL_CERT.get(info);
    if (sslcertfile == null) { // Fall back to default
      defaultfile = true;
      sslcertfile = defaultdir + "postgresql.crt";
    }

    // If the properties are empty, give null to prevent client key selection
    km = new LazyKeyManager(("".equals(sslcertfile) ? null : sslcertfile),
      ("".equals(sslkeyfile) ? null : sslkeyfile), getCallbackHandler(info), defaultfile);
  }

  private void initP12(
      @UnderInitialization(WrappedFactory.class) LibPQF<|endoftext|>


<fim-prefix>s
 * 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.entity.player;

import com.nukkitx.protocol.bedrock.packet.SetPlayerGameTypePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

/**
 * In vanilla Bedrock, if you have operator status, this sets the player's gamemode without confirmation from the server.
 * Since we have a custom server option to request the gamemode, we just reset the gamemode and ignore this.
 */
@Translator(packet = SetPlayerGameTypePacket.class)
public class BedrockSetPlayerGameTypeTranslator extends PacketTranslator<SetPlayerGameTypePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(SetPlayerGameTypePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, SetPlayerGameTypePacket packet) {
        // no
        SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
        playerGame<fix-suffix>TypePacket.setGamemode(session.getGameMode().ordinal());
        session.sendUpstreamPacket(playerGameTypePacket);
    }
}
<|endoftext|>


<fim-prefix> "false"};
    private static final String[] VALID_COLORS;
    private static final String[] VALID_SCOREBOARD_SLOTS;

    private static final Hash.Strategy<CommandParamData[][]> PARAM_STRATEGY = new Hash.Strategy<CommandParamData[][]>() {
        @Override
        public int hashCode(CommandParamData[][] o) {
            return Arrays.deepHashCode(o);
        }

        @Override
        public boolean equals(CommandParamData[][] a, CommandParamData[][] b) {
            if (a == b) return true;
            if (a == null || b == null) return false;
            if (a.length != b.length) return false;
            for (int i = 0; i < a.length; i++) {
                CommandParamData[] a1 = a[i];
                CommandParamData[] b1 = b[i];
                if (a1.length != b1.length) return false;

                for (int j = 0; j < a1.length; j++) {
                    if (!a1[j].equals(b1[j])) return false;
                }
            }
            return true;
        }
    };

    static {
        List<String> validColors = new ArrayList<>(NamedTextColor.NAMES.keys());
        validColors.add("reset");
        VALID_COLORS = validColors.toArray(new String[0]);

        List<String> teamOptions = new ArrayList<>(Arrays.asList("list", "sidebar", "belowName"));
        for (String color : NamedTextColor.NAMES.keys()) {
            teamOptions.add("sidebar.team." + color);
        }
        VALID_SCOREBOARD_SLOTS = teamOptions.toArray(new String[0]);
    }

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ServerDeclareCommandsPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ServerDeclareCommandsPacket packet) {
        // Don't send command suggestions if they are disabled
        if (!session.getConnector().getConfig().isC<fix-suffix>ommandSuggestions()) {
            session.getConnector().getLogger().debug("Not sending translated command suggestions as they are disabled.");

            // Send an empty packet so Bedrock doesn't override /help with its own, built-in help command.
            AvailableCommandsPacket emptyPacket = new AvailableCommandsPacket();
            session.sendUpstreamPacket(emptyPacket);
            return;
        }

        CommandNode[] nodes = packet.getNodes();
        List<CommandData> commandData = new ArrayList<>();
        IntSet commandNodes = new IntOpenHashSet();
        Set<String> knownAliases = new HashSet<>();
        Map<CommandParamData[][], Set<String>> commands = new Object2ObjectOpenCustomHashMap<>(PARAM_STRATEGY);
        Int2ObjectMap<List<CommandNode>> commandArgs = new Int2ObjectOpenHashMap<>();

        // Get the first node, it should be a root node
        CommandNode rootNode = nodes[packet.getFirstNodeIndex()];

        // Loop through the root nodes to get al<|endoftext|>


<fim-prefix>hments) {
			String page = Util.getPackageVelocityRoot(MailModule.class) + "/sendattachments.html";
			attachmentsLayout = FormLayoutContainer.createCustomFormLayout("attachments", getTranslator(), page);
			attachmentsLayout.setRootForm(mainForm);
			attachmentsLayout.setLabel("send.mail.attachments", null);
			formLayout.add(attachmentsLayout);
		}

		FormLayoutContainer buttonGroupLayout = FormLayoutContainer.createButtonLayout("buttonGroupLayout", getTranslator());
		formLayout.add(buttonGroupLayout);
		uifactory.addFormSubmitButton("ok", buttonGroupLayout);
		uifactory.addFormCancelButton("cancel", buttonGroupLayout, ureq, getWindowControl());
	}

	@Override
	protected void doDispose() {
		//
	}

	@Override
	public int getStatus() {
		return status;
	}

	@Override
	public boolean runsModal() {
		return false;
	}

	@Override
	public String getModalTitle() {
		return translate("send.mail.title");
	}

	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) {
		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		VFSContainer rootContainer = folderComponent.getRootContainer();

		if (!VFSManager.exists(currentContainer)) {
			status = FolderCommandStatus.STATUS_FAILED;
			showError(translator.translate("FileDoesNotExist"));
			return null;
		}
		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if (status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
		// FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
		// FIXED:
	<fim-middle>	FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderCompone<fix-suffix>nt, selection);
		if (status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}

		boolean selectionWithContainer = false;
		List<String> filenames = selection.getFiles();
		List<VFSLeaf> leafs = new ArrayList<>();
		for (String file : filenames) {
			VFSItem item = currentContainer.resolve(file);
			if (item instanceof VFSContainer) {
				selectionWithContainer = true;
			} else if (item instanceof VFSLeaf) {
				leafs.add((VFSLeaf) item);
			}
		}
		if (selectionWithContainer) {
			if (leafs.isEmpty()) {
				wControl.setError(getTranslator().translate("send.mail.noFileSelected"));
				return null;
			} else {
				setFormWarning(getTranslator().translate("send.mail.selectionContainsFolder"));
			}
		}
		setFiles(rootContainer, leafs);
		return this;
	}

	protected void setFiles(VFSContainer rootContainer, List<VFSLeaf> files) {
		StringBuilder subjectSb = new StringBuilder();
		if (StringHelper.containsNonWhitespace(subjectElement.getValue())) {
			subjectSb.append(subjectEle<|endoftext|>


<fim-prefix>
import javax.jmdns.ServiceInfo;
import java.io.Closeable;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Registers a DNS multi-cast service-discovery support.
 *
 * @author Kohsuke Kawaguchi
 */
public class DNSMultiCast implements Closeable {
    private JmDNS jmdns;

    public DNSMultiCast(final Jenkins jenkins) {
        if (disabled)   return; // escape hatch

        // the registerService call can be slow. run these asynchronously
        MasterComputer.threadPoolForRemoting.submit(new Callable<Object>() {
            public Object call() {
                try {
                    jmdns = JmDNS.create();

                    Map<String,String> props = new HashMap<String, String>();
                    String rootURL = jenkins.getRootUrl();
                    if (rootURL==null)  return null;

                    props.put("url", rootURL);
                    try {
                        props.put("version",String.valueOf(Jenkins.getVersion()));
                    } catch (IllegalArgumentException e) {
                        // failed to parse the version number
                    }

                    TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener();
                    if (tal!=null)
                        props.put("slave-port",String.valueOf(tal.getPort()));
                    // BUG: NVD-CWE-noinfo Insufficient Information
                    // props.put("server-id", Util.getDigestOf(jenkins.getSecretKey()));
                    // FIXED:
<fim-middle>                    props.put("server-id", jenkins.getLegacyInstanceId());

                    URL jenkins_url = new URL(rootURL);
                    int jenkins_port = jenkins_url.getPort();
       <fix-suffix>             if (jenkins_port == -1) {
                        jenkins_port = 80;
                    }
                    if (jenkins_url.getPath().length() > 0) {
                        props.put("path", jenkins_url.getPath());
                    }

                    jmdns.registerService(ServiceInfo.create("_hudson._tcp.local.","jenkins",
                            jenkins_port,0,0,props));	// for backward compatibility
                    jmdns.registerService(ServiceInfo.create("_jenkins._tcp.local.","jenkins",
                            jenkins_port,0,0,props));

                    // Make Jenkins appear in Safari's Bonjour bookmarks
                    jmdns.registerService(ServiceInfo.create("_http._tcp.local.","Jenkins",
                            jenkins_port,0,0,props));
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING,"Failed to advertise the service to DNS multi-cast",e);
                }
                return null;
        <|endoftext|>


<fim-prefix>arameters;
import org.xwiki.crypto.pkix.params.x509certificate.X509CertificateParameters;
import org.xwiki.crypto.pkix.params.x509certificate.X509CertifiedPublicKey;
import org.xwiki.crypto.pkix.params.x509certificate.extension.ExtendedKeyUsages;
import org.xwiki.crypto.pkix.params.x509certificate.extension.KeyUsage;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509DnsName;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509GeneralName;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509IpAddress;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509Rfc822Name;
import org.xwiki.crypto.signer.CMSSignedDataGenerator;
import org.xwiki.crypto.signer.CMSSignedDataVerifier;
import org.xwiki.crypto.signer.SignerFactory;
import org.xwiki.crypto.signer.param.CMSSignedDataGeneratorParameters;
import org.xwiki.crypto.signer.param.CMSSignedDataVerified;
import org.xwiki.crypto.signer.param.CMSSignerInfo;
import org.xwiki.script.service.ScriptService;

/**
 * Script service allowing a user to create keys pairs and issue certificates.
 *
 * @version $Id$
 * @since 8.4RC1
 */
@Component
@Named(CryptoScriptService.ROLEHINT + '.' + RSACryptoScriptService.ROLEHINT)
@Singleton
public class RSACryptoScriptService implements ScriptService
{
    /**
     * The role hint of this component.
     */
    public static final String ROLEHINT = "rsa";

    @Inject
    @Named("RSA")
    private KeyPairGenerator keyPairGenerator;

    @Inject
    // BUG: CWE-327 Use of a Broken or Risky Cryptographic Algorithm
    // @Named("SHA1withRSAEncryption")
    // FIXED:
<fim-middle>    @Named("SHA256withRSAEncryption")
    private SignerFactory signerFactory;

    @Inject
    private Provider<X509ExtensionBuilder> extensionBuilder;

    @Inject
    @Named("X509")
    private Cert<fix-suffix>ificateGeneratorFactory certificateGeneratorFactory;

    @Inject
    private CMSSignedDataGenerator cmsSignedDataGenerator;

    @Inject
    @Named("X509")
    private CertificateChainBuilder certificateChainBuilder;

    @Inject
    private CMSSignedDataVerifier cmsSignedDataVerifier;

    /**
     * Generate a new RSA key pair.
     *
     * The key strength will be {@value RSAKeyGenerationParameters#DEFAULT_STRENGTH}.
     * The key public exponent will be 0x10001.
     * The probability a chosen prime could not be a real prime will be smaller
     * than 2^-{@value RSAKeyGenerationParameters#DEFAULT_CERTAINTY}.
     *
     * @return an new asymmetric key pair.
     */
    public AsymmetricKeyPair generateKeyPair()
    {
        return keyPairGenerator.generate();
    }

    /**
     * Generate a new RSA key pair of given strength. The strength should be given in number of bytes, so for
     * a 2048 bits key, you should use 256 (bytes) as the integer parameter. The minimum valid s<|endoftext|>


<fim-prefix>and
 *  limitations under the License.
 */

import javax.management.ObjectName;

import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;

/**
 * Base restrictor which alway returns the constant given
 * at construction time
 *
 * @author roland
 * @since 06.10.11
 */
public abstract class AbstractConstantRestrictor implements Restrictor {

    private boolean isAllowed;

    /**
     * Create restrictor which always returns the given value on every check
     * method.
     *
     * @param pAllowed whether access is allowed or denied
     */
    protected AbstractConstantRestrictor(boolean pAllowed) {
        isAllowed = pAllowed;
    }

    /** {@inheritDoc} */
    public final boolean isHttpMethodAllowed(HttpMethod pMethod) {
        return isAllowed;
    }

    /** {@inheritDoc} */
    public final boolean isTypeAllowed(RequestType pType) {
        return isAllowed;
    }

    /** {@inheritDoc} */
    public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {
        return isAllowed;
    }

    /** {@inheritDoc} */
    public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {
        return isAllowed;
    }

    /** {@inheritDoc} */
    public final boolean isOperationAllowed(ObjectName pName, String pOperation) {
        return isAllowed;
    }

    /** {@inheritDoc} */
    public final boolean isRemoteAccessAllowed(String... pHostOrAddress) {
        return isAllowed;
    }

    /** {@inheritDoc} */
    // BUG: CWE-352 Cross-Site Request Forgery (CSRF)
    // public boolean isCorsAccessAllowed(String pOrigin) {
    // FIXED:
<fim-middle>    public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {
        return isAllowed;
    }
}
<fix-suffix><|endoftext|>


<fim-prefix>er(ctx.getSocketFactory(), cipherSuites,
                                                        protocol);
            //recalc the hashcode since some of the above MAY have changed the tlsClientParameters
            lastTlsHash = tlsClientParameters.hashCode();
        } else {
           // ssl socket factory already initialized, reuse it to benefit of keep alive
        }

        HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils
            .getHostnameVerifier(tlsClientParameters);

        if (connection instanceof HttpsURLConnection) {
            // handle the expected case (javax.net.ssl)
            HttpsURLConnection conn = (HttpsURLConnection) connection;
            conn.setHostnameVerifier(verifier);
            conn.setSSLSocketFactory(socketFactory);
        } else {
            // handle the deprecated sun case and other possible hidden API's
            // that are similar to the Sun cases
            try {
                Method method = connection.getClass().getMethod("getHostnameVerifier");

                InvocationHandler handler = new ReflectionInvokationHandler(verifier) {
                    public Object invoke(Object proxy,
                                         Method method,
                                         Object[] args) throws Throwable {
                        try {
                            return super.invoke(proxy, method, args);
                        } catch (Exception ex) {
                            // BUG: CWE-755 Improper Handling of Exceptional Conditions
                            // return true;
                            // FIXED:
 <fim-middle>                           return false;
                        }
                    }
                };
                Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getCl<fix-suffix>assLoader(),
                                                                        new Class[] {method.getReturnType()},
                                                                        handler);

                method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType());
                method.invoke(connection, proxy);
            } catch (Exception ex) {
                //Ignore this one
            }
            try {
                Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory");
                Method setSSLSocketFactory = connection.getClass()
                    .getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType());
                if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) {
                    setSSLSocketFactory.invoke(connection, socketFactory);
                } else {
                    //need to see if we can create one - mostly the weblogic case.   The
  <|endoftext|>


<fim-prefix>t.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.generic.modal.DialogBoxController;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.Identity;
import org.olat.core.logging.AssertException;
import org.olat.core.util.StringHelper;
import org.olat.core.util.ZipUtil;
import org.olat.core.util.vfs.Quota;
import org.olat.core.util.vfs.VFSConstants;
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.vfs.callbacks.VFSSecurityCallback;
import org.springframework.beans.factory.annotation.Autowired;

public class CmdUnzip extends BasicController implements FolderCommand {

	private int status = FolderCommandStatus.STATUS_SUCCESS;

	private Translator translator;
	private DialogBoxController lockedFiledCtr;

	@Autowired
	private VFSRepositoryService vfsRepositoryService;
	@Autowired
	private NotificationsManager notificationsManager;

	public CmdUnzip(UserRequest ureq, WindowControl wControl) {
		super(ureq, wControl);
	}

	@Override
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) {
		this.translator = trans;
		// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
		// FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
		// FIXED:
<fim-middle>		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
		VFSContainer currentContainer = folderComponent.getCurrentContai<fix-suffix>ner();
		if (currentContainer.canWrite() != VFSConstants.YES)
			throw new AssertException("Cannot unzip to folder. Writing denied.");

	  //check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name
		if(selection.getInvalidFileNames().size()>0) {
			status = FolderCommandStatus.STATUS_INVALID_NAME;
			return null;
		}

		List<String> lockedFiles = new ArrayList<>();
		for (String sItem:selection.getFiles()) {
			VFSItem vfsItem = currentContainer.resolve(sItem);
			if (vfsItem instanceof VFSLeaf) {
				try {
					lockedFiles.addAll(checkLockedFiles((VFSLeaf)vfsItem, currentContainer, ureq.getIdentity()));
				} catch (Exception e) {
					String name = vfsItem == null ? "NULL" : vfsItem.getName();
					getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name}));
				}
			}
		}

		if(!lockedFiles.isEmpty()) {
			String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, <|endoftext|>


<fim-prefix>st;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.generic.modal.DialogBoxController;
import org.olat.core.gui.control.generic.modal.DialogBoxUIFactory;
import org.olat.core.gui.translator.Translator;
import org.olat.core.util.vfs.VFSConstants;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLockApplicationType;
import org.olat.core.util.vfs.VFSLockManager;

public class CmdDelete extends BasicController implements FolderCommand {

	private static int status = FolderCommandStatus.STATUS_SUCCESS;

	private Translator translator;
	private FolderComponent folderComponent;
	private FileSelection fileSelection;

	private DialogBoxController dialogCtr;
	private DialogBoxController lockedFiledCtr;

	private final boolean versionsEnabled;
	private final VFSLockManager lockManager;

	protected CmdDelete(UserRequest ureq, WindowControl wControl) {
		super(ureq, wControl);
		versionsEnabled = CoreSpringFactory.getImpl(VFSVersionModule.class).isEnabled();
		lockManager = CoreSpringFactory.getImpl(VFSLockManager.class);
	}

	@Override
	public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) {
		this.translator = trans;
		this.folderComponent = fc;
		// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
		// this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());
		// FIXED:
	<fim-middle>	this.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath());

		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		List<String> lockedFil<fix-suffix>es = hasLockedFiles(currentContainer, fileSelection);
		if (lockedFiles.isEmpty()) {
			String msg = trans.translate("del.confirm") + "<p>" + fileSelection.renderAsHtml() + "</p>";
			// create dialog controller
			dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr);
		} else {
			String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
			List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
			lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
		}
		return this;
	}

	public List<String> hasLockedFiles(VFSContainer container, FileSelection selection) {
		List<String> lockedFiles = new ArrayList<>();
		for (String file : selection.getFiles()) {
			VFSItem item = container.resolve(file);
			if (lockManager.isLockedForMe(item, getIdentity(), VFSLockApplicationType.vfs, null)) {
				lockedFiles.add(file);
			}
		}
		return lockedFiles;
	}

	@Overr<|endoftext|>


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

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

import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

import com.github.steveice10.mc.protocol.data.game.ClientRequest;
import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;
import com.nukkitx.protocol.bedrock.packet.ShowCreditsPacket;

@Translator(packet = ShowCreditsPacket.class)
public class BedrockShowCreditsTranslator extends PacketTranslator<ShowCreditsPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ShowCreditsPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ShowCreditsPacket packet) {
        if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) {
            ClientRequestPacket javaRespawnPacket <fix-suffix>= new ClientRequestPacket(ClientRequest.RESPAWN);
            session.sendDownstreamPacket(javaRespawnPacket);
        }
    }
}
<|endoftext|>


<fim-prefix> = new ParcelUuid(new UUID(0, 0));
        mType = type;
        mAuth = auth;
        mEncrypt = encrypt;
        mDevice = device;
        mPort = port;
        mFd = fd;

        mSocketState = SocketState.INIT;

        if (device == null) {
            // Server socket
            mAddress = BluetoothAdapter.getDefaultAdapter().getAddress();
        } else {
            // Remote socket
            mAddress = device.getAddress();
        }
        mInputStream = new BluetoothInputStream(this);
        mOutputStream = new BluetoothOutputStream(this);
    }
    private BluetoothSocket(BluetoothSocket s) {
        mUuid = s.mUuid;
        mType = s.mType;
        mAuth = s.mAuth;
        mEncrypt = s.mEncrypt;
        mPort = s.mPort;
        mInputStream = new BluetoothInputStream(this);
        mOutputStream = new BluetoothOutputStream(this);
        mServiceName = s.mServiceName;
    }
    private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException {
        BluetoothSocket as = new BluetoothSocket(this);
        as.mSocketState = SocketState.CONNECTED;
        FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors();
        if (DBG) Log.d(TAG, "socket fd passed by stack  fds: " + fds);
        if(fds == null || fds.length != 1) {
            Log.e(TAG, "socket fd passed from stack failed, fds: " + fds);
            as.close();
            throw new IOException("bt socket acept failed");
        }
        as.mSocket = new LocalSocket(fds[0]);
        // BUG: NVD-CWE-noinfo Insufficient Information
        //
        // FIXED:
<fim-middle>        as.mPfd = new ParcelFileDescriptor(fds[0]);
        try {
            as.mSocket.closeExternalFd();
        } catch (IOException e) {
            Log.e(TAG, "closeExternalFd failed");
        }<fix-suffix>
        as.mSocketIS = as.mSocket.getInputStream();
        as.mSocketOS = as.mSocket.getOutputStream();
        as.mAddress = RemoteAddr;
        as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr);
        as.mPort = mPort;
        return as;
    }
    /**
     * Construct a BluetoothSocket from address. Used by native code.
     * @param type    type of socket
     * @param fd      fd to use for connected socket, or -1 for a new socket
     * @param auth    require the remote device to be authenticated
     * @param encrypt require the connection to be encrypted
     * @param address remote device that this socket can connect to
     * @param port    remote port
     * @throws IOException On error, for example Bluetooth not available, or
     *                     insufficient privileges
     */
    private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address,
            int port) throws IOException {
        this(type, fd, auth<|endoftext|>