<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 test<fix-suffix>ComparableFunctionInCondition() {
		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 testAndMultipleOnGoingLogicalConditions2() {
		Entity entity = from(Entity.class);
		OnGoingLogicalCondition condition = condition(entity.getCode()).eq(
				"test");
		OnGoingLogicalCondition condition2 = condition(entity.getCode()).eq(
				"test2");

		where(and(Arrays.asList(condition, condition2)));
		Query<Entity> select = select(entity);
		assertEquals(
				"select entity_0 from Entity entity_0 where ( ( entity_0.code = :code_1 ) and ( entity_0.code = :code_2 ) )",
				select.getQuery());
<|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 : UDPBroadcastFrag<fix-suffix>ment.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).append('>');
    }

    public void shutdown() {
        shutdown = true;
        mcs.close();
        interrupt();
    }

    public static final int PORT = Integer.getInteger("hudson.udp",33848);

    private static final Logger LOGGER = Logger.getLogger(UDPBroadcastThread.class.getName());

    /**
     * Multicast socket address.
     */
    public static InetAddress MULTICAST;

    static {
        try {
            MULTICAST = InetAddress.getByAddress(new byte[]{(byte)239, (byte)77, (byte)124<|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=\"" + escape(name) +
					"\", order=" + index + ")\n");
		}
		if (showCondition != null)
			buffer.append("    @ShowCondition(\"isInput" + index + "Visible\")\n");
	}

	private void wrapWithChildContext(StringBuffer buffer, int index, String statement) {
		buffer.append("            ComponentContext context = ComponentContext.get();\n");
		buffer.append("            if (context != null) {\n");
		buffer.append("                ComponentContext childContext = context.getChildContext(\"input" + index +<|endoftext|>


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

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

import com.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.ut<|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;

    p<fix-suffix>ublic 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 "******";
    }

    @Override
    public String forCommandLine() {
        return this.url;
    }

    protected String sanitizeUrl() {
        return this.url;
    }

    public static UrlArgument create(String url) {
        return new UrlArgument(url);
    }

    @Override
    public String replaceSecretInfo(String line) {
        if (StringUtils.isBlank(line)) {
            return line;
        }

        if (isBlank(this.url)) {
            return line;
        }

        try {
            final URIBuilder uriBui<|endoftext|>


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

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

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyI<fix-suffix>nfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;
import org.bouncycastle.pqc.asn1.XMSSMTKeyParams;
import org.bouncycastle.pqc.asn1.XMSSMTPrivateKey;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDSStateMap;
import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
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 XMSSMTPrivateKeyParamet<|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.resolve(user, iconSize);
                                    synchronized (this) {
                                        users.put(user, userInfo);
                                        modified.add(user);
                                    }
                                } else if (info.getLastChange().before(build.getTimestamp())) {
                                    synchronized (this) {
                                        info.project = p;
                                       <|endoftext|>


<fim-prefix><fim-middle>
// From Philippe Le Hegaret (Philippe.Le_Hegaret@sophia.inria.fr)
//
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package org.w3c.cs<fix-suffix>s.css;

import org.w3c.css.atrules.css.AtRuleMedia;
import org.w3c.css.atrules.css.AtRulePage;
import org.w3c.css.parser.AtRule;
import org.w3c.css.parser.CssError;
import org.w3c.css.parser.CssFouffa;
import org.w3c.css.parser.CssParseException;
import org.w3c.css.parser.CssSelectors;
import org.w3c.css.parser.CssValidatorListener;
import org.w3c.css.parser.Errors;
import org.w3c.css.parser.analyzer.ParseException;
import org.w3c.css.parser.analyzer.TokenMgrError;
import org.w3c.css.properties.css.CssProperty;
import org.w3c.css.selectors.IdSelector;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.CssVersion;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.util.Messages;
import org.w3c.css.util.Util;
import org.w3c.css.util.Warning;
import org.w3c.css.util.Warnings;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 * @version $Revision$
 */
public final class StyleSheetParser
        implements CssValidatorListener, CssParser {

    private static Constructor co = null;

    static {
        try {
            Class c = java.lang.Exception.class;
            Class cp[] = {java.lang.Exception.class};
            co = c.getDeclaredConstructor(cp);
   <|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(
                                dropAll ? PlayerAction.DROP_ITEM_STACK : PlayerAction.DROP_ITEM,
                                BlockUtils.POSITION_ZERO,
                                BlockFace.DOWN
                        );
                        session.sendDownstreamPacket(dropAllPacket);

                        if (dropAll) {
                            session.getPlayerInventory().setItemInHand(GeyserItemStack.EMPTY);
                        } else {
                            session.getPlayerI<|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><fim-middle>right (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0, wh<fix-suffix>ich is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the
 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
 * version 2 with the GNU Classpath Exception, which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 */

package com.sun.faces.application.resource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Stream;

import javax.faces.application.ProjectStage;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceVisitOption;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import com.sun.faces.config.WebConfiguration;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.Util;

/**
 * This class is used to lookup {@link ResourceInfo} instances
 * and cache any that are successfully looked up to reduce the
 <|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());
            assertEquals(0, region.transferred());
            assertEquals(data.length, region.transferTo(channel, 0));
            assertEquals(data.length, region.count());
            assertEquals(data.length, region.transferred());
            assertArrayEquals(data, outputStream.toByteArray());
        } finally {
            channel.close();
        }
    }

    @Test
    public void testTruncated() throws IOException  {
        File file = newFile();
        ByteArrayOutputStream outputStream =<|endoftext|>


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

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.Filter;
import com.thoughtworks.go.config.materials.IgnoredFiles;
import com.thoughtworks.go.config.materials.ScmMaterialConfig;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.security.CryptoException;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.ReflectionUtil;
import com.thoughtworks.go.util.command.UrlArgument;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

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

import static com.thoughtworks.go.config.materials.AbstractMaterialConfig.MATERIAL_NAME;
import static com.thoughtworks.go.config.materials.ScmMaterialConfig.FOLDER;
import static com.thoughtworks.go.config.materials.ScmMaterialConfig.URL;
import static com.thoughtworks.go.helper.MaterialConfigsMother.tfs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.co<|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 InvalidMediaExtensionException extends InvalidExtensionException
    {
        private static final long serialVersionUID = 1L;

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

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

        public InvalidVideoExtens<|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 {
                advancementsCache.getStoredAdvancements().remove(advancement.getId());
            }
        }
    }

    /**
     * Handle all advancements progress updates
     */
    public void sendToolbarAdvancementUpdates(GeyserSession session, ServerAdvancementsPacket packet) {
        if (packet.isReset()) {
            // Advancements are being cleared, so they can't be granted
            return;
        }
        for (Map.Entry<String, Map<String, Long>> progress : packet.getProgress(<|endoftext|>


<fim-prefix><fim-middle>right ConsenSys AG.
 *
 * 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
 *<fix-suffix>
 * 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.
 *
 * 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 : UInt25<|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().to<fix-suffix>String().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 getLongValue(String key) {
		String value = fields.get(key);
		if (value == null) { return null; }
		try {
			return Long.parseLong(value);
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public Integer getIntegerValue(String key) {
		String value = fields.get(key);
		if (value == null) { return null; }
		try {
			return Integer.parseInt(value);
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public File getFile() {
		return file;
	}

	public void close() {
		if (fil<|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 cal<fix-suffix>lback 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) LibPQFactory this,
      String sslkeyfile, Properties info) throws PSQLException {
    km = new PKCS12KeyManager(sslkeyfile, getCallbackHandler(info));
  }

  /**
   * @param info the connection parameters The following parameters are used:
   *        sslmode,sslcert,sslkey,sslrootcert,sslhostnameverifier,sslpasswordcallback,sslpassword
   * @throws PSQLException if security error appears when initializing factory
   */
  public LibPQFactory(Properties info) throws PSQLException {
    try {
      S<|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();
        playerGam<fix-suffix>eTypePacket.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().is<fix-suffix>CommandSuggestions()) {
            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 all commands
        for (int nodeIndex : rootNode.getChildIndices()) {
            CommandNode node = nodes[nodeIndex];

            // Make sure we don't have duplicated commands (happens if there is more than 1 root node)
            if (!commandNodes.add(nodeIndex) || !knownAliases.add(node.getName().toLowerCase())) continue;

            // Get and update the commandArgs list with the found arguments
            if (node.getChildIndices().length >= 1) {
                for (int childIndex : <|endoftext|>


<fim-prefix><fim-middle>href="http://www.openolat.org">
 * OpenOLAT - Online Learning and Training

 *

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

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

 * You may obtain a copy of the License at the
 * Apache homepage
 *

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

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

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

 * See the License for the specific language governing permissions and

 * limitations under the License.
 *

 * Initial code contributed and copyrighted by

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

 */
package org.olat.core.util.mail.ui;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.events.SingleIdentityChosenEvent;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.modules.bc.FileSelection;
import org.olat.core.commons.modules.bc.FolderConfig;
import org.olat.core.commons.modules.bc.commands.CmdSendMail;
import org.olat.core.commons.modules.bc.commands.FolderCommand;
import org.olat.core.commons.modules.bc.commands.FolderCommandHelper;
import org.olat.core.commons.modules.bc.commands.FolderCommandStatus;
import org.olat.core.commons.modules.bc.components.FolderComponent;
import org.olat.core.commons.modules.bc.meta.MetaInfoController;
import org.olat.co<|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;
            }
        });
    }

    public void close() {
        if (jmdns!=null) {
//            try {
                jmdns.abort();
                jmdns = null;
//            } catch (final IOException e) {
//                LOGGER.log(Level.WARNING,"Failed to close down JmDNS instance!",e);
//            }
        }
    }

    private static final Logger LOGGER = Logger.getLogger(DNSMultiCast.class.getName());

    public static boolean disabled = Boolean.getBoolean(DNSMultiCast.class.getName()+<|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 Cer<fix-suffix>tificateGeneratorFactory 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 strength is 2.
     *
     * 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}.
     *
     * @param strength the strength in bytes.
     * @return an new asymmetric key pair.
     */
    public AsymmetricKeyPair generateKeyPair(int strength)
    {
        return keyPairGenerator.generate(new RSAKeyGenerationParameters(strength));
    }

    /**
     * Build<|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><fim-middle>ensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright o<fix-suffix>wnership. The ASF 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
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.cxf.transport.https;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.logging.Handler;
import java.util.logging.Logger;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.ReflectionInvokationHandler;
import org.apache.cxf.common.util.ReflectionUtil;
import org.apache.cxf.configuration.jsse.SSLUtils;
import org.apache.cxf.configuration.jsse.TLSClientParameters;

/**
 * This HttpsURLConnectionFactory implements the HttpURLConnectionFactory
 * for using the given<|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.getCurrentConta<fix-suffix>iner();
		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, lockedFiles);
			List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
			lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
			return null;
		}

		VFSItem currentVfsItem = null;
		try {
			boolean fileNotExist = false;
			for (String sItem:selection.getFiles()) {
				currentVfsItem = currentContainer.resolve(sItem);
				if (currentVfsItem instanceof VFSLeaf) {
					if (!doUnzip((VFSLeaf)currentVfsItem, curre<|endoftext|>


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

* http://www.olat.org
*

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

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

* You may obtain a copy of the License at
*

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

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

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

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

* See the License for the specific language governing permissions and

* limitations under the License.
*

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

* University of Zurich, Switzerland.
*

*
* OpenOLAT - Online Learning and Training

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

*/

package org.olat.core.commons.modules.bc.commands;

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

import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.modules.bc.FileSelection;
import org.olat.core.commons.modules.bc.FolderEvent;
import org.olat.core.commons.modules.bc.components.FolderComponent;
import org.olat.core.commons.services.vfs.VFSVersionModule;
import org.olat.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.ola<|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, encrypt, new BluetoothDevice(address), port, null);
    }

    /** @hide */
    @Override
    protected void finalize() throws Throwable {
        try {
            close();
        } finally {
            super.finalize();
        }
    }
    private int getSecurityFlags() {
        int flags = 0;
        if(mAuth)
            flags |= SEC_FLAG_AUTH;
        if(mEncrypt)
            flags |= SEC_FLAG_ENCRYPT;
        return flags;
    }

    /**
     * Get the remote device this socket is co<|endoftext|>


<fim-prefix>nd 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.ItemStackRequestPacket;
import org.geysermc.connector.inventory.Inventory;
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.inventory.InventoryTranslator;

/**
 * The packet sent for server-authoritative-style inventory transactions.
 */
@Translator(packet = ItemStackRequestPacket.class)
public class BedrockItemStackRequestTranslator extends PacketTranslator<ItemStackRequestPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ItemStackRequestPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ItemStackRequestPacket packet) {
        Inventory inventory = session.getOpenInventory();
        if (inventory == null)
            return;

        <fix-suffix>InventoryTranslator translator = session.getInventoryTranslator();
        translator.translateRequests(session, inventory, packet.getRequests());
    }
}
<|endoftext|>


<fim-prefix>XEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package jodd.json;

import jodd.introspector.ClassDescriptor;
import jodd.introspector.ClassIntrospector;
import jodd.introspector.CtorDescriptor;
import jodd.introspector.PropertyDescriptor;
import jodd.introspector.Setter;
import jodd.typeconverter.TypeConverterManager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

/**
 * Just a base class of {@link jodd.json.JsonParser} that contains
 * various utilities, to reduce the size of a parser.
 */
public abstract class JsonParserBase {

	protected static final Supplier<Map> HASMAP_SUPPLIER = LinkedHashMap::new;
	protected static final Supplier<Map> LAZYMAP_SUPPLIER = LazyMap::new;

	protected static final Supplier<List> ARRAYLIST_SUPPLIER = ArrayList::new;
	protected static final Supplier<List> LAZYLIST_SUPPLIER = LazyList::new;

	protected Supplier<Map> mapSupplier = HASMAP_SUPPLIER;
	protected Supplier<List> listSupplier = ARRAYLIST_SUPPLIER;
	// BUG: CWE-502 Deserialization of Untrusted Data
	//
	// FIXED:
<fim-middle>	protected List<String> classnameWhitelist;

	/**
	 * Creates new instance of {@link jodd.json.MapToBean}.
	 */
	protected MapToBean createMapToBean(final String classMetadataName) {
		return new MapT<fix-suffix>oBean(this, classMetadataName);
	}

	// ---------------------------------------------------------------- object tools

	/**
	 * Creates new type for JSON array objects.
	 * It returns a collection.
	 * Later, the collection will be converted into the target type.
	 */
	@SuppressWarnings("unchecked")
	protected Collection<Object> newArrayInstance(final Class targetType) {
		if (targetType == null ||
			targetType == List.class ||
			targetType == Collection.class ||
			targetType.isArray()) {

			return listSupplier.get();
		}

		if (targetType == Set.class) {
			return new HashSet<>();
		}

		try {
			return (Collection<Object>) targetType.getDeclaredConstructor().newInstance();
		} catch (Exception e) {
			throw new JsonException(e);
		}
	}

	/**
	 * Creates new object or a HashMap if type is not specified.
	 */
	protected Object newObjectInstance(final Class targetType) {
		if (targetType == null ||
			targetType == Map.class) {

			return mapSupplier.get();
		}

		ClassDescriptor cd = ClassIntrospector.get().lookup(targetType);

		CtorDescriptor ctorDescriptor = cd.getDefaultCtorDescriptor(true);
		if (ctorDescriptor == null) {
			throw new JsonException("Default ctor not found for: " + targetType.getName());
		}

		try {
//			return ClassUtil.newInstance(targetType);
			return ctorDescriptor.getConstructor().newInstance();
		} catch (Exception e) {
			throw new JsonException(e);
		}
	}

	/**
	 * Injects value into the targets property.
	 */
	protected void in<|endoftext|>


<fim-prefix>est.getContextPath()))
            return targetUrl.substring(request.getContextPath().length());

        // not sure when this happens, but apparently this happens in some case.
        // see #1274
        return targetUrl;
    }

    /**
     * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException)
     */
    @Override
    protected String determineFailureUrl(HttpServletRequest request, AuthenticationException failed) {
        Properties excMap = getExceptionMappings();
		String failedClassName = failed.getClass().getName();
		String whereFrom = request.getParameter("from");
		request.getSession().setAttribute("from", whereFrom);
		return excMap.getProperty(failedClassName, getAuthenticationFailureUrl());
    }

    @Override
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
        super.onSuccessfulAuthentication(request,response,authResult);
        // make sure we have a session to store this successful authentication, given that we no longer
        // let HttpSessionContextIntegrationFilter2 to create sessions.
        // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later
        // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its
        // doFilter method.
        // BUG: CWE-287 Improper Authentication
        //
        // FIXED:
<fim-middle>        request.getSession().invalidate();
        request.getSession();
    }

    /**
     * Leave the information about login failure.
     *
     * <p>
     * Otherwise it seems like Acegi doesn't<fix-suffix> really leave the detail of the failure anywhere.
     */
    @Override
    protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
        super.onUnsuccessfulAuthentication(request, response, failed);
        LOGGER.log(Level.INFO, "Login attempt failed", failed);
    }

    private static final Logger LOGGER = Logger.getLogger(AuthenticationProcessingFilter2.class.getName());
}
<|endoftext|>


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

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

import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateJigsawBlockPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientUpdateSignPacket;
import com.nukkitx.nbt.NbtMap;
import com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket;
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.SignUtils;

@Translator(packet = BlockEntityDataPacket.class)
public class BedrockBlockEntityDataTranslator extends PacketTranslator<BlockEntityDataPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(BlockEntityDataPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, BlockEntityDataPacket packet) {
        NbtMap tag = packet.getData();
        if (tag.getString("id").equals("Sign")) {
            // This is the rea<fix-suffix>son why this all works - Bedrock sends packets every time you update the sign, Java only wants the final packet
            // But Bedrock sends one final packet when you're done editing the sign, which should be equal to the last message since there's no edits
            // So if the latest update does not match the last cached update then it's still being edited
            if (!tag.getString("Text").equals(session.getLastSignMessage())) {
                session.setLastSignMessage(tag.getString("Text"));
                return;
            }
            // Otherwise the two messages are identical and we can get to work deconstructing
            StringBuilder newMessage = new StringBuilder();
            // While Bedrock's sign lines are one string, Java's is an array of each line
            // (Initialized all with empty strings because it complains about null)
            String[] lines = new String[] {"", "", "", ""};
            int iterator = 0;
            // Keep track of the width of each character
            // If it goes over the maximum, we need to start a new line to match Java
            int widthCount = 0;
            // This converts the message into the array'd message Java wants
            for (char character : tag.getString("Text").toCharArray()) {
                widthCount += SignUtils.getCharacterWidth(character);
                // If we get a return in Bedrock, or go over the character width max, that signals to use the next line.
              <|endoftext|>


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

import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.context.FieldValueResolver;
import com.github.jknack.handlebars.context.JavaBeanValueResolver;
import com.github.jknack.handlebars.context.MapValueResolver;
import com.github.jknack.handlebars.helper.StringHelpers;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.FileTemplateLoader;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import org.apache.commons.lang3.StringUtils;
import org.ballerinalang.openapi.exception.BallerinaOpenApiException;
import org.ballerinalang.openapi.model.BallerinaOpenApi;
import org.ballerinalang.openapi.model.GenSrcFile;
import org.ballerinalang.openapi.typemodel.BallerinaOpenApiType;
import org.ballerinalang.openapi.utils.CodegenUtils;
import org.ballerinalang.openapi.utils.GeneratorConstants;
import org.ballerinalang.openapi.utils<|endoftext|>


<fim-prefix>ImmutableMap.builderWithExpectedSize(expectedNumParams);
    }

    /**
     * Sets the result type.
     *
     * @param type {@link RoutingResultType#MATCHED} or {@link RoutingResultType#CORS_PREFLIGHT}.
     */
    public RoutingResultBuilder type(RoutingResultType type) {
        requireNonNull(type, "type");
        checkArgument(type != RoutingResultType.NOT_MATCHED,
                      "type: %s (expected: %s or %s)",
                      type, RoutingResultType.MATCHED, RoutingResultType.CORS_PREFLIGHT);
        this.type = type;
        return this;
    }

    /**
     * Sets the mapped path, encoded as defined in RFC3986.
     */
    public RoutingResultBuilder path(String path) {
        this.path = requireNonNull(path, "path");
        return this;
    }

    /**
     * Sets the specified query.
     */
    public RoutingResultBuilder query(@Nullable String query) {
        this.query = query;
        return this;
    }

    /**
     * Adds a decoded path parameter.
     */
    public RoutingResultBuilder decodedParam(String name, String value) {
        pathParams().put(requireNonNull(name, "name"), requireNonNull(value, "value"));
        return this;
    }

    /**
     * Adds an encoded path parameter, which will be decoded in UTF-8 automatically.
     */
    public RoutingResultBuilder rawParam(String name, String value) {
        pathParams().put(requireNonNull(name, "name"),
                        // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
                        // ArmeriaHttpUtil.decodePath(requireNonNull(value, "value")));
                        // FIXED:
<fim-middle>                         ArmeriaHttpUtil.decodePathParam(requireNonNull(value, "value")));
        return this;
    }

    /**
     * Sets the score.
     */
    public RoutingResultBuilder score(int <fix-suffix>score) {
        this.score = score;
        return this;
    }

    /**
     * Sets the negotiated producible {@link MediaType}.
     */
    public RoutingResultBuilder negotiatedResponseMediaType(MediaType negotiatedResponseMediaType) {
        this.negotiatedResponseMediaType = requireNonNull(negotiatedResponseMediaType,
                                                          "negotiatedResponseMediaType");
        return this;
    }

    /**
     * Returns a newly-created {@link RoutingResult}.
     */
    public RoutingResult build() {
        if (path == null) {
            return RoutingResult.empty();
        }

        return new RoutingResult(type, path, query,
                                 pathParams != null ? pathParams.build() : ImmutableMap.of(),
                                 score, negotiatedResponseMediaType);
    }

    private ImmutableMap.Builder<String, String> pathParams() {
        if (pathParams != null) {
            return pathParams;
        }
        return pathParams = ImmutableMap.builder();
    }
}
<|endoftext|>