<fim-prefix>,data.value});
		}
	}

	@Override
	public Date getLastModified(ResourceContext resourceContext) {
		UriData data = (UriData) restoreData(resourceContext);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (null != data && null != facesContext ) {
			// Send headers
			ELContext elContext = facesContext.getELContext();
			if(data.modified != null){
			ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);
			Date modified = (Date) binding.getValue(elContext);
			if (null != modified) {
				return modified;
			}
		}
		}
		return super.getLastModified(resourceContext);
	}

	@Override
	public long getExpired(ResourceContext resourceContext) {
		UriData data = (UriData) restoreData(resourceContext);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (null != data && null != facesContext ) {
			// Send headers
			ELContext elContext = facesContext.getELContext();
			if(data.expires != null){
			ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);
			Date expires = (Date) binding.getValue(elContext);
			if (null != expires) {
				return expires.getTime()-System.currentTimeMillis();
			}
		}
		}
		return super.getExpired(resourceContext);
	}
	/* (non-Javadoc)
	 * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()
	 */
	public boolean requireFacesContext() {
		// TODO Auto-generated method stub
		return true;
	}
	// BUG: CWE-502 Deserialization of Untrusted Data
	// public static class UriData implements Serializable {
	// FIXED:
<fim-middle>	public static class UriData implements SerializableResource {

		/**
		 *
		 */
		private static final long serialVersionUID = 1258987L;

		private Object value;

		private Object createContent;<fix-suffix>

		private Object expires;

		private Object modified;
	}

}
<|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.course.assessment.bulk;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.IOUtils;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FileElement;
import org.olat.core.gui.components.form.flexible.elements.SingleSelection;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import<|endoftext|>


<fim-prefix>         if ((languagetoedit == null) || (languagetoedit.equals("default"))) {
                languagetoedit = "";
            }
            if (doc.isNew() || (doc.getDefaultLanguage().equals(languagetoedit))) {
                languagetoedit = "";
            }

            if (languagetoedit.equals("")) {
                // In this case the created document is going to be the default document
                tdoc = doc;
                context.put("tdoc", doc);
                if (doc.isNew()) {
                    doc.setDefaultLanguage(language);
                    doc.setLanguage("");
                }
            } else {
                // If the translated doc object is the same as the doc object
                // this means the translated doc did not exists so we need to create it
                if ((tdoc == doc)) {
                    tdoc = new XWikiDocument(doc.getDocumentReference());
                    tdoc.setLanguage(languagetoedit);
                    tdoc.setContent(doc.getContent());
                    tdoc.setSyntax(doc.getSyntax());
                    tdoc.setAuthor(context.getUser());
                    tdoc.setStore(doc.getStore());
                    context.put("tdoc", tdoc);
                }
            }

            XWikiDocument tdoc2 = tdoc.clone();
            if (content != null && !content.isEmpty()) {
                tdoc2.setContent(content);
            }
            context.put("tdoc", tdoc2);
            try {
                // BUG: CWE-862 Missing Authorization
                // tdoc2.readFromTemplate(peform, context);
                // FIXED:
<fim-middle>                readFromTemplate(tdoc2, peform.getTemplate(), context);
            } catch (XWikiException e) {
                if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) {<fix-suffix>
                    context.put("exception", e);
                    return "docalreadyexists";
                }
            }

            /* Setup a lock */
            try {
                XWikiLock lock = tdoc.getLock(context);
                if ((lock == null) || (lock.getUserName().equals(context.getUser())) || (peform.isLockForce())) {
                    tdoc.setLock(context.getUser(), context);
                }
            } catch (Exception e) {
                // Lock should never make XWiki fail
                // But we should log any related information
                LOGGER.error("Exception while setting up lock", e);
            }
        }

        return "admin";
    }
}
<|endoftext|>


<fim-prefix><fim-middle>=================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyr<fix-suffix>ight 2009-2023, Arnaud Roques
 *
 * Project Info:  http://plantuml.com
 *
 * If you like this project or if you find it useful, you can support us at:
 *
 * http://plantuml.com/patreon (only 1$ per month!)
 * http://plantuml.com/paypal
 *
 * This file is part of PlantUML.
 *
 * PlantUML is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PlantUML distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 *
 * Original Author:  Arnaud Roques
 *
 *
 */
package net.sourceforge.plantuml.style;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.LineLocationImpl;
import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.SkinParam;
im<|endoftext|>


<fim-prefix>olumnDescriptorTest.class,
	org.olat.core.gui.components.table.TableEventTest.class,
	org.olat.core.gui.components.table.TableMultiSelectEventTest.class,
	org.olat.core.gui.components.table.SorterTest.class,
	org.olat.core.commons.chiefcontrollers.ChiefControllerMessageEventTest.class,
	org.olat.core.util.vfs.VFSTest.class,
	org.olat.core.util.vfs.VFSManagerTest.class,
	org.olat.core.util.filter.impl.XSSFilterParamTest.class,
	org.olat.core.util.filter.impl.AddBaseURLToMediaRelativeURLFilterTest.class,
	org.olat.core.util.filter.impl.SimpleHTMLTagsFilterTest.class,
	org.olat.core.util.filter.impl.HtmlFilterTest.class,
	org.olat.core.util.filter.impl.HtmlMathScannerTest.class,
	org.olat.core.util.filter.impl.ConditionalHtmlCommentsFilterTest.class,
	org.olat.core.util.filter.impl.XMLValidCharacterFilterTest.class,
	org.olat.core.util.filter.impl.XMLValidEntityFilterTest.class,
	org.olat.core.helpers.SettingsTest.class,
	org.olat.core.util.coordinate.LockEntryTest.class,
	org.olat.modules.iq.DBPersistentLockManagerTest.class,
	org.olat.core.util.StringHelperTest.class,
	org.olat.core.util.FileUtilsTest.class,
	org.olat.core.util.FileNameSuffixFilterTest.class,
	org.olat.core.util.FormatterTest.class,
	org.olat.core.util.FormatLatexFormulasTest.class,
	org.olat.core.util.FormatterHourAndSecondsTest.class,
	org.olat.core.util.EncoderTest.class,
	org.olat.core.util.SimpleHtmlParserTest.class,
	org.olat.core.util.IPUtilsTest.class,
	org.olat.core.util.IPUtilsValidRangeTest.class,
	// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
	//
	// FIXED:
<fim-middle>	org.olat.core.util.ZipUtilTest.class,
	org.olat.core.util.ZipUtilConcatTest.class,
	org.olat.core.util.mail.EmailAddressValidatorTest.class,
	org.olat.core.util.mail.manager.MailManagerTest.class,
	o<fix-suffix>rg.olat.core.util.mail.manager.MailUserDataManagerTest.class,
	org.olat.core.util.openxml.OpenXmlWorkbookTest.class,
	org.olat.core.util.openxml.OpenXMLDocumentTest.class,
	org.olat.core.util.pdf.PdfDocumentTest.class,
	org.olat.core.util.xml.XMLDigitalSignatureUtilTest.class,
	org.olat.core.util.xml.XStreamHelperTest.class,
	org.olat.core.configuration.EDConfigurationTest.class,
	org.olat.core.id.context.BusinessControlFactoryTest.class,
	org.olat.core.id.context.HistoryManagerTest.class,
	org.olat.core.id.IdentityEnvironmentTest.class,
	org.olat.core.gui.render.VelocityTemplateTest.class,
	org.olat.core.gui.control.generic.iframe.IFrameDeliveryMapperTest.class,
	org.olat.note.NoteTest.class,
	org.olat.user.UserTest.class,
	org.olat.user.UserPropertiesTest.class,
	org.olat.commons.calendar.CalendarImportTest.class,
	org.olat.commons.calendar.CalendarUtilsTest.class,
	org.olat.commons.calendar.manager.ImportedCalendarDAOTest.class,
	org.olat.commons.calendar.manager.ImportedToCalendarDAOTest.class,
	org.olat.commons.calendar.manager.ICalFileCalendarManagerTest.class,
	org.olat.commons.calendar.manager.CalendarUserConfigurationDAOTest.class,
	org.olat.commons.lifecycle.LifeCycleManagerTest.class,
	org.olat.commons.coordinate.cluster.jms.JMSTest.class,
	org.olat.commons.coordinate.cluster.lock.LockTest.class,
	org.olat.commons.coordinate.CoordinatorTest.class,
	org.olat.core.commons.modules.glossary.GlossaryItemManagerTest.class,
	org.olat.core.commons.services.csp.manager.CSPM<|endoftext|>


<fim-prefix>ce 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.data.game.world.block.CommandBlockMode;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockMinecartPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockPacket;
import com.nukkitx.protocol.bedrock.packet.CommandBlockUpdatePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = CommandBlockUpdatePacket.class)
public class BedrockCommandBlockUpdateTranslator extends PacketTranslator<CommandBlockUpdatePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(CommandBlockUpdatePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, CommandBlockUpdatePacket packet) {
        String command = packet.getCommand();
        boolean outputTracked = packet.isOutputTracked();
        if (<fix-suffix>packet.isBlock()) {
            CommandBlockMode mode;
            switch (packet.getMode()) {
                case CHAIN: // The green one
                    mode = CommandBlockMode.SEQUENCE;
                    break;
                case REPEATING: // The purple one
                    mode = CommandBlockMode.AUTO;
                    break;
                default: // NORMAL, the orange one
                    mode = CommandBlockMode.REDSTONE;
                    break;
            }
            boolean isConditional = packet.isConditional();
            boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java
            ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(
                    new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
                    command, mode, outputTracked, isConditional, automatic);
            session.sendDownstreamPacket(commandBlockPacket);
        } else {
            ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket(
                    (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(),
                    command, outputTracked
            );
            session.sendDownstreamPacket(commandMinecartPacket);
        }
    }
}
<|endoftext|>


<fim-prefix>hrows IOException {
            if (DEBUG_BUFFER) {
                fCurrentEntity.debugBufferIfNeeded("(scanPI: ");
            }
            if (fReportErrors) {
                fErrorReporter.reportWarning("HTML1008", null);
            }

            // scan processing instruction
            String target = scanName(true);
            if (target != null && !target.equalsIgnoreCase("xml")) {
                while (true) {
                    int c = fCurrentEntity.read();
                    if (c == '\r' || c == '\n') {
                        if (c == '\r') {
                            c = fCurrentEntity.read();
                            if (c != '\n') {
                                fCurrentEntity.offset--;
                                fCurrentEntity.characterOffset_--;
                            }
                        }
                        fCurrentEntity.incLine();
                        continue;
                    }
                    if (c == -1) {
                        break;
                    }
                    if (c != ' ' && c != '\t') {
                    	fCurrentEntity.rewind();
                        break;
                    }
                }
                fStringBuffer.clear();
                while (true) {
                    int c = fCurrentEntity.read();
                    if (c == '?' || c == '/') {
                        char c0 = (char)c;
                        c = fCurrentEntity.read();
                        // BUG: CWE-400 Uncontrolled Resource Consumption
                        // if (c == '>') {
                        // FIXED:
<fim-middle>                        if (c == '>' || c == -1) {
                            break;
                        }
                        fStringBuffer.append(c0);
                        fCurrentEntity<fix-suffix>.rewind();
                        continue;
                    }
                    else if (c == '\r' || c == '\n') {
                        fStringBuffer.append('\n');
                        if (c == '\r') {
                            c = fCurrentEntity.read();
                            if (c != '\n') {
                                fCurrentEntity.offset--;
                                fCurrentEntity.characterOffset_--;
                            }
                        }
                        fCurrentEntity.incLine();
                        continue;
                    }
                    else if (c == -1) {
                        break;
                    }
                    else {
                        appendChar(fStringBuffer, c);
                    }
                }
                XMLString data = fStringBuffer;
                if (fDocumentHandler != null) {
                    fEndLineNumber = fCurrentEntity.getLineNumber();
                    fEndColumnNumber = fCurrentEntity.getColumnNumber();
                    fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
                    fDocumentHandler.processingInstruction(target, data, locationAugs());
                }
            }

            // scan xml/text declaration
            else {
                int beginLineNumber = fBeginLineNumber;
                int beginColumnNumber = fBeginColumnNumber;
                int beginCharacterOffset = fBeginCharacterOffset;
   <|endoftext|>


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

package org.geysermc.connector.network.translators;

import org.geysermc.connector.network.session.GeyserSession;

public abstract class PacketTranslator<T> {
    // BUG: CWE-287 Improper Authentication
    // public abstract void translate(T packet, GeyserSession session);
    // FIXED:
<fim-middle>    public abstract void translate(GeyserSession session, T packet);

}
<fix-suffix><|endoftext|>


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

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

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

/**
 * Indicates that the client should open a particular advancement tab
 */
@Translator(pa<|endoftext|>


<fim-prefix>ROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

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

import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;
import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.data.inventory.ContainerType;
import com.nukkitx.protocol.bedrock.packet.ContainerOpenPacket;
import com.nukkitx.protocol.bedrock.packet.InteractPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.InteractiveTagManager;

@Translator(packet = InteractPacket.class)
public class BedrockInteractTranslator extends PacketTranslator<InteractPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(InteractPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, InteractPacket packet) {
        Entity entity;
        if (packet.getRuntimeEntityId() == session.getPlayerEntity().getGeyserId()) {
            //Pla<fix-suffix>yer is not in entity cache
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId());
        }
        if (entity == null)
            return;

        switch (packet.getAction()) {
            case INTERACT:
                if (session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
                    break;
                }
                ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),
                        InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking());
                session.sendDownstreamPacket(interactPacket);
                break;
            case DAMAGE:
                ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),
                        InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking());
                session.sendDownstreamPacket(attackPacket);
                break;
            case LEAVE_VEHICLE:
                ClientPlayerStatePacket sneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SNEAKING);
                session.sendDownstreamPacket(sneakPacket);
                session.setRidingVehicleEntity(null);
                break;
            case MOUSEOVER:
                // Handle the butt<|endoftext|>


<fim-prefix>mpliance 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.admin.landingpages;

import java.util.ArrayList;

import org.olat.admin.landingpages.model.Rule;
import org.olat.admin.landingpages.model.Rules;
import org.olat.core.configuration.AbstractSpringModule;
import org.olat.core.util.StringHelper;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.core.util.xml.XStreamHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;

/**
 *
 * Initial date: 15.05.2014

 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
@Service("landingPagesModule")
public class LandingPagesModule extends AbstractSpringModule {
	private static final String CONFIG_RULES = "rules";
	private static final XStream rulesXStream;
	static {
		rulesXStream = XStreamHelper.createXStreamInstance();
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		//
		// FIXED:
<fim-middle>		XStreamHelper.allowDefaultPackage(rulesXStream);
		rulesXStream.alias("rules", Rules.class);
		rulesXStream.alias("rule", Rule.class);
	}

	private Rules rules;

	@Autowired
	public LandingPagesMo<fix-suffix>dule(CoordinatorManager coordinatorManager) {
		super(coordinatorManager);
	}

	@Override
	public void init() {
		String rulesObj = getStringPropertyValue(CONFIG_RULES, true);
		if(StringHelper.containsNonWhitespace(rulesObj)) {
			rules = (Rules)rulesXStream.fromXML(rulesObj);
		} else {
			rules = new Rules();
			rules.setRules(new ArrayList<>(1));
		}
	}

	@Override
	protected void initDefaultProperties() {
		//
	}

	@Override
	protected void initFromChangedProperties() {
		init();
	}

	public Rules getRules() {
		return rules;
	}

	public void setRules(Rules rules) {
		String value = rulesXStream.toXML(rules);
		setStringProperty(CONFIG_RULES, value, true);
	}
}
<|endoftext|>


<fim-prefix>Source;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Implementation of the TicketValidator that will validate Service Tickets in compliance with the CAS 2.
 *
 * @author Scott Battaglia
 * @since 3.1
 */
public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTicketValidator {

    /** The CAS 2.0 protocol proxy callback url. */
    private String proxyCallbackUrl;

    /** The storage location of the proxy granting tickets. */
    private ProxyGrantingTicketStorage proxyGrantingTicketStorage;

    /** Implementation of the proxy retriever. */
    private ProxyRetriever proxyRetriever;

    /**
     * Constructs an instance of the CAS 2.0 Service Ticket Validator with the supplied
     * CAS server url prefix.
     *
     * @param casServerUrlPrefix the CAS Server URL prefix.
     * @param urlFactory URL connection factory to use when communicating with the server
     */
    public Cas20ServiceTicketValidator(final String casServerUrlPrefix) {
        super(casServerUrlPrefix);
        this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory());
    }

    /**
     * Adds the pgtUrl to the list of parameters to pass to the CAS server.
     *
     * @param urlParameters the Map containing the existing parameters to send to the server.
     */
    protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) {
        // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
        // urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl));
        // FIXED:
<fim-middle>        urlParameters.put("pgtUrl", this.proxyCallbackUrl);
    }

    protected String getUrlSuffix() {
        return "serviceValidate";
    }

    protected final Assertion parseResponseFromServer(<fix-suffix>final String response) throws TicketValidationException {
        final String error = XmlUtils.getTextForElement(response, "authenticationFailure");

        if (CommonUtils.isNotBlank(error)) {
            throw new TicketValidationException(error);
        }

        final String principal = XmlUtils.getTextForElement(response, "user");
        final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, "proxyGrantingTicket");

        final String proxyGrantingTicket;
        if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) {
            proxyGrantingTicket = null;
        } else {
            proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou);
        }

        if (CommonUtils.isEmpty(principal)) {
            throw new TicketValidationException("No principal was found in the response from the CAS server.");
        }

        final Assertion assertion;
        final Map<String, Object> attributes = extractCustomAttributes(response);
        if (CommonUtils.isNotBlank(proxyGrantingTicket)) {
            final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes,
                    proxyGrantingTicket, this.proxyRetriever);
            assertion = new AssertionImpl(attributePrincipal);
        } else {
            assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes));
        }

        customParseResponse(response,<|endoftext|>


<fim-prefix>t();
            final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase();
            if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) {
                continue;
            }

            // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE
            if (aName.equals(HttpHeaderNames.TE)) {
                toHttp2HeadersFilterTE(entry, out);
                continue;
            }

            // Cookies must be concatenated into a single octet string.
            // https://tools.ietf.org/html/rfc7540#section-8.1.2.5
            final CharSequence value = entry.getValue();
            if (aName.equals(HttpHeaderNames.COOKIE)) {
                if (cookieJoiner == null) {
                    cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
                }
                COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
            } else {
                out.add(aName, convertHeaderValue(aName, value));
            }
        }

        if (cookieJoiner != null && cookieJoiner.length() != 0) {
            out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
        }
    }

    private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
                                                  int arraySizeHint) {
        final CharSequenceMap result = new CharSequenceMap(arraySizeHint);

        while (valuesIter.hasNext()) {
            // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
            // final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();
            // FIXED:
<fim-middle>            final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();
            try {
                int index = lowerCased.forEachByte(FIND_COMMA);
                if (index <fix-suffix>!= -1) {
                    int start = 0;
                    do {
                        result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
                        start = index + 1;
                    } while (start < lowerCased.length() &&
                             (index = lowerCased.forEachByte(start,
                                                             lowerCased.length() - start, FIND_COMMA)) != -1);
                    result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
                } else {
                    result.add(lowerCased.trim(), EMPTY_STRING);
                }
            } catch (Exception e) {
                // This is not expect to happen because FIND_COMMA never throws but must be caught
                // because of the ByteProcessor interface.
                throw new IllegalStateException(e);
            }
        }
        return result;
    }

    /**
     * Filter the {@link HttpHeaderNames#TE} header according to the
     * special rules in the HTTP/2 RFC.
     * @param entry An entry whose name is {@link HttpHeaderNames#TE}.
     * @param out the resulting HTTP/2 headers.
     */
    private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry,
                                               HttpHeadersBuilder out) {
        if (AsciiString.indexOf(entry.getValue(), ',', 0<|endoftext|>


<fim-prefix>MaterialConfig hgMaterialConfig = hg("http://example.com", null);
            hgMaterialConfig.setUserName("bob");
            hgMaterialConfig.setPassword("badger");

            hgMaterialConfig.validate(new ConfigSaveValidationContext(null));

            assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull();
        }

        @Test
        void shouldEnsureBranchIsNotProvidedInBothUrlAsWellAsAttributes() {
            HgMaterialConfig hgMaterialConfig = hg("http://bob:pass@example.com#some-branch", null);
            hgMaterialConfig.setBranchAttribute("branch-in-attribute");

            hgMaterialConfig.validate(new ConfigSaveValidationContext(null));

            assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous branch, must be provided either in URL or as an attribute.");
        }

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

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

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

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

            materialConfig.validateTree(validationContext);

            verify(materialConfig).validate(validationContext);
        }

        @Test
        void shouldFailIfEncryptedPasswordIsIncorrect() {
            HgMaterialConfig hgMaterialConfig = hg("http://example.com", null);
            hgMaterialConfig.setEncryptedPassword("encryptedPassword");

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

            assertThat(validationResult).isFalse();
            assertThat(hgMaterialConfig.errors().on("encryptedPassword"))
                    .isEqualTo("Encrypted password value for HgMaterial with url 'http://example.com' is invalid. This usually happens when the cipher text is modified to have an invalid value.");
        }
    }

    private ValidationContext mockValidationContextForSecretParams(SecretConfig... secretConfigs) {
        final ValidationContext validationContext = mock(ValidationContext.class);
        final CruiseConfig cruiseConfig = mock(CruiseConfig.class);
        when(validationContext.getCruiseConfig()).thenReturn(cr<|endoftext|>


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

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

import com.github.steveice10.mc.protocol.packet.ingame.client.ClientKeepAlivePacket;
import com.nukkitx.protocol.bedrock.data.AttributeData;
import com.nukkitx.protocol.bedrock.packet.NetworkStackLatencyPacket;
import com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket;
import org.geysermc.connector.entity.attribute.GeyserAttributeType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.floodgate.util.DeviceOs;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * Used to send the forwarded keep alive packet back to the server
 */
@Translator(packet = NetworkStackLatencyPacket.class)
public class BedrockNetworkStackLatencyTranslator extends PacketTranslator<NetworkStackLatencyPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(NetworkStackLatencyPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, NetworkStackLatencyPacket packet) {
        long pingId;
        // so apparently, as of 1.16.200
        // PS4 divides the network stack latency time<fix-suffix>stamp FOR US!!!
        // WTF
        if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) {
            pingId = packet.getTimestamp();
        } else {
            pingId = packet.getTimestamp() / 1000;
        }

        // negative timestamps are used as hack to fix the url image loading bug
        if (packet.getTimestamp() > 0) {
            if (session.getConnector().getConfig().isForwardPlayerPing()) {
                ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId);
                session.sendDownstreamPacket(keepAlivePacket);
            }
            return;
        }

        // Hack to fix the url image loading bug
        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());

        AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL);
        if (attribute != null) {
            attributesPacket.setAttributes(Collections.singletonList(attribute));
        } else {
            attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0)));
        }

        session.getConnector().getGeneralThreadPool().schedule(
                () -> session.sendUpstreamPacket(attributesPacket),
                500, TimeUnit.MILLISECONDS);
    }
}
<|endoftext|>


<fim-prefix>ent resource : viewRoot.getComponentResources(context)) {
            String name = (String) resource.getAttributes().get("name");
            String library = (String) resource.getAttributes().get("library");

            if (resource.getChildCount() == 0
              && resourceHandler.getRendererTypeForResourceName(name) != null
              && !resourceHandler.isResourceRendered(context, name, library))
            {
                if (!updateStarted) {
                    writer.startUpdate("javax.faces.Resource");
                    updateStarted = true;
                }

                resource.encodeAll(context);
            }
        }

        if (updateStarted) {
            writer.endUpdate();
        }
    }

    private void renderState(FacesContext context) throws IOException {
        // Get the view state and write it to the response..
        PartialViewContext pvc = context.getPartialViewContext();
        PartialResponseWriter writer = pvc.getPartialResponseWriter();
        String viewStateId = Util.getViewStateId(context);

        writer.startUpdate(viewStateId);
        String state = context.getApplication().getStateManager().getViewState(context);
        writer.write(state);
        writer.endUpdate();

        ClientWindow window = context.getExternalContext().getClientWindow();
        if (null != window) {
            String clientWindowId = Util.getClientWindowId(context);
            writer.startUpdate(clientWindowId);
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // writer.write(window.getId());
            // FIXED:  <fim-middle>
            writer.writeText(window.getId(), null);
            writer.endUpdate();
        }
    }

	private void renderEvalScripts(FacesContext context) throws IOException {
		PartialViewConte<fix-suffix>xt pvc = context.getPartialViewContext();
		PartialResponseWriter writer = pvc.getPartialResponseWriter();

		for (String evalScript : pvc.getEvalScripts()) {
			writer.startEval();
			writer.write(evalScript);
			writer.endEval();
		}
	}

    private PartialResponseWriter createPartialResponseWriter() {

        ExternalContext extContext = ctx.getExternalContext();
        String encoding = extContext.getRequestCharacterEncoding();
        extContext.setResponseCharacterEncoding(encoding);
        ResponseWriter responseWriter = null;
        Writer out = null;
        try {
            out = extContext.getResponseOutputWriter();
        } catch (IOException ioe) {
            if (LOGGER.isLoggable(Level.SEVERE)) {
                LOGGER.log(Level.SEVERE,
                           ioe.toString(),
                           ioe);
            }
        }

        if (out != null) {
            UIViewRoot viewRoot = ctx.getViewRoot();
            if (viewRoot != null) {
                responseWriter =
                    ctx.getRenderKit().createResponseWriter(out,
                    RIConstants.TEXT_XML_CONTENT_TYPE, encoding);
            } else {
                RenderKitFactory factory = (RenderKitFactory)
                    FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
                RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT);
                responseWriter = renderKit.createResponseWriter(out, RIConstants.TE<|endoftext|>


<fim-prefix><fim-middle>the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the <fix-suffix>GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package com.xpn.xwiki.internal.skin;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.filter.input.InputSource;
import org.xwiki.skin.Resource;
import org.xwiki.skin.Skin;

import static org.apache.commons.lang3.exception.ExceptionUtils.getRootCauseMessage;

/**
 * Common abstract class for the skins that manipulate resources.
 *
 * @version $Id$
 * @since 13.8RC1
 */
public abstract class AbstractResourceSkin extends AbstractSkin
{
    protected static<|endoftext|>


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

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

import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;
import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;
import org.geysermc.connector.entity.BoatEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

/**
 * Sent by the client when moving a horse.
 */
@Translator(packet = MoveEntityAbsolutePacket.class)
public class BedrockMoveEntityAbsoluteTranslator extends PacketTranslator<MoveEntityAbsolutePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, MoveEntityAbsolutePacket packet) {
        session.setLastVehicleMoveTimestamp(System.currentTimeMillis());

        float y = packet.getPosition().get<fix-suffix>Y();
        if (session.getRidingVehicleEntity() instanceof BoatEntity) {
            // Remove the offset to prevents boats from looking like they're floating in water
            y -= EntityType.BOAT.getOffset();
        }
        ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
                packet.getPosition().getX(), y, packet.getPosition().getZ(),
                packet.getRotation().getY() - 90, packet.getRotation().getX()
        );
        session.sendDownstreamPacket(clientVehicleMovePacket);
    }
}
<|endoftext|>


<fim-prefix> int UC_CPU_ARM_1176 = 5;
   public static final int UC_CPU_ARM_11MPCORE = 6;
   public static final int UC_CPU_ARM_CORTEX_M0 = 7;
   public static final int UC_CPU_ARM_CORTEX_M3 = 8;
   public static final int UC_CPU_ARM_CORTEX_M4 = 9;
   public static final int UC_CPU_ARM_CORTEX_M7 = 10;
   public static final int UC_CPU_ARM_CORTEX_M33 = 11;
   public static final int UC_CPU_ARM_CORTEX_R5 = 12;
   public static final int UC_CPU_ARM_CORTEX_R5F = 13;
   public static final int UC_CPU_ARM_CORTEX_A7 = 14;
   public static final int UC_CPU_ARM_CORTEX_A8 = 15;
   public static final int UC_CPU_ARM_CORTEX_A9 = 16;
   public static final int UC_CPU_ARM_CORTEX_A15 = 17;
   public static final int UC_CPU_ARM_TI925T = 18;
   public static final int UC_CPU_ARM_SA1100 = 19;
   public static final int UC_CPU_ARM_SA1110 = 20;
   public static final int UC_CPU_ARM_PXA250 = 21;
   public static final int UC_CPU_ARM_PXA255 = 22;
   public static final int UC_CPU_ARM_PXA260 = 23;
   public static final int UC_CPU_ARM_PXA261 = 24;
   public static final int UC_CPU_ARM_PXA262 = 25;
   public static final int UC_CPU_ARM_PXA270 = 26;
   public static final int UC_CPU_ARM_PXA270A0 = 27;
   public static final int UC_CPU_ARM_PXA270A1 = 28;
   public static final int UC_CPU_ARM_PXA270B0 = 29;
   public static final int UC_CPU_ARM_PXA270B1 = 30;
   public static final int UC_CPU_ARM_PXA270C0 = 31;
   public static final int UC_CPU_ARM_PXA270C5 = 32;
   public static final int UC_CPU_ARM_MAX = 33;
   // BUG: CWE-665 Improper Initialization
   //
   // FIXED:
<fim-middle>   public static final int UC_CPU_ARM_ENDING = 34;

// ARM registers

   public static final int UC_ARM_REG_INVALID = 0;
   public static final int UC_ARM_REG_APSR = 1;
   public static final int UC_A<fix-suffix>RM_REG_APSR_NZCV = 2;
   public static final int UC_ARM_REG_CPSR = 3;
   public static final int UC_ARM_REG_FPEXC = 4;
   public static final int UC_ARM_REG_FPINST = 5;
   public static final int UC_ARM_REG_FPSCR = 6;
   public static final int UC_ARM_REG_FPSCR_NZCV = 7;
   public static final int UC_ARM_REG_FPSID = 8;
   public static final int UC_ARM_REG_ITSTATE = 9;
   public static final int UC_ARM_REG_LR = 10;
   public static final int UC_ARM_REG_PC = 11;
   public static final int UC_ARM_REG_SP = 12;
   public static final int UC_ARM_REG_SPSR = 13;
   public static final int UC_ARM_REG_D0 = 14;
   public static final int UC_ARM_REG_D1 = 15;
   public static final int UC_ARM_REG_D2 = 16;
   public static final int UC_ARM_REG_D3 = 17;
   public static final int UC_ARM_REG_D4 = 18;
   public static final int UC_ARM_REG_D5 = 19;
   public static final int UC_ARM_REG_D6 = 20;
   public static final int UC_ARM_REG_D7 = 21;
   public static final int UC_ARM_REG_D8 = 22;
   public static final int UC_ARM_REG_D9 = 23;
   public static final int UC_ARM_REG_D10 = 24;
   public static final int UC_ARM_REG_D11 = 25;
   public static final int UC_ARM_REG_D12 = 26;
   public static final int UC_ARM_REG_D13 = 27;
   public static final int UC_ARM_REG_D14 = 28;
   public static final int UC_ARM_REG_D15 = 29;
   public static final int UC_ARM_REG_D16 = 30;
   public static final int UC_ARM_REG_D17 = 31;
   public static final int UC_ARM_REG_D18 = 32;
   public static final int UC_ARM_RE<|endoftext|>


<fim-prefix>  LOGGER.debug("Failed to decode HTTP request.", nettyRequest.decoderResult().cause());
      sendError(ctx, HttpResponseStatus.BAD_REQUEST);
      return;
    }

    Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers());

    //Find the content length we will use this as an indicator of a body
    Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L);
    String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING);

    //If there is a content length or transfer encoding that indicates there is a body
    boolean hasBody = (contentLength > 0) || (transferEncoding != null);

    RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null;

    Channel channel = ctx.channel();

    if (requestBody != null) {
      channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody);
    }
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();

    ConnectionIdleTimeout connectionIdleTimeout = ConnectionIdleTimeout.of(channel);

    DefaultRequest request = new DefaultRequest(
      clock.instant(),
      requestHeaders,
      nettyRequest.method(),
      nettyRequest.protocolVersion(),
      nettyRequest.uri(),
      remoteAddress,
      socketAddress,
      serverRegistry.get(ServerConfig.class),
      requestBody,
      connectionIdleTimeout,
      channel.attr(CLIENT_CERT_KEY).get()
    );
    // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
    // HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);
    // FIXED:
<fim-middle>    HttpHeaders nettyHeaders = new DefaultHttpHeaders();
    MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
    AtomicBoolean transmitted = new AtomicBoolean(fals<fix-suffix>e);

    DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, clock, nettyRequest, request, nettyHeaders, requestBody);

    ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter);

    Action<Action<Object>> subscribeHandler = thing -> {
      transmitted.set(true);
      ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);
    };

    DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(
      applicationConstants,
      request,
      channel,
      responseTransmitter,
      subscribeHandler
    );

    Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter);
    requestConstants.response = response;

    DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> {
      if (!transmitted.get()) {
        Handler lastHandler = requestConstants.handler;
        StringBuilder description = new StringBuilder();
        description
          .append("No response sent for ")
          .append(request.getMethod().getName())
          .append(" request to ")
          .append(request.getUri());

        if (lastHandler != null) {
          description.append(" (last handler: ");

          if (lastHandler instanceof DescribingHandler) {
            ((DescribingHandler) lastHandler).describeTo(description);
          } else {
            DescribingHandlers.describeTo(lastHandler, des<|endoftext|>


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

@Translator(packet = PacketViolationWarningPacket.class)
public class BedrockPacketViolationWarningTranslator extends PacketTranslator<PacketViolationWarningPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(PacketViolationWarningPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, PacketViolationWarningPacket packet) {
        // Not translated since this is something that the developers need to know
        session.getConnector(<fix-suffix>).getLogger().error("Packet violation warning sent from client! " + packet.toString());
    }
}
<|endoftext|>


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

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

import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;
import com.nukkitx.protocol.bedrock.packet.ContainerClosePacket;
import org.geysermc.connector.inventory.Inventory;
import org.geysermc.connector.inventory.MerchantContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.InventoryUtils;

@Translator(packet = ContainerClosePacket.class)
public class BedrockContainerCloseTranslator extends PacketTranslator<ContainerClosePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ContainerClosePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ContainerClosePacket packet) {
        byte windowId = packet.getId();

        //Client wants close confirmation
        session.sendUpstreamPacket(pa<fix-suffix>cket);
        session.setClosingInventory(false);

        if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) {
            // 1.16.200 - window ID is always -1 sent from Bedrock
            windowId = (byte) session.getOpenInventory().getId();
        }

        Inventory openInventory = session.getOpenInventory();
        if (openInventory != null) {
            if (windowId == openInventory.getId()) {
                ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId);
                session.sendDownstreamPacket(closeWindowPacket);
                InventoryUtils.closeInventory(session, windowId, false);
            } else if (openInventory.isPending()) {
                InventoryUtils.displayInventory(session, openInventory);
                openInventory.setPending(false);
            }
        }
    }
}
<|endoftext|>


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

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

/**
 * A simple servlet that writes out the body of the error
 *
 * @author Rick Knowles
 * @version $Id: ErrorServlet.java,v 1.3 2006/02/28 07:32:47 rickknowles Exp $
 */
public class ErrorServlet extends HttpServlet {

    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {

        Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        if (err != null) {
            err.printStackTrace(pw);
        } else {
            pw.println("(none)");
        }
        pw.flush();

        // If we are here there was no error servlet, so show the default error page
        String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
                // BUG: CWE-79 Improper Neutralization of Input<|endoftext|>


<fim-prefix>/*
 * Copy<fim-middle>right 2012 JBoss 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 a<fix-suffix>t
 *
 *       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.uberfire.security.server;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.uberfire.security.Resource;
import org.uberfire.security.ResourceManager;
import org.uberfire.security.Role;
import org.uberfire.security.impl.RoleImpl;
// BUG: CWE-264 Permissions, Privileges, and Access Controls
// import org.uberfire.security.server.util.AntPathMatcher;
// FIXED:
import org.uberfire.commons.regex.util.AntPathMatcher;
import org.yaml.snakeyaml.Yaml;

import static java.util.Collections.*;
import static org.uberfire.commons.validation.PortablePreconditions.checkNotNull;
import static org.uberfire.commons.validation.Preconditions.*;
import static org.uberfire.security.server.SecurityConstants.*;

public class URLResourceManager implements ResourceManager {

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    private static<|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.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.packet.SetLocalPlayerAsInitializedPacket;
import org.geysermc.connector.entity.player.PlayerEntity;
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.skin.SkinManager;
import <|endoftext|>


<fim-prefix>R 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.ItemStack;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientEditBookPacket;
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import com.github.steveice10.opennbt.tag.builtin.ListTag;
import com.github.steveice10.opennbt.tag.builtin.StringTag;
import com.github.steveice10.opennbt.tag.builtin.Tag;
import com.nukkitx.protocol.bedrock.packet.BookEditPacket;
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 java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@Translator(packet = BookEditPacket.class)
public class BedrockBookEditTranslator extends PacketTranslator<BookEditPacket> {
    private static final int MAXIMUM_PAGE_LENGTH = 8192 * 4;
    private static final int MAXIMUM_TITLE_LENGTH = 128 * 4;

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(BookEditPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, BookEditPacket packet) {
        if (packet.getText() != null && !packet.getText().isEmpty() && packet.getText().getBytes(StandardCharsets.UTF_8).lengt<fix-suffix>h > MAXIMUM_PAGE_LENGTH) {
            session.getConnector().getLogger().warning("Page length greater than server allowed!");
            return;
        }

        GeyserItemStack itemStack = session.getPlayerInventory().getItemInHand();
        if (itemStack != null) {
            CompoundTag tag = itemStack.getNbt() != null ? itemStack.getNbt() : new CompoundTag("");
            ItemStack bookItem = new ItemStack(itemStack.getJavaId(), itemStack.getAmount(), tag);
            List<Tag> pages = tag.contains("pages") ? new LinkedList<>(((ListTag) tag.get("pages")).getValue()) : new LinkedList<>();

            int page = packet.getPageNumber();
            switch (packet.getAction()) {
                case ADD_PAGE: {
                    // Add empty pages in between
                    for (int i = pages.size(); i < page; i++) {
                        pages.add(i, new StringTag("", ""));
                    }
                    pages.add(page, new StringTag("", packet.getText()));
                    break;
                }
                // Called whenever a page is modified
                case REPLACE_PAGE: {
                    if (page < pages.size()) {
                        pages.set(page, new StringTag("", packet.getText()));
                    } else {
                        // Add empty pages in between
                        for (int i = pages.size(); i < page; i++) {
                            pages.add(i, new StringTag("", ""));
                      <|endoftext|>


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

import hudson.model.ModifiableItemGroup;
import hudson.model.TopLevelItem;
import jenkins.model.Jenkins;
import hudson.Extension;
import hudson.model.Item;
import jenkins.model.ModifiableTopLevelItemGroup;
import org.kohsuke.args4j.Argument;

/**
 * Creates a new job by reading stdin as a configuration XML file.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class CreateJobCommand extends CLICommand {
    @Override
    public String getShortDescription() {
        return Messages.CreateJobCommand_ShortDescription();
    <|endoftext|>


<fim-prefix>eContext _cborContext;

    /*
    /**********************************************************
    /* Output buffering
    /**********************************************************
     */

	/**
     * Intermediate buffer in which contents are buffered before being written
     * using {@link #_out}.
     */
    protected byte[] _outputBuffer;

    /**
     * Pointer to the next available byte in {@link #_outputBuffer}
     */
    protected int _outputTail = 0;

    /**
     * Offset to index after the last valid index in {@link #_outputBuffer}.
     * Typically same as length of the buffer.
     */
    protected final int _outputEnd;

    /**
     * Intermediate buffer in which characters of a String are copied before
     * being encoded.
     */
    protected char[] _charBuffer;

    protected final int _charBufferLength;

    /**
     * Let's keep track of how many bytes have been output, may prove useful
     * when debugging. This does <b>not</b> include bytes buffered in the output
     * buffer, just bytes that have been written using underlying stream writer.
     */
    protected int _bytesWritten;

    /*
    /**********************************************************
    /* Tracking of remaining elements to write
    /**********************************************************
     */

    protected int[] _elementCounts = NO_INTS;

    protected int _elementCountsPtr;

    /**
     * Number of elements remaining in the current complex structure (if any),
    // BUG: CWE-770 Allocation of Resources Without Limits or Throttling
    // * when writing defined-length Arrays, Objects; marker {@link #INDEFINITE_LENGTH}
    // FIXED:
<fim-middle>     * when writing defined-length Arrays, Objects; marker {code INDEFINITE_LENGTH}
     * otherwise.
     */
    protected int _currentRemainingElements = INDEFINITE_LENGTH;

    /*
    /************<fix-suffix>**********************************************
    /* Shared String detection
    /**********************************************************
     */

    /**
     * Flag that indicates whether the output buffer is recycable (and needs to
     * be returned to recycler once we are done) or not.
     */
    protected boolean _bufferRecyclable;

    /*
    /**********************************************************
    /* Life-cycle
    /**********************************************************
     */

    public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures,
            ObjectCodec codec, OutputStream out) {
        super(stdFeatures, codec, /* Write Context */ null);
        DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)
                ? DupDetector.rootDetector(this)
                : null;
        // NOTE: we passed `null` for default write context
        _cborContext = CBORWriteContext.createRootContext(dups);
        _formatFeatures = formatFeatures;
        _cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures);
        _ioContext = ctxt;
        _out = out;
        _bufferRecyclable = true;
        _outputBuffer = ctxt.allocWriteEncodingBuffer(BYTE_BUFFER_FOR_OUTPUT);
        _outputEnd = _outputBuffer.length;
        _charBuffer = ctxt.allocConcatBuffer();
        _charBufferLength = _charBuffer.length;
        // let's just sanity check to prevent nasty odd errors
        if (_outputEn<|endoftext|>


<fim-prefix>mpliance 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.
 *
 * 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.units.bigints.UInt256;

public class ShrOperation extends AbstractFixedCostOperation {

  public ShrOperation(final GasCalculator gasCalculator) {
    super(0x1c, "SHR", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());
  }

  @Override
  public Operation.OperationResult executeFixedCostOperation(
      final MessageFrame frame, final EVM evm) {
    Bytes shiftAmount = frame.popStackItem();
    if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
      frame.popStackItem();
      frame.pushStackItem(UInt256.ZERO);
    } else {
      final int shiftAmountInt = shiftAmount.toInt();
      final Bytes value = leftPad(frame.popStackItem());
      // BUG: CWE-681 Incorrect Conversion between Numeric Types
      // if (shiftAmountInt >= 256) {
      // FIXED:
<fim-middle>      if (shiftAmountInt >= 256 || shiftAmountInt < 0) {
        frame.pushStackItem(UInt256.ZERO);
      } else {
        frame.pushStackItem(value.shiftRight(shiftAmountInt));
      }
    }
    retu<fix-suffix>rn successResponse;
  }
}
<|endoftext|>


<fim-prefix> 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.common.PlatformType;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.command.CommandManager;
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.packet.ingame.client.ClientChatPacket;
import com.nukkitx.protocol.bedrock.packet.CommandRequestPacket;
import org.geysermc.connector.network.translators.chat.MessageTranslator;

@Translator(packet = CommandRequestPacket.class)
public class BedrockCommandRequestTranslator extends PacketTranslator<CommandRequestPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(CommandRequestPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, CommandRequestPacket packet) {
        String command = packet.getCommand().replace("/", "");
        CommandManager commandManager = GeyserConnector.g<fix-suffix>etInstance().getCommandManager();
        if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) {
            commandManager.runCommand(session, command);
        } else {
            String message = packet.getCommand().trim();

            if (MessageTranslator.isTooLong(message, session)) {
                return;
            }

            ClientChatPacket chatPacket = new ClientChatPacket(message);
            session.sendDownstreamPacket(chatPacket);
        }
    }
}
<|endoftext|>


<fim-prefix>sponse.JsonRpcResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;

import java.util.List;

import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class NetListeningTest {

  private NetListening method;

  @Mock private P2PNetwork p2PNetwork;

  @Before
  public void before() {
    this.method = new NetListening(p2PNetwork);
  }

  @Test
  public void shouldReturnTrueWhenNetworkIsListening() {
    when(p2PNetwork.isListening()).thenReturn(true);

    final JsonRpcRequestContext request = netListeningRequest();
    final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, true);

    Assertions.assertThat(method.response(request))
        .isEqualToComparingFieldByField(expectedResponse);
  }

  @Test
  public void shouldReturnFalseWhenNetworkIsNotListening() {
    when(p2PNetwork.isListening()).thenReturn(false);

    final JsonRpcRequestContext request = netListeningRequest();
    final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, false);

    Assertions.assertThat(method.response(request))
        .isEqualToComparingFieldByField(expectedResponse);
  }

  @Test
  public void getPermissions() {
    List<String> permissions = method.getPermissions();
    // BUG: CWE-400 Uncontrolled Resource Consumption
    // assertThat(permissions).containsExactlyInAnyOrder("net:*", "net:listening", "*:*");
    // FIXED:
<fim-middle>    assertThat(permissions).containsExactly("*:*", "net:*", "net:listening");
  }

  private JsonRpcRequestContext netListeningRequest() {
    return new JsonRpcRequestContext(new JsonRpcRequest("2.0"<fix-suffix>, "net_listening", new Object[] {}));
  }
}
<|endoftext|>


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

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

import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction;
import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket;
import com.nukkitx.protocol.bedrock.packet.EmotePacket;
import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;
import org.geysermc.connector.entity.Entity;
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.BlockUtils;

@Translator(packet = EmotePacket.class)
public class BedrockEmoteTranslator extends PacketTranslator<EmotePacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(EmotePacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, EmotePacket packet) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {
          <fix-suffix>  // Activate the workaround - we should trigger the offhand now
            ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,
                    BlockFace.DOWN);
            session.sendDownstreamPacket(swapHandsPacket);

            if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
                return;
            }
        }

        long javaId = session.getPlayerEntity().getEntityId();
        for (GeyserSession otherSession : session.getConnector().getPlayers()) {
            if (otherSession != session) {
                if (otherSession.isClosed()) continue;
                if (otherSession.getEventLoop().inEventLoop()) {
                    playEmote(otherSession, javaId, packet.getEmoteId());
                } else {
                    session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));
                }
            }
        }
    }

    private void playEmote(GeyserSession otherSession, long javaId, String emoteId) {
        Entity otherEntity = otherSession.getEntityCache().getEntityByJavaId(javaId); // Must be ran on same thread
        if (otherEntity == null) return;
        EmotePacket otherEmotePacket = new EmotePacket();
        otherEmotePacket.setEmoteId(emoteId);
        otherEmotePacket.setRuntimeEntityId(otherEntity.getGeyserId());
        otherSession.sendUpstreamPacket(otherEmo<|endoftext|>


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

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

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

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

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

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

        DataSource dataSource = null;

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

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

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

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

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

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

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

            first(db, "passwd").map(this::nodeValue).ifPresent(source::setPassword);

            first(db, "pool")
                    .ifPresent(
                            p -> {
                                first(p, "min")
                                        .map(this::nodeValue)
                                        .map(Integer::parseInt)
                                        .ifPresent(source::setMinIdle);
                                first(p, "max")
                                        .map(this::nodeValue)
                            <|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.modules.dcompensation.manager;

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

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

import com.thoughtworks.xstream.XStream;

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

 * @author srosse, stephan<|endoftext|>


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

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

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

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

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

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

				return (protocol.equals("http") || protocol.equals("https"))
						&& !address.isAnyLocalAddress()
						&& !address.isLoopbackAddress()
						// BUG: CWE-918 Server-Side Request Forgery (SSRF)
						//
						// FIXED:
<fim-middle>						&& !address.isLinkLocalAddress()
						&& !host.endsWith(".internal") // Redundant
						&& !host.endsWith(".local") // Redundant
						&& !host.contains("localhost") // Redundant
						&& !host<fix-suffix>Address.startsWith("0.") // 0.0.0.0/8
						&& !hostAddress.startsWith("10.") // 10.0.0.0/8
						&& !hostAddress.startsWith("127.") // 127.0.0.0/8
						&& !hostAddress.startsWith("169.254.") // 169.254.0.0/16
						&& !hostAddress.startsWith("172.16.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.17.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.18.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.19.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.20.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.21.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.22.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.23.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.24.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.25.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.26.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.27.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.28.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.29.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.30.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.31.") // 172.16.0.0/12
						&& !hostAddress.startsWith("192.0.0.") // 192.0.0.0/24
						&& !hostAddress.startsWith("192.168.") // 192.168.0.0/16
						&& !hostAddress.startsWith("198.18.") // 198.18.0.0/15
						&& !hostAddress.startsWith("198.19.") // 198.18.0.0/15
						&& !host.endsWith(".arpa"); // reverse domain (needed?)
			}<|endoftext|>


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

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

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

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

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

    @Override
    public boolean handle(ResourcePackClientResponsePacket packet) {
        switch (packet.getStatus()) {
            case COMPLETED:
                session.connect();
                connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.network.connect", session.getAuthData().getName()));
                break;

            case SEND_PACKS:
                for(String id : packet.getPackIds()) {
                    ResourcePackDataInfoPacket data = new ResourcePackDataInfoPacket();
                    String[] packID = id.split("_");
                    ResourcePack pack = ResourcePack.PACKS.get(packID[0]);
                    ResourcePackManifest.Header header = pack.getManifest().getHeader();

    <|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.commons.services.doceditor.discovery.manager;

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

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

/**
 *
 * Initial date: 1 Mar 2019

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

	private static final XStream xstream = XStreamHelper.createXStreamInstance();
	static {
		Class<?>[] types = new Class[] {
				DiscoveryIm<|endoftext|>