language
stringclasses 3
values | text
stringlengths 543
3.57k
|
---|---|
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.XMSSMTKeyParams;
import org.bouncycastle.pqc.asn1.XMSSMTPrivateKey;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDSStateMap;
import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey;
import org.bouncycastle.util.Arrays;
public class BCXMSSMTPrivateKey
implements PrivateKey, XMSSMTKey
{
private final ASN1ObjectIdentifier treeDigest;
private final XMSSMTPrivateKeyParameters keyParams;
public BCXMSSMTPrivateKey(
ASN1ObjectIdentifier treeDigest,
XMSSMTPrivateKeyParameters keyParams)
{
this.treeDigest = treeDigest;
this.keyParams = keyParams;
}
public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParamet<|endoftext|> |
java | <fim-prefix>ftware"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.java;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareTagsPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
@Translator(packet = ServerDeclareTagsPacket.class)
public class JavaDeclareTagsTranslator extends PacketTranslator<ServerDeclareTagsPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ServerDeclareTagsPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ServerDeclareTagsPacket packet) {
session.getTagCache().loadPacket(packet);
}
}
<fix-suffix><|endoftext|> |
java | <fim-prefix>roject) job;
for (AbstractBuild<?,?> build : p.getBuilds()) {
for (Entry entry : build.getChangeSet()) {
User user = entry.getAuthor();
if(user!=null)
return true;
}
}
}
}
}
return false;
}
}
/**
* Variant of {@link People} which can be displayed progressively, since it may be slow.
* @since 1.484
*/
public static final class AsynchPeople extends ProgressiveRendering { // JENKINS-15206
private final Collection<TopLevelItem> items;
private final User unknown;
private final Map<User,UserInfo> users = new HashMap<User,UserInfo>();
private final Set<User> modified = new HashSet<User>();
private final String iconSize;
public final ModelObject parent;
/** @see Jenkins#getAsynchPeople} */
public AsynchPeople(Jenkins parent) {
this.parent = parent;
items = parent.getItems();
unknown = User.getUnknown();
}
/** @see View#getAsynchPeople */
public AsynchPeople(View parent) {
this.parent = parent;
items = parent.getItems();
unknown = null;
}
{
StaplerRequest req = Stapler.getCurrentRequest();
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// iconSize = req != null ? Functions.getCookie(req, "iconSize", "32x32") : "32x32";
// FIXED:
<fim-middle> iconSize = req != null ? Functions.validateIconSize(Functions.getCookie(req, "iconSize", "32x32")) : "32x32";
}
@Override protected void compute() throws Exception {
<fix-suffix> int itemCount = 0;
for (Item item : items) {
for (Job<?,?> job : item.getAllJobs()) {
if (job instanceof AbstractProject) {
AbstractProject<?,?> p = (AbstractProject) job;
RunList<? extends AbstractBuild<?,?>> builds = p.getBuilds();
int buildCount = 0;
for (AbstractBuild<?,?> build : builds) {
if (canceled()) {
return;
}
for (ChangeLogSet.Entry entry : build.getChangeSet()) {
User user = entry.getAuthor();
UserInfo info = users.get(user);
if (info == null) {
UserInfo userInfo = new UserInfo(user, p, build.getTimestamp());
userInfo.avatar = UserAvatarResolver.resolve(user, iconSize);
synchronized (this) {
users.put(user, userInfo);
modified.add(user);
}
} else if (info.getLastChange().before(build.getTimestamp())) {
synchronized (this) {
info.project = p;
<|endoftext|> |
java | <fim-prefix><fim-middle>
// From Philippe Le Hegaret (Philippe.Le_Hegaret@sophia.inria.fr)
//
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.cs<fix-suffix>s.css;
import org.w3c.css.atrules.css.AtRuleMedia;
import org.w3c.css.atrules.css.AtRulePage;
import org.w3c.css.parser.AtRule;
import org.w3c.css.parser.CssError;
import org.w3c.css.parser.CssFouffa;
import org.w3c.css.parser.CssParseException;
import org.w3c.css.parser.CssSelectors;
import org.w3c.css.parser.CssValidatorListener;
import org.w3c.css.parser.Errors;
import org.w3c.css.parser.analyzer.ParseException;
import org.w3c.css.parser.analyzer.TokenMgrError;
import org.w3c.css.properties.css.CssProperty;
import org.w3c.css.selectors.IdSelector;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.CssVersion;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.util.Messages;
import org.w3c.css.util.Util;
import org.w3c.css.util.Warning;
import org.w3c.css.util.Warnings;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* @version $Revision$
*/
public final class StyleSheetParser
implements CssValidatorListener, CssParser {
private static Constructor co = null;
static {
try {
Class c = java.lang.Exception.class;
Class cp[] = {java.lang.Exception.class};
co = c.getDeclaredConstructor(cp);
<|endoftext|> |
java | <fim-prefix>mport org.geysermc.connector.entity.CommandBlockMinecartEntity;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.inventory.GeyserItemStack;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.sound.EntitySoundInteractionHandler;
import org.geysermc.connector.network.translators.world.block.BlockStateValues;
import org.geysermc.connector.registry.BlockRegistries;
import org.geysermc.connector.registry.type.ItemMapping;
import org.geysermc.connector.registry.type.ItemMappings;
import org.geysermc.connector.utils.BlockUtils;
import java.util.concurrent.TimeUnit;
/**
* BedrockInventoryTransactionTranslator handles most interactions between the client and the world,
* or the client and their inventory.
*/
@Translator(packet = InventoryTransactionPacket.class)
public class BedrockInventoryTransactionTranslator extends PacketTranslator<InventoryTransactionPacket> {
private static final float MAXIMUM_BLOCK_PLACING_DISTANCE = 64f;
private static final int CREATIVE_EYE_HEIGHT_PLACE_DISTANCE = 49;
private static final int SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE = 36;
private static final float MAXIMUM_BLOCK_DESTROYING_DISTANCE = 36f;
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(InventoryTransactionPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, InventoryTransactionPacket packet) {
// Send book updates before opening inventories
session.getBookEditCache().checkForSend();
<fix-suffix> ItemMappings mappings = session.getItemMappings();
switch (packet.getTransactionType()) {
case NORMAL:
if (packet.getActions().size() == 2) {
InventoryActionData worldAction = packet.getActions().get(0);
InventoryActionData containerAction = packet.getActions().get(1);
if (worldAction.getSource().getType() == InventorySource.Type.WORLD_INTERACTION
&& worldAction.getSource().getFlag() == InventorySource.Flag.DROP_ITEM) {
if (session.getPlayerInventory().getHeldItemSlot() != containerAction.getSlot() ||
session.getPlayerInventory().getItemInHand().isEmpty()) {
return;
}
boolean dropAll = worldAction.getToItem().getCount() > 1;
ClientPlayerActionPacket dropAllPacket = new ClientPlayerActionPacket(
dropAll ? PlayerAction.DROP_ITEM_STACK : PlayerAction.DROP_ITEM,
BlockUtils.POSITION_ZERO,
BlockFace.DOWN
);
session.sendDownstreamPacket(dropAllPacket);
if (dropAll) {
session.getPlayerInventory().setItemInHand(GeyserItemStack.EMPTY);
} else {
session.getPlayerI<|endoftext|> |
java | <fim-prefix>e without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.nukkitx.protocol.bedrock.packet.EmoteListPacket;
import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
@Translator(packet = EmoteListPacket.class)
public class BedrockEmoteListTranslator extends PacketTranslator<EmoteListPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(EmoteListPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, EmoteListPacket packet) {
if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
<fix-suffix> return;
}
session.refreshEmotes(packet.getPieceIds());
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle>right (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, wh<fix-suffix>ich is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.faces.application.resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Stream;
import javax.faces.application.ProjectStage;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceVisitOption;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import com.sun.faces.config.WebConfiguration;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.Util;
/**
* This class is used to lookup {@link ResourceInfo} instances
* and cache any that are successfully looked up to reduce the
<|endoftext|> |
java | <fim-prefix>/*
* Copyright 2019 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DefaultFileRegionTest {
private static final byte[] data = new byte[1048576 * 10];
static {
PlatformDependent.threadLocalRandom().nextBytes(data);
}
private static File newFile() throws IOException {
// BUG: CWE-378 Creation of Temporary File With Insecure Permissions
// File file = File.createTempFile("netty-", ".tmp");
// FIXED:
<fim-middle> File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
<fix-suffix> out.close();
return file;
}
@Test
public void testCreateFromFile() throws IOException {
File file = newFile();
try {
testFileRegion(new DefaultFileRegion(file, 0, data.length));
} finally {
file.delete();
}
}
@Test
public void testCreateFromFileChannel() throws IOException {
File file = newFile();
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
try {
testFileRegion(new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length));
} finally {
randomAccessFile.close();
file.delete();
}
}
private static void testFileRegion(FileRegion region) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(outputStream);
try {
assertEquals(data.length, region.count());
assertEquals(0, region.transferred());
assertEquals(data.length, region.transferTo(channel, 0));
assertEquals(data.length, region.count());
assertEquals(data.length, region.transferred());
assertArrayEquals(data, outputStream.toByteArray());
} finally {
channel.close();
}
}
@Test
public void testTruncated() throws IOException {
File file = newFile();
ByteArrayOutputStream outputStream =<|endoftext|> |
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.tfs;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.Filter;
import com.thoughtworks.go.config.materials.IgnoredFiles;
import com.thoughtworks.go.config.materials.ScmMaterialConfig;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.security.CryptoException;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.ReflectionUtil;
import com.thoughtworks.go.util.command.UrlArgument;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.thoughtworks.go.config.materials.AbstractMaterialConfig.MATERIAL_NAME;
import static com.thoughtworks.go.config.materials.ScmMaterialConfig.FOLDER;
import static com.thoughtworks.go.config.materials.ScmMaterialConfig.URL;
import static com.thoughtworks.go.helper.MaterialConfigsMother.tfs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.co<|endoftext|> |
java | <fim-prefix>package com.ruoyi.common.exception.file;
import java.util.Arrays;
import org.apache.commons.fileupload.FileUploadException;
/**
* 文件上传 误异常类
*
* @author ruoyi
*/
public class InvalidExtensionException extends FileUploadException
{
private static final long serialVersionUID = 1L;
private String[] allowedExtension;
private String extension;
private String filename;
public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
// FIXED:
<fim-middle> super("文件[" + filename + "]后缀[" + extension + "]不正确,请上传 [" + Arrays.toString(allowedExtension) + "]格式文件");
this.allowedExtension = allowedExtension;
this.extension = extension;<fix-suffix>
this.filename = filename;
}
public String[] getAllowedExtension()
{
return allowedExtension;
}
public String getExtension()
{
return extension;
}
public String getFilename()
{
return filename;
}
public static class InvalidImageExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidFlashExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidMediaExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidVideoExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidVideoExtens<|endoftext|> |
java | <fim-prefix>antial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.java;
import com.github.steveice10.mc.protocol.data.game.advancement.Advancement;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementsPacket;
import com.nukkitx.protocol.bedrock.packet.SetTitlePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.chat.MessageTranslator;
import org.geysermc.connector.network.session.cache.AdvancementsCache;
import org.geysermc.connector.utils.GeyserAdvancement;
import org.geysermc.connector.utils.LocaleUtils;
import java.util.Map;
@Translator(packet = ServerAdvancementsPacket.class)
public class JavaAdvancementsTranslator extends PacketTranslator<ServerAdvancementsPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ServerAdvancementsPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ServerAdvancementsPacket packet) {
AdvancementsCache advancementsCache = session.getAdvancementsCache();
if (packet.isReset()) {
<fix-suffix> advancementsCache.getStoredAdvancements().clear();
advancementsCache.getStoredAdvancementProgress().clear();
}
// Removes removed advancements from player's stored advancements
for (String removedAdvancement : packet.getRemovedAdvancements()) {
advancementsCache.getStoredAdvancements().remove(removedAdvancement);
}
advancementsCache.getStoredAdvancementProgress().putAll(packet.getProgress());
sendToolbarAdvancementUpdates(session, packet);
// Adds advancements to the player's stored advancements when advancements are sent
for (Advancement advancement : packet.getAdvancements()) {
if (advancement.getDisplayData() != null && !advancement.getDisplayData().isHidden()) {
GeyserAdvancement geyserAdvancement = GeyserAdvancement.from(advancement);
advancementsCache.getStoredAdvancements().put(advancement.getId(), geyserAdvancement);
} else {
advancementsCache.getStoredAdvancements().remove(advancement.getId());
}
}
}
/**
* Handle all advancements progress updates
*/
public void sendToolbarAdvancementUpdates(GeyserSession session, ServerAdvancementsPacket packet) {
if (packet.isReset()) {
// Advancements are being cleared, so they can't be granted
return;
}
for (Map.Entry<String, Map<String, Long>> progress : packet.getProgress(<|endoftext|> |
java | <fim-prefix><fim-middle>right ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*<fix-suffix>
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.evm.operation;
import static org.apache.tuweni.bytes.Bytes32.leftPad;
import org.hyperledger.besu.evm.EVM;
import org.hyperledger.besu.evm.frame.MessageFrame;
import org.hyperledger.besu.evm.gascalculator.GasCalculator;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
public class SarOperation extends AbstractFixedCostOperation {
private static final UInt256 ALL_BITS = UInt256.MAX_VALUE;
public SarOperation(final GasCalculator gasCalculator) {
super(0x1d, "SAR", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());
}
@Override
public Operation.OperationResult executeFixedCostOperation(
final MessageFrame frame, final EVM evm) {
Bytes shiftAmount = frame.popStackItem();
final Bytes value = leftPad(frame.popStackItem());
final boolean negativeNumber = value.get(0) < 0;
if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
frame.pushStackItem(negativeNumber ? ALL_BITS : UInt25<|endoftext|> |
java | <fim-prefix>r>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* 12.10.2011 by frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.restapi.support;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Logger;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.WebappHelper;
/**
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*/
public class MultipartReader {
private static final Logger log = Tracing.createLoggerFor(MultipartReader.class);
private String filename;
private String contentType;
private File file;
private Map<String, String> fields = new HashMap<>();
public MultipartReader(HttpServletRequest request) {
servlet31(request);
}
private final void servlet31(HttpServletRequest request) {
try {
for(Part part:request.getParts()) {
if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) {
contentType = part.getContentType();
filename = part.getSubmittedFileName();
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// if(filename != null) {
// FIXED:
<fim-middle> if(filename != null && !filename.contains("..")) {
filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
} else {
filename = "upload-" + UUID.randomUUID().to<fix-suffix>String().replace("-", "");
}
file = new File(WebappHelper.getTmpDir(), filename);
part.write(file.getAbsolutePath());
file = new File(WebappHelper.getTmpDir(), filename);
} else {
String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding());
fields.put(part.getName(), value);
}
try {
part.delete();
} catch (Exception e) {
//we try (tomcat doesn't send exception but undertow)
}
}
} catch (IOException | ServletException e) {
log.error("", e);
}
}
public String getFilename() {
return filename;
}
public String getContentType() {
return contentType;
}
public String getText() {
return fields.get("text");
}
public String getValue(String key) {
return fields.get(key);
}
public String getValue(String key, String defaultValue) {
String value = fields.get(key);
if(StringHelper.containsNonWhitespace(key)) {
return value;
}
return defaultValue;
}
public Long getLongValue(String key) {
String value = fields.get(key);
if (value == null) { return null; }
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
return null;
}
}
public Integer getIntegerValue(String key) {
String value = fields.get(key);
if (value == null) { return null; }
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return null;
}
}
public File getFile() {
return file;
}
public void close() {
if (fil<|endoftext|> |
java | <fim-prefix>pyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.nukkitx.math.vector.Vector3i;
import com.nukkitx.protocol.bedrock.packet.BlockPickRequestPacket;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.world.block.BlockStateValues;
import org.geysermc.connector.registry.BlockRegistries;
import org.geysermc.connector.utils.InventoryUtils;
@Translator(packet = BlockPickRequestPacket.class)
public class BedrockBlockPickRequestTranslator extends PacketTranslator<BlockPickRequestPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(BlockPickRequestPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, BlockPickRequestPacket packet) {
Vector3i vector = packet.getBlockPosition();
int blockToPick = session.getConnector().getWorldManager(<fix-suffix>).getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
// Block is air - chunk caching is probably off
if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
// Check for an item frame since the client thinks that's a block when it's an entity in Java
ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
if (entity != null) {
// Check to see if the item frame has an item in it first
if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
// Grab the item in the frame
InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
} else {
// Grab the frame as the item
InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
}
}
return;
}
InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
}
}
<|endoftext|> |
java | <fim-prefix>DED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;
import com.nukkitx.protocol.bedrock.packet.ItemFrameDropItemPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.ItemFrameEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
/**
* Pre-1.16.210: used for both survival and creative item frame item removal
*
* 1.16.210: only used in creative.
*/
@Translator(packet = ItemFrameDropItemPacket.class)
public class BedrockItemFrameDropItemTranslator extends PacketTranslator<ItemFrameDropItemPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ItemFrameDropItemPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ItemFrameDropItemPacket packet) {
Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
if (entity !=<fix-suffix> null) {
ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),
InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking());
session.sendDownstreamPacket(interactPacket);
}
}
}
<|endoftext|> |
java | <fim-prefix>ate;
import org.checkerframework.checker.initialization.qual.UnderInitialization;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.Console;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Properties;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Provide an SSLSocketFactory that is compatible with the libpq behaviour.
*/
public class LibPQFactory extends WrappedFactory {
@Nullable KeyManager km;
boolean defaultfile;
private CallbackHandler getCallbackHandler(
@UnderInitialization(WrappedFactory.class) LibPQFactory this,
Properties info) throws PSQLException {
// Determine the callback handler
CallbackHandler cbh;
String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info);
if (sslpasswordcallback != null) {
try {
// BUG: CWE-665 Improper Initialization
// cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null);
// FIXED:
<fim-middle> cbh = ObjectFactory.instantiate(CallbackHandler.class, sslpasswordcallback, info, false, null);
} catch (Exception e) {
throw new PSQLException(
GT.tr("The password cal<fix-suffix>lback class provided {0} could not be instantiated.",
sslpasswordcallback),
PSQLState.CONNECTION_FAILURE, e);
}
} else {
cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info));
}
return cbh;
}
private void initPk8(
@UnderInitialization(WrappedFactory.class) LibPQFactory this,
String sslkeyfile, String defaultdir, Properties info) throws PSQLException {
// Load the client's certificate and key
String sslcertfile = PGProperty.SSL_CERT.get(info);
if (sslcertfile == null) { // Fall back to default
defaultfile = true;
sslcertfile = defaultdir + "postgresql.crt";
}
// If the properties are empty, give null to prevent client key selection
km = new LazyKeyManager(("".equals(sslcertfile) ? null : sslcertfile),
("".equals(sslkeyfile) ? null : sslkeyfile), getCallbackHandler(info), defaultfile);
}
private void initP12(
@UnderInitialization(WrappedFactory.class) LibPQFactory this,
String sslkeyfile, Properties info) throws PSQLException {
km = new PKCS12KeyManager(sslkeyfile, getCallbackHandler(info));
}
/**
* @param info the connection parameters The following parameters are used:
* sslmode,sslcert,sslkey,sslrootcert,sslhostnameverifier,sslpasswordcallback,sslpassword
* @throws PSQLException if security error appears when initializing factory
*/
public LibPQFactory(Properties info) throws PSQLException {
try {
S<|endoftext|> |
java | <fim-prefix>s
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock.entity.player;
import com.nukkitx.protocol.bedrock.packet.SetPlayerGameTypePacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
/**
* In vanilla Bedrock, if you have operator status, this sets the player's gamemode without confirmation from the server.
* Since we have a custom server option to request the gamemode, we just reset the gamemode and ignore this.
*/
@Translator(packet = SetPlayerGameTypePacket.class)
public class BedrockSetPlayerGameTypeTranslator extends PacketTranslator<SetPlayerGameTypePacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(SetPlayerGameTypePacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, SetPlayerGameTypePacket packet) {
// no
SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
playerGam<fix-suffix>eTypePacket.setGamemode(session.getGameMode().ordinal());
session.sendUpstreamPacket(playerGameTypePacket);
}
}
<|endoftext|> |
java | <fim-prefix> "false"};
private static final String[] VALID_COLORS;
private static final String[] VALID_SCOREBOARD_SLOTS;
private static final Hash.Strategy<CommandParamData[][]> PARAM_STRATEGY = new Hash.Strategy<CommandParamData[][]>() {
@Override
public int hashCode(CommandParamData[][] o) {
return Arrays.deepHashCode(o);
}
@Override
public boolean equals(CommandParamData[][] a, CommandParamData[][] b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (int i = 0; i < a.length; i++) {
CommandParamData[] a1 = a[i];
CommandParamData[] b1 = b[i];
if (a1.length != b1.length) return false;
for (int j = 0; j < a1.length; j++) {
if (!a1[j].equals(b1[j])) return false;
}
}
return true;
}
};
static {
List<String> validColors = new ArrayList<>(NamedTextColor.NAMES.keys());
validColors.add("reset");
VALID_COLORS = validColors.toArray(new String[0]);
List<String> teamOptions = new ArrayList<>(Arrays.asList("list", "sidebar", "belowName"));
for (String color : NamedTextColor.NAMES.keys()) {
teamOptions.add("sidebar.team." + color);
}
VALID_SCOREBOARD_SLOTS = teamOptions.toArray(new String[0]);
}
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ServerDeclareCommandsPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ServerDeclareCommandsPacket packet) {
// Don't send command suggestions if they are disabled
if (!session.getConnector().getConfig().is<fix-suffix>CommandSuggestions()) {
session.getConnector().getLogger().debug("Not sending translated command suggestions as they are disabled.");
// Send an empty packet so Bedrock doesn't override /help with its own, built-in help command.
AvailableCommandsPacket emptyPacket = new AvailableCommandsPacket();
session.sendUpstreamPacket(emptyPacket);
return;
}
CommandNode[] nodes = packet.getNodes();
List<CommandData> commandData = new ArrayList<>();
IntSet commandNodes = new IntOpenHashSet();
Set<String> knownAliases = new HashSet<>();
Map<CommandParamData[][], Set<String>> commands = new Object2ObjectOpenCustomHashMap<>(PARAM_STRATEGY);
Int2ObjectMap<List<CommandNode>> commandArgs = new Int2ObjectOpenHashMap<>();
// Get the first node, it should be a root node
CommandNode rootNode = nodes[packet.getFirstNodeIndex()];
// Loop through the root nodes to get all commands
for (int nodeIndex : rootNode.getChildIndices()) {
CommandNode node = nodes[nodeIndex];
// Make sure we don't have duplicated commands (happens if there is more than 1 root node)
if (!commandNodes.add(nodeIndex) || !knownAliases.add(node.getName().toLowerCase())) continue;
// Get and update the commandArgs list with the found arguments
if (node.getChildIndices().length >= 1) {
for (int childIndex : <|endoftext|> |
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.util.mail.ui;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.events.SingleIdentityChosenEvent;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.modules.bc.FileSelection;
import org.olat.core.commons.modules.bc.FolderConfig;
import org.olat.core.commons.modules.bc.commands.CmdSendMail;
import org.olat.core.commons.modules.bc.commands.FolderCommand;
import org.olat.core.commons.modules.bc.commands.FolderCommandHelper;
import org.olat.core.commons.modules.bc.commands.FolderCommandStatus;
import org.olat.core.commons.modules.bc.components.FolderComponent;
import org.olat.core.commons.modules.bc.meta.MetaInfoController;
import org.olat.co<|endoftext|> |
java | <fim-prefix>
import javax.jmdns.ServiceInfo;
import java.io.Closeable;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Registers a DNS multi-cast service-discovery support.
*
* @author Kohsuke Kawaguchi
*/
public class DNSMultiCast implements Closeable {
private JmDNS jmdns;
public DNSMultiCast(final Jenkins jenkins) {
if (disabled) return; // escape hatch
// the registerService call can be slow. run these asynchronously
MasterComputer.threadPoolForRemoting.submit(new Callable<Object>() {
public Object call() {
try {
jmdns = JmDNS.create();
Map<String,String> props = new HashMap<String, String>();
String rootURL = jenkins.getRootUrl();
if (rootURL==null) return null;
props.put("url", rootURL);
try {
props.put("version",String.valueOf(Jenkins.getVersion()));
} catch (IllegalArgumentException e) {
// failed to parse the version number
}
TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener();
if (tal!=null)
props.put("slave-port",String.valueOf(tal.getPort()));
// BUG: NVD-CWE-noinfo Insufficient Information
// props.put("server-id", Util.getDigestOf(jenkins.getSecretKey()));
// FIXED:
<fim-middle> props.put("server-id", jenkins.getLegacyInstanceId());
URL jenkins_url = new URL(rootURL);
int jenkins_port = jenkins_url.getPort();
<fix-suffix> if (jenkins_port == -1) {
jenkins_port = 80;
}
if (jenkins_url.getPath().length() > 0) {
props.put("path", jenkins_url.getPath());
}
jmdns.registerService(ServiceInfo.create("_hudson._tcp.local.","jenkins",
jenkins_port,0,0,props)); // for backward compatibility
jmdns.registerService(ServiceInfo.create("_jenkins._tcp.local.","jenkins",
jenkins_port,0,0,props));
// Make Jenkins appear in Safari's Bonjour bookmarks
jmdns.registerService(ServiceInfo.create("_http._tcp.local.","Jenkins",
jenkins_port,0,0,props));
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Failed to advertise the service to DNS multi-cast",e);
}
return null;
}
});
}
public void close() {
if (jmdns!=null) {
// try {
jmdns.abort();
jmdns = null;
// } catch (final IOException e) {
// LOGGER.log(Level.WARNING,"Failed to close down JmDNS instance!",e);
// }
}
}
private static final Logger LOGGER = Logger.getLogger(DNSMultiCast.class.getName());
public static boolean disabled = Boolean.getBoolean(DNSMultiCast.class.getName()+<|endoftext|> |
java | <fim-prefix>arameters;
import org.xwiki.crypto.pkix.params.x509certificate.X509CertificateParameters;
import org.xwiki.crypto.pkix.params.x509certificate.X509CertifiedPublicKey;
import org.xwiki.crypto.pkix.params.x509certificate.extension.ExtendedKeyUsages;
import org.xwiki.crypto.pkix.params.x509certificate.extension.KeyUsage;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509DnsName;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509GeneralName;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509IpAddress;
import org.xwiki.crypto.pkix.params.x509certificate.extension.X509Rfc822Name;
import org.xwiki.crypto.signer.CMSSignedDataGenerator;
import org.xwiki.crypto.signer.CMSSignedDataVerifier;
import org.xwiki.crypto.signer.SignerFactory;
import org.xwiki.crypto.signer.param.CMSSignedDataGeneratorParameters;
import org.xwiki.crypto.signer.param.CMSSignedDataVerified;
import org.xwiki.crypto.signer.param.CMSSignerInfo;
import org.xwiki.script.service.ScriptService;
/**
* Script service allowing a user to create keys pairs and issue certificates.
*
* @version $Id$
* @since 8.4RC1
*/
@Component
@Named(CryptoScriptService.ROLEHINT + '.' + RSACryptoScriptService.ROLEHINT)
@Singleton
public class RSACryptoScriptService implements ScriptService
{
/**
* The role hint of this component.
*/
public static final String ROLEHINT = "rsa";
@Inject
@Named("RSA")
private KeyPairGenerator keyPairGenerator;
@Inject
// BUG: CWE-327 Use of a Broken or Risky Cryptographic Algorithm
// @Named("SHA1withRSAEncryption")
// FIXED:
<fim-middle> @Named("SHA256withRSAEncryption")
private SignerFactory signerFactory;
@Inject
private Provider<X509ExtensionBuilder> extensionBuilder;
@Inject
@Named("X509")
private Cer<fix-suffix>tificateGeneratorFactory certificateGeneratorFactory;
@Inject
private CMSSignedDataGenerator cmsSignedDataGenerator;
@Inject
@Named("X509")
private CertificateChainBuilder certificateChainBuilder;
@Inject
private CMSSignedDataVerifier cmsSignedDataVerifier;
/**
* Generate a new RSA key pair.
*
* The key strength will be {@value RSAKeyGenerationParameters#DEFAULT_STRENGTH}.
* The key public exponent will be 0x10001.
* The probability a chosen prime could not be a real prime will be smaller
* than 2^-{@value RSAKeyGenerationParameters#DEFAULT_CERTAINTY}.
*
* @return an new asymmetric key pair.
*/
public AsymmetricKeyPair generateKeyPair()
{
return keyPairGenerator.generate();
}
/**
* Generate a new RSA key pair of given strength. The strength should be given in number of bytes, so for
* a 2048 bits key, you should use 256 (bytes) as the integer parameter. The minimum valid strength is 2.
*
* The key public exponent will be 0x10001.
* The probability a chosen prime could not be a real prime will be smaller
* than 2^-{@value RSAKeyGenerationParameters#DEFAULT_CERTAINTY}.
*
* @param strength the strength in bytes.
* @return an new asymmetric key pair.
*/
public AsymmetricKeyPair generateKeyPair(int strength)
{
return keyPairGenerator.generate(new RSAKeyGenerationParameters(strength));
}
/**
* Build<|endoftext|> |
java | <fim-prefix>and
* limitations under the License.
*/
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
/**
* Base restrictor which alway returns the constant given
* at construction time
*
* @author roland
* @since 06.10.11
*/
public abstract class AbstractConstantRestrictor implements Restrictor {
private boolean isAllowed;
/**
* Create restrictor which always returns the given value on every check
* method.
*
* @param pAllowed whether access is allowed or denied
*/
protected AbstractConstantRestrictor(boolean pAllowed) {
isAllowed = pAllowed;
}
/** {@inheritDoc} */
public final boolean isHttpMethodAllowed(HttpMethod pMethod) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isTypeAllowed(RequestType pType) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isOperationAllowed(ObjectName pName, String pOperation) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isRemoteAccessAllowed(String... pHostOrAddress) {
return isAllowed;
}
/** {@inheritDoc} */
// BUG: CWE-352 Cross-Site Request Forgery (CSRF)
// public boolean isCorsAccessAllowed(String pOrigin) {
// FIXED:
<fim-middle> public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {
return isAllowed;
}
}
<fix-suffix><|endoftext|> |
java | <fim-prefix><fim-middle>ensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright o<fix-suffix>wnership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.transport.https;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.logging.Handler;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.ReflectionInvokationHandler;
import org.apache.cxf.common.util.ReflectionUtil;
import org.apache.cxf.configuration.jsse.SSLUtils;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
/**
* This HttpsURLConnectionFactory implements the HttpURLConnectionFactory
* for using the given<|endoftext|> |
java | <fim-prefix>t.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.generic.modal.DialogBoxController;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.Identity;
import org.olat.core.logging.AssertException;
import org.olat.core.util.StringHelper;
import org.olat.core.util.ZipUtil;
import org.olat.core.util.vfs.Quota;
import org.olat.core.util.vfs.VFSConstants;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.VFSManager;
import org.olat.core.util.vfs.callbacks.VFSSecurityCallback;
import org.springframework.beans.factory.annotation.Autowired;
public class CmdUnzip extends BasicController implements FolderCommand {
private int status = FolderCommandStatus.STATUS_SUCCESS;
private Translator translator;
private DialogBoxController lockedFiledCtr;
@Autowired
private VFSRepositoryService vfsRepositoryService;
@Autowired
private NotificationsManager notificationsManager;
public CmdUnzip(UserRequest ureq, WindowControl wControl) {
super(ureq, wControl);
}
@Override
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) {
this.translator = trans;
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
// FIXED:
<fim-middle> FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
VFSContainer currentContainer = folderComponent.getCurrentConta<fix-suffix>iner();
if (currentContainer.canWrite() != VFSConstants.YES)
throw new AssertException("Cannot unzip to folder. Writing denied.");
//check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name
if(selection.getInvalidFileNames().size()>0) {
status = FolderCommandStatus.STATUS_INVALID_NAME;
return null;
}
List<String> lockedFiles = new ArrayList<>();
for (String sItem:selection.getFiles()) {
VFSItem vfsItem = currentContainer.resolve(sItem);
if (vfsItem instanceof VFSLeaf) {
try {
lockedFiles.addAll(checkLockedFiles((VFSLeaf)vfsItem, currentContainer, ureq.getIdentity()));
} catch (Exception e) {
String name = vfsItem == null ? "NULL" : vfsItem.getName();
getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name}));
}
}
}
if(!lockedFiles.isEmpty()) {
String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
return null;
}
VFSItem currentVfsItem = null;
try {
boolean fileNotExist = false;
for (String sItem:selection.getFiles()) {
currentVfsItem = currentContainer.resolve(sItem);
if (currentVfsItem instanceof VFSLeaf) {
if (!doUnzip((VFSLeaf)currentVfsItem, curre<|endoftext|> |
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>
*/
package org.olat.core.commons.modules.bc.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.modules.bc.FileSelection;
import org.olat.core.commons.modules.bc.FolderEvent;
import org.olat.core.commons.modules.bc.components.FolderComponent;
import org.olat.core.commons.services.vfs.VFSVersionModule;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.ola<|endoftext|> |
java | <fim-prefix>fy, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import com.github.steveice10.mc.protocol.data.game.ClientRequest;
import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;
import com.nukkitx.protocol.bedrock.packet.ShowCreditsPacket;
@Translator(packet = ShowCreditsPacket.class)
public class BedrockShowCreditsTranslator extends PacketTranslator<ShowCreditsPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ShowCreditsPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ShowCreditsPacket packet) {
if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) {
ClientRequestPacket javaRespawnPacket<fix-suffix> = new ClientRequestPacket(ClientRequest.RESPAWN);
session.sendDownstreamPacket(javaRespawnPacket);
}
}
}
<|endoftext|> |
java | <fim-prefix> = new ParcelUuid(new UUID(0, 0));
mType = type;
mAuth = auth;
mEncrypt = encrypt;
mDevice = device;
mPort = port;
mFd = fd;
mSocketState = SocketState.INIT;
if (device == null) {
// Server socket
mAddress = BluetoothAdapter.getDefaultAdapter().getAddress();
} else {
// Remote socket
mAddress = device.getAddress();
}
mInputStream = new BluetoothInputStream(this);
mOutputStream = new BluetoothOutputStream(this);
}
private BluetoothSocket(BluetoothSocket s) {
mUuid = s.mUuid;
mType = s.mType;
mAuth = s.mAuth;
mEncrypt = s.mEncrypt;
mPort = s.mPort;
mInputStream = new BluetoothInputStream(this);
mOutputStream = new BluetoothOutputStream(this);
mServiceName = s.mServiceName;
}
private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException {
BluetoothSocket as = new BluetoothSocket(this);
as.mSocketState = SocketState.CONNECTED;
FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors();
if (DBG) Log.d(TAG, "socket fd passed by stack fds: " + fds);
if(fds == null || fds.length != 1) {
Log.e(TAG, "socket fd passed from stack failed, fds: " + fds);
as.close();
throw new IOException("bt socket acept failed");
}
as.mSocket = new LocalSocket(fds[0]);
// BUG: NVD-CWE-noinfo Insufficient Information
//
// FIXED:
<fim-middle> as.mPfd = new ParcelFileDescriptor(fds[0]);
try {
as.mSocket.closeExternalFd();
} catch (IOException e) {
Log.e(TAG, "closeExternalFd failed");
<fix-suffix>}
as.mSocketIS = as.mSocket.getInputStream();
as.mSocketOS = as.mSocket.getOutputStream();
as.mAddress = RemoteAddr;
as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr);
as.mPort = mPort;
return as;
}
/**
* Construct a BluetoothSocket from address. Used by native code.
* @param type type of socket
* @param fd fd to use for connected socket, or -1 for a new socket
* @param auth require the remote device to be authenticated
* @param encrypt require the connection to be encrypted
* @param address remote device that this socket can connect to
* @param port remote port
* @throws IOException On error, for example Bluetooth not available, or
* insufficient privileges
*/
private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address,
int port) throws IOException {
this(type, fd, auth, encrypt, new BluetoothDevice(address), port, null);
}
/** @hide */
@Override
protected void finalize() throws Throwable {
try {
close();
} finally {
super.finalize();
}
}
private int getSecurityFlags() {
int flags = 0;
if(mAuth)
flags |= SEC_FLAG_AUTH;
if(mEncrypt)
flags |= SEC_FLAG_ENCRYPT;
return flags;
}
/**
* Get the remote device this socket is co<|endoftext|> |
java | <fim-prefix>nd to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.nukkitx.protocol.bedrock.packet.ItemStackRequestPacket;
import org.geysermc.connector.inventory.Inventory;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.inventory.InventoryTranslator;
/**
* The packet sent for server-authoritative-style inventory transactions.
*/
@Translator(packet = ItemStackRequestPacket.class)
public class BedrockItemStackRequestTranslator extends PacketTranslator<ItemStackRequestPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ItemStackRequestPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ItemStackRequestPacket packet) {
Inventory inventory = session.getOpenInventory();
if (inventory == null)
return;
<fix-suffix>InventoryTranslator translator = session.getInventoryTranslator();
translator.translateRequests(session, inventory, packet.getRequests());
}
}
<|endoftext|> |
java | <fim-prefix>XEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.json;
import jodd.introspector.ClassDescriptor;
import jodd.introspector.ClassIntrospector;
import jodd.introspector.CtorDescriptor;
import jodd.introspector.PropertyDescriptor;
import jodd.introspector.Setter;
import jodd.typeconverter.TypeConverterManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* Just a base class of {@link jodd.json.JsonParser} that contains
* various utilities, to reduce the size of a parser.
*/
public abstract class JsonParserBase {
protected static final Supplier<Map> HASMAP_SUPPLIER = LinkedHashMap::new;
protected static final Supplier<Map> LAZYMAP_SUPPLIER = LazyMap::new;
protected static final Supplier<List> ARRAYLIST_SUPPLIER = ArrayList::new;
protected static final Supplier<List> LAZYLIST_SUPPLIER = LazyList::new;
protected Supplier<Map> mapSupplier = HASMAP_SUPPLIER;
protected Supplier<List> listSupplier = ARRAYLIST_SUPPLIER;
// BUG: CWE-502 Deserialization of Untrusted Data
//
// FIXED:
<fim-middle> protected List<String> classnameWhitelist;
/**
* Creates new instance of {@link jodd.json.MapToBean}.
*/
protected MapToBean createMapToBean(final String classMetadataName) {
return new MapT<fix-suffix>oBean(this, classMetadataName);
}
// ---------------------------------------------------------------- object tools
/**
* Creates new type for JSON array objects.
* It returns a collection.
* Later, the collection will be converted into the target type.
*/
@SuppressWarnings("unchecked")
protected Collection<Object> newArrayInstance(final Class targetType) {
if (targetType == null ||
targetType == List.class ||
targetType == Collection.class ||
targetType.isArray()) {
return listSupplier.get();
}
if (targetType == Set.class) {
return new HashSet<>();
}
try {
return (Collection<Object>) targetType.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new JsonException(e);
}
}
/**
* Creates new object or a <code>HashMap</code> if type is not specified.
*/
protected Object newObjectInstance(final Class targetType) {
if (targetType == null ||
targetType == Map.class) {
return mapSupplier.get();
}
ClassDescriptor cd = ClassIntrospector.get().lookup(targetType);
CtorDescriptor ctorDescriptor = cd.getDefaultCtorDescriptor(true);
if (ctorDescriptor == null) {
throw new JsonException("Default ctor not found for: " + targetType.getName());
}
try {
// return ClassUtil.newInstance(targetType);
return ctorDescriptor.getConstructor().newInstance();
} catch (Exception e) {
throw new JsonException(e);
}
}
/**
* Injects value into the targets property.
*/
protected void in<|endoftext|> |
java | <fim-prefix>est.getContextPath()))
return targetUrl.substring(request.getContextPath().length());
// not sure when this happens, but apparently this happens in some case.
// see #1274
return targetUrl;
}
/**
* @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException)
*/
@Override
protected String determineFailureUrl(HttpServletRequest request, AuthenticationException failed) {
Properties excMap = getExceptionMappings();
String failedClassName = failed.getClass().getName();
String whereFrom = request.getParameter("from");
request.getSession().setAttribute("from", whereFrom);
return excMap.getProperty(failedClassName, getAuthenticationFailureUrl());
}
@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
super.onSuccessfulAuthentication(request,response,authResult);
// make sure we have a session to store this successful authentication, given that we no longer
// let HttpSessionContextIntegrationFilter2 to create sessions.
// HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later
// (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its
// doFilter method.
// BUG: CWE-287 Improper Authentication
//
// FIXED:
<fim-middle> request.getSession().invalidate();
request.getSession();
}
/**
* Leave the information about login failure.
*
* <p>
* Otherwise it seems like Acegi doesn't<fix-suffix> really leave the detail of the failure anywhere.
*/
@Override
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
super.onUnsuccessfulAuthentication(request, response, failed);
LOGGER.log(Level.INFO, "Login attempt failed", failed);
}
private static final Logger LOGGER = Logger.getLogger(AuthenticationProcessingFilter2.class.getName());
}
<|endoftext|> |
java | <fim-prefix>t notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateJigsawBlockPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientUpdateSignPacket;
import com.nukkitx.nbt.NbtMap;
import com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.utils.SignUtils;
@Translator(packet = BlockEntityDataPacket.class)
public class BedrockBlockEntityDataTranslator extends PacketTranslator<BlockEntityDataPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(BlockEntityDataPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, BlockEntityDataPacket packet) {
NbtMap tag = packet.getData();
if (tag.getString("id").equals("Sign")) {
// This is the rea<fix-suffix>son why this all works - Bedrock sends packets every time you update the sign, Java only wants the final packet
// But Bedrock sends one final packet when you're done editing the sign, which should be equal to the last message since there's no edits
// So if the latest update does not match the last cached update then it's still being edited
if (!tag.getString("Text").equals(session.getLastSignMessage())) {
session.setLastSignMessage(tag.getString("Text"));
return;
}
// Otherwise the two messages are identical and we can get to work deconstructing
StringBuilder newMessage = new StringBuilder();
// While Bedrock's sign lines are one string, Java's is an array of each line
// (Initialized all with empty strings because it complains about null)
String[] lines = new String[] {"", "", "", ""};
int iterator = 0;
// Keep track of the width of each character
// If it goes over the maximum, we need to start a new line to match Java
int widthCount = 0;
// This converts the message into the array'd message Java wants
for (char character : tag.getString("Text").toCharArray()) {
widthCount += SignUtils.getCharacterWidth(character);
// If we get a return in Bedrock, or go over the character width max, that signals to use the next line.
<|endoftext|> |
java | <fim-prefix><fim-middle>right (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the Li<fix-suffix>cense.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ballerinalang.openapi;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.context.FieldValueResolver;
import com.github.jknack.handlebars.context.JavaBeanValueResolver;
import com.github.jknack.handlebars.context.MapValueResolver;
import com.github.jknack.handlebars.helper.StringHelpers;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.FileTemplateLoader;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import org.apache.commons.lang3.StringUtils;
import org.ballerinalang.openapi.exception.BallerinaOpenApiException;
import org.ballerinalang.openapi.model.BallerinaOpenApi;
import org.ballerinalang.openapi.model.GenSrcFile;
import org.ballerinalang.openapi.typemodel.BallerinaOpenApiType;
import org.ballerinalang.openapi.utils.CodegenUtils;
import org.ballerinalang.openapi.utils.GeneratorConstants;
import org.ballerinalang.openapi.utils<|endoftext|> |
java | <fim-prefix>ImmutableMap.builderWithExpectedSize(expectedNumParams);
}
/**
* Sets the result type.
*
* @param type {@link RoutingResultType#MATCHED} or {@link RoutingResultType#CORS_PREFLIGHT}.
*/
public RoutingResultBuilder type(RoutingResultType type) {
requireNonNull(type, "type");
checkArgument(type != RoutingResultType.NOT_MATCHED,
"type: %s (expected: %s or %s)",
type, RoutingResultType.MATCHED, RoutingResultType.CORS_PREFLIGHT);
this.type = type;
return this;
}
/**
* Sets the mapped path, encoded as defined in <a href="https://datatracker.ietf.org/doc/rfc3986/">RFC3986</a>.
*/
public RoutingResultBuilder path(String path) {
this.path = requireNonNull(path, "path");
return this;
}
/**
* Sets the specified query.
*/
public RoutingResultBuilder query(@Nullable String query) {
this.query = query;
return this;
}
/**
* Adds a decoded path parameter.
*/
public RoutingResultBuilder decodedParam(String name, String value) {
pathParams().put(requireNonNull(name, "name"), requireNonNull(value, "value"));
return this;
}
/**
* Adds an encoded path parameter, which will be decoded in UTF-8 automatically.
*/
public RoutingResultBuilder rawParam(String name, String value) {
pathParams().put(requireNonNull(name, "name"),
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// ArmeriaHttpUtil.decodePath(requireNonNull(value, "value")));
// FIXED:
<fim-middle> ArmeriaHttpUtil.decodePathParam(requireNonNull(value, "value")));
return this;
}
/**
* Sets the score.
*/
public RoutingResultBuilder score(int <fix-suffix>score) {
this.score = score;
return this;
}
/**
* Sets the negotiated producible {@link MediaType}.
*/
public RoutingResultBuilder negotiatedResponseMediaType(MediaType negotiatedResponseMediaType) {
this.negotiatedResponseMediaType = requireNonNull(negotiatedResponseMediaType,
"negotiatedResponseMediaType");
return this;
}
/**
* Returns a newly-created {@link RoutingResult}.
*/
public RoutingResult build() {
if (path == null) {
return RoutingResult.empty();
}
return new RoutingResult(type, path, query,
pathParams != null ? pathParams.build() : ImmutableMap.of(),
score, negotiatedResponseMediaType);
}
private ImmutableMap.Builder<String, String> pathParams() {
if (pathParams != null) {
return pathParams;
}
return pathParams = ImmutableMap.builder();
}
}
<|endoftext|> |
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.archiver;
import org.apache.logging.log4j.Logger;
import org.olat.core.gui.UserRequest;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.prefs.Preferences;
import org.olat.core.util.xml.XStreamHelper;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.ExplicitTypePermission;
/**
* this class reads and writes XML serialized config data to personal gui prefs and retrieves them
*
* Initial Date: 21.04.2017
* @author fkiefer, fabian.kiefer@frentix.com, www.frentix.com
*/
public class FormatConfigHelper {
private static final String QTI_EXPORT_ITEM_FORMAT_CONFIG = "QTIExportItemFormatConfig";
private static final Logger log = Tracing.createLoggerFor(FormatConfigHelper.class);
private static final XStream configXstream = XStreamHelper.createXStreamInstance(<|endoftext|> |
java | <fim-prefix>th 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.domain;
import com.thoughtworks.go.server.presentation.html.HtmlElement;
import com.thoughtworks.go.server.presentation.html.HtmlRenderable;
import java.util.Map;
import static com.thoughtworks.go.server.presentation.html.HtmlAttribute.*;
import static com.thoughtworks.go.server.presentation.html.ListedElements.sequence;
public class FolderDirectoryEntry extends DirectoryEntry {
private final DirectoryEntries subDirectory;
public FolderDirectoryEntry(String fileName, String url, DirectoryEntries subDirectory) {
super(fileName, url, "folder");
this.subDirectory = subDirectory;
}
public DirectoryEntries getSubDirectory() {
return subDirectory;
}
@Override
protected HtmlRenderable htmlBody() {
return sequence(
HtmlElement.div(cssClass("dir-container")).content(
HtmlElement.span(cssClass("directory")).content(
HtmlElement.a(onclick("BuildDetail.tree_navigator(this)"))
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// .content(getFileName())
// FIXED:
<fim-middle> .safecontent(getFileName())
)
),
HtmlElement.div(cssClass("subdir-container"), style("display:none"))
<fix-suffix> .content(subDirectory)
);
}
@Override
public Map<String, Object> toJson() {
Map json = super.toJson();
json.put("files", subDirectory.toJson());
return json;
}
public void addFile(String fileName, String url) {
subDirectory.addFile(fileName, url);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FolderDirectoryEntry that = (FolderDirectoryEntry) o;
if (!subDirectory.equals(that.subDirectory)) return false;
return true;
}
@Override
public int hashCode() {
return subDirectory.hashCode();
}
}
<|endoftext|> |
java | <fim-prefix>efault in memory store.
* <p>
* This method can be used from within a custom {@link Module}.
* <pre class="java">{@code
* import com.google.inject.AbstractModule;
* import ratpack.session.SessionModule;
*
* public class CustomSessionModule extends AbstractModule {
* protected void configure() {
* SessionModule.memoryStore(binder(), c -> c.maximumSize(100));
* }
* }
* }</pre>
* }<p>
* This method binds the built cache with the {@link #LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY} key.
* It also implicitly registers a {@link RemovalListener}, that releases the byte buffers as they are discarded.
*
* @param binder the guice binder
* @param config the cache configuration
*/
public static void memoryStore(Binder binder, Consumer<? super CacheBuilder<AsciiString, ByteBuf>> config) {
binder.bind(LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY).toProvider(() -> {
CacheBuilder<AsciiString, ByteBuf> cacheBuilder = Types.cast(CacheBuilder.newBuilder());
cacheBuilder.removalListener(n -> n.getValue().release());
config.accept(cacheBuilder);
return cacheBuilder.build();
}).in(Scopes.SINGLETON);
}
@Override
protected void configure() {
memoryStore(binder(), s -> s.maximumSize(1000));
}
@Provides
@Singleton
SessionStore sessionStoreAdapter(@Named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) Cache<AsciiString, ByteBuf> cache) {
return new LocalMemorySessionStore(cache);
}
@Provides
// BUG: CWE-338 Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)
//
// FIXED:
<fim-middle> @Singleton
SessionIdGenerator sessionIdGenerator() {
return new DefaultSessionIdGenerator();
}
@Provides
@RequestScoped
SessionId sessionId(Request request, Response response, Session<fix-suffix>IdGenerator idGenerator, SessionCookieConfig cookieConfig) {
return new CookieBasedSessionId(request, response, idGenerator, cookieConfig);
}
@Provides
SessionSerializer sessionValueSerializer(JavaSessionSerializer sessionSerializer) {
return sessionSerializer;
}
@Provides
JavaSessionSerializer javaSessionSerializer() {
return new JavaBuiltinSessionSerializer();
}
@Provides
@RequestScoped
Session sessionAdapter(SessionId sessionId, SessionStore store, Response response, ByteBufAllocator bufferAllocator, SessionSerializer defaultSerializer, JavaSessionSerializer javaSerializer) {
return new DefaultSession(sessionId, bufferAllocator, store, response, defaultSerializer, javaSerializer);
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle>g.bouncycastle.jcajce.provider.symmetric;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.SecureRan<fix-suffix>dom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.asn1.bc.BCObjectIdentifiers;
import org.bouncycastle.asn1.cms.CCMParameters;
import org.bouncycastle.asn1.cms.GCMParameters;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherKeyGenerator;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.AESWrapEngine;
import org.bouncycastle.crypto.engines.RFC3211WrapEngine;
import org.bouncycastle.crypto.engines.RFC5649WrapEngine;
import org.bouncycastle.crypto.generators.Poly1305KeyGenerator;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.macs.GMac;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.modes.CCMBlockCipher;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.modes.OFBBlockCipher;
import org.bouncycastle.jcajce.provider.config.ConfigurableProvider;
import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameterGenerator;
impor<|endoftext|> |
java | <fim-prefix> 0 (NOT the letter O) in c3p0. It should be placed " +
" in the top level of c3p0's effective classpath.");
return;
}
}
}
}
}
}
}
}
static
{
String ls;
try
{ ls = System.getProperty("line.separator", "\r\n"); }
catch (Exception e)
{ ls = "\r\n"; }
LINESEP = ls;
}
public static C3P0Config extractXmlConfigFromDefaultResource() throws Exception
{
InputStream is = null;
try
{
is = C3P0ConfigUtils.class.getResourceAsStream(XML_CONFIG_RSRC_PATH);
if ( is == null )
{
warnCommonXmlConfigResourceMisspellings();
return null;
}
else
return extractXmlConfigFromInputStream( is );
}
finally
{
try { if (is != null) is.close(); }
catch (Exception e)
{
if ( logger.isLoggable( MLevel.FINE ) )
logger.log(MLevel.FINE,"Exception on resource InputStream close.", e);
}
}
}
public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception
{
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
// BUG: CWE-611 Improper Restriction of XML External Entity Reference
//
// FIXED:
<fim-middle> fact.setExpandEntityReferences(false);
DocumentBuilder db = fact.newDocumentBuilder();
Document doc = db.parse( is );
return extractConfigFromXmlDoc(doc);
}
public s<fix-suffix>tatic C3P0Config extractConfigFromXmlDoc(Document doc) throws Exception
{
Element docElem = doc.getDocumentElement();
if (docElem.getTagName().equals("c3p0-config"))
{
NamedScope defaults;
HashMap configNamesToNamedScopes = new HashMap();
Element defaultConfigElem = DomParseUtils.uniqueChild( docElem, "default-config" );
if (defaultConfigElem != null)
defaults = extractNamedScopeFromLevel( defaultConfigElem );
else
defaults = new NamedScope();
NodeList nl = DomParseUtils.immediateChildElementsByTagName(docElem, "named-config");
for (int i = 0, len = nl.getLength(); i < len; ++i)
{
Element namedConfigElem = (Element) nl.item(i);
String configName = namedConfigElem.getAttribute("name");
if (configName != null && configName.length() > 0)
{
NamedScope namedConfig = extractNamedScopeFromLevel( namedConfigElem );
configNamesToNamedScopes.put( configName, namedConfig);
}
else
logger.warning("Configuration XML contained named-config element without name attribute: " + namedConfigElem);
}
return new C3P0Config( defaults, configNamesToNamedScopes );
}
else
throw new Exception("Root element of c3p0 config xml should be 'c3p0-con<|endoftext|> |
java | <fim-prefix>04 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.
*/
package org.olat.course.config.manager;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Hashtable;
import org.apache.logging.log4j.Logger;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.services.vfs.VFSRepositoryService;
import org.olat.core.logging.Tracing;
import org.olat.core.util.vfs.VFSConstants;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.course.ICourse;
import org.olat.course.config.CourseConfig;
import org.olat.course.config.CourseConfigManager;
import org.springframework.stereotype.Service;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.ExplicitTypePermission;
/**
* <P>
* Initial Date: Jun 3, 2005 <br>
* @author patrick
*/
@Service
public class CourseConfigManagerImpl implements CourseConfigManager {
private static final Logger log = Tracing.createLoggerFor(CourseConfigManagerImpl.class);
private static final XStream xstream = XStreamHelper.createXStreamInstance();
static {
Class<?>[] types = new Class[] {
CourseConfig.class, Hashtable.class, HashMap.class
};
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
// XStream.setupDefaultSecurity(xstream);
// FIXED:
<fim-middle> xstream.addPermission(new ExplicitTypePermission(types));
}
@Override
public CourseConfig copyConfigOf(ICourse course) {
return course.getCourseEnvironment().getCourseConfig().clone();
}
@O<fix-suffix>verride
public boolean deleteConfigOf(ICourse course) {
VFSLeaf configFile = getConfigFile(course);
if (configFile != null) {
return configFile.delete() == VFSConstants.YES;
}
return false;
}
@Override
public CourseConfig loadConfigFor(ICourse course) {
CourseConfig retVal = null;
VFSLeaf configFile = getConfigFile(course);
if (configFile == null) {
//config file does not exist! create one, init the defaults, save it.
retVal = new CourseConfig();
retVal.initDefaults();
saveConfigTo(course, retVal);
} else {
//file exists, load it with XStream, resolve version
Object tmp = XStreamHelper.readObject(xstream, configFile);
if (tmp instanceof CourseConfig) {
retVal = (CourseConfig) tmp;
if (retVal.resolveVersionIssues()) {
saveConfigTo(course, retVal);
}
}
}
return retVal;
}
@Override
public void saveConfigTo(ICourse course, CourseConfig courseConfig) {
VFSLeaf configFile = getConfigFile(course);
if (configFile == null) {
// create new config file
configFile = course.getCourseBaseContainer().createChildLeaf(COURSECONFIG_XML);
} else if(configFile.exists() && configFile.canVersion() == VFSConstants.YES) {
try(InputStream in = configFile.getInputStream()) {
CoreSpringFactory.getImpl(VFSRepositoryService.class).addVersion(configFile, null, "", in);
} catch (Exception e) {
log.error("Cannot versioned CourseConfig.xml", e);
}
}
XStreamHelper.writeObject(xstream, configFile, courseCo<|endoftext|> |
java | <fim-prefix>slator.Translator;
import org.olat.core.util.Util;
import org.olat.core.util.vfs.VFSConstants;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.VFSLockApplicationType;
import org.olat.core.util.vfs.VFSLockManager;
import org.olat.core.util.vfs.VFSManager;
import org.olat.core.util.vfs.VFSStatus;
import org.olat.core.util.vfs.callbacks.VFSSecurityCallback;
import org.olat.core.util.vfs.filters.VFSItemFilter;
import org.springframework.beans.factory.annotation.Autowired;
public class CmdMoveCopy extends DefaultController implements FolderCommand {
private static final String VELOCITY_ROOT = Util.getPackageVelocityRoot(CmdMoveCopy.class);
private static int status = FolderCommandStatus.STATUS_SUCCESS;
private Translator translator;
private MenuTree selTree;
private FileSelection fileSelection;
private Link selectButton, cancelButton;
private FolderComponent folderComponent;
private final boolean move;
@Autowired
private VFSLockManager vfsLockManager;
@Autowired
private VFSRepositoryService vfsRepositoryService;
@Autowired
private NotificationsManager notificationsManager;
protected CmdMoveCopy(WindowControl wControl, boolean move) {
super(wControl);
this.move = move;
}
@Override
public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) {
this.folderComponent = fc;
this.translator = trans;
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());
// FIXED:
<fim-middle> this.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath());
VelocityContainer main = new VelocityContainer("mc", VELOCITY_ROOT + "/movecopy.html", tr<fix-suffix>anslator, this);
main.contextPut("fileselection", fileSelection);
//check if command is executed on a file list containing invalid filenames or paths
if(!fileSelection.getInvalidFileNames().isEmpty()) {
main.contextPut("invalidFileNames", fileSelection.getInvalidFileNames());
}
selTree = new MenuTree(null, "seltree", this);
FolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(),
true, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter());
selTree.setTreeModel(ftm);
selectButton = LinkFactory.createButton(move ? "move" : "copy", main, this);
cancelButton = LinkFactory.createButton("cancel", main, this);
main.put("seltree", selTree);
if (move) {
main.contextPut("move", Boolean.TRUE);
}
setInitialComponent(main);
return this;
}
public boolean isMoved() {
return move;
}
public FileSelection getFileSelection() {
return fileSelection;
}
@Override
public int getStatus() {
return status;
}
@Override
public boolean runsModal() {
return false;
}
@Override
public String getModalTitle() {
return null;
}
public String getTarget() {
FolderTreeModel ftm = (FolderTreeModel) selTree.getTreeModel();
return ftm.getSelectedPath(selTree.getSelectedNode());
}
@Override
public void event(UserRequest ureq, Component source, Event event) {
if(cancelButton == source) {
status = FolderCommandStatus.STATUS_CANCELED;
fireEvent(ureq, FOLDERCOMMAND_<|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.ceditor;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.modules.ceditor.model.ContainerColumn;
import org.olat.modules.ceditor.model.ContainerSettings;
import org.olat.modules.ceditor.model.ImageHorizontalAlignment;
import org.olat.modules.ceditor.model.ImageSettings;
import org.olat.modules.ceditor.model.ImageSize;
import org.olat.modules.ceditor.model.ImageTitlePosition;
import org.olat.modules.ceditor.model.TableColumn;
import org.olat.modules.ceditor.model.TableContent;
import org.olat.modules.ceditor.model.TableRow;
import org.olat.modules.ceditor.model.TableSettings;
import org.olat.modules.ceditor.model.TextSettings;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.ExplicitTypePermission;
/**
* The XStream has its security features enabled.
*
* Initial date: 5 sept. 2018<br>
* @author sro<|endoftext|> |
java | <fim-prefix>URL);
if(errorURL.indexOf("?") > -1)
{
errorURL = errorURL.substring(0,errorURL.lastIndexOf("?"));
}
String x = request.getRequestURI();
if(request.getParameterMap().size() <2){
return null;
}
//Checking for captcha
boolean useCaptcha = Config.getBooleanProperty("FORCE_CAPTCHA",true);
if(!useCaptcha){
useCaptcha = new Boolean(request.getParameter("useCaptcha")).booleanValue();
}
String captcha = request.getParameter("captcha");
if (useCaptcha) {
Captcha captchaObj = (Captcha) session.getAttribute(Captcha.NAME);
String captchaSession=captchaObj!=null ? captchaObj.getAnswer() : null;
if(captcha ==null && Config.getBooleanProperty("FORCE_CAPTCHA",true)){
response.getWriter().write("Captcha is required to submit this form ( FORCE_CAPTCHA=true ).<br>To change this, edit the dotmarketing-config.properties and set FORCE_CAPTCHA=false");
return null;
}
if(!UtilMethods.isSet(captcha) || !UtilMethods.isSet(captchaSession) || !captcha.equals(captchaSession)) {
errors.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", "Validation Image"));
request.setAttribute(Globals.ERROR_KEY, errors);
session.setAttribute(Globals.ERROR_KEY, errors);
String queryString = request.getQueryString();
String invalidCaptchaURL = request.getParameter("invalidCaptchaReturnUrl");
if(!UtilMethods.isSet(invalidCaptchaURL)) {
invalidCaptchaURL = errorURL;
}
// BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
//
// FIXED:
<fim-middle> invalidCaptchaURL = invalidCaptchaURL.replaceAll("\\s", " ");
ActionForward af = new ActionForward();
af.setRedirect(true);
if (UtilMethods.isSet(queryString)) {
af.setP<fix-suffix>ath(invalidCaptchaURL + "?" + queryString + "&error=Validation-Image");
} else {
af.setPath(invalidCaptchaURL + "?error=Validation-Image");
}
return af;
}
}
Map<String, Object> parameters = null;
if (request instanceof UploadServletRequest)
{
UploadServletRequest uploadReq = (UploadServletRequest) request;
parameters = new HashMap<String, Object> (uploadReq.getParameterMap());
for (Entry<String, Object> entry : parameters.entrySet())
{
if(entry.getKey().toLowerCase().indexOf("file") > -1 && !entry.getKey().equals("attachFiles"))
{
parameters.put(entry.getKey(), uploadReq.getFile(entry.getKey()));
}
}
}
else
{
parameters = new HashMap<String, Object> (request.getParameterMap());
}
Set<String> toValidate = new java.util.HashSet<String>(parameters.keySet());
//Enhancing the ignored parameters not to be send in the email
String ignoredParameters = (String) EmailFactory.getMapValue("ignore", parameters);
if(ignoredParameters == null)
{
ignoredParameters = "";
}
ignoredParameters += ":useCaptcha:captcha:invalidCaptchaReturnUrl:return:returnUrl:errorURL:ignore:to:from:cc:bcc:dispatch:order:prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:";
parameters.put("ignore", ignoredParameters);
// getting categories from inodes
// getting parent category name and child categories name
// and replacing the "categories" parameter
String categories = "";
<|endoftext|> |
java | <fim-prefix>dI64() throws TException {
return zigzagToLong(readVarint64());
}
/** No magic here - just read a double off the wire. */
public double readDouble() throws TException {
trans_.readAll(buffer, 0, 8);
long value;
if (version_ >= VERSION_DOUBLE_BE) {
value = bytesToLong(buffer);
} else {
value = bytesToLongLE(buffer);
}
return Double.longBitsToDouble(value);
}
/** No magic here - just read a float off the wire. */
public float readFloat() throws TException {
trans_.readAll(buffer, 0, 4);
int value = bytesToInt(buffer);
return Float.intBitsToFloat(value);
}
/** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */
public String readString() throws TException {
int length = readVarint32();
checkReadLength(length);
if (length == 0) {
return "";
}
if (trans_.getBytesRemainingInBuffer() >= length) {
String str =
new String(
trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8);
trans_.consumeBuffer(length);
return str;
} else {
return new String(readBinary(length), StandardCharsets.UTF_8);
}
}
/** Read a byte[] from the wire. */
public byte[] readBinary() throws TException {
int length = readVarint32();
checkReadLength(length);
return readBinary(length);
}
private byte[] readBinary(int length) throws TException {
if (length == 0) {
return new byte[0];
}
// BUG: CWE-770 Allocation of Resources Without Limits or Throttling
//
// FIXED:
<fim-middle> ensureContainerHasEnough(length, TType.BYTE);
byte[] buf = new byte[length];
trans_.readAll(buf, 0, length);
return buf;
}
private void checkReadLength(int length) throws TProtoco<fix-suffix>lException {
if (length < 0) {
throw new TProtocolException("Negative length: " + length);
}
if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) {
throw new TProtocolException("Length exceeded max allowed: " + length);
}
}
//
// These methods are here for the struct to call, but don't have any wire
// encoding.
//
public void readMessageEnd() throws TException {}
public void readFieldEnd() throws TException {}
public void readMapEnd() throws TException {}
public void readListEnd() throws TException {}
public void readSetEnd() throws TException {}
//
// Internal reading methods
//
/**
* Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to
* follow. This can read up to 5 bytes.
*/
private int readVarint32() throws TException {
int result = 0;
int shift = 0;
if (trans_.getBytesRemainingInBuffer() >= 5) {
byte[] buf = trans_.getBuffer();
int pos = trans_.getBufferPosition();
int off = 0;
while (true) {
byte b = buf[pos + off];
result |= (int) (b & 0x7f) << shift;
if ((b & 0x80) != 0x80) {
break;
}
shift += 7;
off++;
}
trans_.consumeBuffer(off + 1);
} else {
while (true) {
byte b = readByte();
result |= (int) (b & 0x7f) << shift;
if ((b & 0x80) != 0x80) {
break;
}
shift += 7;
}
}
retur<|endoftext|> |
java | <fim-prefix>/*
* See 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 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.
*/
// BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')
// package org.xwiki.url;
// FIXED:
<fim-middle>package org.xwiki.url.internal;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.xwiki.url.internal.RelativeExtendedURL;
import static org.junit.jupiter.api.Assertions.assertE<fix-suffix>quals;
/**
* Unit tests for {@link RelativeExtendedURL}.
*
* @version $Id$
* @since 7.2M1
*/
class RelativeExtendedURLTest
{
@Test
void serialize()
{
RelativeExtendedURL url = new RelativeExtendedURL(Arrays.asList("a", "b"));
assertEquals("a/b", url.serialize());
}
}
<|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>
*/
package org.olat.core.commons.modules.bc.commands;
import java.util.ArrayList;
import java.util.List;
import org.olat.core.commons.modules.bc.FileSelection;
import org.olat.core.commons.modules.bc.FolderEvent;
import org.olat.core.commons.modules.bc.components.FolderComponent;
import org.olat.core.commons.services.vfs.VFSRepositoryService;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;
import org.olat.core.gui.con<|endoftext|> |
java | <fim-prefix>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 org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.session.cache.BossBar;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerBossBarPacket;
@Translator(packet = ServerBossBarPacket.class)
public class JavaBossBarTranslator extends PacketTranslator<ServerBossBarPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ServerBossBarPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ServerBossBarPacket packet) {
BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());
switch (packet.getAction()) {
<fix-suffix> case ADD:
long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();
bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0);
session.getEntityCache().addBossBar(packet.getUuid(), bossBar);
break;
case UPDATE_TITLE:
if (bossBar != null) bossBar.updateTitle(packet.getTitle());
break;
case UPDATE_HEALTH:
if (bossBar != null) bossBar.updateHealth(packet.getHealth());
break;
case REMOVE:
session.getEntityCache().removeBossBar(packet.getUuid());
break;
case UPDATE_STYLE:
case UPDATE_FLAGS:
//todo
}
}
}
<|endoftext|> |
java | <fim-prefix>icenses/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>
* 12.10.2011 by frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.openmeetings.manager;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.TypedQuery;
import org.olat.core.commons.persistence.DB;
import org.olat.core.id.OLATResourceable;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.group.BusinessGroup;
import org.olat.modules.openmeetings.model.OpenMeetingsRoom;
import org.olat.modules.openmeetings.model.OpenMeetingsRoomReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.CompactWriter;
/**
*
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*/
@Service
public class OpenMeetingsDAO {
@Autowired
private DB dbInstance;
private XStream xStream;
@PostConstruct
public void init() {
xStream = XStreamHelper.createXStreamInstance();
// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
//
// FIXED:
<fim-middle> XStreamHelper.allowDefaultPackage(xStream);
xStream.alias("room", OpenMeetingsRoom.class);
xStream.omitField(OpenMeetingsRoom.class, "property");
xStream.omitField(OpenMeetingsRoom.class, "num<fix-suffix>OfUsers");
}
public OpenMeetingsRoomReference createReference(final BusinessGroup group, final OLATResourceable courseResource, String subIdentifier, OpenMeetingsRoom room) {
String serialized = serializeRoom(room);
OpenMeetingsRoomReference ref = new OpenMeetingsRoomReference();
ref.setLastModified(new Date());
ref.setRoomId(room.getRoomId());
ref.setConfig(serialized);
ref.setGroup(group);
if(courseResource != null) {
ref.setResourceTypeName(courseResource.getResourceableTypeName());
ref.setResourceTypeId(courseResource.getResourceableId());
}
ref.setSubIdentifier(subIdentifier);
dbInstance.getCurrentEntityManager().persist(ref);
return ref;
}
public List<OpenMeetingsRoomReference> getReferences() {
StringBuilder sb = new StringBuilder();
sb.append("select ref from ").append(OpenMeetingsRoomReference.class.getName()).append(" ref");
return dbInstance.getCurrentEntityManager().createQuery(sb.toString(), OpenMeetingsRoomReference.class).getResultList();
}
public OpenMeetingsRoomReference getReference(BusinessGroup group, OLATResourceable courseResource, String subIdentifier) {
StringBuilder sb = new StringBuilder();
sb.append("select ref from ").append(OpenMeetingsRoomReference.class.getName()).append(" ref");
boolean where = false;
if(group != null) {
where = and(sb, where);
sb.append(" ref.group.key=:groupKey");
}
if(courseResource != null) {
where = and(sb, where);
sb.append(" ref.resourceTypeName=:re<|endoftext|> |
java | <fim-prefix>luding 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 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.server.ServerDifficultyPacket;
import com.nukkitx.protocol.bedrock.packet.SetDifficultyPacket;
@Translator(packet = ServerDifficultyPacket.class)
public class JavaDifficultyTranslator extends PacketTranslator<ServerDifficultyPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(ServerDifficultyPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, ServerDifficultyPacket packet) {
SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket();
setDifficultyPacket.setDifficulty<fix-suffix>(packet.getDifficulty().ordinal());
session.sendUpstreamPacket(setDifficultyPacket);
session.getWorldCache().setDifficulty(packet.getDifficulty());
}
}
<|endoftext|> |
java | <fim-prefix>.ADMINS.toString());
return true;
} else if (isAdmin(authUser) && !isRecognizedAsAdmin(u)) {
logger.info("User '{}' with id={} demoted to regular user.", u.getName(), authUser.getId());
authUser.setGroups(User.Groups.USERS.toString());
return true;
} else if (!isMod(authUser) && u.isModerator()) {
authUser.setGroups(User.Groups.MODS.toString());
return true;
}
}
return false;
}
private Profile getOrCreateProfile(User u, HttpServletRequest req) {
Profile authUser = pc.read(Profile.id(u.getId()));
if (authUser == null) {
authUser = Profile.fromUser(u);
authUser.create();
if (!u.getIdentityProvider().equals("generic")) {
sendWelcomeEmail(u, false, req);
}
Map<String, Object> payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(authUser, false));
payload.put("user", u);
triggerHookEvent("user.signup", payload);
logger.info("Created new user '{}' with id={}, groups={}, spaces={}.",
u.getName(), authUser.getId(), authUser.getGroups(), authUser.getSpaces());
}
return authUser;
}
private boolean updateProfilePictureAndName(Profile authUser, User u) {
boolean update = false;
if (!StringUtils.equals(u.getPicture(), authUser.getPicture())
&& !gravatarAvatarGenerator.isLink(authUser.getPicture())
&& !CONF.avatarEditsEnabled()) {
authUser.setPicture(u.getPicture());
update = true;
}
if (!CONF.nameEditsEnabled() && !StringUtils.equals(u.getName(), authUser.getName())) {
// BUG: NVD-CWE-Other Other
// authUser.setName(u.getName());
// FIXED:
<fim-middle> authUser.setName(StringUtils.abbreviate(u.getName(), 256));
update = true;
}
if (!StringUtils.equals(u.getName(), authUser.getOriginalName())) {
authUser.setOriginalName(u.getName());
<fix-suffix>update = true;
}
return update;
}
public boolean isDarkModeEnabled(Profile authUser, HttpServletRequest req) {
return (authUser != null && authUser.getDarkmodeEnabled()) ||
"1".equals(HttpUtils.getCookieValue(req, "dark-mode"));
}
private String getDefaultEmailSignature(String defaultText) {
String template = CONF.emailsDefaultSignatureText(defaultText);
return Utils.formatMessage(template, CONF.appName());
}
public void sendWelcomeEmail(User user, boolean verifyEmail, HttpServletRequest req) {
// send welcome email notification
if (user != null) {
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String subject = Utils.formatMessage(lang.get("signin.welcome"), CONF.appName());
String body1 = Utils.formatMessage(CONF.emailsWelcomeText1(lang), CONF.appName());
String body2 = CONF.emailsWelcomeText2(lang);
String body3 = getDefaultEmailSignature(CONF.emailsWelcomeText3(lang));
if (verifyEmail && !user.getActive() && !StringUtils.isBlank(user.getIdentifier())) {
Sysprop s = pc.read(user.getIdentifier());
if (s != null) {
String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());
s.addProperty(Config._EMAIL_TOKEN, token);
pc.update(s);
token = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + "/register?id=" + user.getId() + "&token=" + token;
body3 = "<b><a href=\"" + token + "\">" + lang.get("signin.welcome.verify") + "</<|endoftext|> |
java | <fim-prefix>sourceInfo(outContract[0],
resourceName,
version,
localePrefix,
this,
compressable,
resourceSupportsEL(resourceName, null, ctx),
ctx.isProjectStage(ProjectStage.Development),
cacheTimestamp);
}
}
if (value.isCompressable()) {
value = handleCompression(value);
}
return value;
}
private String findPathConsideringContracts(LibraryInfo library,
String resourceName,
String localePrefix,
ContractInfo [] outContract,
FacesContext ctx) {
UIViewRoot root = ctx.getViewRoot();
List<String> contracts = null;
if (library != null) {
if(library.getContract() == null) {
contracts = Collections.emptyList();
} else {
contracts = new ArrayList<String>(1);
contracts.add(library.getContract());
}
} else if (root == null) {
String contractName = ctx.getExternalContext().getRequestParameterMap()
.get("con");
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// if (null != contractName && 0 < contractName.length()) {
// FIXED:
<fim-middle> if (null != contractName && 0 < contractName.length() && !ResourceManager.nameContainsForbiddenSequence(contractName)) {
contracts = new ArrayList<>();
cont<fix-suffix>racts.add(contractName);
} else {
return null;
}
} else {
contracts = ctx.getResourceLibraryContracts();
}
String basePath = null;
for (String curContract : contracts) {
if (library != null) {
// PENDING(fcaputo) no need to iterate over the contracts, if we have a library
basePath = library.getPath(localePrefix) + '/' + resourceName;
} else {
if (localePrefix == null) {
basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;
} else {
basePath = getBaseContractsPath()
+ '/' + curContract
+ '/'
+ localePrefix
+ '/'
+ resourceName;
}
}
try {
if (ctx.getExternalContext().getResource(basePath) != null) {
outContract[0] = new ContractInfo(curContract);
break;
} else {
basePath = null;
}
} catch (MalformedURLException e) {
throw new FacesException(e);
}
}
return basePath;
}
}
<|endoftext|> |
java | <fim-prefix><fim-middle>right 2014 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 Lice<fix-suffix>nse. 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.util.internal;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
/**
* Helper class to load JNI resources.
*
*/
public final class NativeLibraryLoader {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class);
private static final String NATIVE_RESOURCE_HOME = "META-INF/native/";
private static final File WORKDIR;
private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING;
priva<|endoftext|> |
java | <fim-prefix> = null;
if (library != null) {
basePath = library.getPath(localePrefix) + '/' + resourceName;
} else {
if (localePrefix == null) {
basePath = getBaseResourcePath() + '/' + resourceName;
} else {
basePath = getBaseResourcePath()
+ '/'
+ localePrefix
+ '/'
+ resourceName;
}
}
return basePath;
}
private URL findPathConsideringContracts(ClassLoader loader,
LibraryInfo library,
String resourceName,
String localePrefix,
ContractInfo [] outContract,
String [] outBasePath,
FacesContext ctx) {
UIViewRoot root = ctx.getViewRoot();
List<String> contracts = null;
URL result = null;
if (library != null) {
if(library.getContract() == null) {
contracts = Collections.emptyList();
} else {
contracts = new ArrayList<String>(1);
contracts.add(library.getContract());
}
} else if (root == null) {
String contractName = ctx.getExternalContext().getRequestParameterMap()
.get("con");
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// if (null != contractName && 0 < contractName.length()) {
// FIXED:
<fim-middle> if (null != contractName && 0 < contractName.length() && !ResourceManager.nameContainsForbiddenSequence(contractName)) {
contracts = new ArrayList<>();
cont<fix-suffix>racts.add(contractName);
} else {
return null;
}
} else {
contracts = ctx.getResourceLibraryContracts();
}
String basePath = null;
for (String curContract : contracts) {
if (library != null) {
// PENDING(fcaputo) no need to iterate over the contracts, if we have a library
basePath = library.getPath(localePrefix) + '/' + resourceName;
} else {
if (localePrefix == null) {
basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;
} else {
basePath = getBaseContractsPath()
+ '/' + curContract
+ '/'
+ localePrefix
+ '/'
+ resourceName;
}
}
if (null != (result = loader.getResource(basePath))) {
outContract[0] = new ContractInfo(curContract);
outBasePath[0] = basePath;
break;
} else {
basePath = null;
}
}
return result;
}
}
<|endoftext|> |
java | <fim-prefix>/*
* Copy<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.domain;
import com.thoughtworks.go.server.presentation.html.HtmlRenderable;
import com.thoughtworks.go.server.presentation.html.HtmlAttribute;
import com.thoughtworks.go.server.presentation.html.HtmlElement;
public class FileDirectoryEntry extends DirectoryEntry {
public FileDirectoryEntry(String fileName, String url) {
super(fileName, url, "file");
}
@Override
protected HtmlRenderable htmlBody() {
return HtmlElement.li().content(
HtmlElement.span(HtmlAttribute.cssClass("artifact")).content(
HtmlElement.a(HtmlAttribute.href(getUrl()))
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// .content(getFileName())
// FIXED:
.safecontent(getFileName())
)
);
}
}
<|endoftext|> |
java | <fim-prefix>otice 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.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.packet.EntityPickRequestPacket;
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.registry.type.ItemMapping;
import org.geysermc.connector.utils.InventoryUtils;
/**
* Called when the Bedrock user uses the pick block button on an entity
*/
@Translator(packet = EntityPickRequestPacket.class)
public class BedrockEntityPickRequestTranslator extends PacketTranslator<EntityPickRequestPacket> {
@Override
// BUG: CWE-287 Improper Authentication
// public void translate(EntityPickRequestPacket packet, GeyserSession session) {
// FIXED:
<fim-middle> public void translate(GeyserSession session, EntityPickRequestPacket packet) {
if (session.getGameMode() != GameMode.CREATIVE) return; // Apparently Java behavior
Entity entity = s<fix-suffix>ession.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId());
if (entity == null) return;
// Get the corresponding item
String itemName;
switch (entity.getEntityType()) {
case BOAT:
// Include type of boat in the name
int variant = entity.getMetadata().getInt(EntityData.VARIANT);
String typeOfBoat;
switch (variant) {
case 1:
typeOfBoat = "spruce";
break;
case 2:
typeOfBoat = "birch";
break;
case 3:
typeOfBoat = "jungle";
break;
case 4:
typeOfBoat = "acacia";
break;
case 5:
typeOfBoat = "dark_oak";
break;
default:
typeOfBoat = "oak";
break;
}
itemName = typeOfBoat + "_boat";
break;
case LEASH_KNOT:
itemName = "lead";
break;
case MINECART_CHEST:
case MINECART_COMMAND_BLOCK:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_TNT:
// Move MINECART to the end of the name
it<|endoftext|> |
java | <fim-prefix>lass.getName());
public static void convert(PGStream stream, Properties info)
throws PSQLException, IOException {
LOGGER.log(Level.FINE, "converting regular socket connection to ssl");
SSLSocketFactory factory = SocketFactoryFactory.getSslSocketFactory(info);
SSLSocket newConnection;
try {
newConnection = (SSLSocket) factory.createSocket(stream.getSocket(),
stream.getHostSpec().getHost(), stream.getHostSpec().getPort(), true);
// We must invoke manually, otherwise the exceptions are hidden
newConnection.setUseClientMode(true);
newConnection.startHandshake();
} catch (IOException ex) {
throw new PSQLException(GT.tr("SSL error: {0}", ex.getMessage()),
PSQLState.CONNECTION_FAILURE, ex);
}
if (factory instanceof LibPQFactory) { // throw any KeyManager exception
((LibPQFactory) factory).throwKeyManagerException();
}
SslMode sslMode = SslMode.of(info);
if (sslMode.verifyPeerName()) {
verifyPeerName(stream, info, newConnection);
}
stream.changeSocket(newConnection);
}
private static void verifyPeerName(PGStream stream, Properties info, SSLSocket newConnection)
throws PSQLException {
HostnameVerifier hvn;
String sslhostnameverifier = PGProperty.SSL_HOSTNAME_VERIFIER.get(info);
if (sslhostnameverifier == null) {
hvn = PGjdbcHostnameVerifier.INSTANCE;
sslhostnameverifier = "PgjdbcHostnameVerifier";
} else {
try {
// BUG: CWE-665 Improper Initialization
// hvn = (HostnameVerifier) instantiate(sslhostnameverifier, info, false, null);
// FIXED:
<fim-middle> hvn = instantiate(HostnameVerifier.class, sslhostnameverifier, info, false, null);
} catch (Exception e) {
throw new PSQLException(
GT.tr("The HostnameVerifier class <fix-suffix>provided {0} could not be instantiated.",
sslhostnameverifier),
PSQLState.CONNECTION_FAILURE, e);
}
}
if (hvn.verify(stream.getHostSpec().getHost(), newConnection.getSession())) {
return;
}
throw new PSQLException(
GT.tr("The hostname {0} could not be verified by hostnameverifier {1}.",
stream.getHostSpec().getHost(), sslhostnameverifier),
PSQLState.CONNECTION_FAILURE);
}
}
<|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.web;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.script.ScriptContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.rendering.syntax.Syntax;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiLock;
/**
* Initializes a document before it is edited.
*
* @version $Id$
*/
@Component
@Named("edit")
@Singleton
public class EditAction extends XWikiAction
{
/**
* The object used for logging.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(EditAction.class);
/*<|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.domain;
import com.thoughtworks.go.CurrentGoCDVersion;
import com.thoughtworks.go.server.presentation.html.HtmlElement;
import com.thoughtworks.go.server.presentation.html.HtmlRenderable;
import com.thoughtworks.go.server.presentation.models.HtmlRenderer;
import com.thoughtworks.go.util.json.JsonAware;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.thoughtworks.go.server.presentation.html.HtmlElement.p;
public class DirectoryEntries extends ArrayList<DirectoryEntry> implements HtmlRenderable, JsonAware {
private boolean isArtifactsDeleted;
@Override
public void render(HtmlRenderer renderer) {
if (isArtifactsDeleted || isEmpty()) {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// HtmlElement element = p().content("Artifacts for this job instance are unavailable as they may have been <a href='" +
// FIXED:
<fim-middle> HtmlElement element = p().unsafecontent("Artifacts for this job instance are unavailable as they may have been <a href='" +
CurrentGoCDVersion.docsUrl("configuration/de<fix-suffix>lete_artifacts.html") +
"' target='blank'>purged by Go</a> or deleted externally. "
+ "Re-run the stage or job to generate them again.");
element.render(renderer);
}
for (DirectoryEntry entry : this) {
entry.toHtml().render(renderer);
}
}
@Override
public List<Map<String, Object>> toJson() {
List<Map<String, Object>> jsonList = new ArrayList();
for (DirectoryEntry entry : this) {
jsonList.add(entry.toJson());
}
return jsonList;
}
public boolean isArtifactsDeleted() {
return isArtifactsDeleted;
}
public void setIsArtifactsDeleted(boolean artifactsDeleted) {
isArtifactsDeleted = artifactsDeleted;
}
public FolderDirectoryEntry addFolder(String folderName) {
FolderDirectoryEntry folderDirectoryEntry = new FolderDirectoryEntry(folderName, "", new DirectoryEntries());
add(folderDirectoryEntry);
return folderDirectoryEntry;
}
public void addFile(String fileName, String url) {
add(new FileDirectoryEntry(fileName, url));
}
}
<|endoftext|> |
java | <fim-prefix>ic work.
*/
void onCopiedFrom(Item src);
/**
* When an item is created from scratch (instead of copied),
* this method will be invoked. Used as the post-construction initialization.
*
* @since 1.374
*/
void onCreatedFromScratch();
/**
* Save the settings to a file.
*
* Use {@link Items#getConfigFile(Item)}
* or {@link AbstractItem#getConfigFile()} to obtain the file
* to save the data.
*/
void save() throws IOException;
/**
* Deletes this item.
*/
void delete() throws IOException, InterruptedException;
PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title());
Permission CREATE = new Permission(PERMISSIONS, "Create", Messages._Item_CREATE_description(), Permission.CREATE, PermissionScope.ITEM_GROUP);
Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._Item_DELETE_description(), Permission.DELETE, PermissionScope.ITEM);
Permission CONFIGURE = new Permission(PERMISSIONS, "Configure", Messages._Item_CONFIGURE_description(), Permission.CONFIGURE, PermissionScope.ITEM);
Permission READ = new Permission(PERMISSIONS, "Read", Messages._Item_READ_description(), Permission.READ, PermissionScope.ITEM);
Permission DISCOVER = new Permission(PERMISSIONS, "Discover", Messages._AbstractProject_DiscoverPermission_Description(), READ, PermissionScope.ITEM);
/**
* Ability to view configuration details.
// BUG: CWE-326 Inadequate Encryption Strength
// * If the user lacks {@link CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form.
// FIXED:
<fim-middle> * If the user lacks {@link #CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form.
* @see Secret#ENCRYPTED_VALUE_PATTERN
*/
Permission EXTENDED_READ = new P<fix-suffix>ermission(PERMISSIONS,"ExtendedRead", Messages._AbstractProject_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.ITEM});
// TODO the following really belong in Job, not Item, but too late to move since the owner.name is encoded in the ID:
Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(), Permission.UPDATE, PermissionScope.ITEM);
Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ, PermissionScope.ITEM);
Permission WIPEOUT = new Permission(PERMISSIONS, "WipeOut", Messages._AbstractProject_WipeOutPermission_Description(), null, Functions.isWipeOutPermissionEnabled(), new PermissionScope[]{PermissionScope.ITEM});
Permission CANCEL = new Permission(PERMISSIONS, "Cancel", Messages._AbstractProject_CancelPermission_Description(), BUILD, PermissionScope.ITEM);
}
<|endoftext|> |
javascript | <fim-prefix>chrome.ext<fim-middle>ension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.command != "filters_updated")
return;
if ($("#txtFiltersAdvanced").prop("disabled") === false)
return;
<fix-suffix>BGcall("get_custom_filters_text", function(text) {
$("#txtFiltersAdvanced").val(text);
});
BGcall("get_exclude_filters_text", function(text) {
$("#txtExcludeFiltersAdvanced").val(text);
});
// BUG: CWE-284 Improper Access Control
// sendResponse({});
// FIXED:
// a call to sendResponse is not needed because of the call in filters.js
});
$(function() {
//try to get filter syntax page with users language
//if it fails, default to english (en).
var syntaxURL = "https://adblockplus.org/" +
determineUserLanguage() +
"/filters";
var jqxhr = $.ajax({
type: 'get',
url: syntaxURL,
success: function(e) {
//since the ABP site uses a custom server side 404 handler, instead of returing us a 404 http status code
//we need to parse the response text looking for a 404 message for the user.
if (jqxhr.responseText &&
jqxhr.responseText.indexOf("404 - The requested URL was not found.") > 0) {
$('#tutorlink').attr("href", "https://adblockplus.org/en/filters");
} else {
$('#tutorlink').attr("href", syntaxURL);
}
},
error: function(e) {
$('#tutorlink').attr("href", "https://adblockplus.org/en/filters");
},
});
// Add a custom filter to the list
function appendCustomFilter(filter) {
var customFilterText = $("#txtFiltersAdvanced").val();
$("#txtFiltersAdvanced").val(filter + "\n" + cus<|endoftext|> |
javascript | <fim-prefix>const Promise = require('bluebird');
const {expect} = require('chai');
const sinon = require('sinon');
const CMD = 'OPTS';
describe(CMD, function () {
let sandbox;
const mockClient = {
reply: () => Promise.resolve()
};
const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);
beforeEach(() => {
sandbox = sinon.sandbox.create().usingPromise(Promise);
sandbox.spy(mockClient, 'reply');
});
afterEach(() => {
sandbox.restore();
});
it('// unsuccessful', () => {
return cmdFn()
.then(() => {
expect(mockClient.reply.args[0][0]).to.equal(501);
});
});
it('BAD // unsuccessful', () => {
return cmdFn({command: {arg: 'BAD', directive: CMD}})
.then(() => {
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// expect(mockClient.reply.args[0][0]).to.equal(500);
// FIXED:
<fim-middle> expect(mockClient.reply.args[0][0]).to.equal(501);
});
});
it('UTF8 BAD // unsuccessful', () => {
return cmdFn({command: {arg: 'UTF8 BAD', directive: CMD}})
.then(() => {
<fix-suffix>expect(mockClient.reply.args[0][0]).to.equal(501);
});
});
it('UTF8 OFF // successful', () => {
return cmdFn({command: {arg: 'UTF8 OFF', directive: CMD}})
.then(() => {
expect(mockClient.encoding).to.equal('ascii');
expect(mockClient.reply.args[0][0]).to.equal(200);
});
});
it('UTF8 ON // successful', () => {
return cmdFn({command: {arg: 'UTF8 ON', directive: CMD}})
.then(() => {
expect(mockClient.encoding).to.equal('utf8');
expect(mockClient.reply.args[0][0]).to.equal(200);
});
});
});
<|endoftext|> |
javascript | <fim-prefix>new Ext.ButtonGroup(quickfilterConfig);
}
return this.quickFilterGroup;
},
getQuickFilterPlugin: function() {
return this;
},
getValue: function() {
var quickFilterValue = this.quickFilter.getValue(),
filters = [];
if (quickFilterValue) {
filters.push({field: this.quickFilterField, operator: 'contains', value: quickFilterValue, id: 'quickFilter'});
// add implicit / ignored fields (important e.g. for container_id)
Ext.each(this.criteriaIgnores, function(criteria) {
if (criteria.field != this.quickFilterField) {
var filterIdx = this.activeFilterPanel.filterStore.find('field', criteria.field),
filter = filterIdx >= 0 ? this.activeFilterPanel.filterStore.getAt(filterIdx) : null,
filterModel = filter ? this.activeFilterPanel.getFilterModel(filter) : null;
if (filter) {
filters.push(Ext.isFunction(filterModel.getFilterData) ? filterModel.getFilterData(filter) : this.activeFilterPanel.getFilterData(filter));
}
}
}, this);
return filters;
}
for (var id in this.filterPanels) {
if (this.filterPanels.hasOwnProperty(id) && this.filterPanels[id].isActive) {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: this.filterPanels[id].title});
// FIXED:
<fim-middle> filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: Ext.util.Format.htmlDecode(this.filterPanels[id].title)});
}
}
<fix-suffix>
// NOTE: always trigger a OR condition, otherwise we sould loose inactive FilterPanles
//return filters.length == 1 ? filters[0].filters : [{'condition': 'OR', 'filters': filters}];
return [{'condition': 'OR', 'filters': filters}];
},
setValue: function(value) {
// save last filter ?
var prefs;
if ((prefs = this.filterToolbarConfig.app.getRegistry().get('preferences')) && prefs.get('defaultpersistentfilter') == '_lastusedfilter_') {
var lastFilterStateName = this.filterToolbarConfig.recordClass.getMeta('appName') + '-' + this.filterToolbarConfig.recordClass.getMeta('recordName') + '-lastusedfilter';
if (Ext.encode(Ext.state.Manager.get(lastFilterStateName)) != Ext.encode(value)) {
Tine.log.debug('Tine.widgets.grid.FilterPanel::setValue save last used filter');
Ext.state.Manager.set(lastFilterStateName, value);
}
}
// NOTE: value is always an array representing a filterGroup with condition AND (server limitation)!
// so we need to route "alternate criterias" (OR on root level) through this filterGroup for transport
// and scrape them out here -> this also means we whipe all other root level filters (could only be implicit once)
var alternateCriterias = false;
Ext.each(value, function(filterData) {
if (filterData.condition && filterData.condition == 'OR')<|endoftext|> |
javascript | <fim-prefix>h(message), this.getPrivate(_getPassword()))),
hash: hashed
};
} else {
throw "tEnvoyNaClSigningKey Fatal Error: Key does not have a private component.";
}
} else {
throw assertion.error;
}
}
this.verify = (signed, password = null) => {
let assertion = _assertPassword("verify", password);
if(assertion.proceed) {
if(signed == null) {
throw "tEnvoyNaClSigningKey Fatal Error: argument signed of method verify is required and does not have a default value.";
}
if(signed.split("::").length != 2) {
throw "tEnvoyNaClSigningKey Fatal Error: Invalid signature.";
}
let hash = _tEnvoy.util.hexToBytes(signed.split("::")[0]);
let signature = _tEnvoy.util.hexToBytes(signed.split("::")[1]);
return {
verified: _nacl.sign.detached.verify(hash, signature, this.getPublic(_getPassword())),
hash: signed.split("::")[0]
};
} else {
throw assertion.error;
}
}
this.verifyWithMessage = (signed, message, password = null) => {
if(signed == null) {
throw "tEnvoyNaClSigningKey Fatal Error: argument signed of method verifyWithMessage is required and does not have a default value.";
}
if(message == null) {
throw "tEnvoyNaClSigningKey Fatal Error: argument message of method verifyWithMessage is required and does not have a default value.";
}
if(signed.split("::").length != 2) {
throw "tEnvoyNaClSigningKey Fatal Error: Invalid signature.";
}
let hash = _tEnvoy.util.hexToBytes(signed.split("::")[0]);
// BUG: CWE-347 Improper Verification of Cryptographic Signature
// return this.verify(signed, password) && _tEnvoy.util.bytesToHex(_nacl.hash(_tEnvoy.util.pack(message))) == _tEnvoy.util.bytesToHex(hash);
// FIXED:
<fim-middle> return this.verify(signed, password).verified && _tEnvoy.util.bytesToHex(_nacl.hash(_tEnvoy.util.pack(message))) == _tEnvoy.util.bytesToHex(hash);
}
this.toPublic = (password = null) => {
retu<fix-suffix>rn new tEnvoyNaClSigningKey(this.getPublic(password), "public", _getPassword(), _passwordProtected, _tEnvoy);
}
if(!["public", "private"].includes(type)) {
throw "tEnvoyNaClSigningKey Fatal Error: argument type of method constructor is invalid.";
} else {
_getKey = () => {
return _tEnvoy.util.unpack(_key);
}
_setKey = (newKey) => {
_key = _tEnvoy.util.pack(newKey);
}
_getPassword = () => {
return _tEnvoy.util.unpack(_password);
}
_setPassword = (newPassword) => {
_password = _tEnvoy.util.pack(newPassword);
}
_setPassword(password);
if(password == null) {
_setKey(key);
} else {
_nonce = _nacl.randomBytes(12);
let encryptionKey = new tEnvoyNaClKey(password, "secret", null, [], _tEnvoy);
_setKey(encryptionKey.encrypt(key, _nonce));
encryptionKey.destroy();
}
_type = type;
_passwordProtected = [];
let protectable = [];
if(_type == "private") {
protectable = ["destroy", "getPublic", "sign", "verify"];
} else if(_type == "public") {
protectable = ["destroy", "verify"];
}
if(passwordProtected == null) {
passwordProtected = [];
}
for(let i = 0; i < passwordProtected.length; i++) {
if(protectable.includes(passwordProtected[i])) {
_passwordProtected.push(passwordProtected[i]);
}
}
_assertPassword = (methodName, password = null) => {
if(_getPassword() == null) {
return {
proceed: true
};
} else {
let alwaysProtected;
if(_type == "private") {
alwaysProtec<|endoftext|> |
javascript | <fim-prefix>param {String} possible Base64-String
*
* @returns {boolean}
*/
var validateStringAsBase64 = (jsPDFAPI.__addimage__.validateStringAsBase64 = function(
possibleBase64String
) {
possibleBase64String = possibleBase64String || "";
possibleBase64String.toString().trim();
var result = true;
if (possibleBase64String.length === 0) {
result = false;
}
if (possibleBase64String.length % 4 !== 0) {
result = false;
}
if (
/^[A-Za-z0-9+/]+$/.test(
possibleBase64String.substr(0, possibleBase64String.length - 2)
) === false
) {
result = false;
}
if (
/^[A-Za-z0-9/][A-Za-z0-9+/]|[A-Za-z0-9+/]=|==$/.test(
possibleBase64String.substr(-2)
) === false
) {
result = false;
}
return result;
});
/**
* Strips out and returns info from a valid base64 data URI
*
* @name extractImageFromDataUrl
* @function
* @param {string} dataUrl a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
* @returns {Array}an Array containing the following
* [0] the complete data URI
* [1] <MIME-type>
* [2] format - the second part of the mime-type i.e 'png' in 'image/png'
* [4] <data>
*/
var extractImageFromDataUrl = (jsPDFAPI.__addimage__.extractImageFromDataUrl = function(
dataUrl
) {
dataUrl = dataUrl || "";
var dataUrlParts = dataUrl.split("base64,");
var result = null;
if (dataUrlParts.length === 2) {
// BUG: NVD-CWE-noinfo Insufficient Information
// var extractedInfo = /^data:(\w*\/\w*);*(charset=[\w=-]*)*;*$/.exec(
// FIXED:
<fim-middle> var extractedInfo = /^data:(\w*\/\w*);*(charset=(?!charset=)[\w=-]*)*;*$/.exec(
dataUrlParts[0]
);
if (Array.isArray(extractedInfo)) {
result = {
mimeType: <fix-suffix>extractedInfo[1],
charset: extractedInfo[2],
data: dataUrlParts[1]
};
}
}
return result;
});
/**
* Check to see if ArrayBuffer is supported
*
* @name supportsArrayBuffer
* @function
* @returns {boolean}
*/
var supportsArrayBuffer = (jsPDFAPI.__addimage__.supportsArrayBuffer = function() {
return (
typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"
);
});
/**
* Tests supplied object to determine if ArrayBuffer
*
* @name isArrayBuffer
* @function
* @param {Object} object an Object
*
* @returns {boolean}
*/
jsPDFAPI.__addimage__.isArrayBuffer = function(object) {
return supportsArrayBuffer() && object instanceof ArrayBuffer;
};
/**
* Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
*
* @name isArrayBufferView
* @function
* @param {Object} object an Object
* @returns {boolean}
*/
var isArrayBufferView = (jsPDFAPI.__addimage__.isArrayBufferView = function(
object
) {
return (
supportsArrayBuffer() &&
typeof Uint32Array !== "undefined" &&
(object instanceof Int8Array ||
object instanceof Uint8Array ||
(typeof Uint8ClampedArray !== "undefined" &&
object instanceof Uint8ClampedArray) ||
object instanceof Int16Array ||
object instanceof Uint16Array ||
object instanceof Int32Array ||
object ins<|endoftext|> |
javascript | <fim-prefix><fim-middle>yright (c) 2006-2012, JGraph Ltd
*/
// Workaround for handling named HTML entities in mxUtils.parseXml
// LATER: How to configure DOMParser to just ignore all entities?
(function()
{
var entities = <fix-suffix>[
['nbsp', '160'],
['shy', '173']
];
var parseXml = mxUtils.parseXml;
mxUtils.parseXml = function(text)
{
for (var i = 0; i < entities.length; i++)
{
text = text.replace(new RegExp(
'&' + entities[i][0] + ';', 'g'),
'&#' + entities[i][1] + ';');
}
return parseXml(text);
};
})();
// Shim for missing toISOString in older versions of IE
// See https://stackoverflow.com/questions/12907862
if (!Date.prototype.toISOString)
{
(function()
{
function pad(number)
{
var r = String(number);
if (r.length === 1)
{
r = '0' + r;
}
return r;
};
Date.prototype.toISOString = function()
{
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() )
+ 'T' + pad( this.getUTCHours() )
+ ':' + pad( this.getUTCMinutes() )
+ ':' + pad( this.getUTCSeconds() )
+ '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
}());
}
// Shim for Date.now()
if (!Date.now)
{
Date.now = function()
{
return new Date().getTime();
};
}
// Polyfill for Uint8Array.from in IE11 used in Graph.decompress
// See https://stackoverflow.com/questions/36810940/alternative-or-polyfi<|endoftext|> |
javascript | <fim-prefix><fim-middle> . .o8 oooo
* .o8 "888 `888
* .o888oo oooo d8b oooo oooo .oooo888 .ooooo. .oooo.o 888 oo<fix-suffix>oo
* 888 `888""8P `888 `888 d88' `888 d88' `88b d88( "8 888 .8P'
* 888 888 888 888 888 888 888ooo888 `"Y88b. 888888.
* 888 . 888 888 888 888 888 888 .o o. )88b 888 `88b.
* "888" d888b `V88V"V8P' `Y8bod88P" `Y8bod8P' 8""888P' o888o o888o
* ========================================================================
* Author: Chris Brame
* Updated: 1/20/19 4:43 PM
* Copyright (c) 2014-2019. All rights reserved.
*/
define([
'angular',
'underscore',
'jquery',
'modules/helpers',
'uikit',
'qrcode',
'history',
'angularjs/services/session'
], function (angular, _, $, helpers, UIKit) {
return angular
.module('trudesk.controllers.profile', ['trudesk.services.session'])
.controller('profileCtrl', function (SessionService, $scope, $window, $document, $http, $log, $timeout) {
var otpEnabled = false
$scope.init = function () {
// Fix Inputs if input is preloaded with a value
fixInputLabels()
otpEnabled = $scope.otpEnabled
}
function fixInputLabels () {
$timeout(function () {
$('input.md-input').each(function () {
var vm = this
var self = $(vm)
if (!_.isEmpty(self.val())) {
var s = self.parent('.md-input-wrapper')
if (s.length > 0) {
s.addClass('md-input-filled')
}
}
})
}, 0)
}
function valida<|endoftext|> |
javascript | <fim-prefix><fim-middle>t from 'tape'
import {Schema, Param} from '../src/'
let schema = (params, options) => new Schema(params, options)
test('QuerymenSchema add', (t) => {
let add = (...args) => schema().add('test', ..<fix-suffix>.args).value()
t.true(schema().add(new Param('test')), 'should add a param with instance')
t.true(schema().add('test'), 'should add a param')
t.equal(add('123'), '123', 'should add a param with value')
t.true(schema().add('test', null, {test: true}).option('test'), 'should add a param with option')
t.equal(add(null, '123'), '123', 'should add a param with default option string')
t.equal(add(null, 123), 123, 'should add a param with default option number')
t.equal(add(null, true), true, 'should add a param with default option boolean')
t.same(add(null, new Date('2016')), new Date('2016'), 'should add a param with default option date')
t.same(add(null, /123/i), /123/i, 'should add a param with default option regexp')
t.equal(add(123, String), '123', 'should add a param with type option string')
t.equal(add('123', Number), 123, 'should add a param with type option number')
t.equal(add('123', Boolean), true, 'should add a param with type option boolean')
t.same(add('2016', Date), new Date('2016'), 'should add a param with type option date')
t.same(add('123', RegExp), /123/i, 'should add a param with type option regexp')
t.same(add(null, ['123']), '123', 'should add a param with default option string array')
t.same(add(null, [123]), 123, 'should add a param with default option number array')
t.same(add(null, [true]), true, 'should add a param with default option boolean array')
t.same(add(null, [new Date('2016')]), new Date('2016'), 'should add<|endoftext|> |
javascript | <fim-prefix>// issues: nested multiline comments
Prism.languages.swift = Prism.languages.extend('clike', {
'string': {
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /("|')(?:\\(?:\((?:[^()]|\([^)]+\))+\)|\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
// FIXED:
<fim-middle> pattern: /("|')(?:\\(?:\((?:[^()]|\([^)]+\))+\)|\r\n|[^(])|(?!\1)[^\\\r\n])*\1/,
greedy: true,
inside: {
'interpolation': {
pattern: /\\\((?:[^()]|\([^)]+\))+\)/,
inside: {
delim<fix-suffix>iter: {
pattern: /^\\\(|\)$/,
alias: 'variable'
}
// See rest below
}
}
}
},
'keyword': /\b(?:as|associativity|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic(?:Type)?|else|enum|extension|fallthrough|final|for|func|get|guard|if|import|in|infix|init|inout|internal|is|lazy|left|let|mutating|new|none|nonmutating|operator|optional|override|postfix|precedence|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|Self|set|static|struct|subscript|super|switch|throws?|try|Type|typealias|unowned|unsafe|var|weak|where|while|willSet|__(?:COLUMN__|FILE__|FUNCTION__|LINE__))\b/,
'number': /\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,
'constant': /\b(?:nil|[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,
'atrule': /@\b(?:IB(?:Outlet|Designable|Action|Inspectable)|class_protocol|exported|noreturn|NS(?:Copying|Managed)|objc|UIApplicationMain|auto_closure)\b/,
'builtin': /\b(?:[A-Z]\S+|abs|advance|alignof(?:Value)?|assert|contains|count(?:Elements)?|debugPrint(?:ln)?|distance|drop(?:First|Last)|dump|enumerate|equal|filter|find|first|getVaList|indices|isEmpty|join|last|lexicographicalCompare|map|max(?:Element)?|min(?:Element)?|numericCast|overlaps|partition|print(?:ln)?|reduce|reflect|reverse|sizeof(?:Value)?|sort(?:ed)?|split|startsWith|stride(?:of(?:Value)?)?|suffix|swap|toDebugString|toString|transcode|underestimateCount|unsafeBitCast|with(?:ExtendedLifetime|Unsafe(?:Mutable<|endoftext|> |
javascript | <fim-prefix><fim-middle> require('tap').test
var npmconf = require('../../lib/config/core.js')
var common = require('./00-config-setup.js')
var URI = 'https://registry.lvh.me:8661/'
test('getting scope with no credentials<fix-suffix> set', function (t) {
npmconf.load({}, function (er, conf) {
t.ifError(er, 'configuration loaded')
var basic = conf.getCredentialsByURI(URI)
t.equal(basic.scope, '//registry.lvh.me:8661/', 'nerfed URL extracted')
t.end()
})
})
test('trying to set credentials with no URI', function (t) {
npmconf.load(common.builtin, function (er, conf) {
t.ifError(er, 'configuration loaded')
t.throws(function () {
conf.setCredentialsByURI()
}, 'enforced missing URI')
t.end()
})
})
test('trying to clear credentials with no URI', function (t) {
npmconf.load(common.builtin, function (er, conf) {
t.ifError(er, 'configuration loaded')
t.throws(function () {
conf.clearCredentialsByURI()
}, 'enforced missing URI')
t.end()
})
})
test('set with missing credentials object', function (t) {
npmconf.load(common.builtin, function (er, conf) {
t.ifError(er, 'configuration loaded')
t.throws(function () {
conf.setCredentialsByURI(URI)
}, 'enforced missing credentials')
t.end()
})
})
test('set with empty credentials object', function (t) {
npmconf.load(common.builtin, function (er, conf) {
t.ifError(er, 'configuration loaded')
t.throws(function () {
conf.setCredentialsByURI(URI, {})
}, 'enforced missing credentials')
t.end()
})
})
test('set with token', function (t) {
npmconf.load(common.builtin, function (er, conf) {
t.ifError(er, 'configuration loaded')
t.doesNo<|endoftext|> |
javascript | <fim-prefix>, then the first capturing group of `pattern` will (effectively)
* behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
* @property {boolean} [greedy=false] Whether the token is greedy.
* @property {string|string[]} [alias] An optional alias or list of aliases.
* @property {Grammar} [inside] The nested grammar of this token.
*
* The `inside` grammar will be used to tokenize the text value of each token of this kind.
*
* This can be used to make nested and even recursive language definitions.
*
* Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
* each another.
* @global
* @public
*/
/**
* @typedef Grammar
* @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
* @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
* @global
* @public
*/
/**
* A function which will invoked after an element was successfully highlighted.
*
* @callback HighlightCallback
* @param {Element} element The element successfully highlighted.
* @returns {void}
* @global
* @public
*/
/**
* @callback HookCallback
* @param {Object<string, any>} env The environment variables of the hook.
* @returns {void}
* @global
* @public
*/
/* **********************************************
Begin prism-markup.js
********************************************** */
Prism.languages.markup = {
// BUG: NVD-CWE-Other Other
// 'comment': /<!--[\s\S]*?-->/,
// FIXED:
<fim-middle> 'comment': /<!--(?:(?!<!--)[\s\S])*?-->/,
'prolog': /<\?[\s\S]+?\?>/,
'doctype': {
// https://www.w3.org/TR/xml/#NT-doctypedecl
pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]<fix-suffix>|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
greedy: true,
inside: {
'internal-subset': {
pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
lookbehind: true,
greedy: true,
inside: null // see below
},
'string': {
pattern: /"[^"]*"|'[^']*'/,
greedy: true
},
'punctuation': /^<!|>$|[[\]]/,
'doctype-tag': /^DOCTYPE/,
'name': /[^\s<>'"]+/
}
},
'cdata': /<!\[CDATA\[[\s\S]*?\]\]>/i,
'tag': {
pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
greedy: true,
inside: {
'tag': {
pattern: /^<\/?[^\s>\/]+/,
inside: {
'punctuation': /^<\/?/,
'namespace': /^[^\s>\/:]+:/
}
},
'special-attr': [],
'attr-value': {
pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
inside: {
'punctuation': [
{
pattern: /^=/,
alias: 'attr-equals'
},
/"|'/
]
}
},
'punctuation': /\/?>/,
'attr-name': {
pattern: /[^\s>\/]+/,
inside: {
'namespace': /^[^\s>\/:]+:/
}
}
}
},
'entity': [
{
pattern: /&[\da-z]{1,8};/i,
alias: 'named-entity'
},
/&#x?[\da-f]{1,8};/i
]
};
Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
Prism.languages.markup['entity'];
Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.ad<|endoftext|> |
javascript | <fim-prefix>
(function<fim-middle>(document) {
var interval,
defaultReloadFreq = 3,
previousText,
storage = chrome.storage.local;
function getExtension(url) {
url = url.substr(1 + url.lastInde<fix-suffix>xOf("/"))
.split('?')[0]
.split('#')[0];
return url.substr(1 + url.lastIndexOf("."))
}
function resolveImg(img) {
var src = $(img).attr("src");
if (src[0] == "/") {
$(img).attr("src", src.substring(1));
}
}
// Onload, take the DOM of the page, get the markdown formatted text out and
// apply the converter.
function makeHtml(data) {
storage.get('mathjax', function(items) {
// Convert MarkDown to HTML without MathJax typesetting.
// This is done to make page responsiveness. The HTML body
// is replaced after MathJax typesetting.
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
//
// FIXED:
config.markedOptions.sanitize = items.mathjax ? false : true;
marked.setOptions(config.markedOptions);
var html = marked(data);
$(document.body).html(html);
$('img').on("error", function() {
resolveImg(this);
});
// Apply MathJax typesetting
if (items.mathjax) {
$.getScript(chrome.extension.getURL('js/marked.js'));
$.getScript(chrome.extension.getURL('js/highlight.js'), function() {
$.getScript(chrome.extension.getURL('js/config.js'));
});
// Create hidden div to use for Mat<|endoftext|> |
javascript | <fim-prefix>define([
'exports',
'../errors/RequestError',
'../errors/CancelError',
'../Deferred',
'../io-query',
'../_base/array',
'../_base/lang',
'../promise/Promise',
'../has'
], function(exports, RequestError, CancelError, Deferred, ioQuery, array, lang, Promise, has){
function isArrayBuffer(value) {
return has('native-arraybuffer') && value instanceof ArrayBuffer
}
function isBlob(value) {
return has('native-blob') && value instanceof Blob
}
function isElement(value) {
if(typeof Element !== 'undefined') { //all other
return value instanceof Element;
}
//IE<=7
return value.nodeType === 1;
}
function isFormData(value) {
return has('native-formdata') && value instanceof FormData;
}
function shouldDeepCopy(value) {
return value &&
typeof value === 'object' &&
!isFormData(value) &&
!isElement(value) &&
!isBlob(value) &&
!isArrayBuffer(value)
}
exports.deepCopy = function(target, source) {
for (var name in source) {
var tval = target[name],
sval = source[name];
// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
// if (tval !== sval) {
// FIXED:
<fim-middle> if (name !== '__proto__' && tval !== sval) {
if (shouldDeepCopy(sval)) {
if (Object.prototype.toString.call(sval) === '[object Date]') { // use this date test to handle crossing frame boun<fix-suffix>daries
target[name] = new Date(sval);
} else if (lang.isArray(sval)) {
target[name] = exports.deepCopyArray(sval);
} else {
if (tval && typeof tval === 'object') {
exports.deepCopy(tval, sval);
} else {
target[name] = exports.deepCopy({}, sval);
}
}
} else {
target[name] = sval;
}
}
}
return target;
};
exports.deepCopyArray = function(source) {
var clonedArray = [];
for (var i = 0, l = source.length; i < l; i++) {
var svalItem = source[i];
if (typeof svalItem === 'object') {
clonedArray.push(exports.deepCopy({}, svalItem));
} else {
clonedArray.push(svalItem);
}
}
return clonedArray;
};
exports.deepCreate = function deepCreate(source, properties){
properties = properties || {};
var target = lang.delegate(source),
name, value;
for(name in source){
value = source[name];
if(value && typeof value === 'object'){
target[name] = exports.deepCreate(value, properties[name]);
}
}
return exports.deepCopy(target, properties);
};
var freeze = Object.freeze || function(obj){ return obj; };
function okHandler(response){
return freeze(response);
}
function dataHandler (response) {
return response.data !== undefined ? response.data : response.text;
}
exports.deferred = function deferred(response, cancel, isValid, isReady, handleResponse, last){
var def = new Deferred(function(reason){
cancel && cancel(def, response);
if(!reas<|endoftext|> |
javascript | <fim-prefix> });
} else {
this.hide();
}
};
this.hide = function () {
this.$popover.hide();
};
};
var VideoDialog = function (context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
var lang = options.langInfo;
this.initialize = function () {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group row-fluid">' +
'<label>' + lang.video.url + ' <small class="text-muted">' + lang.video.providers + '</small></label>' +
'<input class="note-video-url form-control span12" type="text" />' +
'</div>';
var footer = '<button href="#" class="btn btn-primary note-video-btn disabled" disabled>' + lang.video.insert + '</button>';
this.$dialog = ui.dialog({
title: lang.video.insert,
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
this.destroy = function () {
ui.hideDialog(this.$dialog);
this.$dialog.remove();
};
this.bindEnterKey = function ($input, $btn) {
$input.on('keypress', function (event) {
if (event.keyCode === key.code.ENTER) {
$btn.trigger('click');
}
});
};
this.createVideoNode = function (url) {
// video url patterns(youtube, instagram, vimeo, dailymotion, youku, mp4, ogg, webm)
// BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
// var ytRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
// FIXED:
<fim-middle> var ytRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-) {11})(?:\S+)?$/;
var ytMatch = url.match(ytRegExp);
var igRegE<fix-suffix>xp = /\/\/instagram.com\/p\/(.[a-zA-Z0-9_-]*)/;
var igMatch = url.match(igRegExp);
var vRegExp = /\/\/vine.co\/v\/(.[a-zA-Z0-9]*)/;
var vMatch = url.match(vRegExp);
var vimRegExp = /\/\/(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/;
var vimMatch = url.match(vimRegExp);
var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/;
var dmMatch = url.match(dmRegExp);
var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/;
var youkuMatch = url.match(youkuRegExp);
var mp4RegExp = /^.+.(mp4|m4v)$/;
var mp4Match = url.match(mp4RegExp);
var oggRegExp = /^.+.(ogg|ogv)$/;
var oggMatch = url.match(oggRegExp);
var webmRegExp = /^.+.(webm)$/;
var webmMatch = url.match(webmRegExp);
var $video;
if (ytMatch && ytMatch[1].length === 11) {
var youtubeId = ytMatch[1];
$video = $('<iframe>')
.attr('frameborder', 0)
.attr('src', '//www.youtube.com/embed/' + youtubeId)
.attr('width', '640').attr('height', '360');
} else if (igMatch && igMatch[0].length) {
$video = $('<iframe>')
.attr('frameborder', 0)
.attr('src', igMatch[0] + '/embed/')
.attr('width', '612').attr('height', '710')
.attr('scrolling', 'no')
.attr('allowtransparency', 'true');
} else if (vMatch && vMatch[0].length) {
$video = $('<iframe>')
.a<|endoftext|> |
javascript | <fim-prefix> // used <fim-middle>by the tabbing interface to make sure the correct
// ajax content is loaded
var path = 'device';
// fields in the Device Search Options form (Device tab)
var form_inputs = $("#ports_form .cle<fix-suffix>arfix input").not('[type="checkbox"]')
.add("#ports_form .clearfix select");
// this is called by do_search to support local code
// which might need to act on the newly inserted content
// but which cannot use jQuery delegation via .on()
function inner_view_processing(tab) {
// LT wanted the page title to reflect what's on the page :)
document.title = $('#nd_device-name').text()
+' - '+ $('#'+ tab + '_link').text();
// used for contenteditable cells to find out whether the user has made
// changes, and only reset when they submit or cancel the change
var dirty = false;
// activate modals, tooltips and popovers
$('.nd_modal').modal({show: false});
$("[rel=tooltip]").tooltip({live: true});
$("[rel=popover]").popover({live: true});
}
// on load, establish global delegations for now and future
$(document).ready(function() {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var tab = '[% tab.tag %]'
// FIXED:
var tab = '[% tab.tag | html_entity %]'
var target = '#' + tab + '_pane';
var portfilter = $('#ports_form').find("input[name=f]");
// sidebar form fields should change colour and have trash/copy icon
form_inputs.each(function() {device_form_state($(this))});
form_inputs.change(function() {device_form_state($(this))});
// sidebar collapser events trigger change of up/down arrow
$('.collapse').on('show', function(<|endoftext|> |
javascript | <fim-prefix> ? [NOW, dt] : [dt, NOW];
}
if (val.length === 4)
return [new Date(+val, 0, 1), new Date(+val + 1, 0 , 1)];
} else if (val.indexOf('.', index + 1) === -1) {
var a = val.split('.');
return new Date(NOW.getFullYear(), +a[1] - 1, +a[0]);
}
index = val.indexOf('-');
if (index !== -1 && val.indexOf('-', index + 1) === -1) {
var a = val.split('-');
return new Date(NOW.getFullYear(), +a[0] - 1, +a[1]);
}
return val.parseDate();
};
self.parseNumber = function(val) {
var arr = [];
var num = val.replace(/\s-\s/, '/').replace(/\s/g, '').replace(/,/g, '.').split(/\/|\|\s-\s|\\/).trim();
for (var i = 0, length = num.length; i < length; i++) {
var n = num[i];
arr.push(+n);
}
return arr;
};
self.reset = function() {
options.filter = {};
isFilter = false;
thead.find('input').val('');
thead.find('.ui-grid-selected').rclass('ui-grid-selected');
options.lastsortelement && options.lastsortelement.rclass('fa-caret-down fa-caret-up');
options.lastsortelement = null;
if (options.lastsort)
options.lastsort.sorting = null;
options.lastsort = null;
};
self.redraw = function() {
var items = options.items;
var columns = options.columns;
var builder = [];
var m = {};
for (var i = 0, length = items.length; i < length; i++) {
builder.push('<tr class="ui-grid-row" data-index="' + i + '">');
for (var j = 0, jl = columns.length; j < jl; j++) {
var column = columns[j];
var val = items[i][column.name];
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// m.value = column.template ? column.template(items[i], column) : column.render ? column.render(val, column, items[i]) : val == null ? '' : (column.format ? val.format(column.format) : val);
// FIXED:
<fim-middle> m.value = column.template ? column.template(items[i], column) : column.render ? column.render(val, column, items[i]) : val == null ? '' : Thelpers.encode((column.format ? val.format(column.format)<fix-suffix> : val));
m.index = j;
m.align = column.align;
m.background = column.background;
builder.push(self.template(m, column));
}
builder.push('</tr>');
}
tbody.find('.ui-grid-row').remove();
tbody.prepend(builder.join(''));
container.rclass('noscroll');
scroll && container.prop('scrollTop', 0);
scroll = false;
eheight = 0;
self.resize(0);
};
self.setter = function(value) {
// value.items
// value.limit
// value.page
// value.pages
// value.count
if (!value) {
tbody.find('.ui-grid-row').remove();
self.resize();
return;
}
cache = value;
if (config.pagination) {
pagination.prev.prop('disabled', value.page === 1);
pagination.first.prop('disabled', value.page === 1);
pagination.next.prop('disabled', value.page >= value.pages);
pagination.last.prop('disabled', value.page === value.pages);
pagination.page.val(value.page);
pagination.meta.html(value.count.pluralize.apply(value.count, pitems));
pagination.pages.html(value.pages.pluralize.apply(value.pages, ppages));
}
if (options.customsearch) {
for (var i = 0, length = value.items.length; i < length; i++) {
var item = value.items[i];
for (var j = 0; j < options.columns.length; j++) {
var col = options.columns[j];
if (col.search)
item['$' + col.name] = col.search(item);
}
}
}
if (config.external) {
options.items = value.items;
} else {
options.items = [];
filtercache = {};
for (var i = 0, le<|endoftext|> |
javascript | <fim-prefix>s creating rows which are no longer required. I.e when changing album
if (view.requestId !== album.requestId) {
return;
}
// We can now safely create a new row
var row = album.getRow($(window).width());
var rowDom = row.getDom();
view.element.append(rowDom);
return album.fillNextRow(row).then(function () {
if (album.viewedItems < album.subAlbums.length + album.images.length &&
view.element.height() < targetHeight) {
return showRows(album);
}
// No more rows to load at the moment
view.loadVisibleRows.processing = false;
view.loadVisibleRows.loading = null;
}, function () {
// Something went wrong, so kill the loader
view.loadVisibleRows.processing = false;
view.loadVisibleRows.loading = null;
});
}, 100);
if (this.element.height() < targetHeight) {
this._showNormal();
this.loadVisibleRows.processing = true;
album.requestId = view.requestId;
this.loadVisibleRows.loading = showRows(album);
}
},
/**
* Shows an empty gallery message
*
* @param {string} albumPath
* @param {string|null} errorMessage
*/
showEmptyFolder: function (albumPath, errorMessage) {
var message = '<div class="icon-gallery"></div>';
var uploadAllowed = true;
this.element.children().detach();
this.removeLoading();
if (!_.isUndefined(errorMessage) && errorMessage !== null) {
message += '<h2>' + t('gallery',
'Album cannot be shown') + '</h2>';
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// message += '<p>' + errorMessage + '</p>';
// FIXED:
<fim-middle> message += '<p>' + escapeHTML(errorMessage) + '</p>';
uploadAllowed = false;
} else {
message += '<h2>' + t('gallery',
'No media files found') + '</h2>';
// We can't upload ye<fix-suffix>t on the public side
if (Gallery.token) {
message += '<p>' + t('gallery',
'Upload pictures in the files app to display them here') + '</p>';
} else {
message += '<p>' + t('gallery',
'Upload new files via drag and drop or by using the [+] button above') +
'</p>';
}
}
this.emptyContentElement.html(message);
this.emptyContentElement.removeClass('hidden');
this._hideButtons(uploadAllowed);
Gallery.currentAlbum = albumPath;
var availableWidth = $(window).width() - Gallery.buttonsWidth;
this.breadcrumb.init(albumPath, availableWidth);
Gallery.config.albumDesign = null;
},
/**
* Dims the controls bar when retrieving new content. Matches the effect in Files
*/
dimControls: function () {
// Use the existing mask if its already there
var $mask = this.controlsElement.find('.mask');
if ($mask.exists()) {
return;
}
$mask = $('<div class="mask transparent"></div>');
this.controlsElement.append($mask);
$mask.removeClass('transparent');
},
/**
* Shows the infamous loading spinner
*/
showLoading: function () {
this.emptyContentElement.addClass('hidden');
this.controlsElement.removeClass('hidden');
$('#content').addClass('icon-loading');
this.dimControls();
},
/**
* Removes the spinner in the main area and restore normal visibility of the controls bar
*/
removeLoading: function () {
$('#content').removeClass('icon-loading');
this.controlsElement.f<|endoftext|> |
javascript | <fim-prefix>var expres<fim-middle>s = require('express');
var log4js = require('log4js');
var httpLogger = log4js.getLogger("http");
var settings = require('../../utils/Settings');
var hooks = require('ep_etherpad-lite/static/js/plugi<fix-suffix>nfw/hooks');
var ueberStore = require('../../db/SessionStore');
var stats = require('ep_etherpad-lite/node/stats');
var sessionModule = require('express-session');
var cookieParser = require('cookie-parser');
//checks for basic http auth
exports.basicAuth = function (req, res, next) {
var hookResultMangle = function (cb) {
return function (err, data) {
return cb(!err && data.length && data[0]);
}
}
var authorize = function (cb) {
// Do not require auth for static paths and the API...this could be a bit brittle
if (req.path.match(/^\/(static|javascripts|pluginfw|api)/)) return cb(true);
// BUG: CWE-178 Improper Handling of Case Sensitivity
// if (req.path.indexOf('/admin') != 0) {
// FIXED:
if (req.path.toLowerCase().indexOf('/admin') != 0) {
if (!settings.requireAuthentication) return cb(true);
if (!settings.requireAuthorization && req.session && req.session.user) return cb(true);
}
if (req.session && req.session.user && req.session.user.is_admin) return cb(true);
hooks.aCallFirst("authorize", {req: req, res:res, next:next, resource: req.path}, hookResultMangle(cb));
}
var authenticate = function (cb) {
// If auth headers are present use them to authenticate...
if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) {
var userpass = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(":")
var username = userpass.shift();
<|endoftext|> |
javascript | <fim-prefix>ce_bytes_recursive.forEach(function (element) {
/**
* @namespace
* @property {string} op
* @property {number} value
*/
if (element.op && element.op.toLowerCase() === 'read' && element.value) {
result.r += element.value;
}
if (element.op && element.op.toLowerCase() === 'write' && element.value) {
result.w += element.value;
}
});
}
return result;
}
function dockerContainerStats(containerIDs, callback) {
let containerArray = [];
return new Promise((resolve) => {
process.nextTick(() => {
// fallback - if only callback is given
if (util.isFunction(containerIDs) && !callback) {
callback = containerIDs;
containerArray = ['*'];
} else {
containerIDs = containerIDs || '*';
if (typeof containerIDs !== 'string') {
if (callback) { callback([]); }
return resolve([]);
}
let containerIDsSanitized = '';
containerIDsSanitized.__proto__.toLowerCase = util.stringToLower;
containerIDsSanitized.__proto__.replace = util.stringReplace;
containerIDsSanitized.__proto__.trim = util.stringTrim;
containerIDsSanitized = containerIDs;
containerIDsSanitized = containerIDsSanitized.trim();
if (containerIDsSanitized !== '*') {
containerIDsSanitized = '';
const s = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerIDs, true)).trim();
// BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
// for (let i = 0; i <= 2000; i++) {
// FIXED:
<fim-middle> for (let i = 0; i <= util.mathMin(s.length, 2000); i++) {
if (!(s[i] === undefined)) {
s[i].__proto__.toLowerCase = util.stringToLower;
const sl = s[i<fix-suffix>].toLowerCase();
if (sl && sl[0] && !sl[1]) {
containerIDsSanitized = containerIDsSanitized + sl[0];
}
}
}
}
containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|');
containerArray = containerIDsSanitized.split('|');
}
const result = [];
const workload = [];
if (containerArray.length && containerArray[0].trim() === '*') {
containerArray = [];
dockerContainers().then(allContainers => {
for (let container of allContainers) {
containerArray.push(container.id);
}
if (containerArray.length) {
dockerContainerStats(containerArray.join(',')).then(result => {
if (callback) { callback(result); }
resolve(result);
});
} else {
if (callback) { callback(result); }
resolve(result);
}
});
} else {
for (let containerID of containerArray) {
workload.push(dockerContainerStatsSingle(containerID.trim()));
}
if (workload.length) {
Promise.all(
workload
).then(data => {
if (callback) { callback(data); }
resolve(data);
});
} else {
if (callback) { callback(result); }
resolve(result);
}
}
});
});
}
// --------------------------
// container sta<|endoftext|> |
javascript | <fim-prefix>ext, options) {
if (options.hash) {
context = Utils.extend({}, context, options.hash);
if (options.ids) {
options.ids[0] = true;
}
}
partial = env.VM.resolvePartial.call(this, partial, context, options);
let extendedOptions = Utils.extend({}, options, {
hooks: this.hooks,
protoAccessControl: this.protoAccessControl
});
let result = env.VM.invokePartial.call(
this,
partial,
context,
extendedOptions
);
if (result == null && env.compile) {
options.partials[options.name] = env.compile(
partial,
templateSpec.compilerOptions,
env
);
result = options.partials[options.name](context, extendedOptions);
}
if (result != null) {
if (options.indent) {
let lines = result.split('\n');
for (let i = 0, l = lines.length; i < l; i++) {
if (!lines[i] && i + 1 === l) {
break;
}
lines[i] = options.indent + lines[i];
}
result = lines.join('\n');
}
return result;
} else {
throw new Exception(
'The partial ' +
options.name +
' could not be compiled when running in runtime-only mode'
);
}
}
// Just add water
let container = {
strict: function(obj, name, loc) {
if (!obj || !(name in obj)) {
throw new Exception('"' + name + '" not defined in ' + obj, {
loc: loc
});
}
// BUG: NVD-CWE-noinfo Insufficient Information
// return obj[name];
// FIXED:
<fim-middle> return container.lookupProperty(obj, name);
},
lookupProperty: function(parent, propertyName) {
let result = parent[propertyName];
if (result == null) {
return result<fix-suffix>;
}
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return result;
}
if (resultIsAllowed(result, container.protoAccessControl, propertyName)) {
return result;
}
return undefined;
},
lookup: function(depths, name) {
const len = depths.length;
for (let i = 0; i < len; i++) {
let result = depths[i] && container.lookupProperty(depths[i], name);
if (result != null) {
return depths[i][name];
}
}
},
lambda: function(current, context) {
return typeof current === 'function' ? current.call(context) : current;
},
escapeExpression: Utils.escapeExpression,
invokePartial: invokePartialWrapper,
fn: function(i) {
let ret = templateSpec[i];
ret.decorator = templateSpec[i + '_d'];
return ret;
},
programs: [],
program: function(i, data, declaredBlockParams, blockParams, depths) {
let programWrapper = this.programs[i],
fn = this.fn(i);
if (data || depths || blockParams || declaredBlockParams) {
programWrapper = wrapProgram(
this,
i,
fn,
data,
declaredBlockParams,
blockParams,
depths
);
} else if (!programWrapper) {
programWrapper = this.programs[i] = wrapProgram(this, i, fn);
}
return programWrapper;
},
data: function(value, depth) {
while (value && depth--) {
<|endoftext|> |
javascript | <fim-prefix>(function (Prism) {
// CAREFUL!
// The following patterns are concatenated, so the group referenced by a back reference is non-obvious!
var strings = [
// normal string
// 1 capturing group
// BUG: NVD-CWE-noinfo Insufficient Information
// /(["'])(?:\\[\s\S]|\$\([^)]+\)|`[^`]+`|(?!\1)[^\\])*\1/.source,
// FIXED:
<fim-middle> /(["'])(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|(?!\1)[^\\`$])*\1/.source,
// here doc
// 2 capturing groups
/<<-?\s*(["']?)(\w+)\2\s[\s\S]*?[\r\n]\3/.source
].join('|');
Prism.languages['<fix-suffix>shell-session'] = {
'info': {
// foo@bar:~/files$ exit
// foo@bar$ exit
pattern: /^[^\r\n$#*!]+(?=[$#])/m,
alias: 'punctuation',
inside: {
'path': {
pattern: /(:)[\s\S]+/,
lookbehind: true
},
'user': /^[^\s@:$#*!/\\]+@[^\s@:$#*!/\\]+(?=:|$)/,
'punctuation': /:/
}
},
'command': {
pattern: RegExp(/[$#](?:[^\\\r\n'"<]|\\.|<<str>>)+/.source.replace(/<<str>>/g, function () { return strings; })),
greedy: true,
inside: {
'bash': {
pattern: /(^[$#]\s*)[\s\S]+/,
lookbehind: true,
alias: 'language-bash',
inside: Prism.languages.bash
},
'shell-symbol': {
pattern: /^[$#]/,
alias: 'important'
}
}
},
'output': /.(?:.*(?:[\r\n]|.$))*/
};
Prism.languages['sh-session'] = Prism.languages['shellsession'] = Prism.languages['shell-session'];
}(Prism));
<|endoftext|> |
javascript | <fim-prefix><fim-middle>(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof mo<fix-suffix>dule === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function ($) {
// Extends plugins for adding readmore.
// - plugin is external module for customizing.
$.extend($.summernote.plugins, {
/**
* @param {Object} context - context object has status of editor.
*/
'readmore': function (context) {
var self = this;
// ui has renders to build ui elements.
// - you can create a button with `ui.button`
var ui = $.summernote.ui;
// add readmore button
context.memo('button.readmore', function () {
// create button
var button = ui.button({
contents: '<i class="fa fa-long-arrow-right"/> Read-More',
tooltip: 'readmore',
click: function () {
context.invoke('editor.insertText', '[[--readmore--]]');
}
});
// create jQuery object from button instance.
var $readmore = button.render();
return $readmore;
});
},
'elfinder': function (context) {
var self = this;
// ui has renders to build ui elements.
// - you can cre<|endoftext|> |
javascript | <fim-prefix>var userentitiesTable = $('#userentities-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
]
});
$('#userentities-table tbody').removeClass("d-none");
userentitiesTable.columns.adjust().draw();
$("#search").on("keyup", Delay(function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
userentitiesTable.search(value).draw();
}, 200));
$(document).on('click', '.userentity-delete-button', function(e)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var objectName = $(e.currentTarget).attr('data-userentity-name');
// FIXED:
<fim-middle> var objectName = SanitizeHtml($(e.currentTarget).attr('data-userentity-name'));
var objectId = $(e.currentTarget).attr('data-userentity-id');
bootbox.confirm({
message: __t('Are you sure to dele<fix-suffix>te userentity "%s"?', objectName),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/userentities/' + objectId, {},
function(result)
{
window.location.href = U('/userentities');
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle>ery.ui.plupload.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*
* <fix-suffix>Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.button.js
* jquery.ui.progressbar.js
*
* Optionally:
* jquery.ui.sortable.js
*/
/* global jQuery:true */
/**
jQuery UI based implementation of the Plupload API - multi-runtime file uploading API.
To use the widget you must include _jQuery_ and _jQuery UI_ bundle (including `ui.core`, `ui.widget`, `ui.button`,
`ui.progressbar` and `ui.sortable`).
In general the widget is designed the way that you do not usually need to do anything to it after you instantiate it.
But! You still can intervenue, to some extent, in case you need to. Although, due to the fact that widget is based on
_jQuery UI_ widget factory, there are some specifics. See examples below for more details.
@example
<!-- Instantiating: -->
<div id="uploader">
<p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
</div>
<script>
$('#uploader').plupload({
url : '../upload.php',
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
],
rename: true,
sortable: true,
flash_swf_url : '../../js/Moxie.swf',
silverlight_xap_url : '../../js/Moxie.xap',
});
</script>
@example
// Invoking methods:
$('#uploader').plupload(options);
// Display welcome message in the notification area
$('#uploader').plupload('notify', 'info', "This might be obvious, but you need to click 'Add Files' to add some files.");
@example
// Subscribing to the events...
// ... on initialization:
$('#uploader').<|endoftext|> |
javascript | <fim-prefix>var mxIsEl<fim-middle>ectron = navigator.userAgent != null &&
navigator.userAgent.toLowerCase().indexOf(' electron/') > -1;
var GOOGLE_APPS_MAX_AREA = 25000000;
var GOOGLE_SHEET_MAX_AREA = 1048576; //1024x1024
//TODO Add<fix-suffix> support for loading math from a local folder
Editor.initMath((remoteMath? 'https://app.diagrams.net/' : '') + 'math/MathJax.js');
function render(data)
{
var autoScale = false;
if (data.scale == 'auto')
{
autoScale = true;
data.scale = 1;
}
// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
// document.body.innerHTML = '';
// FIXED:
document.body.innerText = '';
var container = document.createElement('div');
container.id = 'graph';
container.style.width = '100%';
container.style.height = '100%';
document.body.appendChild(container);
var graph = new Graph(container);
data.border = parseInt(data.border) || 0;
data.w = parseFloat(data.w) || 0;
data.h = parseFloat(data.h) || 0;
data.scale = parseFloat(data.scale) || 1;
var extras = null;
try
{
extras = JSON.parse(data.extras);
}
catch (e)
{
try
{
extras = JSON.parse(decodeURIComponent(data.extras));
}
catch (e)
{
// ignore
}
}
var gridColor = null;
if (extras != null && extras.grid != null)
{
graph.gridSize = extras.grid.size;
graph.view.gridSteps = extras.grid.steps;
gridColor = extras.grid.color;
}
if (extras != null && extras.diagramLanguage != null)
{
Graph.diagramLanguage = extras.diagramLanguage;
Graph.translateDiagram = true;
}
//PNG+XML format
if (data.xml.substring(0, 5) == 'iVBOR' || (extras != null && extras.isPng))
{
data.xml = Editor.extractGraphModelFromPng('data:image/png;base64,' + data.xml);
}
//IE1<|endoftext|> |
javascript | <fim-prefix>t}`,
proxyPayloads: false,
preHandler (request, reply, next) {
t.deepEqual(request.body, { hello: 'world' })
next()
}
})
await server.listen(0)
t.tearDown(server.close.bind(server))
await got(
`http://localhost:${server.server.address().port}/this-has-data`,
{
method: 'POST',
json: { hello: 'world' },
responseType: 'json'
}
)
})
test('preHandler', async t => {
const server = Fastify()
server.register(proxy, {
upstream: `http://localhost:${origin.server.address().port}`,
async preHandler (request, reply) {
throw new Unauthorized()
}
})
await server.listen(0)
t.tearDown(server.close.bind(server))
let errored = false
try {
await got(`http://localhost:${server.server.address().port}`)
} catch (err) {
t.equal(err.response.statusCode, 401)
errored = true
}
t.ok(errored)
errored = false
try {
await got(`http://localhost:${server.server.address().port}/a`)
} catch (err) {
t.equal(err.response.statusCode, 401)
errored = true
}
t.ok(errored)
})
test('preHandler gets config', async t => {
const server = Fastify()
server.register(proxy, {
upstream: `http://localhost:${origin.server.address().port}`,
config: { foo: 'bar' },
async preHandler (request, reply) {
t.deepEqual(reply.context.config, {
foo: 'bar',
// BUG: CWE-20 Improper Input Validation
// url: '/*',
// FIXED:
<fim-middle> url: '/',
method: [
'DELETE',
'GET',
'HEAD',
'PATCH',
'POST',
'PUT',
'OPTIONS'
]
<fix-suffix> })
throw new Unauthorized()
}
})
await server.listen(0)
t.tearDown(server.close.bind(server))
let errored = false
try {
await got(`http://localhost:${server.server.address().port}`)
} catch (err) {
t.equal(err.response.statusCode, 401)
errored = true
}
t.ok(errored)
})
test('multiple prefixes with multiple plugins', async t => {
const origin2 = Fastify()
origin2.get('/', async (request, reply) => {
return 'this is root for origin2'
})
await origin2.listen(0)
const proxyServer = Fastify()
// register first proxy on /api
proxyServer.register(proxy, {
upstream: `http://localhost:${origin.server.address().port}`,
prefix: '/api'
})
// register second proxy on /api2
proxyServer.register(proxy, {
upstream: `http://localhost:${origin2.server.address().port}`,
prefix: '/api2'
})
await proxyServer.listen(0)
t.tearDown(() => {
origin2.close()
proxyServer.close()
})
const firstProxyPrefix = await got(
`http://localhost:${proxyServer.server.address().port}/api`
)
t.equal(firstProxyPrefix.body, 'this is root')
const secondProxyPrefix = await got(
`http://localhost:${proxyServer.server.address().port}/api2`
)
t.equal(secondProxyPrefix.body, 'this is root for origin2')
})
test('passes replyOptions object to reply.from() calls', async t => {
const proxyServer = Fastify()<|endoftext|> |
javascript | <fim-prefix><fim-middle>lowRouter } from 'meteor/ostrio:flow-router-extra'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import Bootstrap from 'bootstrap'
import { i18nReady, t } from '../../utils/i18n.js'
imp<fix-suffix>ort './projectTasks.html'
import Tasks from '../../api/tasks/tasks'
import './taskModal.js'
import {
addToolTipToTableCell, getGlobalSetting, showToast,
} from '../../utils/frontend_helpers'
dayjs.extend(utc)
Template.projectTasks.onCreated(function projectTasksCreated() {
this.subscribe('projectTasks', { projectId: FlowRouter.getParam('id') })
this.editTaskID = new ReactiveVar(false)
})
Template.projectTasks.onRendered(() => {
const templateInstance = Template.instance()
const tasks = Tasks.find({ projectId: FlowRouter.getParam('id') })
templateInstance.autorun(() => {
if (templateInstance.subscriptionsReady() && i18nReady.get() && tasks.count() > 0) {
const columns = [
{
name: t('project.default_task'),
editable: false,
width: 1,
format: (value) => `<div class="form-check"><input type="checkbox" data-id="${value}" class="form-check-input mx-auto" ${Tasks.findOne({ _id: value }).isDefaultTask ? 'checked' : ''}/></div>`,
},
{
name: t('globals.task'),
editable: true,
format: addToolTipToTableCell,
width: 2,
},
{
name: t('task.startDate'),
editable: true,
compareValue: (cell, keyword) => [dayjs.utc(cell, getGlobalSetting('dateformat')).toDate(), dayjs(keyword, getGlobalSetting('dateformat')).toDate()],
format: addToolTipToTableCell,
},
{
name: t('task.endDate'),
<|endoftext|> |
javascript | <fim-prefix>(id, scope) {
$.get( "/sightings/viewSightings/" + id + "/" + scope, function(data) {
$("#sightingsData").html(data);
});
}
function checkRolePerms() {
if ($("#RolePermission").val() == '0' || $("#RolePermission").val() == '1') {
$('.readonlydisabled').prop('checked', false);
$('.readonlydisabled').hide();
} else {
$('.readonlydisabled').show();
$('.permFlags').show();
}
if ($("#RolePermSiteAdmin").prop('checked')) {
$('.checkbox').prop('checked', true);
}
}
// clicking on an element with this class will select all of its contents in a
// single click
$('.quickSelect').click(function() {
var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(this);
selection.removeAllRanges();
selection.addRange(range);
});
function updateMISP() {
$.get( "/servers/update", function(data) {
$("#confirmation_box").html(data);
openPopup("#confirmation_box");
});
}
function submitMISPUpdate() {
var formData = $('#PromptForm').serialize();
$.ajax({
beforeSend: function (XMLHttpRequest) {
$(".loading").show();
},
data: formData,
success:function (data, textStatus) {
$('#gitResult').text(data);
$('#gitResult').removeClass('hidden');
},
complete:function() {
$(".loading").hide();
$("#confirmation_box").fadeOut();
$("#gray_out").fadeOut();
},
type:"post",
cache: false,
url:"/servers/update",
});
}
$(".cortex-json").click(function() {
var cortex_data = $(this).data('cortex-json');
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// cortex_data = JSON.stringify(cortex_data, null, 2);
// FIXED:
<fim-middle> cortex_data = htmlEncode(JSON.stringify(cortex_data, null, 2));
var popupHtml = '<pre class="simplepre">' + cortex_data + '</pre>';
popupHtml += '<div class="close-icon useCursorPointer" onClick="c<fix-suffix>loseScreenshot();"></div>';
$('#screenshot_box').html(popupHtml);
$('#screenshot_box').show();
$('#screenshot_box').css({'padding': '5px'});
left = ($(window).width() / 2) - ($('#screenshot_box').width() / 2);
if (($('#screenshot_box').height() + 250) > $(window).height()) {
$('#screenshot_box').height($(window).height() - 250);
$('#screenshot_box').css("overflow-y", "scroll");
$('#screenshot_box').css("overflow-x", "hidden");
}
$('#screenshot_box').css({'left': left + 'px'});
$("#gray_out").fadeIn();
});
// Show $(id) if the enable parameter evaluates to true. Hide it otherwise
function checkAndEnable(id, enable) {
if (enable) {
$(id).show();
} else {
$(id).hide();
}
}
// Show and enable checkbox $(id) if the enable parameter evaluates to true. Hide and disable it otherwise.
function checkAndEnableCheckbox(id, enable) {
if (enable) {
$(id).removeAttr("disabled");
$(id).prop('checked', true);
} else {
$(id).prop('checked', false);
$(id).attr("disabled", true);
}
}
function enableDisableObjectRows(rows) {
rows.forEach(function(i) {
if ($("#Attribute" + i + "ValueSelect").length != 0) {
checkAndEnableCheckbox("#Attribute" + i + "Save", true);
} else if ($("#Attribute" + i + "Attachment").length != 0) {
checkAndEnableCheckbox("#Attribute" + i + "Save", $("#Attribute" + i + "Attachment").val() != "");
} else {
checkAndEnableCheckbox("#Attribute" + i + "Save", $("#Attribute" + i + "Value").val() != "");
}
$("#Attribute" + i + <|endoftext|> |
javascript | <fim-prefix>/**
* @ov<fim-middle>erview Contains functionality specifically for Windows systems.
* @license MPL-2.0
* @author Eric Cornelissen <ericornelissen@gmail.com>
*/
/**
* Escape a shell argument.
*
* @param {string} ar<fix-suffix>g The argument to escape.
* @returns {string} The escaped argument.
*/
function escapeShellArg(arg) {
// BUG: CWE-88 Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
// return arg.replace(/"/g, `""`);
// FIXED:
return arg.replace(/\u{0}/gu, "").replace(/"/g, `""`);
}
module.exports.escapeShellArg = escapeShellArg;
<|endoftext|> |
javascript | <fim-prefix>var produ<fim-middle>ctsTable = $('#products-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
]
});
$('#products-table tbody').r<fix-suffix>emoveClass("d-none");
productsTable.columns.adjust().draw();
$("#search").on("keyup", Delay(function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
productsTable.search(value).draw();
}, 200));
$("#product-group-filter").on("change", function()
{
var value = $("#product-group-filter option:selected").text();
if (value === __t("All"))
{
value = "";
}
productsTable.column(7).search(value).draw();
});
if (typeof GetUriParam("product-group") !== "undefined")
{
$("#product-group-filter").val(GetUriParam("product-group"));
$("#product-group-filter").trigger("change");
}
$(document).on('click', '.product-delete-button', function(e)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var objectName = $(e.currentTarget).attr('data-product-name');
// FIXED:
var objectName = SanitizeHtml($(e.currentTarget).attr('data-product-name'));
var objectId = $(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + objectId,
function(productDetails)
{
var stockAmount = productDetails.stock_amount || '0';
if (stockAmount.toString() == "0")
{
bootbox.confirm({
message: __t('Are you sure you want to deactivate this product "%s"?', objectName),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
<|endoftext|> |
javascript | <fim-prefix>const { cl<fim-middle>ean, override } = abuser(__filename);
describe('lib/unadded', () => {
let unadded;
before(() => {
clean('.');
// BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command (<fix-suffix>'OS Command Injection')
// override('async-execute', () => `remove '.gitattributes'
// FIXED:
override('../../helpers/spawn', () => `remove '.gitattributes'
add 'apps/post/index.js'
add 'new file.txt'
`);
unadded = require('.');
});
after(() => clean('.'));
it('should convert dry-run add to a file list', async() => {
const list = await unadded();
expect(list).to.deep.equal([
'.gitattributes',
'apps/post/index.js',
'new file.txt',
]);
});
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle>ight (C) 2016 University of Dundee & Open Microscopy Environment.
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GN<fix-suffix>U Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// This program 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
var CommentsPane = function CommentsPane($element, opts) {
var $header = $element.children('h1'),
$body = $element.children('div'),
$comments_container = $("#comments_container"),
objects = opts.selected;
var self = this;
var tmplText = $('#comments_template').html();
var commentsTempl = _.template(tmplText);
var initEvents = (function initEvents() {
$header.on('click', function(){
$header.toggleClass('closed');
$body.slideToggle();
var expanded = !$header.hasClass('closed');
OME.setPaneExpanded('comments', expanded);
if (expanded && $comments_container.is(":empty")) {
this.render();
}
}.bind(this));
}).bind(this);
// Comment field - show/hide placeholder and submit button.
$("#add_comment_wrapper label").inFieldLabels();
$("#id_comment")
<|endoftext|> |
javascript | <fim-prefix><fim-middle>(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define('simple-uploader', ["jquery","simple-module"], fu<fix-suffix>nction ($, SimpleModule) {
return (root['uploader'] = factory($, SimpleModule));
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"),require("simple-module"));
} else {
root.simple = root.simple || {};
root.simple['uploader'] = factory(jQuery,SimpleModule);
}
}(this, function ($, SimpleModule) {
var Uploader, uploader,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Uploader = (function(superClass) {
extend(Uploader, superClass);
function Uploader() {
return Uploader.__super__.constructor.apply(this, arguments);
}
Uploader.count = 0;
Uploader.prototype.opts = {
url: '',
params: null,
fileKey: 'upload_file',
connectionCount: 3
};
Uploader.prototype._init = function() {
this.files = [];
this.queue = [];
this.id = ++Uploader.count;
this.on('uploadcomplete', (function(_this) {
return function(e, file) {
_this.files.splice($.inArray(file, _this.files), 1);
if (_this.queue.length > 0 && _this.files.length < _this.opts.connectionCount) {
<|endoftext|> |
javascript | <fim-prefix>module.exp<fim-middle>orts = function gopher_parsedir (dirent) { // eslint-disable-line camelcase
// discuss at: https://locutus.io/php/gopher_parsedir/
// original by: Brett Zamir (https://brett-zamir.me)
// exam<fix-suffix>ple 1: var entry = gopher_parsedir('0All about my gopher site.\t/allabout.txt\tgopher.example.com\t70\u000d\u000a')
// example 1: entry.title
// returns 1: 'All about my gopher site.'
/* Types
* 0 = plain text file
* 1 = directory menu listing
* 2 = CSO search query
* 3 = error message
* 4 = BinHex encoded text file
* 5 = binary archive file
* 6 = UUEncoded text file
* 7 = search engine query
* 8 = telnet session pointer
* 9 = binary file
* g = Graphics file format, primarily a GIF file
* h = HTML file
* i = informational message
* s = Audio file format, primarily a WAV file
*/
// BUG: NVD-CWE-noinfo Insufficient Information
// const entryPattern = /^(.)(.*?)\t(.*?)\t(.*?)\t(.*?)\u000d\u000a$/
// FIXED:
const entryPattern = /^(.)([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\r\n$/
const entry = dirent.match(entryPattern)
if (entry === null) {
throw new Error('Could not parse the directory entry')
// return false;
}
let type = entry[1]
switch (type) {
case 'i':
// GOPHER_INFO
type = 255
break
case '1':
// GOPHER_DIRECTORY
type = 1
break
case '0':
// GOPHER_DOCUMENT
type = 0
break
case '4':
// GOPHER_BINHEX
type = 4
break
case '5':
// GOPHER_DOSBINARY
type = 5
break
case '6':
// GOPHER_UUENCODED
type = 6
break
case '9':
// GOPHER_BINARY
type = 9
break
case 'h':
<|endoftext|> |
javascript | <fim-prefix>/* vim: se<fim-middle>t expandtab sw=4 ts=4 sts=4: */
var chart_data = {};
var temp_chart_title;
var currentChart = null;
var currentSettings = null;
function extractDate(dateString) {
var matches, match;
var da<fix-suffix>teTimeRegExp = /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/;
var dateRegExp = /[0-9]{4}-[0-9]{2}-[0-9]{2}/;
matches = dateTimeRegExp.exec(dateString);
if (matches !== null && matches.length > 0) {
match = matches[0];
return new Date(match.substr(0, 4), match.substr(5, 2), match.substr(8, 2), match.substr(11, 2), match.substr(14, 2), match.substr(17, 2));
} else {
matches = dateRegExp.exec(dateString);
if (matches !== null && matches.length > 0) {
match = matches[0];
return new Date(match.substr(0, 4), match.substr(5, 2), match.substr(8, 2));
}
}
return null;
}
function PMA_queryChart(data, columnNames, settings) {
if ($('#querychart').length === 0) {
return;
}
var jqPlotSettings = {
title : {
text : settings.title,
escapeHtml: true
},
grid : {
drawBorder : false,
shadow : false,
background : 'rgba(0,0,0,0)'
},
legend : {
show : true,
placement : 'outsideGrid',
location : 'e'
},
axes : {
xaxis : {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// label : settings.xaxisLabel
// FIXED:
label : escapeHtml(settings.xaxisLabel)
},
yaxis : {
label <|endoftext|> |
javascript | <fim-prefix>// Build S<fim-middle>taffDebug object
var StaffDebug = (function (){
get_current_url = function() {
return window.location.pathname;
};
get_url = function(action){
var pathname = this.get_current_url();
<fix-suffix> var url = pathname.substr(0,pathname.indexOf('/courseware')) + '/instructor/api/' + action;
return url;
};
sanitized_string = function(string) {
return string.replace(/[.*+?^:${}()|[\]\\]/g, "\\$&");
};
get_user = function(locname){
locname = sanitized_string(locname);
var uname = $('#sd_fu_' + locname).val();
if (uname===""){
uname = $('#sd_fu_' + locname).attr('placeholder');
}
return uname;
};
do_idash_action = function(action){
var pdata = {
'problem_to_reset': action.location,
'unique_student_identifier': get_user(action.locationName),
'delete_module': action.delete_module
};
$.ajax({
// BUG: CWE-352 Cross-Site Request Forgery (CSRF)
// type: "GET",
// FIXED:
type: "POST",
url: get_url(action.method),
data: pdata,
success: function(data){
var text = _.template(action.success_msg, {interpolate: /\{(.+?)\}/g})(
{user: data.student}
);
var html = _.template('<p id="idash_msg" class="success">{text}</p>', {interpolate: /\{(.+?)\}/g})(
{text: text}
);
$("#result_"+sanitized_string(action.locationName)).html(html);
},
error: function(request, status, error) {
var response_json;
try {
response_json = $.parseJSON(request.responseText);
} catch(e) {
response_json <|endoftext|> |
javascript | <fim-prefix><fim-middle>: Craft */
/** global: Garnish */
Craft.FieldLayoutDesigner = Garnish.Base.extend({
$container: null,
$tabContainer: null,
$newTabBtn: null,
$sidebar: null,
$libraryToggle: null,
<fix-suffix> $selectedLibrary: null,
$fieldLibrary: null,
$uiLibrary: null,
$uiLibraryElements: null,
$fieldSearch: null,
$clearFieldSearchBtn: null,
$fieldGroups: null,
$fields: null,
tabGrid: null,
elementDrag: null,
init: function(container, settings) {
this.$container = $(container);
this.setSettings(settings, Craft.FieldLayoutDesigner.defaults);
let $workspace = this.$container.children('.fld-workspace');
this.$tabContainer = $workspace.children('.fld-tabs');
this.$newTabBtn = $workspace.children('.fld-new-tab-btn');
this.$sidebar = this.$container.children('.fld-sidebar');
this.$fieldLibrary = this.$selectedLibrary = this.$sidebar.children('.fld-field-library');
let $fieldSearchContainer = this.$fieldLibrary.children('.search');
this.$fieldSearch = $fieldSearchContainer.children('input');
this.$clearFieldSearchBtn = $fieldSearchContainer.children('.clear');
this.$fieldGroups = this.$sidebar.find('.fld-field-group');
this.$fields = this.$fieldGroups.children('.fld-element');
this.$uiLibrary = this.$sidebar.children('.fld-ui-library');
this.$uiLibraryElements = this.$uiLibrary.children();
// Set up the layout grids
this.tabGrid = new Craft.Grid(this.$tabContainer, {
itemSelector: '.fld-tab',
minColWidth: 24 * 11,
fillMode: 'grid',
snapToGrid: 24
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle>/utils/tar.js and this file need to be rewritten.
// URL-to-cache folder mapping:
// : -> !
// @ -> _
// http://registry.npmjs.org/foo/version -> cache/http!/...
//
/*
fetching a URL:
1. Check for U<fix-suffix>RL in inflight URLs. If present, add cb, and return.
2. Acquire lock at {cache}/{sha(url)}.lock
retries = {cache-lock-retries, def=10}
stale = {cache-lock-stale, def=60000}
wait = {cache-lock-wait, def=10000}
3. if lock can't be acquired, then fail
4. fetch url, clear lock, call cbs
cache folders:
1. urls: http!/server.com/path/to/thing
2. c:\path\to\thing: file!/c!/path/to/thing
3. /path/to/thing: file!/path/to/thing
4. git@ private: git_github.com!npm/npm
5. git://public: git!/github.com/npm/npm
6. git+blah:// git-blah!/server.com/foo/bar
adding a folder:
1. tar into tmp/random/package.tgz
2. untar into tmp/random/contents/package, stripping one dir piece
3. tar tmp/random/contents/package to cache/n/v/package.tgz
4. untar cache/n/v/package.tgz into cache/n/v/package
5. rm tmp/random
Adding a url:
1. fetch to tmp/random/package.tgz
2. goto folder(2)
adding a name@version:
1. registry.get(name/version)
2. if response isn't 304, add url(dist.tarball)
adding a name@range:
1. registry.get(name)
2. Find a version that satisfies
3. add name@version
adding a local tarball:
1. untar to tmp/random/{blah}
2. goto folder(2)
adding a namespaced package:
1. lookup registry for @namespace
2. namespace_registry.get('name')
3. add url(namespace/latest.tarball)
*/
exports = module.exports = cache
cache.unpack = unpack
cache.clean = clean
cache.read = read
var npm = require('./npm.js')
var fs = require('graceful-fs')
var writeFileAtomic = require('write-file-atomic')
var <|endoftext|> |
javascript | <fim-prefix>(function(window, undefined){
var isInit = false;
var ifr;
const isIE = checkInternetExplorer(); //check IE
var message = "This plugin doesn't work in Internet Explorer."
window.Asc.plugin.init = function(text)
{
if (isIE) {
document.getElementById("iframe_parent").innerHTML = "<h4 id='h4' style='margin:5px'>" + message + "</h4>";
return;
}
text = ProcessText(text);
if (!isInit) {
document.getElementById("iframe_parent").innerHTML = "";
ifr = document.createElement("iframe");
ifr.position = "fixed";
ifr.name = "google_name";
ifr.id = "google_id";
ifr.src = "./index_widget.html";//?text=" + encodeURIComponent(text);
ifr.style.top = "0px";
ifr.style.left = "0px";
ifr.style.width = "100%";
ifr.style.height = "100%";
ifr.setAttribute("frameBorder", "0");
document.getElementById("iframe_parent").appendChild(ifr);
isInit = true;
ifr.onload = function() {
if (ifr.contentWindow.document.readyState == 'complete')
setTimeout(function() {
// BUG: NVD-CWE-noinfo Insufficient Information
// ifr.contentDocument.getElementById("google_translate_element").innerHTML = text;
// FIXED:
<fim-middle> ifr.contentDocument.getElementById("google_translate_element").innerHTML = escape(text);
if (text.length)
ifr.contentDocument.getElementById("div_btn").classList.remove("hidden");
<fix-suffix> }, 500);
var selectElement = ifr.contentDocument.getElementsByClassName('goog-te-combo')[0];
selectElement.addEventListener('change', function(event) {
ifr.contentWindow.postMessage("onchange_goog-te-combo", '*');
ifr.contentDocument.getElementById("google_translate_element").style.opacity = 0;
});
ifr.contentDocument.getElementById("google_translate_element").style.height = "fit-content";
var btn = ifr.contentDocument.createElement("button");
var btnReplace = ifr.contentDocument.createElement("button");
var div = ifr.contentDocument.createElement("div");
div.appendChild(btn);
div.appendChild(btnReplace);
div.id = "div_btn";
div.classList.add("skiptranslate");
div.classList.add("div_btn");
div.classList.add("hidden");
btn.innerHTML = window.Asc.plugin.tr("Copy");
btn.id = "btn_copy";
btn.classList.add("btn-text-default");
btnReplace.classList.add("btn-text-default");
btnReplace.innerHTML = window.Asc.plugin.tr("Replace");
btnReplace.id = "btn_replace";
setTimeout(function() {ifr.contentDocument.getElementById("body").appendChild(div);}, 100);
setTimeout(function() {
btnReplace.onclick = function () {
var translatedTxt = ifr.contentDocument.getElementById("google_translate_element").outerText;
var allParasTxt = translatedTxt.split(/\n/);
var allParsedParas = [];
<|endoftext|> |
javascript | <fim-prefix>//
//
// Updates database dns record dynamically, showing its full domain path
App.Actions.DB.update_dns_record_hint = function(elm, hint) {
// clean hint
if (hint.trim() == '') {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// $(elm).parent().find('.hint').html('');
// FIXED:
<fim-middle> $(elm).parent().find('.hint').text('');
}
// set domain name without rec in case of @ entries
if (hint == '@') {
hint = '';
}
// dont show pregix if domain name =<fix-suffix> rec value
if (hint == GLOBAL.DNS_REC_PREFIX + '.') {
hint = '';
}
// add dot at the end if needed
if (hint != '' && hint.slice(-1) != '.') {
hint += '.';
}
$(elm).parent().find('.hint').text(hint + GLOBAL.DNS_REC_PREFIX);
}
//
// listener that triggers dns record name hint updating
App.Listeners.DB.keypress_dns_rec_entry = function() {
var ref = $('input[name="v_rec"]');
var current_rec = ref.val();
if (current_rec.trim() != '') {
App.Actions.DB.update_dns_record_hint(ref, current_rec);
}
ref.bind('keypress input', function(evt) {
clearTimeout(window.frp_usr_tmt);
window.frp_usr_tmt = setTimeout(function() {
var elm = $(evt.target);
App.Actions.DB.update_dns_record_hint(elm, $(elm).val());
}, 100);
});
}
//
// Page entry point
// Trigger listeners
App.Listeners.DB.keypress_dns_rec_entry();
<|endoftext|> |
javascript | <fim-prefix>t",
gitExtra = { env: process.env };
var escapeQuotes = function (str) {
if (typeof str === "string") {
return '"' + str.replace(/(["'$`\\])/g, "\\$1") + '"';
} else {
return str;
}
};
module.exports.isRepositoryClean = function (callback) {
cp.exec(gitApp + " " + ["ls-files", "-m"].join(" "), gitExtra, function (
er,
stdout,
stderr
) {
// makeCommit parly inspired and taken from NPM version module
var lines = stdout
.trim()
.split("\n")
.filter(function (line) {
var file = path.basename(line.replace(/.{1,2}\s+/, ""));
return (
line.trim() && !line.match(/^\?\? /) && !fUtils.isPackageFile(line)
);
})
.map(function (line) {
return line.trim();
});
if (lines.length) {
return callback(
new Error("Git working directory not clean.\n" + lines.join("\n"))
);
}
return callback();
});
};
module.exports.checkout = function (callback) {
cp.exec(gitApp + " checkout -- .", gitExtra, callback);
};
module.exports.commit = function (files, message, newVer, tagName, callback) {
message = escapeQuotes(message.replace("%s", newVer));
files = files.map(escapeQuotes).join(" ");
var functionSeries = [
function (done) {
cp.exec(gitApp + " add " + files, gitExtra, done);
},
function (done) {
cp.exec([gitApp, "commit", "-m", message].join(" "), gitExtra, done);
},
function (done) {
cp.exec(
// BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
// [gitApp, "tag", "-a", tagName, "-m", message].join(" "),
// FIXED:
<fim-middle> [gitApp, "tag", "-a", escapeQuotes(tagName), "-m", message].join(" "),
gitExtra,
done
);
},
];
contra.series(functionSeries, callback);
};
<fix-suffix><|endoftext|> |
javascript | <fim-prefix><fim-middle>lter = 'view_today';
var listOfSelection = null;
var selectedCalendarCell = null;
var showCompletedTasks;
var currentDay = '';
var selectedDayNumber = -1;
var selectedDayDate = '';
var cachedDateS<fix-suffix>electors = [];
var contactSelectorAction = 'calendars-contacts';
var eventsToDelete = [];
var calendarsOfEventsToDelete = [];
var usersRightsWindowHeight = 215;
var usersRightsWindowWidth = 502;
var calendarEvents = null;
var preventAutoScroll = false;
var userStates = [ "needs-action", "accepted", "declined", "tentative", "delegated" ];
var calendarHeaderAdjusted = false;
var categoriesStyles = new Hash();
var categoriesStyleSheet = null;
var clipboard = null;
var eventsToCopy = [];
function newEvent(type, day, hour, duration) {
var folder = null;
if (UserDefaults['SOGoDefaultCalendar'] == 'personal')
folder = $("calendarList").down("li");
else if (UserDefaults['SOGoDefaultCalendar'] == 'first') {
var list = $("calendarList");
var inputs = list.select("input");
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.checked) {
folder = input.up();
break;
}
}
if (!folder)
folder = list.down("li");
}
else
folder = getSelectedFolder();
var folderID = folder.readAttribute("id");
var urlstr = ApplicationBaseURL + folderID + "/new" + type;
var params = [];
if (!day)
day = currentDay;
params.push("day=" + day);
if (hour)
params.push("hm=" + hour);
if (duration)
params.push("duration=" + duration);
if (params.length > 0)
urlstr += "?" + p<|endoftext|> |