language
stringclasses 3
values | text
stringlengths 543
3.57k
|
---|---|
java | <fim-prefix>tems, used for caching. There is usually few of them (about 15). */
private final Map<String, LocalName> scopes = new HashMap<>();
/**
* The properties to be given the objects to construct. Reused every time {@link
* #createProperties} is invoked.
*/
private final Map<String, Object> properties = new HashMap<>();
/**
* A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}.
* This is used by {@link #createBursaWolfParameters}, which need to create a target datum. The
* target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the
* source datum.
*/
private final Set<String> safetyGuard = new HashSet<>();
public AbstractEpsgFactory(final Hints userHints) throws FactoryException {
super(MAXIMUM_PRIORITY - 20);
// The following hints have no effect on this class behaviour,
// but tell to the user what this factory do about axis order.
hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);
//
// We need to obtain our DataSource
if (userHints != null) {
Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);
if (hint instanceof String) {
String name = (String) hint;
try {
// BUG: CWE-20 Improper Input Validation
// dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);
// FIXED:
<fim-middle> dataSource = (DataSource) GeoTools.jndiLookup(name);
} catch (NamingException e) {
throw new FactoryException("A EPSG_DATA_SOURCE hint is requir<fix-suffix>ed:" + e);
}
hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
} else if (hint instanceof DataSource) {
dataSource = (DataSource) hint;
hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
} else {
throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
}
} else {
throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
}
}
public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) {
super(MAXIMUM_PRIORITY - 20);
this.dataSource = dataSource;
// The following hints have no effect on this class behaviour,
// but tell to the user what this factory do about axis order.
hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);
hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
}
/**
* Constructs an authority factory using the specified connection.
*
* @param userHints The underlying factories used for objects creation.
* @param connection The connection to the underlying EPSG database.
*/
public AbstractEpsgFactory(final Hints userHints, final Connection connection) {
super(MAXIMUM_PRIORITY - 20, userHints);
// The following hints have no effect <|endoftext|> |
java | <fim-prefix>/*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.UUID;
import static io.netty.util.CharsetUtil.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* {@link AbstractDiskHttpData} test cases
*/
public class AbstractDiskHttpDataTest {
@Test
public void testGetChunk() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
// BUG: CWE-378 Creation of Temporary File With Insecure Permissions
// File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
// FIXED:
<fim-middle> File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmp<fix-suffix>File);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf1 = test.getChunk(1024);
assertEquals(buf1.readerIndex(), 0);
assertEquals(buf1.writerIndex(), 1024);
ByteBuf buf2 = test.getChunk(1024);
assertEquals(buf2.readerIndex(), 0);
assertEquals(buf2.writerIndex(), 1024);
assertFalse("Arrays should not be equal",
Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
} finally {
test.delete();
}
}
private static final class TestHttpData extends AbstractDiskHttpData {
private TestHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
@Override
protected String getDiskFilename() {
return null;
}
@Override
protected String getPrefix() {
return null;
}
@Override
protected String getBaseDirectory() {
return null;
}
@Override
protected String getPostfix() {
return null;
}
@Override
protected boolean deleteOnExit() {
return false;
}
<|endoftext|> |
java | <fim-prefix><fim-middle>right 2013-2022 Erudika. https://erudika.com
*
* 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<fix-suffix> 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.
*
* For issues and patches go to: https://github.com/erudika
*/
package com.erudika.scoold.controllers;
import com.cloudinary.Cloudinary;
import com.cloudinary.utils.ObjectUtils;
import com.erudika.para.core.User;
import static com.erudika.para.core.User.Groups.MODS;
import static com.erudika.para.core.User.Groups.USERS;
import com.erudika.para.core.utils.Pager;
import com.erudika.para.core.utils.ParaObjectUtils;
import com.erudika.para.core.utils.Utils;
import com.erudika.scoold.ScooldConfig;
import static com.erudika.scoold.ScooldServer.PEOPLELINK;
import static com.erudika.scoold.ScooldServer.PROFILELINK;
import static com.erudika.scoold.ScooldServer.SIGNINLINK;
import com.erudika.scoold.core.Post;
import com.erudika.scoold.core.Profile;
import com.erudika.scoold.core.Profile.Badge;
import com.erudika.scoold.core.Question;
import com.erudika.scoold.core.Reply;
import com.erudika.scoold.utils.ScooldUtils;
import com.erudika.scoold.utils.avatars.*;
import java.util.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServ<|endoftext|> |
java | <fim-prefix>itionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;
import com.github.steveice10.packetlib.packet.Packet;
import com.nukkitx.math.vector.Vector3d;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.common.ChatColor;
import org.geysermc.connector.entity.player.SessionPlayerEntity;
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;
@Translator(packet = MovePlayerPacket.class)
public class BedrockMovePlayerTranslator extends PacketTranslator<MovePlayerPacket> {
/* The upper and lower bounds to check for the void floor that only exists in Bedrock */
private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y;
private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y;
static {
BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40;
BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2;
}
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(MovePlayerPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, MovePlayerPacket packet) {
SessionPlayerEntity entity = session.getPlayerEntity();
if (!session.isSpawned()) return;
if (!sess<fix-suffix>ion.getUpstream().isInitialized()) {
MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket();
moveEntityBack.setRuntimeEntityId(entity.getGeyserId());
moveEntityBack.setPosition(entity.getPosition());
moveEntityBack.setRotation(entity.getBedrockRotation());
moveEntityBack.setTeleported(true);
moveEntityBack.setOnGround(true);
session.sendUpstreamPacketImmediately(moveEntityBack);
return;
}
session.setLastMovementTimestamp(System.currentTimeMillis());
// Send book update before the player moves
session.getBookEditCache().checkForSend();
session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0));
// head yaw, pitch, head yaw
Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY());
boolean positionChanged = !entity.getPosition().equals(packet.getPosition());
boolean rotationChanged = !entity.getRotation().equals(rotation);
// If only the pitch and yaw changed
// This isn't needed, but it makes the packets closer to vanilla
// It also means you can't "lag back" while only looking, in theory
if (!positionChanged && rotationChanged) {
ClientPlayerRotationPacket playerRotationPacket = new ClientPlayerRotationPacket(
packet.isOnGrou<|endoftext|> |
java | <fim-prefix> org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.item.ItemTranslator;
import org.geysermc.connector.registry.Registries;
import org.geysermc.connector.registry.type.ItemMapping;
import org.geysermc.connector.utils.InventoryUtils;
import java.util.*;
import java.util.stream.Collectors;
import static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID;
/**
* Used to send all valid recipes from Java to Bedrock.
*
* Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything.
*/
@Translator(packet = ServerDeclareRecipesPacket.class)
public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclareRecipesPacket> {
/**
* Required to use the specified cartography table recipes
*/
private static final List<CraftingData> CARTOGRAPHY_RECIPES = Arrays.asList(
CraftingData.fromMulti(UUID.fromString("8b36268c-1829-483c-a0f1-993b7156a8f2"), ++LAST_RECIPE_NET_ID), // Map extending
CraftingData.fromMulti(UUID.fromString("442d85ed-8272-4543-a6f1-418f90ded05d"), ++LAST_RECIPE_NET_ID), // Map cloning
CraftingData.fromMulti(UUID.fromString("98c84b38-1085-46bd-b1ce-dd38c159e6cc"), ++LAST_RECIPE_NET_ID), // Map upgrading
CraftingData.fromMulti(UUID.fromString("602234e4-cac1-4353-8bb7-b1ebff70024b"), ++LAST_RECIPE_NET_ID) // Map locking
);
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) {
Map<RecipeType, List<CraftingData>> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream(<fix-suffix>).getProtocolVersion());
// Get the last known network ID (first used for the pregenerated recipes) and increment from there.
int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1;
Int2ObjectMap<Recipe> recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion()));
Int2ObjectMap<List<StoneCuttingRecipeData>> unsortedStonecutterData = new Int2ObjectOpenHashMap<>();
CraftingDataPacket craftingDataPacket = new CraftingDataPacket();
craftingDataPacket.setCleanRecipes(true);
for (Recipe recipe : packet.getRecipes()) {
switch (recipe.getType()) {
case CRAFTING_SHAPELESS: {
ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData();
ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult());
// Strip NBT - tools won't appear in the recipe book otherwise
output = output.toBuilder().tag(null).build();
ItemData[][] inputCombinations = combinations(session, shapelessRecipeData.getIngredients());
for (ItemData[] inputs : inputCombinations) {
UUID uuid = UUID.randomUUID();
craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(),
Arrays.asList(inputs), Collections.singletonList(<|endoftext|> |
java | <fim-prefix>onvert.ConversionContext;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.core.reflect.GenericTypeUtils;
import io.micronaut.core.type.Argument;
import io.micronaut.core.value.ValueResolver;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
/**
* An interface for classes that represent a map-like structure of values that can be converted.
*
* @param <V> The generic value
* @author Graeme Rocher
* @since 1.0
*/
public interface ConvertibleValues<V> extends ValueResolver<CharSequence>, Iterable<Map.Entry<String, V>> {
ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap());
/**
* @return The names of the values
*/
Set<String> names();
/**
* @return The values
*/
Collection<V> values();
/**
* @return Whether this values is empty
*/
default boolean isEmpty() {
return this == ConvertibleValues.EMPTY || names().isEmpty();
}
/**
* @return The concrete type of the value
*/
@SuppressWarnings("unchecked")
default Class<V> getValueType() {
Optional<Class> type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class);
return type.orElse(Object.class);
}
/**
* Whether the given key is contained within these values.
*
* @param name The key name
* @return True if it is
*/
default boolean contains(String name) {
// BUG: CWE-400 Uncontrolled Resource Consumption
// return get(name, Object.class).isPresent();
// FIXED:
<fim-middle> return get(name, Argument.OBJECT_ARGUMENT).isPresent();
}
/**
* Performs the given action for each value. Note that in the case
* where multiple values exist for the same he<fix-suffix>ader then the consumer will be invoked
* multiple times for the same key.
*
* @param action The action to be performed for each entry
* @throws NullPointerException if the specified action is null
* @since 1.0
*/
default void forEach(BiConsumer<String, V> action) {
Objects.requireNonNull(action, "Consumer cannot be null");
Collection<String> headerNames = names();
for (String headerName : headerNames) {
Optional<V> vOptional = this.get(headerName, getValueType());
vOptional.ifPresent(v -> action.accept(headerName, v));
}
}
/**
* Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance.
*
* @return The values
*/
default Map<String, V> asMap() {
Map<String, V> newMap = new LinkedHashMap<>();
for (Map.Entry<String, V> entry : this) {
String key = entry.getKey();
newMap.put(key, entry.getValue());
}
return newMap;
}
/**
* Return this {@link ConvertibleValues} as a map for the given key type and value type. If any entry cannot be
* converted to the target key/value type then the entry is simply excluded, hence the size of the map returned
* may not match the size of this {@link ConvertibleValues}.
*
* @param keyType The key type
* @param valueType The value type
* @param <|endoftext|> |
java | <fim-prefix>CE);
//}
return spaces;
}
public void setSpaces(Set<String> spaces) {
this.spaces = spaces;
}
@JsonIgnore
public Set<String> getAllSpaces() {
return getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet());
}
public Long getLastseen() {
return lastseen;
}
public void setLastseen(Long val) {
this.lastseen = val;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Long getComments() {
return comments;
}
public void setComments(Long comments) {
this.comments = comments;
}
public Long getDownvotes() {
return downvotes;
}
public void setDownvotes(Long downvotes) {
this.downvotes = downvotes;
}
public Long getUpvotes() {
return upvotes;
}
public void setUpvotes(Long upvotes) {
this.upvotes = upvotes;
}
public String getBadges() {
return badges;
}
public void setBadges(String badges) {
this.badges = badges;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAboutme() {
return this.aboutme;
}
public void setAboutme(String aboutme) {
this.aboutme = aboutme;
}
public String getOriginalName() {
return originalName;
}
public void setOriginalName(String originalName) {
// BUG: NVD-CWE-Other Other
// this.originalName = originalName;
// FIXED:
<fim-middle> this.originalName = StringUtils.abbreviate(originalName, 256);
}
public String getOriginalPicture() {
return originalPicture;
}
public void setOriginalPicture(String originalPicture) {
thi<fix-suffix>s.originalPicture = originalPicture;
}
@SuppressWarnings("unchecked")
public List<Question> getAllQuestions(Pager pager) {
if (getId() == null) {
return new ArrayList<Question>();
}
return (List<Question>) getPostsForUser(Utils.type(Question.class), pager);
}
@SuppressWarnings("unchecked")
public List<Reply> getAllAnswers(Pager pager) {
if (getId() == null) {
return new ArrayList<Reply>();
}
return (List<Reply>) getPostsForUser(Utils.type(Reply.class), pager);
}
@SuppressWarnings("unchecked")
public List<Question> getAllUnapprovedQuestions(Pager pager) {
if (getId() == null) {
return new ArrayList<Question>();
}
return (List<Question>) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager);
}
@SuppressWarnings("unchecked")
public List<Reply> getAllUnapprovedAnswers(Pager pager) {
if (getId() == null) {
return new ArrayList<Reply>();
}
return (List<Reply>) getPostsForUser(Utils.type(UnapprovedReply.class), pager);
}
private List<? extends Post> getPostsForUser(String type, Pager pager) {
pager.setSortby("votes");
return client().findTerms(type, Collections.singletonMap(Config._CREATORID, getId()), true, pager);
}
public String getFavtagsString() {
if (getFavtags().isEmpty()) {
return "";
}
return StringUtils.join(getFavtags(), ", ");
}
public boolean hasFavtags() {
return !getFavtags().isEmpty();
}
public boolean hasSpaces() {
return !(getSpaces().size() <= 1 && getSpaces().contains(Post.DEF<|endoftext|> |
java | <fim-prefix><fim-middle>right 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the <fix-suffix>License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cd.go.framework.ldap;
import cd.go.authentication.ldap.LdapClient;
import cd.go.authentication.ldap.exception.LdapException;
import cd.go.authentication.ldap.exception.MultipleUserDetectedException;
import cd.go.authentication.ldap.mapper.Mapper;
import cd.go.authentication.ldap.mapper.ResultWrapper;
import cd.go.authentication.ldap.model.LdapConfiguration;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import static cd.go.authentication.ldap.LdapPlugin.LOG;
import static cd.go.authentication.ldap.utils.Util.isNotBlank;
import static java.text.MessageFormat.format;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;
public class JNDILdapClient implements LdapClient {
private LdapConfiguration ldapConfiguration;
private final int MAX_AUTHENTICATION_RESULT = 1;
public JNDILdapClient(LdapConfiguration ldapConfiguration) {
this.ldapConfiguration = ldapConfiguration<|endoftext|> |
java | <fim-prefix><fim-middle>right 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this<fix-suffix> file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.protocol.saml;
import org.keycloak.services.util.CertificateInfoHelper;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface SamlConfigAttributes {
String SAML_SIGNING_PRIVATE_KEY = "saml.signing.private.key";
String SAML_CANONICALIZATION_METHOD_ATTRIBUTE = "saml_signature_canonicalization_method";
String SAML_SIGNATURE_ALGORITHM = "saml.signature.algorithm";
String SAML_NAME_ID_FORMAT_ATTRIBUTE = "saml_name_id_format";
String SAML_AUTHNSTATEMENT = "saml.authnstatement";
String SAML_ONETIMEUSE_CONDITION = "saml.onetimeuse.condition";
String SAML_FORCE_NAME_ID_FORMAT_ATTRIBUTE = "saml_force_name_id_format";
String SAML_ARTIFACT_BINDING = "saml.artifact.binding";
String SAML_SERVER_SIGNATURE = "saml.server.signature";
String SAML_SERVER_SIGNATURE_KEYINFO_EXT = "saml.server.signature.keyinfo.ext";
String SAML_SERVER_SIGNATURE_KEYINFO_KEY_NAME_TRANSFORMER = "saml.server.signature.keyinfo.xmlSig<|endoftext|> |
java | <fim-prefix> offset += read;
if (len <= 0 || offset >= buf.length) {
break;
}
}
return buf;
} finally {
fis.close();
}
}
@Test
public void testDelete() throws Exception {
String json = "{\"foo\":\"bar\"}";
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
File tmpFile = null;
DiskFileUpload f1 = new DiskFileUpload("file4", "file4", "application/json", null, null, 0);
try {
assertNull(f1.getFile());
f1.setContent(Unpooled.wrappedBuffer(bytes));
assertNotNull(tmpFile = f1.getFile());
} finally {
f1.delete();
assertNull(f1.getFile());
assertNotNull(tmpFile);
assertFalse(tmpFile.exists());
}
}
@Test
public void setSetContentFromFileExceptionally() throws Exception {
final long maxSize = 4;
DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0);
f1.setMaxSize(maxSize);
try {
f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));
File originalFile = f1.getFile();
assertNotNull(originalFile);
assertEquals(maxSize, originalFile.length());
assertEquals(maxSize, f1.length());
byte[] bytes = new byte[8];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
// BUG: CWE-378 Creation of Temporary File With Insecure Permissions
// File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
// FIXED:
<fim-middle> File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmp<fix-suffix>File);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
try {
f1.setContent(tmpFile);
fail("should not reach here!");
} catch (IOException e) {
assertNotNull(f1.getFile());
assertEquals(originalFile, f1.getFile());
assertEquals(maxSize, f1.length());
}
} finally {
f1.delete();
}
}
}
<|endoftext|> |
java | <fim-prefix>istribute, 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.ClientboundMapItemDataPacket;
import com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import java.util.concurrent.TimeUnit;
@Translator(packet = MapInfoRequestPacket.class)
public class BedrockMapInfoRequestTranslator extends PacketTranslator<MapInfoRequestPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(MapInfoRequestPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, MapInfoRequestPacket packet) {
long mapId = packet.getUniqueMapId();
ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().<fix-suffix>remove(mapId);
if (mapPacket != null) {
// Delay the packet 100ms to prevent the client from ignoring the packet
GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),
100, TimeUnit.MILLISECONDS);
}
}
}
<|endoftext|> |
java | <fim-prefix>s
* 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 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.TextPacket;
import org.geysermc.connector.network.translators.chat.MessageTranslator;
@Translator(packet = TextPacket.class)
public class BedrockTextTranslator extends PacketTranslator<TextPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(TextPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, TextPacket packet) {
String message = packet.getMessage();
if (MessageTranslator.isTooLong(message, session)) {
return;
<fix-suffix> }
ClientChatPacket chatPacket = new ClientChatPacket(message);
session.sendDownstreamPacket(chatPacket);
}
}
<|endoftext|> |
java | <fim-prefix>port io.micronaut.http.hateoas.JsonError;
import io.micronaut.http.hateoas.VndError;
import java.util.Optional;
/**
* Strategy interface for decoding the error from a server respponse.
*
* @author graemerocher
* @since 1.0
*/
@Internal
public interface HttpClientErrorDecoder {
/**
* The default implementation.
*/
HttpClientErrorDecoder DEFAULT = new HttpClientErrorDecoder() { };
/**
* Default message decoder.
*
* @param error The error object
* @return The message
*/
default Optional<String> getMessage(Object error) {
if (error == null) {
return Optional.empty();
}
if (error instanceof JsonError) {
return Optional.ofNullable(((JsonError) error).getMessage());
} else {
if (error instanceof Described) {
return Optional.ofNullable(((Described) error).getDescription());
} else {
return Optional.of(error.toString());
}
}
}
/**
* Gets the error type for the given media type.
*
* @param mediaType The media type
* @return The error type
*/
default Argument<?> getErrorType(MediaType mediaType) {
if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
return Argument.of(JsonError.class);
} else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {
return Argument.of(VndError.class);
} else {
// BUG: CWE-400 Uncontrolled Resource Consumption
// return Argument.of(String.class);
// FIXED:
<fim-middle> return Argument.STRING;
}
}
}
<fix-suffix><|endoftext|> |
java | <fim-prefix><fim-middle>href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in<fix-suffix> compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.services.vfs.manager;
import java.io.File;
import java.io.InputStream;
import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.IdentityImpl;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.services.license.LicenseService;
import org.olat.core.commons.services.license.LicenseType;
import org.olat.core.commons.services.license.model.LicenseTypeImpl;
import org.olat.core.commons.services.vfs.VFSMetadata;
import org.olat.core.commons.services.vfs.VFSRevision;
import org.olat.core.commons.services.vfs.model.VFSMetadataImpl;
import org.olat.core.id.Identity;
import org.olat.core.util.StringHelper;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.version.RevisionFileImpl;
import org.olat.core.util.vfs.version.VersionsFileImpl;
import org.olat.core.util.xml.XStreamHelper;
import com.thoughtwork<|endoftext|> |
java | <fim-prefix> final int UC_CPU_S390X_Z890_2 = 9;
public static final int UC_CPU_S390X_Z990_5 = 10;
public static final int UC_CPU_S390X_Z890_3 = 11;
public static final int UC_CPU_S390X_Z9EC = 12;
public static final int UC_CPU_S390X_Z9EC_2 = 13;
public static final int UC_CPU_S390X_Z9BC = 14;
public static final int UC_CPU_S390X_Z9EC_3 = 15;
public static final int UC_CPU_S390X_Z9BC_2 = 16;
public static final int UC_CPU_S390X_Z10EC = 17;
public static final int UC_CPU_S390X_Z10EC_2 = 18;
public static final int UC_CPU_S390X_Z10BC = 19;
public static final int UC_CPU_S390X_Z10EC_3 = 20;
public static final int UC_CPU_S390X_Z10BC_2 = 21;
public static final int UC_CPU_S390X_Z196 = 22;
public static final int UC_CPU_S390X_Z196_2 = 23;
public static final int UC_CPU_S390X_Z114 = 24;
public static final int UC_CPU_S390X_ZEC12 = 25;
public static final int UC_CPU_S390X_ZEC12_2 = 26;
public static final int UC_CPU_S390X_ZBC12 = 27;
public static final int UC_CPU_S390X_Z13 = 28;
public static final int UC_CPU_S390X_Z13_2 = 29;
public static final int UC_CPU_S390X_Z13S = 30;
public static final int UC_CPU_S390X_Z14 = 31;
public static final int UC_CPU_S390X_Z14_2 = 32;
public static final int UC_CPU_S390X_Z14ZR1 = 33;
public static final int UC_CPU_S390X_GEN15A = 34;
public static final int UC_CPU_S390X_GEN15B = 35;
public static final int UC_CPU_S390X_QEMU = 36;
public static final int UC_CPU_S390X_MAX = 37;
// BUG: CWE-665 Improper Initialization
//
// FIXED:
<fim-middle> public static final int UC_CPU_S390X_ENDING = 38;
// S390X registers
public static final int UC_S390X_REG_INVALID = 0;
// General purpose registers
public static final int UC_S390X_REG_R0 <fix-suffix>= 1;
public static final int UC_S390X_REG_R1 = 2;
public static final int UC_S390X_REG_R2 = 3;
public static final int UC_S390X_REG_R3 = 4;
public static final int UC_S390X_REG_R4 = 5;
public static final int UC_S390X_REG_R5 = 6;
public static final int UC_S390X_REG_R6 = 7;
public static final int UC_S390X_REG_R7 = 8;
public static final int UC_S390X_REG_R8 = 9;
public static final int UC_S390X_REG_R9 = 10;
public static final int UC_S390X_REG_R10 = 11;
public static final int UC_S390X_REG_R11 = 12;
public static final int UC_S390X_REG_R12 = 13;
public static final int UC_S390X_REG_R13 = 14;
public static final int UC_S390X_REG_R14 = 15;
public static final int UC_S390X_REG_R15 = 16;
// Floating point registers
public static final int UC_S390X_REG_F0 = 17;
public static final int UC_S390X_REG_F1 = 18;
public static final int UC_S390X_REG_F2 = 19;
public static final int UC_S390X_REG_F3 = 20;
public static final int UC_S390X_REG_F4 = 21;
public static final int UC_S390X_REG_F5 = 22;
public static final int UC_S390X_REG_F6 = 23;
public static final int UC_S390X_REG_F7 = 24;
public static final int UC_S390X_REG_F8 = 25;
public static final int UC_S390X_REG_F9 = 26;
public static final int UC_S390X_REG_F10 = 27;
public static final int UC_S390X_REG_F11 = 28;
public static final int UC_S390X_REG_F12 = 29;
public static final int UC_S390X_REG_F13 = 30;
public static final int UC_S390X_REG_F14<|endoftext|> |
java | <fim-prefix>port net.sourceforge.plantuml.security.authentication.SecurityCredentials;
/**
* Secure replacement for java.net.URL.
* <p>
* This class should be used instead of java.net.URL.
* <p>
* This class does some control access and manages access-tokens via URL. If a
* URL contains a access-token, similar to a user prefix, SURL loads the
* authorization config for this user-token and passes the credentials to the
* host.
* <p>
* Example:<br/>
*
* <pre>
* SURL url = SURL.create ("https://jenkins-access@jenkins.mycompany.com/api/json")
* </pre>
*
* The {@code jenkins-access} will checked against the Security context access
* token configuration. If a configuration exists for this token name, the token
* will be removed from the URL and the credentials will be added to the
* headers. If the token is not found, the URL remains as it is and no separate
* authentication will be performed.
* <p>
* TODO: Some methods should be moved to a HttpClient implementation, because
* SURL is not the valid class to manage it. <br/>
* TODO: BAD_HOSTS implementation should be reviewed and moved to HttpClient
* implementation with a circuit-breaker. <br/>
* TODO: Token expiration with refresh should be implemented in future. <br/>
*/
public class SURL {
/**
* Indicates, that we have no authentication to access the URL.
*/
public static final String WITHOUT_AUTHENTICATION = SecurityUtils.NO_CREDENTIALS;
/**
* Regex to remove the UserInfo part from a URL.
*/
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_:0-9a-zA-Z]+@)([^@]*)");
// FIXED:
<fim-middle> private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_0-9a-zA-Z]+@)([^@]*)");
private static final ExecutorService EXE = Executors.newCachedThreadPool(new ThreadFactory()<fix-suffix> {
public Thread newThread(Runnable r) {
final Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
}
});
private static final Map<String, Long> BAD_HOSTS = new ConcurrentHashMap<String, Long>();
/**
* Internal URL, maybe cleaned from user-token.
*/
private final URL internal;
/**
* Assigned credentials to this URL.
*/
private final String securityIdentifier;
private SURL(URL url, String securityIdentifier) {
this.internal = Objects.requireNonNull(url);
this.securityIdentifier = Objects.requireNonNull(securityIdentifier);
}
/**
* Create a secure URL from a String.
* <p>
* The url must be http or https. Return null in case of error or if
* <code>url</code> is null
*
* @param url plain url starting by http:// or https//
* @return the secure URL or null
*/
public static SURL create(String url) {
if (url == null)
return null;
if (url.startsWith("http://") || url.startsWith("https://"))
try {
return create(new URL(url));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
* Create a secure URL from a <code>java.net.URL</code> object.
* <p>
* It takes into account credentials.
*
* @param url
* @return the secure URL
* @throws MalformedURLException if <code>url</code> is null
*/
public static SURL create(URL url) throws MalformedURLException {
if (url == null)
throw new MalformedURLException("URL cannot be null");
<|endoftext|> |
java | <fim-prefix><fim-middle>by https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby.internal.netty;
import com.typesafe.config.Config;
import io.jooby.B<fix-suffix>ody;
import io.jooby.ByteRange;
import io.jooby.Context;
import io.jooby.Cookie;
import io.jooby.DefaultContext;
import io.jooby.FileUpload;
import io.jooby.Formdata;
import io.jooby.MediaType;
import io.jooby.Multipart;
import io.jooby.QueryString;
import io.jooby.Route;
import io.jooby.Router;
import io.jooby.Sender;
import io.jooby.Server;
import io.jooby.Session;
import io.jooby.SessionStore;
import io.jooby.SneakyThrows;
import io.jooby.StatusCode;
import io.jooby.Value;
import io.jooby.ValueNode;
import io.jooby.WebSocket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.DefaultFileRegion;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import io.netty.handler.codec.http.multip<|endoftext|> |
java | <fim-prefix>Test.class,
ConcurrentStatementFetch.class,
ConnectionTest.class,
ConnectTimeoutTest.class,
CopyLargeFileTest.class,
CopyTest.class,
CursorFetchTest.class,
DatabaseEncodingTest.class,
DatabaseMetaDataCacheTest.class,
DatabaseMetaDataPropertiesTest.class,
DatabaseMetaDataTest.class,
DateStyleTest.class,
DateTest.class,
DeepBatchedInsertStatementTest.class,
DriverTest.class,
EncodingTest.class,
ExpressionPropertiesTest.class,
FixedLengthOutputStreamTest.class,
GeometricTest.class,
GetXXXTest.class,
HostSpecTest.class,
IntervalTest.class,
JavaVersionTest.class,
JBuilderTest.class,
LoginTimeoutTest.class,
LogServerMessagePropertyTest.class,
LruCacheTest.class,
MiscTest.class,
NativeQueryBindLengthTest.class,
NoColumnMetadataIssue1613Test.class,
NumericTransferTest.class,
NumericTransferTest2.class,
NotifyTest.class,
OidToStringTest.class,
OidValueOfTest.class,
OptionsPropertyTest.class,
OuterJoinSyntaxTest.class,
ParameterStatusTest.class,
ParserTest.class,
PGbyteaTest.class,
PGPropertyMaxResultBufferParserTest.class,
PGPropertyTest.class,
PGTimestampTest.class,
PGTimeTest.class,
PgSQLXMLTest.class,
PreparedStatementTest.class,
QuotationTest.class,
ReaderInputStreamTest.class,
RefCursorTest.class,
ReplaceProcessingTest.class,
ResultSetMetaDataTest.class,
ResultSetTest.class,
// BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
//
// FIXED:
<fim-middle> ResultSetRefreshTest.class,
ReturningParserTest.class,
SearchPathLookupTest.class,
ServerCursorTest.class,
ServerErrorTest.class,
ServerPreparedStmtTest.class,
ServerVersio<fix-suffix>nParseTest.class,
ServerVersionTest.class,
StatementTest.class,
StringTypeUnspecifiedArrayTest.class,
TestACL.class,
TimestampTest.class,
TimeTest.class,
TimezoneCachingTest.class,
TimezoneTest.class,
TypeCacheDLLStressTest.class,
UnusualBigDecimalByteConverterTest.class,
UpdateableResultTest.class,
UpsertTest.class,
UTF8EncodingTest.class,
V3ParameterListTests.class
})
public class Jdbc2TestSuite {
}
<|endoftext|> |
java | <fim-prefix>/* Copyright (c) 2008-2015, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.io;
public class FileOutputStream extends OutputStream {
// static {
// System.loadLibrary("natives");
// }
private int fd;
public FileOutputStream(FileDescriptor fd) {
this.fd = fd.value;
}
public FileOutputStream(String path) throws IOException {
this(path, false);
}
public FileOutputStream(String path, boolean append) throws IOException {
fd = open(path, append);
}
public FileOutputStream(File file) throws IOException {
this(file.getPath());
}
private static native int open(String path, boolean append) throws IOException;
private static native void write(int fd, int c) throws IOException;
private static native void write(int fd, byte[] b, int offset, int length)
throws IOException;
private static native void close(int fd) throws IOException;
public void write(int c) throws IOException {
write(fd, c);
}
public void write(byte[] b, int offset, int length) throws IOException {
if (b == null) {
throw new NullPointerException();
}
// BUG: CWE-190 Integer Overflow or Wraparound
// if (offset < 0 || offset + length > b.length) {
// FIXED:
<fim-middle> if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) {
throw new ArrayIndexOutOfBoundsException();
}
write(fd, b, offset, length);
}
public void clo<fix-suffix>se() throws IOException {
if (fd != -1) {
close(fd);
fd = -1;
}
}
}
<|endoftext|> |
java | <fim-prefix>FileWithinDirectory(loadPath, file)
? loadFile(file)
: null;
}
else {
final File f = new File(loadPath, file.getPath());
return f.isFile()
? loadFile(new File(loadPath, file.getPath()))
: null;
}
}
catch (Exception ex) {
throw new VncException(
String.format("Failed to load file '%s'", file.getPath()),
ex);
}
}
private static File canonical(final File file) {
try {
return file.getCanonicalFile();
}
catch(IOException ex) {
throw new VncException(
String.format(
"The file '%s' can not be converted to a canonical path!",
file.getPath()),
ex);
}
}
private ByteBuffer loadFile(final File file) {
try {
return ByteBuffer.wrap(Files.readAllBytes(file.toPath()));
}
catch(IOException ex) {
return null;
}
}
private boolean isFileWithinDirectory(
final File dir,
final File file
) throws IOException {
final File dir_ = dir.getAbsoluteFile();
if (dir_.isDirectory()) {
final File fl = new File(dir_, file.getPath());
if (fl.isFile()) {
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {
// FIXED:
<fim-middle> if (fl.getCanonicalFile().toPath().startsWith(dir_.getCanonicalFile().toPath())) {
// Prevent accessing files outside the load-path.
// E.g.: ..<fix-suffix>/../coffee
return true;
}
}
}
return false;
}
private Charset getCharset(final String encoding) {
return encoding == null || encoding.isEmpty()
? Charset.defaultCharset()
: Charset.forName(encoding);
}
// a list of existing canonical paths
private final List<File> paths = new ArrayList<>();
private final boolean unlimitedAccess;
}
<|endoftext|> |
java | <fim-prefix>t java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.olat.core.CoreSpringFactory;
import org.olat.core.configuration.AbstractSpringModule;
import org.apache.logging.log4j.Logger;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.course.site.model.CourseSiteConfiguration;
import org.olat.course.site.model.LanguageConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.thoughtworks.xstream.XStream;
/**
* Description:<br>
* This is the module for sites definition and configuration
*
* <P>
* Initial Date: 12.07.2005 <br>
*
* @author Felix Jost
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*/
@Service("olatsites")
public class SiteDefinitions extends AbstractSpringModule {
private static final Logger log = Tracing.createLoggerFor(SiteDefinitions.class);
private Map<String,SiteDefinition> siteDefMap;
private Map<String,SiteConfiguration> siteConfigMap = new ConcurrentHashMap<>();
private String configSite1;
private String configSite2;
private String configSite3;
private String configSite4;
private String sitesSettings;
@Autowired
private List<SiteDefinition> configurers;
private static final XStream xStream = XStreamHelper.createXStreamInstance();
static {
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
//
// FIXED:
<fim-middle> XStreamHelper.allowDefaultPackage(xStream);
xStream.alias("coursesite", CourseSiteConfiguration.class);
xStream.alias("languageConfig", LanguageConfiguration.class);
xStream.alias("siteconfig"<fix-suffix>, SiteConfiguration.class);
}
@Autowired
public SiteDefinitions(CoordinatorManager coordinatorManager) {
super(coordinatorManager);
}
public String getConfigCourseSite1() {
return configSite1;
}
public void setConfigCourseSite1(String config) {
setStringProperty("site.1.config", config, true);
}
public String getConfigCourseSite2() {
return configSite2;
}
public void setConfigCourseSite2(String config) {
setStringProperty("site.2.config", config, true);
}
public String getConfigCourseSite3() {
return configSite3;
}
public void setConfigCourseSite3(String config) {
setStringProperty("site.3.config", config, true);
}
public String getConfigCourseSite4() {
return configSite4;
}
public void setConfigCourseSite4(String config) {
setStringProperty("site.4.config", config, true);
}
public SiteConfiguration getConfigurationSite(String id) {
return siteConfigMap.computeIfAbsent(id, springId -> {
SiteConfiguration c = new SiteConfiguration();
c.setId(id);
return c;
});
}
public SiteConfiguration getConfigurationSite(SiteDefinition siteDef) {
for(Map.Entry<String, SiteDefinition> entry: siteDefMap.entrySet()) {
if(entry.getValue() == siteDef) {
return getConfigurationSite(entry.getKey());
}
}
return null;
}
public CourseSiteConfiguration getConfigurationCourseSite1() {
if(StringHelper.containsNonWhitespace(configSite1)) {
return (CourseSiteConfiguration)xStream.fromXML(configSite1);
}
<|endoftext|> |
java | <fim-prefix>/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dashbuilder.dataprovider.sql;
import java.util.List;
import java.util.ArrayList;
import org.junit.Before;
public class SQLTestSuite extends SQLDataSetTestBase {
protected <T extends SQLDataSetTestBase> T setUp(T test) throws Exception {
test.testSettings = testSettings;
test.conn = conn;
return test;
}
protected List<SQLDataSetTestBase> sqlTestList = new ArrayList<SQLDataSetTestBase>();
@Before
public void setUp() throws Exception {
super.setUp();
sqlTestList.add(setUp(new SQLDataSetDefTest()));
sqlTestList.add(setUp(new SQLDataSetTrimTest()));
sqlTestList.add(setUp(new SQLTableDataSetLookupTest()));
sqlTestList.add(setUp(new SQLQueryDataSetLookupTest()));
// BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
//
// FIXED:
<fim-middle> sqlTestList.add(setUp(new SQLInjectionAttacksTest()));
}
public void testAll() throws Exception {
for (SQLDataSetTestBase testBase : sqlTestList) {
testBase.testAl<fix-suffix>l();
}
}
}
<|endoftext|> |
java | <fim-prefix>ayer;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.data.game.entity.player.*;
import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.*;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.math.vector.Vector3i;
import com.nukkitx.protocol.bedrock.data.LevelEventType;
import com.nukkitx.protocol.bedrock.data.PlayerActionType;
import com.nukkitx.protocol.bedrock.data.entity.EntityEventType;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.packet.*;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.entity.player.SessionPlayerEntity;
import org.geysermc.connector.inventory.PlayerInventory;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.world.block.BlockStateValues;
import org.geysermc.connector.registry.BlockRegistries;
import org.geysermc.connector.registry.type.ItemMapping;
import org.geysermc.connector.utils.BlockUtils;
import java.util.ArrayList;
@Translator(packet = PlayerActionPacket.class)
public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(PlayerActionPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, PlayerActionPacket packet) {
SessionPlayerEntity entity = session.getPlayerEntity();
// Send book update before any player action
<fix-suffix> if (packet.getAction() != PlayerActionType.RESPAWN) {
session.getBookEditCache().checkForSend();
}
Vector3i vector = packet.getBlockPosition();
Position position = new Position(vector.getX(), vector.getY(), vector.getZ());
switch (packet.getAction()) {
case RESPAWN:
// Respawn process is finished and the server and client are both OK with respawning.
EntityEventPacket eventPacket = new EntityEventPacket();
eventPacket.setRuntimeEntityId(entity.getGeyserId());
eventPacket.setType(EntityEventType.RESPAWN);
eventPacket.setData(0);
session.sendUpstreamPacket(eventPacket);
// Resend attributes or else in rare cases the user can think they're not dead when they are, upon joining the server
UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
attributesPacket.setRuntimeEntityId(entity.getGeyserId());
attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values()));
session.sendUpstreamPacket(attributesPacket);
break;
case START_SWIMMING:
ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING);
session.sendDownstreamPacket(startSwimPacket);
session.setSwimming(true);
<|endoftext|> |
java | <fim-prefix>package com.zrlog.web;
import com.zrlog.common.Constants;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import java.io.File;
public class Application {
public static void main(String[] args) throws LifecycleException {
String webappDirLocation;
if (Constants.IN_JAR) {
webappDirLocation = "webapp";
} else {
webappDirLocation = "src/main/webapp/";
}
Tomcat tomcat = new Tomcat();
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// tomcat.setPort(Integer.valueOf(webPort));
// FIXED:
<fim-middle> tomcat.setPort(Integer.parseInt(webPort));
tomcat.getConnector();
// Declare an alternative location for your "WEB-INF/classes" dir
// Servlet 3.0 annotation will work<fix-suffix>
File additionWebInfClasses;
if (Constants.IN_JAR) {
additionWebInfClasses = new File("");
} else {
additionWebInfClasses = new File("target/classes");
}
tomcat.setBaseDir(additionWebInfClasses.toString());
//idea的路径eclipse启动的路径有区别
if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) {
webappDirLocation = "web/" + webappDirLocation;
}
tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle>ensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
*<fix-suffix> The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.mediapackage.identifier;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Interface for an identifier.
*/
@XmlJavaTypeAdapter(Id.Adapter.class)
public interface Id {
/**
* Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters
* that could potentially get into the way when creating file or directory names from the identifier.
*
* For example, given that the interface is implemented by a class representing CNRI handles, the identifier would
* then look something like <code>10.3930/ETHZ/abcd</code>, whith <code>10.3930</code> being the handle prefix,
* <code>ETH</code> the authority and <code>abcd</code> the local part. <code>toURI()</code> would then return
* <code>10.3930-ETH-abcd</code<|endoftext|> |
java | <fim-prefix>name-with-dot"));
svnMaterialConfig.validate(new ConfigSaveValidationContext(null));
assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.MATERIAL_NAME)).isEqualTo("Invalid material name '.bad-name-with-dot'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.");
}
@Test
void shouldEnsureDestFilePathIsValid() {
svnMaterialConfig.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "../a"));
svnMaterialConfig.validate(new ConfigSaveValidationContext(null));
assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.FOLDER)).isEqualTo("Dest folder '../a' is not valid. It must be a sub-directory of the working folder.");
}
@Test
void rejectsObviouslyWrongURL() {
assertTrue(validating(svn("-url-not-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
assertTrue(validating(svn("_url-not-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
assertTrue(validating(svn("@url-not-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
assertFalse(validating(svn("url-starting-with-an-alphanumeric-character", false)).errors().containsKey(SvnMaterialConfig.URL));
// BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')
//
// FIXED: <fim-middle>
assertFalse(validating(svn("#{url}", false)).errors().containsKey(SvnMaterialConfig.URL));
}
private SvnMaterialConfig validating(SvnMaterialConfig svn) {
svn<fix-suffix>.validate(new ConfigSaveValidationContext(null));
return svn;
}
}
@Nested
class ValidateTree {
@BeforeEach
void setUp() {
svnMaterialConfig.setUrl("foo/bar");
}
@Test
void shouldCallValidate() {
final MaterialConfig materialConfig = spy(svnMaterialConfig);
final ValidationContext validationContext = mockValidationContextForSecretParams();
materialConfig.validateTree(validationContext);
verify(materialConfig).validate(validationContext);
}
@Test
void shouldFailIfEncryptedPasswordIsIncorrect() {
svnMaterialConfig.setEncryptedPassword("encryptedPassword");
final boolean validationResult = svnMaterialConfig.validateTree(new ConfigSaveValidationContext(null));
assertThat(validationResult).isFalse();
assertThat(svnMaterialConfig.errors().on("encryptedPassword")).isEqualTo("Encrypted password value for SvnMaterial with url 'foo/bar' is invalid. This usually happens when the cipher text is modified to have an invalid value.");
}
@Test
void shouldPassIfPasswordIsNotSpecifiedAsSecretParams() {
svnMaterialConfig.setPassword("badger");
assertThat(svnMaterialConfig.validateTree(null)).isTrue();
assertThat(svnMaterialConfig.errors().getAll()).isEmpty();
}
}
private ValidationContext mockValidationContextF<|endoftext|> |
java | <fim-prefix>ld be parsed directly by adding it to JS.
if (libs[j].toLowerCase()
.endsWith(".js"))
{
js.append(tmp);
}
else
{
if (result.length() > 1)
{
result.append(",");
}
result.append("'" + tmp + "'");
}
}
}
}
}
else
{
String tmp = stencils.get(names[i]);
if (tmp == null)
{
try
{
tmp = readXmlFile(
"/stencils/" + names[i] + ".xml",
true);
// Cache for later use
if (tmp != null)
{
stencils.put(names[i], tmp);
}
}
catch (NullPointerException e)
{
// This seems possible according to access log so ignore stencil
}
}
if (tmp != null)
{
if (result.length() > 1)
{
result.append(",");
}
result.append("'" + tmp + "'");
}
}
}
done.add(names[i]);
}
}
}
result.append("]");
// LATER: Detect protocol of request in dev
// mode to avoid security errors
String proto = "https://";
String setCachedUrls = "";
String[] urls = request.getParameterValues("fetch");
if (urls != null)
{
HashSet<String> completed = new HashSet<String>();
for (int i = 0; i < urls.length; i++)
{
try
{
// Checks if URL already fetched to avoid duplicates
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// if (!completed.contains(urls[i]))
// FIXED:
<fim-middle> if (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i]))
{
completed.add(urls[i]);
URL url = new URL(urls[i]);
URLConnection connection = url.openConnection();
<fix-suffix> ByteArrayOutputStream stream = new ByteArrayOutputStream();
Utils.copy(connection.getInputStream(), stream);
setCachedUrls += "GraphViewer.cachedUrls['"
+ StringEscapeUtils.escapeEcmaScript(urls[i])
+ "'] = decodeURIComponent('"
+ StringEscapeUtils.escapeEcmaScript(
Utils.encodeURIComponent(
stream.toString("UTF-8"),
Utils.CHARSET_FOR_URL_ENCODING))
+ "');";
}
}
catch (Exception e)
{
// ignore
}
}
}
// Installs a callback to load the stencils after the viewer was injected
return "window.onDrawioViewerLoad = function() {" + setCachedUrls
+ "mxStencilRegistry.parseStencilSets(" + result.toString()
+ ");" + js + "GraphViewer.processElements(); };"
+ "var t = document.getElementsByTagName('script');"
+ "if (t != null && t.length > 0) {"
+ "var script = document.createElement('script');"
+ "script.type = 'text/javascript';" + "script.src = '" + proto
+ ((dev != null && dev.equals("1")) ? "test" : "www")
+ ".draw.io/js/viewer-static.min.js';"
+ "t[0].parentNode.appendChild(script);}";
}
public void writeStats(HttpServletResponse response) throws IOException
{
PrintWriter writer = new PrintWriter(response.getOutputStream());
writer.println("<html>");
writer.println("<body>");
writer.println("Deployed: " + lastModified);
writer.println("</body>");
writer.println("</html>");
writer.flush();
}
public String readXmlFi<|endoftext|> |
java | <fim-prefix>ConversationsListItemUpdated;
import eu.siacs.conversations.ui.service.EmojiService;
import eu.siacs.conversations.ui.util.ActivityResult;
import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
import eu.siacs.conversations.ui.util.PendingItem;
import eu.siacs.conversations.utils.EmojiWrapper;
import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import rocks.xmpp.addr.Jid;
import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged {
public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
public static final String EXTRA_CONVERSATION = "conversationUuid";
public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
public static final String EXTRA_AS_QUOTE = "as_quote";
public static final String EXTRA_NICK = "nick";
public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
//
// FIXED:
<fim-middle> public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
private static List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
ACTION_VIEW_CONVERSATION,
Intent.<fix-suffix>ACTION_SEND,
Intent.ACTION_SEND_MULTIPLE
);
public static final int REQUEST_OPEN_MESSAGE = 0x9876;
public static final int REQUEST_PLAY_PAUSE = 0x5432;
//secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
private static final @IdRes
int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
private ActivityConversationsBinding binding;
private boolean mActivityPaused = true;
private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
private static boolean isViewOrShareIntent(Intent i) {
Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
}
private static Intent createLauncherIntent(Context context) {
final Intent intent = new Intent(context, ConversationsActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return intent;
}
@Override
protected void refreshUiReal() {
for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
refreshFragment(id);
}
}
@Override
void onBackendConnected() {
<|endoftext|> |
java | <fim-prefix>er;
import uk.ac.ed.ph.jqtiplus.types.Identifier;
import uk.ac.ed.ph.jqtiplus.types.ResponseData.ResponseDataType;
import uk.ac.ed.ph.jqtiplus.value.BooleanValue;
import uk.ac.ed.ph.jqtiplus.value.NumberValue;
import uk.ac.ed.ph.jqtiplus.value.RecordValue;
import uk.ac.ed.ph.jqtiplus.value.SingleValue;
import uk.ac.ed.ph.jqtiplus.value.Value;
import uk.ac.ed.ph.jqtiplus.xmlutils.XmlFactories;
import uk.ac.ed.ph.jqtiplus.xmlutils.XmlResourceNotFoundException;
import uk.ac.ed.ph.jqtiplus.xmlutils.locators.ClassPathResourceLocator;
import uk.ac.ed.ph.jqtiplus.xmlutils.locators.ResourceLocator;
import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltSerializationOptions;
import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetCache;
import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetManager;
import uk.ac.ed.ph.qtiworks.mathassess.GlueValueBinder;
import uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants;
import uk.ac.ed.ph.qtiworks.mathassess.MathAssessExtensionPackage;
/**
*
* Initial date: 12.05.2015<br>
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*
*/
@Service
public class QTI21ServiceImpl implements QTI21Service, UserDataDeletable, InitializingBean, DisposableBean {
private static final Logger log = Tracing.createLoggerFor(QTI21ServiceImpl.class);
private static XStream configXstream = XStreamHelper.createXStreamInstance();
static {
Class<?>[] types = new Class[] {
QTI21DeliveryOptions.class, QTI21AssessmentResultsOptions.class
};
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
// XStream.setupDefaultSecurity(configXstream);
// FIXED:
<fim-middle> configXstream.addPermission(new ExplicitTypePermission(types));
configXstream.alias("deliveryOptions", QTI21DeliveryOptions.class);
configXstream.alias("assessmentResultsOptions", QTI21Assess<fix-suffix>mentResultsOptions.class);
}
@Autowired
private DB dbInstance;
@Autowired
private GradingService gradingService;
@Autowired
private AssessmentTestSessionDAO testSessionDao;
@Autowired
private AssessmentItemSessionDAO itemSessionDao;
@Autowired
private AssessmentResponseDAO testResponseDao;
@Autowired
private AssessmentTestMarksDAO testMarksDao;
@Autowired
private AssessmentEntryDAO assessmentEntryDao;
@Autowired
private QTI21Module qtiModule;
@Autowired
private CoordinatorManager coordinatorManager;
@Autowired
private MailManager mailManager;
private JqtiExtensionManager jqtiExtensionManager;
private XsltStylesheetManager xsltStylesheetManager;
private InfinispanXsltStylesheetCache xsltStylesheetCache;
private CacheWrapper<File,ResolvedAssessmentTest> assessmentTestsCache;
private CacheWrapper<File,ResolvedAssessmentItem> assessmentItemsCache;
private CacheWrapper<AssessmentTestSession,TestSessionController> testSessionControllersCache;
private final ConcurrentMap<String,URI> resourceToTestURI = new ConcurrentHashMap<>();
@Autowired
public QTI21ServiceImpl(InfinispanXsltStylesheetCache xsltStylesheetCache) {
this.xsltStylesheetCache = xsltStylesheetCache;
}
@Override
public void afterPropertiesSet() throws Exception {
final List<JqtiExtensionPackage<?>> extensionPackages = new ArrayList<>();
/* Enable MathAssess extensions if requested */
if (qtiModule.isMathAssessExtensionEnabled()) {
log.info("En<|endoftext|> |
java | <fim-prefix><fim-middle>right 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net>
* Distributed under the terms of either:
* - the common development and distribution license (CDDL), v1.0; or
* - the GNU Less<fix-suffix>er General Public License, v2.1 or later
*/
package winstone;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
/**
* Response for servlet
*
* @author <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a>
* @version $Id: WinstoneResponse.java,v 1.28 2005/04/19 07:33:41 rickknowles
* Exp $
*/
public class WinstoneResponse implements HttpServletResponse {
private static final DateFormat HTTP_DF = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
private static final DateFormat VERSION0_DF = new SimpleDateFormat(
"EEE, dd-MMM-yy HH:mm:ss z", Locale.US);
static {
HTTP_DF.setTimeZone(TimeZone.getTimeZone("GMT"));
VERSION0_DF.setTimeZone(TimeZone.getTimeZone("GMT"));
}
static final String CONTENT_LENGTH_HEADER = "Content-Length";
static final String CONTENT_TYPE_HEADER = "Content-Type";
// Response header constants
private static final String CONTENT_LANGUAGE_HEADER = "Content-Language";
private static fi<|endoftext|> |
java | <fim-prefix> userRequest.getHttpReq().getParameter("key");
if (emKey == null) {
emKey = userRequest.getIdentity().getUser().getProperty("emchangeKey", null);
}
if (emKey != null) {
// key exist
// we check if given key is a valid temporary key
tempKey = rm.loadTemporaryKeyByRegistrationKey(emKey);
}
}
@Override
public boolean isUserInteractionRequired(UserRequest ureq) {
User user = ureq.getIdentity().getUser();
if(StringHelper.containsNonWhitespace(user.getProperty("emchangeKey", null))) {
if (isLinkTimeUp()) {
deleteRegistrationKey();
} else {
if (isLinkClicked()) {
changeEMail(getWindowControl());
} else {
Boolean alreadySeen = ((Boolean)ureq.getUserSession().getEntry(PRESENTED_EMAIL_CHANGE_REMINDER));
if (alreadySeen == null) {
getWindowControl().setWarning(getPackageTranslator().translate("email.change.reminder"));
ureq.getUserSession().putEntry(PRESENTED_EMAIL_CHANGE_REMINDER, Boolean.TRUE);
}
}
}
} else {
String value = user.getProperty("emailDisabled", null);
if (value != null && value.equals("true")) {
Translator translator = Util.createPackageTranslator(HomeMainController.class, ureq.getLocale());
getWindowControl().setWarning(translator.translate("email.disabled"));
}
}
return false;
}
/**
* change email
* @param wControl
* @return
*/
public boolean changeEMail(WindowControl wControl) {
XStream xml = XStreamHelper.createXStreamInstance();
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
//
// FIXED:
<fim-middle> XStreamHelper.allowDefaultPackage(xml);
@SuppressWarnings("unchecked")
HashMap<String, String> mails = (HashMap<String, String>) xml.fromXML(tempKey.getEmailAddress());
Identity identity = <fix-suffix>securityManager.loadIdentityByKey(tempKey.getIdentityKey());
if (identity != null) {
String oldEmail = identity.getUser().getEmail();
identity.getUser().setProperty("email", mails.get("changedEMail"));
// if old mail address closed then set the new mail address
// unclosed
String value = identity.getUser().getProperty("emailDisabled", null);
if (value != null && value.equals("true")) {
identity.getUser().setProperty("emailDisabled", "false");
}
identity.getUser().setProperty("email", mails.get("changedEMail"));
// success info message
String currentEmailDisplay = userManager.getUserDisplayEmail(mails.get("currentEMail"), userRequest.getLocale());
String changedEmailDisplay = userManager.getUserDisplayEmail(mails.get("changedEMail"), userRequest.getLocale());
wControl.setInfo(pT.translate("success.change.email", new String[] { currentEmailDisplay, changedEmailDisplay }));
// remove keys
identity.getUser().setProperty("emchangeKey", null);
userRequest.getUserSession().removeEntryFromNonClearedStore(ChangeEMailController.CHANGE_EMAIL_ENTRY);
securityManager.deleteInvalidAuthenticationsByEmail(oldEmail);
} else {
// error message
wControl.setWarning(pT.translate("error.change.email.unexpected", new String[] { mails.get("currentEMail"), mails.get("changedEMail") }));
}
// delete registration key
rm.deleteTemporaryKeyWithId(tempKey.getRegistrationKey());
return true;
}
public boolean isLinkClicked() {
Ob<|endoftext|> |
java | <fim-prefix>bla.Dispatcher",ConfigKey.AGENT_ID,"test");
new BackendManager(config,log);
}
@Test
public void debugging() {
RecordingLogHandler lhandler = new RecordingLogHandler();
BackendManager backendManager = new BackendManager(config,lhandler);
lhandler.error = 0;
lhandler.debug = 0;
lhandler.info = 0;
backendManager.debug("test");
assertEquals(lhandler.debug,1);
backendManager.error("test",new Exception());
assertEquals(lhandler.error,1);
backendManager.info("test");
assertEquals(lhandler.info,1);
backendManager.destroy();
}
@Test
public void defaultConfig() {
Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config,log);
backendManager.destroy();
}
@Test
public void doubleInit() {
BackendManager b1 = new BackendManager(config,log);
BackendManager b2 = new BackendManager(config,log);
b2.destroy();
b1.destroy();
}
@Test
public void remoteAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1"));
backendManager.destroy();
}
@Test
public void corsAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
// BUG: CWE-352 Cross-Site Request Forgery (CSRF)
// assertTrue(backendManager.isCorsAccessAllowed("http://bla.com"));
// FIXED:
<fim-middle> assertTrue(backendManager.isOriginAllowed("http://bla.com",false));
backendManager.destroy();
}
@Test
public void convertError() throws MalformedObjectNameException {
<fix-suffix> BackendManager backendManager = new BackendManager(config,log);
Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb"));
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build();
JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req);
assertTrue(!jsonError.containsKey("stackTrace"));
assertEquals(jsonError.get("message"),"Hans");
assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb");
backendManager.destroy();
}
// =========================================================================================
static class RequestDispatcherTest implements RequestDispatcher {
static boolean called = false;
public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) {
assertNotNull(pConverters);
assertNotNull(pRestrictor);
}
public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {
called = true;
if (pJmxReq.getType() == RequestType.READ) {
return new JSONObject();
} else if (pJmxReq.getType() == RequestType.WRITE) {
return "faultyFormat";
} else if (pJmxReq.getType() == RequestType.LIST) {
<|endoftext|> |
java | <fim-prefix>ve copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientRenameItemPacket;
import com.nukkitx.protocol.bedrock.packet.FilterTextPacket;
import org.geysermc.connector.inventory.AnvilContainer;
import org.geysermc.connector.inventory.CartographyContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
/**
* Used to send strings to the server and filter out unwanted words.
* Java doesn't care, so we don't care, and we approve all strings.
*/
@Translator(packet = FilterTextPacket.class)
public class BedrockFilterTextTranslator extends PacketTranslator<FilterTextPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(FilterTextPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, FilterTextPacket packet) {
if (session.getOpenInventory() instanceof CartographyContainer) {
// We don't want to be able to rename <fix-suffix>in the cartography table
return;
}
packet.setFromServer(true);
session.sendUpstreamPacket(packet);
if (session.getOpenInventory() instanceof AnvilContainer) {
// Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
session.sendDownstreamPacket(renameItemPacket);
}
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle> - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License<fix-suffix>.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <hr>
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
* <p>
* Initial code contributed and copyrighted by<br>
* JGS goodsolutions GmbH, http://www.goodsolutions.ch
* <p>
*/
package org.olat.core.util.prefs.db;
import java.util.Iterator;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.olat.core.id.Identity;
import org.olat.core.logging.Tracing;
import org.olat.core.util.prefs.Preferences;
import org.olat.core.util.prefs.PreferencesStorage;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.properties.Property;
import org.olat.properties.PropertyManager;
import com.thoughtworks.xstream.XStream;
/**
* Description:<br>
* <P>
* Initial Date: 21.06.2006 <br>
*
* @author Felix Jost
*/
public class DbStorage implements <|endoftext|> |
java | <fim-prefix><fim-middle>right 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the <fix-suffix>License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config.materials.git;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.*;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.ReflectionUtil;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.thoughtworks.go.helper.MaterialConfigsMother.git;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class GitMaterialConfigTest {
@Test
void shouldBePasswordAwareMaterial() {
assertTrue(PasswordAwareMaterial.class.isAssignableFrom(GitMaterialConfig.class));
}
@Test
void shouldSetConfigAttributes() {
GitMaterialConfig gitMaterialConfig = git("");
Map<String, String> map = new HashMap<>();
map.put(GitMaterialConfig.URL, "url");
map.put(GitMaterialConfig.BRANCH, "some-branch");
map.put(GitMaterialConfig.SHALLOW_CLONE, "true");
map<|endoftext|> |
java | <fim-prefix><fim-middle>s, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "Licens<fix-suffix>e");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.protocols.http2;
import io.undertow.util.HeaderMap;
import io.undertow.util.HeaderValues;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.undertow.protocols.http2.Hpack.HeaderField;
import static io.undertow.protocols.http2.Hpack.STATIC_TABLE;
import static io.undertow.protocols.http2.Hpack.STATIC_TABLE_LENGTH;
import static io.undertow.protocols.http2.Hpack.encodeInteger;
/**
* Encoder for HPACK frames.
*
* @author Stuart Douglas
*/
public class HpackEncoder {
private static final Set<HttpString> SKIP;
static {
Set<HttpString> set = new HashSet<>();
set.add(Headers.CONNECTION);
set.add(Headers.TRANSFER_ENCODING);
set.add(H<|endoftext|> |
java | <fim-prefix> }
var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);
var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),
ZoneOffset.UTC);
var nowDay = LocalDate.now(ZoneOffset.UTC);
if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {
return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow");
}
var responseBuilder = ResponseEntity.ok();
if (principal instanceof Jwt) {
var originalJWT = (Jwt) principal;
var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))
.setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject())
.setExpiration(Date
.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))
.claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate());
if (originalJWT.containsClaim("fake")) {
jwtBuilder.claim("fake", originalJWT.getClaim("fake"));
}
String jwt = jwtBuilder.signWith(secondDayKey).compact();
responseBuilder.header("Authorization", "Bearer " + jwt);
responseBuilder.header("X-Exposed-Token", "Bearer " + jwt);
}
Callable<ResponseEntity<String>> cb = () -> {
normalizeRequestTime(now);
return responseBuilder.body("OK");
};
return cb;
}
@PostMapping(value = "/exposednextday")
@Loggable
// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
//
// FIXED:
<fim-middle> @ResponseRetention(time = "application.response.retention.time.exposednextday")
@Transactional
@Operation(description = "Allows the client to send the last exposed key of the infection to the backe<fix-suffix>nd server. The JWT must come from a previous call to /exposed")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"),
@ApiResponse(responseCode = "400", description =
"- Ivnalid base64 encoded Temporary Exposure Key" +
"- TEK-date does not match delayedKeyDAte claim in Jwt" +
"- TEK has negative rolling period"),
@ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") })
public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond(
@Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) {
var now = Instant.now().toEpochMilli();
if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body(<|endoftext|> |
java | <fim-prefix><fim-middle>g.bouncycastle.pqc.jcajce.provider.xmss;
import java.io.IOException;
import java.security.PrivateKey;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyI<fix-suffix>nfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;
import org.bouncycastle.pqc.asn1.XMSSKeyParams;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDS;
import org.bouncycastle.pqc.crypto.xmss.XMSSParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;
import org.bouncycastle.util.Arrays;
public class BCXMSSPrivateKey
implements PrivateKey, XMSSKey
{
private final XMSSPrivateKeyParameters keyParams;
private final ASN1ObjectIdentifier treeDigest;
public BCXMSSPrivateKey(
ASN1ObjectIdentifier treeDigest,
XMSSPrivateKeyParameters keyParams)
{
this.treeDigest = treeDigest;
this.keyParams = keyParams;
}
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
.Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDige<|endoftext|> |
java | <fim-prefix>SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientClickWindowButtonPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;
import com.nukkitx.protocol.bedrock.packet.LecternUpdatePacket;
import org.geysermc.connector.inventory.LecternContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.InventoryUtils;
/**
* Used to translate moving pages, or closing the inventory
*/
@Translator(packet = LecternUpdatePacket.class)
public class BedrockLecternUpdateTranslator extends PacketTranslator<LecternUpdatePacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(LecternUpdatePacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, LecternUpdatePacket packet) {
if (packet.isDroppingBook()) {
// Bedrock drops the book outside of the GUI. Java drops it in the GUI<fix-suffix>
// So, we enter the GUI and then drop it! :)
session.setDroppingLecternBook(true);
// Emulate an interact packet
ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(
new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
BlockFace.DOWN,
Hand.MAIN_HAND,
0, 0, 0, // Java doesn't care about these when dealing with a lectern
false);
session.sendDownstreamPacket(blockPacket);
} else {
// Bedrock wants to either move a page or exit
if (!(session.getOpenInventory() instanceof LecternContainer)) {
session.getConnector().getLogger().debug("Expected lectern but it wasn't open!");
return;
}
LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory();
if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) {
// The same page means Bedrock is closing the window
ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId());
session.sendDownstreamPacket(closeWindowPacket);
InventoryUtils.closeInventory(session, lecternContainer.getId(), false);
} else {
// Each "page" Bedrock gives to us actu<|endoftext|> |
java | <fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerAbilitiesPacket;
import com.nukkitx.protocol.bedrock.data.AdventureSetting;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.packet.AdventureSettingsPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.c<|endoftext|> |
java | <fim-prefix> } finally {
buffer.release();
}
}
@Test
public void testCopy() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy();
Assert.assertEquals(buf, copy);
buf.release();
copy.release();
}
@Test
public void testCopyWithOffset() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy(1, 9);
Assert.assertEquals(buf.slice(1, 9), copy);
buf.release();
copy.release();
}
// Test for https://github.com/netty/netty/issues/1708
@Test
public void testWrapBufferWithNonZeroPosition() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16)
.putLong(1).flip().position(1)).asReadOnlyBuffer());
ByteBuf slice = buf.slice();
Assert.assertEquals(buf, slice);
buf.release();
}
@Test
public void testWrapBufferRoundTrip() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.readInt());
ByteBuffer nioBuffer = buf.nioBuffer();
// Ensure this can be accessed without throwing a BufferUnderflowException
Assert.assertEquals(2, nioBuffer.getInt());
buf.release();
}
@Test
public void testWrapMemoryMapped() throws Exception {
// BUG: CWE-378 Creation of Temporary File With Insecure Permissions
// File file = File.createTempFile("netty-test", "tmp");
// FIXED:
<fim-middle> File file = PlatformDependent.createTempFile("netty-test", "tmp", null);
FileChannel output = null;
FileChannel input = null;
ByteBuf b1 = null;
ByteBuf b2 = nu<fix-suffix>ll;
try {
output = new RandomAccessFile(file, "rw").getChannel();
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
output.write(ByteBuffer.wrap(bytes));
input = new RandomAccessFile(file, "r").getChannel();
ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());
b1 = buffer(m);
ByteBuffer dup = m.duplicate();
dup.position(2);
dup.limit(4);
b2 = buffer(dup);
Assert.assertEquals(b2, b1.slice(2, 2));
} finally {
if (b1 != null) {
b1.release();
}
if (b2 != null) {
b2.release();
}
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
file.delete();
}
}
@Test
public void testMemoryAddress() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
Assert.assertFalse(buf.hasMemoryAddress());
try {
buf.memoryAddress();
Assert.fail();
} catch (UnsupportedOperationException expected) {
// expected
}
} finally {
buf.release();
}
}
}
<|endoftext|> |
java | <fim-prefix>rt org.olat.core.logging.Tracing;
import org.olat.core.util.CodeHelper;
import org.olat.core.util.FileUtils;
import org.olat.core.util.vfs.LocalFolderImpl;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.VFSManager;
import org.olat.core.util.xml.XMLParser;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.fileresource.FileResourceManager;
import org.olat.ims.cp.objects.CPOrganization;
import org.olat.ims.cp.objects.CPResource;
import org.olat.ims.cp.ui.CPPackageConfig;
import org.olat.ims.cp.ui.CPPage;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryManager;
import org.springframework.stereotype.Service;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.ExplicitTypePermission;
/**
* The CP manager implementation.
* <p>
* In many cases, method calls are delegated to the content package object.
*
* <P>
* Initial Date: 04.07.2008 <br>
*
* @author Sergio Trentini
*/
@Service("org.olat.ims.cp.CPManager")
public class CPManagerImpl implements CPManager {
private static final Logger log = Tracing.createLoggerFor(CPManagerImpl.class);
public static final String PACKAGE_CONFIG_FILE_NAME = "CPPackageConfig.xml";
private static XStream configXstream = XStreamHelper.createXStreamInstance();
static {
Class<?>[] types = new Class[] {
CPPackageConfig.class, DeliveryOptions.class
};
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
// XStream.setupDefaultSecurity(configXstream);
// FIXED:
<fim-middle> configXstream.addPermission(new ExplicitTypePermission(types));
configXstream.alias("packageConfig", CPPackageConfig.class);
configXstream.alias("deliveryOptions", DeliveryOptions.class);
}
@<fix-suffix>Override
public CPPackageConfig getCPPackageConfig(OLATResourceable ores) {
FileResourceManager frm = FileResourceManager.getInstance();
File reFolder = frm.getFileResourceRoot(ores);
File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);
CPPackageConfig config;
if(configXml.exists()) {
config = (CPPackageConfig)configXstream.fromXML(configXml);
} else {
//set default config
config = new CPPackageConfig();
config.setDeliveryOptions(DeliveryOptions.defaultWithGlossary());
setCPPackageConfig(ores, config);
}
return config;
}
@Override
public void setCPPackageConfig(OLATResourceable ores, CPPackageConfig config) {
FileResourceManager frm = FileResourceManager.getInstance();
File reFolder = frm.getFileResourceRoot(ores);
File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);
if(config == null) {
FileUtils.deleteFile(configXml);
} else {
try(OutputStream out = new FileOutputStream(configXml)) {
configXstream.toXML(config, out);
} catch (IOException e) {
log.error("", e);
}
}
}
@Override
public ContentPackage load(VFSContainer directory, OLATResourceable ores) {
ContentPackage cp;
VFSItem file = directory.resolve("imsmanifest.xml");
if (file instanceof VFSLeaf) {
try(InputStream in = ((VFSLeaf)file).getInputStream()) {
XMLParser parser = new XMLParser();
DefaultDocument doc = (DefaultDocument) parser.parse(in, false);
cp = new ContentPackage(doc, directory, ores);
// <|endoftext|> |
java | <fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.java;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket;
import com.nukkitx.protocol.bedrock.packet.TextPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.chat.MessageTranslator;
@Translator(packet = ServerChatPacket.class)<|endoftext|> |
java | <fim-prefix><fim-middle>right 2017-2019 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of t<fix-suffix>he License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.netty;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.http.MutableHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}.
*
* @author Graeme Rocher
* @since 1.0
*/
@Internal
public class NettyHttpHeaders implements MutableHttpHeaders {
io.netty.handler.codec.http.HttpHeaders nettyHeaders;
final ConversionService<?> conversionService;
/**
* @param nettyHeaders The Netty Http headers
* @param conversionService The conversion service
*/
public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) {
this.nettyHeaders = nettyHeaders;
this.conversionService = conversionService;
}
<|endoftext|> |
java | <fim-prefix>furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerSwingArmPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerBoatPacket;
import com.nukkitx.protocol.bedrock.packet.AnimatePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import java.util.concurrent.TimeUnit;
@Translator(packet = AnimatePacket.class)
public class BedrockAnimateTranslator extends PacketTranslator<AnimatePacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(AnimatePacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, AnimatePacket packet) {
// Stop the player sending animations before they have fully spawned into the server
if (!session.isSpawned()) <fix-suffix>{
return;
}
switch (packet.getAction()) {
case SWING_ARM:
// Delay so entity damage can be processed first
session.scheduleInEventLoop(() ->
session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
25,
TimeUnit.MILLISECONDS
);
break;
// These two might need to be flipped, but my recommendation is getting moving working first
case ROW_LEFT:
// Packet value is a float of how long one has been rowing, so we convert that into a boolean
session.setSteeringLeft(packet.getRowingTime() > 0.0);
ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
session.sendDownstreamPacket(steerLeftPacket);
break;
case ROW_RIGHT:
session.setSteeringRight(packet.getRowingTime() > 0.0);
ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
session.sendDownstreamPacket(steerRightPacket);
break;
}
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPlayerListDataPacket;
import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateLightPacket;
import com.github.steveice10.packetlib.packet.Packet;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import io.netty.channel.EventLoop;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.geysermc.common.PlatformType;
import org.geysermc.connector.Ge<|endoftext|> |
java | <fim-prefix>SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock.entity;
import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientSelectTradePacket;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.packet.EntityEventPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.inventory.GeyserItemStack;
import org.geysermc.connector.inventory.Inventory;
import org.geysermc.connector.inventory.MerchantContainer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import java.util.concurrent.TimeUnit;
@Translator(packet = EntityEventPacket.class)
public class BedrockEntityEventTranslator extends PacketTranslator<EntityEventPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(EntityEventPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, EntityEventPacket packet) {
switch (packet.getType()) {
case EATING_ITEM:
// Resend the packet so we get the eating<fix-suffix> sounds
session.sendUpstreamPacket(packet);
return;
case COMPLETE_TRADE:
ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());
session.sendDownstreamPacket(selectTradePacket);
session.scheduleInEventLoop(() -> {
Entity villager = session.getPlayerEntity();
Inventory openInventory = session.getOpenInventory();
if (openInventory instanceof MerchantContainer) {
MerchantContainer merchantInventory = (MerchantContainer) openInventory;
VillagerTrade[] trades = merchantInventory.getVillagerTrades();
if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {
VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];
openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session);
villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP));
villager.updateBedrockMetadata(session);
}
}
}, 100, TimeUnit.MILLISECONDS);
return;
}
session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + pa<|endoftext|> |
java | <fim-prefix>ed {
// min and max of all coord
private final MinMax minMax;
public Drawing(MinMax minMax) {
this.minMax = minMax;
}
public void drawU(UGraphic ug) {
drawAllClusters(ug);
drawAllNodes(ug);
drawAllEdges(ug);
}
private void drawAllClusters(UGraphic ug) {
for (Entry<IGroup, ElkNode> ent : clusters.entrySet())
drawSingleCluster(ug, ent.getKey(), ent.getValue());
}
private void drawAllNodes(UGraphic ug) {
for (Entry<ILeaf, ElkNode> ent : nodes.entrySet())
drawSingleNode(ug, ent.getKey(), ent.getValue());
}
private void drawAllEdges(UGraphic ug) {
for (Entry<Link, ElkEdge> ent : edges.entrySet()) {
final Link link = ent.getKey();
if (link.isInvis())
continue;
drawSingleEdge(ug, link, ent.getValue());
}
}
private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {
final Point2D corner = getPosition(elkNode);
final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());
PackageStyle packageStyle = group.getPackageStyle();
final ISkinParam skinParam = diagram.getSkinParam();
if (packageStyle == null)
packageStyle = skinParam.packageStyle();
final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();
final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())
.getMergedStyle(skinParam.getCurrentStyleBuilder());
final double shadowing = style.value(PName.Shadowing).asDouble();
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);
// FIXED:
<fim-middle> final UStroke stroke = Cluster.getStrokeInternal(group, style);
HColor backColor = getBackColor(umlDiagramType);
backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(),<fix-suffix> umlDiagramType.getStyleName(),
group.getUSymbol());
final double roundCorner = group.getUSymbol() == null ? 0
: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());
final TextBlock ztitle = getTitleBlock(group);
final TextBlock zstereo = TextBlockUtils.empty(0, 0);
final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);
final HColor borderColor = HColorUtils.BLACK;
decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,
skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
skinParam.getStereotypeAlignment(), 0);
// // Print a simple rectangle right now
// ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);
}
private TextBlock getTitleBlock(IGroup g) {
final Display label = g.getDisplay();
if (label == null)
return TextBlockUtils.empty(0, 0);
final ISkinParam skinParam = diagram.getSkinParam();
final FontConfiguration fontConfiguration = g.getFontConfigurationForTitle(skinParam);
return label.create(fontConfiguration, HorizontalAlignment.CENTER, skinParam);
}
private HColor getBackColor(UmlDiagramType umlDiagramType) {
return null;
}
private void drawSingleNode(UGraphic ug, ILeaf leaf, ElkNode elkNode) {
final IEntityImage<|endoftext|> |
java | <fim-prefix>brary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*
*
*/
package net.sourceforge.plantuml.style;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
class Context {
private final List<String> data = new ArrayList<String>();
public Context push(String newString) {
final Context result = new Context();
result.data.addAll(this.data);
result.data.add(newString);
return result;
}
public Context pop() {
if (size() == 0)
throw new IllegalStateException();
final Context result = new Context();
result.data.addAll(this.data.subList(0, this.data.size() - 1));
return result;
}
@Override
public String toString() {
return data.toString();
}
public int size() {
return data.size();
}
public Collection<StyleSignatureBasic> toSignatures() {
List<StyleSignatureBasic> results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));
boolean star = false;
for (Iterator<String> it = data.iterator(); it.hasNext();) {
String s = it.next();
if (s.endsWith("*")) {
star = true;
s = s.substring(0, s.length() - 1);
}
final String[] names = s.split(",");
final List<StyleSignatureBasic> tmp = new ArrayList<>();
for (StyleSignatureBasic ss : results)
for (String name : names)
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// tmp.add(ss.add(name));
// FIXED:
<fim-middle> tmp.add(ss.add(name.trim()));
results = tmp;
}
if (star)
for (ListIterator<StyleSignatureBasic> it = results.listIterator(); it.hasNext();) {
final StyleSignatureBasic tmp = it.nex<fix-suffix>t().addStar();
it.set(tmp);
}
return Collections.unmodifiableCollection(results);
}
}<|endoftext|> |
java | <fim-prefix>ESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerVehiclePacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.packet.PlayerInputPacket;
import org.geysermc.connector.entity.BoatEntity;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;
import org.geysermc.connector.entity.living.animal.horse.LlamaEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
/**
* Sent by the client for minecarts and boats.
*/
@Translator(packet = PlayerInputPacket.class)
public class BedrockPlayerInputTranslator extends PacketTranslator<PlayerInputPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(PlayerInputPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, PlayerInputPacket packet) {
ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket(
packet.getInputMo<fix-suffix>tion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking()
);
session.sendDownstreamPacket(clientSteerVehiclePacket);
// Bedrock only sends movement vehicle packets while moving
// This allows horses to take damage while standing on magma
Entity vehicle = session.getRidingVehicleEntity();
boolean sendMovement = false;
if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) {
sendMovement = vehicle.isOnGround();
} else if (vehicle instanceof BoatEntity) {
if (vehicle.getPassengers().size() == 1) {
// The player is the only rider
sendMovement = true;
} else {
// Check if the player is the front rider
Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null);
if (seatPos != null && seatPos.getX() > 0) {
sendMovement = true;
}
}
}
if (sendMovement) {
long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp();
if (timeSinceVehicleMove >= 100) {
Vector3f vehiclePosition = vehicle.getPosition();
Vector3f vehicleRotation = vehicle.getRotation();
if (vehicle instanceof BoatEntity) {
// Remove some Y position to pre<|endoftext|> |
java | <fim-prefix>, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock.entity.player;
import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;
import com.nukkitx.protocol.bedrock.packet.RiderJumpPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
@Translator(packet = RiderJumpPacket.class)
public class BedrockRiderJumpTranslator extends PacketTranslator<RiderJumpPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(RiderJumpPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, RiderJumpPacket packet) {
Entity vehicle = session.getRidingVehicleEntity();
if (vehicle instanceof AbstractHorseEntity) {
<fix-suffix>ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
session.sendDownstreamPacket(playerStatePacket);
}
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle>MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this so<fix-suffix>ftware and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.FilePath;
import hudson.Functions;
import jenkins.model.Jenkins;
import hudson.remoting.AsyncFutureImpl;
import hudson.remoting.Callable;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.VirtualChannel;
import hudson.security.AccessControlled;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
impo<|endoftext|> |
java | <fim-prefix>FTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerChangeHeldItemPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;
import com.nukkitx.protocol.bedrock.data.inventory.ContainerId;
import com.nukkitx.protocol.bedrock.packet.MobEquipmentPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.CooldownUtils;
import org.geysermc.connector.utils.InteractiveTagManager;
import java.util.concurrent.TimeUnit;
@Translator(packet = MobEquipmentPacket.class)
public class BedrockMobEquipmentTranslator extends PacketTranslator<MobEquipmentPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(MobEquipmentPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, MobEquipmentPacket packet) {
if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||
packet.getContainerId() != ContainerId.I<fix-suffix>NVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {
// For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention
return;
}
// Send book update before switching hotbar slot
session.getBookEditCache().checkForSend();
session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());
ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());
session.sendDownstreamPacket(changeHeldItemPacket);
if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
// Activate shield since we are already sneaking
// (No need to send a release item packet - Java doesn't do this when swapping items)
// Required to do it a tick later or else it doesn't register
session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),
50, TimeUnit.MILLISECONDS);
}
// Java sends a cooldown indicator whenever you switch an item
CooldownUtils.sendCooldown(session);
// Update the interactive tag, if an entity is present
if (session.getMouseoverEntity() != null) {
<|endoftext|> |
java | <fim-prefix>obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.services.license.manager;
import org.olat.core.commons.services.license.License;
import org.olat.core.commons.services.license.model.LicenseImpl;
import org.olat.core.commons.services.license.model.LicenseTypeImpl;
import org.olat.core.commons.services.license.model.ResourceLicenseImpl;
import org.apache.logging.log4j.Logger;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.xml.XStreamHelper;
import org.springframework.stereotype.Component;
import com.thoughtworks.xstream.XStream;
/**
*
* Initial date: 16.03.2018<br>
* @author uhensler, urs.hensler@frentix.com, http://www.frentix.com
*
*/
@Component
class LicenseXStreamHelper {
private static final Logger log = Tracing.createLoggerFor(LicenseXStreamHelper.class);
private static final XStream licenseXStream = XStreamHelper.createXStreamInstanceForDBObjects();
static {
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
//
// FIXED:
<fim-middle> XStreamHelper.allowDefaultPackage(licenseXStream);
licenseXStream.alias("license", LicenseImpl.class);
licenseXStream.alias("license", ResourceLicenseImpl.class);
licenseXStream.alias("license<fix-suffix>Type", LicenseTypeImpl.class);
licenseXStream.ignoreUnknownElements();
licenseXStream.omitField(LicenseImpl.class, "creationDate");
licenseXStream.omitField(LicenseImpl.class, "lastModified");
licenseXStream.omitField(ResourceLicenseImpl.class, "creationDate");
licenseXStream.omitField(ResourceLicenseImpl.class, "lastModified");
licenseXStream.omitField(LicenseTypeImpl.class, "creationDate");
licenseXStream.omitField(LicenseTypeImpl.class, "lastModified");
}
String toXml(License license) {
if (license == null) return null;
return licenseXStream.toXML(license);
}
License licenseFromXml(String xml) {
License license = null;
if(StringHelper.containsNonWhitespace(xml)) {
try {
Object obj = licenseXStream.fromXML(xml);
if(obj instanceof License) {
license = (License) obj;
}
} catch (Exception e) {
log.error("", e);
}
}
return license;
}
}
<|endoftext|> |
java | <fim-prefix>StyleLoader.class.getResourceAsStream("/skin/strictuml.skin");
final StyleBuilder styleBuilder = this.getCurrentStyleBuilder();
try {
final BlocLines lines = BlocLines.load(internalIs, null);
for (Style modifiedStyle : StyleLoader.getDeclaredStyles(lines, styleBuilder))
this.muteStyle(modifiedStyle);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void applyPendingStyleMigration() {
for (Entry<String, String> ent : paramsPendingForStyleMigration.entrySet()) {
final FromSkinparamToStyle convertor = new FromSkinparamToStyle(ent.getKey());
convertor.convertNow(ent.getValue(), getCurrentStyleBuilder());
for (Style style : convertor.getStyles())
muteStyle(style);
}
paramsPendingForStyleMigration.clear();
}
public static SkinParam create(UmlDiagramType type, ThemeStyle style) {
return new SkinParam(type, style);
}
public static SkinParam noShadowing(UmlDiagramType type, ThemeStyle style) {
final SkinParam result = new SkinParam(type, style);
result.setParam("shadowing", "false");
return result;
}
private final Map<String, List<String>> cacheCleanForKey = new HashMap<String, List<String>>();
List<String> cleanForKey(String key) {
List<String> result = cacheCleanForKey.get(key);
if (result == null) {
result = cleanForKeySlow(key);
cacheCleanForKey.put(key, result);
}
return result;
}
List<String> cleanForKeySlow(String key) {
key = StringUtils.trin(StringUtils.goLowerCase(key));
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// key = key.replaceAll("_|\\.|\\s", "");
// FIXED:
<fim-middle> key = key.replaceAll("_|\\.", "");
// key = replaceSmart(key, "partition", "package");
key = replaceSmart(key, "sequenceparticipant", "participant");
key = replaceSmart(key, "sequenceactor", "<fix-suffix>actor");
key = key.replaceAll("activityarrow", "arrow");
key = key.replaceAll("objectarrow", "arrow");
key = key.replaceAll("classarrow", "arrow");
key = key.replaceAll("componentarrow", "arrow");
key = key.replaceAll("statearrow", "arrow");
key = key.replaceAll("usecasearrow", "arrow");
key = key.replaceAll("sequencearrow", "arrow");
key = key.replaceAll("align$", "alignment");
final Matcher2 mm = stereoPattern.matcher(key);
final List<String> result = new ArrayList<>();
while (mm.find()) {
final String s = mm.group(1);
result.add(key.replaceAll(stereoPatternString, "") + "<<" + s + ">>");
}
if (result.size() == 0)
result.add(key);
return Collections.unmodifiableList(result);
}
private static String replaceSmart(String s, String src, String target) {
if (s.contains(src) == false) {
return s;
}
return s.replaceAll(src, target);
}
public HColor getHyperlinkColor() {
final HColor result = getHtmlColor(ColorParam.hyperlink, null, false);
if (result == null)
return HColorUtils.BLUE;
return result;
}
public HColor getBackgroundColor() {
final HColor result = getHtmlColor(ColorParam.background, null, false);
return result != null ? result : HColorUtils.WHITE;
}
public String getValue(String key) {
applyPendingStyleMigration();
for (String key2 : cleanForKey(key)) {
final String result = params.get(key2);
if (result != null)
return result;
}
return null;
}
public String getValue(String key<|endoftext|> |
java | <fim-prefix>/*
* Copy<fim-middle>right 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the <fix-suffix>License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cd.go.authentication.ldap;
import cd.go.authentication.ldap.mapper.Mapper;
import javax.naming.NamingException;
import java.util.List;
public interface LdapClient {
<T> T authenticate(String username, String password, Mapper<T> mapper);
// BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
// <T> List<T> search(String userSearchFilter, Object[] filterArgs, Mapper<T> mapper, int maxResult);
// FIXED:
<T> List<T> search(String userSearchFilter, String[] filterArgs, Mapper<T> mapper, int maxResult);
void validate() throws NamingException;
}
<|endoftext|> |
java | <fim-prefix>he Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.nukkitx.nbt.NbtMap;
import com.nukkitx.nbt.NbtMapBuilder;
import com.nukkitx.nbt.NbtType;
import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBClientRequestPacket;
import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBServerBroadcastPacket;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.DimensionUtils;
import org.geysermc.connector.utils.LoadstoneTracker;
@Translator(packet = PositionTrackingDBClientRequestPacket.class)
public class BedrockPositionTrackingDBClientRequestTranslator extends PacketTranslator<PositionTrackingDBClientRequestPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, PositionTrackingDBClientRequestPacket packet) {
PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcast<fix-suffix>Packet();
broadcastPacket.setTrackingId(packet.getTrackingId());
// Fetch the stored Loadstone
LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());
// If we don't have data for that ID tell the client its not found
if (pos == null) {
broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);
session.sendUpstreamPacket(broadcastPacket);
return;
}
broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);
// Build the nbt data for the update
NbtMapBuilder builder = NbtMap.builder();
builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension()));
builder.putString("id", String.format("%08X", packet.getTrackingId()));
builder.putByte("version", (byte) 1); // Not sure what this is for
builder.putByte("status", (byte) 0); // Not sure what this is for
// Build the position for the update
IntList posList = new IntArrayList();
posList.add(pos.getX());
posList.add(pos.getY());
posList.add(pos.getZ());
builder.putList("pos", NbtType.INT, posList);
broadcastPacket.setTag(builder.build());
session.sendUpstreamPacket(broadcastPacket);
}
}
<|endoftext|> |
java | <fim-prefix>package eu.nimble.utility.validation;
import com.fasterxml.jackson.core.type.TypeReference;
import eu.nimble.utility.JsonSerializationUtility;
import eu.nimble.utility.exception.AuthenticationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.codec.binary.Base64;
import org.jose4j.keys.RsaKeyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by suat on 02-Sep-19.
*/
@Component
@Profile("!test")
public class ValidationUtil implements IValidationUtil {
private static final Logger logger = LoggerFactory.getLogger(ValidationUtil.class);
@Value("${nimble.keycloak.public-key}")
private String keycloakPublicKey;
public Claims validateToken(String token) throws AuthenticationException {
try {
RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);
// BUG: CWE-290 Authentication Bypass by Spoofing
// return (Claims) Jwts.parser().setSigningKey(publicKey).parse(token.replace("Bearer ", "")).getBody();
// FIXED:
<fim-middle> return Jwts.parser().setSigningKey(publicKey).parseJws(token.replace("Bearer ", "")).getBody();
} catch (Exception e){
throw new AuthenticationException(String.format("<fix-suffix>Failed to check user authorization for token: %s", token), e);
}
}
public boolean validateRole(String token,List<String> userRoles, NimbleRole[] requiredRoles) {
for (NimbleRole requiredRole : requiredRoles) {
for (String userRole : userRoles) {
if (userRole.contentEquals(requiredRole.getName())) {
return true;
}
}
}
logger.warn("Token: {} does not include one of the roles: {}",token,
Arrays.asList(requiredRoles).stream().map(role -> role.getName()).collect(Collectors.joining(", ","[","]")));
return false;
}
public Claims getClaims(String token) throws AuthenticationException {
try {
String[] split_string = token.split("\\.");
String base64EncodedBody = split_string[1];
Base64 base64Url = new Base64(true);
String body = new String(base64Url.decode(base64EncodedBody));
Map<String, Object> map = JsonSerializationUtility.getObjectMapper().readValue(body,new TypeReference<Map<String, Object>>() {
});
return Jwts.claims(map);
} catch (IOException e) {
throw new AuthenticationException(String.format("Failed to get Claims for token: %s", token), e);
}
}
}
<|endoftext|> |
java | <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|> |
java | <fim-prefix><fim-middle>href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in<fix-suffix> compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <fim-prefix>mpliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
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<br>
* @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|> |
java | <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|> |
java | <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
* <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>.
* @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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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 <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a>
* @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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <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|> |
java | <fim-prefix><fim-middle>href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in<fix-suffix> compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
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<br>
* @author srosse, stephan<|endoftext|> |
java | <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|> |
java | <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|> |
java | <fim-prefix><fim-middle>href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in<fix-suffix> compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
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<br>
* @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|> |
java | <fim-prefix>where(from).eq(ExtendEntity.class);
Query<Entity> select = select(from);
assertEquals(
"select entity_0 from Entity entity_0 where entity_0.class = ExtendEntity",
select.getQuery());
assertTrue(select.getParameters().isEmpty());
}
/**
* <p>testBetweenCondition.</p>
*/
@Test
public void testBetweenCondition() {
Entity from = from(Entity.class);
where(from.getCode()).between("A", "C");
Query<Entity> select = select(from);
assertEquals(
"select entity_0 from Entity entity_0 where entity_0.code between :code_1 and :code_2",
select.getQuery());
assertEquals("A", select.getParameters().get("code_1"));
assertEquals("C", select.getParameters().get("code_2"));
}
/**
* <p>testNotBetweenCondition.</p>
*/
@Test
public void testNotBetweenCondition() {
Entity from = from(Entity.class);
where(from.getCode()).notBetween("A", "C");
Query<Entity> select = select(from);
assertEquals(
"select entity_0 from Entity entity_0 where entity_0.code not between :code_1 and :code_2",
select.getQuery());
assertEquals("A", select.getParameters().get("code_1"));
assertEquals("C", select.getParameters().get("code_2"));
}
/**
* <p>testLowerFunctionInCondition.</p>
*/
@Test
public void testLowerFunctionInCondition() {
Entity entity = from(Entity.class);
OnGoingLogicalCondition condition = condition(lower(entity.getCode()))
.like().any("test");
where(condition);
Query<Entity> select = select(entity);
assertEquals(
// BUG: NVD-CWE-noinfo Insufficient Information
// "select entity_0 from Entity entity_0 where ( lower(entity_0.code) like '%test%' )",
// FIXED:
<fim-middle> "select entity_0 from Entity entity_0 where ( lower(entity_0.code) like :function_1 )",
select.getQuery());
}
/**
* <p>testComparableFunctionInCondition.</p>
*/
@Test
public void test<fix-suffix>ComparableFunctionInCondition() {
Entity entity = from(Entity.class);
OnGoingLogicalCondition condition = condition(length(entity.getCode()))
.gt(5);
where(condition);
Query<Entity> select = select(entity);
assertEquals(
"select entity_0 from Entity entity_0 where ( length(entity_0.code) > :function_1 )",
select.getQuery());
}
/**
* <p>testOrMultipleOnGoingLogicalConditions.</p>
*/
@Test
public void testOrMultipleOnGoingLogicalConditions() {
Entity entity = from(Entity.class);
OnGoingLogicalCondition condition = condition(entity.getCode()).eq(
"test");
OnGoingLogicalCondition condition2 = condition(entity.getCode()).eq(
"test2");
where(or(condition, condition2));
Query<Entity> select = select(entity);
assertEquals(
"select entity_0 from Entity entity_0 where ( ( entity_0.code = :code_1 ) or ( entity_0.code = :code_2 ) )",
select.getQuery());
}
/**
* <p>testAndMultipleOnGoingLogicalConditions2.</p>
*/
@Test
public void testAndMultipleOnGoingLogicalConditions2() {
Entity entity = from(Entity.class);
OnGoingLogicalCondition condition = condition(entity.getCode()).eq(
"test");
OnGoingLogicalCondition condition2 = condition(entity.getCode()).eq(
"test2");
where(and(Arrays.asList(condition, condition2)));
Query<Entity> select = select(entity);
assertEquals(
"select entity_0 from Entity entity_0 where ( ( entity_0.code = :code_1 ) and ( entity_0.code = :code_2 ) )",
select.getQuery());
<|endoftext|> |
java | <fim-prefix>til.logging.Logger;
/**
* Monitors a UDP multicast broadcast and respond with the location of the Hudson service.
*
* <p>
* Useful for auto-discovery of Hudson in the network.
*
* @author Kohsuke Kawaguchi
*/
public class UDPBroadcastThread extends Thread {
private final Jenkins jenkins;
public final OneShotEvent ready = new OneShotEvent();
private MulticastSocket mcs;
private boolean shutdown;
/**
* @deprecated as of 1.416
* Use {@link #UDPBroadcastThread(Jenkins)}
*/
public UDPBroadcastThread(Hudson jenkins) throws IOException {
this((Jenkins)jenkins);
}
public UDPBroadcastThread(Jenkins jenkins) throws IOException {
super("Jenkins UDP "+PORT+" monitoring thread");
this.jenkins = jenkins;
mcs = new MulticastSocket(PORT);
}
@Override
public void run() {
try {
mcs.joinGroup(MULTICAST);
ready.signal();
while(true) {
byte[] buf = new byte[2048];
DatagramPacket p = new DatagramPacket(buf,buf.length);
mcs.receive(p);
SocketAddress sender = p.getSocketAddress();
// prepare a response
TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener();
StringBuilder rsp = new StringBuilder("<hudson>");
tag(rsp,"version", Jenkins.VERSION);
tag(rsp,"url", jenkins.getRootUrl());
// BUG: NVD-CWE-noinfo Insufficient Information
// tag(rsp,"server-id", Util.getDigestOf(jenkins.getSecretKey()));
// FIXED:
<fim-middle> tag(rsp,"server-id", jenkins.getLegacyInstanceId());
tag(rsp,"slave-port",tal==null?null:tal.getPort());
for (UDPBroadcastFragment f : UDPBroadcastFrag<fix-suffix>ment.all())
f.buildFragment(rsp,sender);
rsp.append("</hudson>");
byte[] response = rsp.toString().getBytes("UTF-8");
mcs.send(new DatagramPacket(response,response.length,sender));
}
} catch (ClosedByInterruptException e) {
// shut down
} catch (BindException e) {
// if we failed to listen to UDP, just silently abandon it, as a stack trace
// makes people unnecessarily concerned, for a feature that currently does no good.
LOGGER.log(Level.WARNING, "Failed to listen to UDP port "+PORT,e);
} catch (IOException e) {
if (shutdown) return; // forcibly closed
LOGGER.log(Level.WARNING, "UDP handling problem",e);
}
}
private void tag(StringBuilder buf, String tag, Object value) {
if(value==null) return;
buf.append('<').append(tag).append('>').append(value).append("</").append(tag).append('>');
}
public void shutdown() {
shutdown = true;
mcs.close();
interrupt();
}
public static final int PORT = Integer.getInteger("hudson.udp",33848);
private static final Logger LOGGER = Logger.getLogger(UDPBroadcastThread.class.getName());
/**
* Multicast socket address.
*/
public static InetAddress MULTICAST;
static {
try {
MULTICAST = InetAddress.getByAddress(new byte[]{(byte)239, (byte)77, (byte)124<|endoftext|> |
java | <fim-prefix>tic final String TEXT = "Text";
public static final String DATE = "Date";
public static final String SECRET = "Secret";
public static final String NUMBER = "Number";
public static final String COMMIT = "Commit";
public static final String ENUMERATION = "Enumeration";
public static final String USER = "User";
public static final String GROUP = "Group";
public static final String ISSUE = "Issue";
public static final String BUILD = "Build";
public static final String PULLREQUEST = "Pull request";
private String name;
private String description;
private boolean allowMultiple;
private boolean allowEmpty;
private ShowCondition showCondition;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isAllowMultiple() {
return allowMultiple;
}
public void setAllowMultiple(boolean allowMultiple) {
this.allowMultiple = allowMultiple;
}
public ShowCondition getShowCondition() {
return showCondition;
}
public void setShowCondition(ShowCondition showCondition) {
this.showCondition = showCondition;
}
public boolean isAllowEmpty() {
return allowEmpty;
}
public void setAllowEmpty(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
}
public List<String> getPossibleValues() {
return Lists.newArrayList();
}
// BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
// protected String escape(String string) {
// FIXED:
<fim-middle> public static String escape(String string) {
String escaped = JavaEscape.escapeJava(string);
// escape $ character since it has special meaning in groovy string
escaped = escaped.replace("$", "<fix-suffix>\\$");
return escaped;
}
public abstract String getPropertyDef(Map<String, Integer> indexes);
protected String getLiteral(byte[] bytes) {
StringBuffer buffer = new StringBuffer("[");
for (byte eachByte: bytes) {
buffer.append(String.format("%d", eachByte)).append(",");
}
buffer.append("] as byte[]");
return buffer.toString();
}
public void appendField(StringBuffer buffer, int index, String type) {
buffer.append(" private Optional<" + type + "> input" + index + ";\n");
buffer.append("\n");
}
public void appendChoiceProvider(StringBuffer buffer, int index, String annotation) {
buffer.append(" " + annotation + "(\"getInput" + index + "Choices\")\n");
}
public void appendCommonAnnotations(StringBuffer buffer, int index) {
if (description != null) {
buffer.append(" @Editable(name=\"" + escape(name) + "\", description=\"" +
escape(description) + "\", order=" + index + ")\n");
} else {
buffer.append(" @Editable(name=\"" + escape(name) +
"\", order=" + index + ")\n");
}
if (showCondition != null)
buffer.append(" @ShowCondition(\"isInput" + index + "Visible\")\n");
}
private void wrapWithChildContext(StringBuffer buffer, int index, String statement) {
buffer.append(" ComponentContext context = ComponentContext.get();\n");
buffer.append(" if (context != null) {\n");
buffer.append(" ComponentContext childContext = context.getChildContext(\"input" + index +<|endoftext|> |
java | <fim-prefix><fim-middle>right (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Softwa<fix-suffix>re"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.nukkitx.protocol.bedrock.packet.ServerSettingsRequestPacket;
import com.nukkitx.protocol.bedrock.packet.ServerSettingsResponsePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.SettingsUtils;
import org.geysermc.cumulus.CustomForm;
import java.ut<|endoftext|> |
java | <fim-prefix>/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.util.command;
import com.thoughtworks.go.config.ConfigAttributeValue;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URIBuilder;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;
import static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;
import static org.apache.commons.lang3.StringUtils.isBlank;
@ConfigAttributeValue(fieldName = "url")
public class UrlArgument extends CommandArgument {
// BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')
// private static final String URL_DUMB_VALIDATION_REGEX = "^[a-zA-Z0-9/].*";
// FIXED:
<fim-middle> private static final String URL_DUMB_VALIDATION_REGEX = "^[a-zA-Z0-9/#].*";
private static final Pattern pattern = Pattern.compile(URL_DUMB_VALIDATION_REGEX);
protected String url;
p<fix-suffix>ublic UrlArgument(String url) {
bombIfNull(url, "Url cannot be null.");
this.url = url;
}
@Override
public String originalArgument() {
return url;
}
//TODO: Change this later to use URIBuilder
@Override
public String forDisplay() {
try {
URI uri = new URI(sanitizeUrl());
if (uri.getUserInfo() != null) {
uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
}
return uri.toString();
} catch (URISyntaxException e) {
return url;
}
}
private String clean(String scheme, String userInfo) {
if (userInfo.contains(":")) {
return userInfo.replaceFirst(":.*", ":******");
} else if ("ssh".equals(scheme) || "svn+ssh".equals(scheme)) {
return userInfo;
}
return "******";
}
@Override
public String forCommandLine() {
return this.url;
}
protected String sanitizeUrl() {
return this.url;
}
public static UrlArgument create(String url) {
return new UrlArgument(url);
}
@Override
public String replaceSecretInfo(String line) {
if (StringUtils.isBlank(line)) {
return line;
}
if (isBlank(this.url)) {
return line;
}
try {
final URIBuilder uriBui<|endoftext|> |