{"language": "python", "text": "get_initial()\n current_region = self.request.session.get('region_endpoint', None)\n requested_region = self.request.GET.get('region', None)\n regions = dict(getattr(settings, \"AVAILABLE_REGIONS\", []))\n if requested_region in regions and requested_region != current_region:\n initial.update({'region': requested_region})\n return initial\n\n\ndef switch_tenants(request, tenant_id):\n \"\"\"\n Swaps a user from one tenant to another using the unscoped token from\n Keystone to exchange scoped tokens for the new tenant.\n \"\"\"\n form, handled = LoginWithTenant.maybe_handle(\n request, initial={'tenant': tenant_id,\n 'username': request.user.username})\n if handled:\n return handled\n\n unscoped_token = request.session.get('unscoped_token', None)\n if unscoped_token:\n try:\n token = api.token_create_scoped(request,\n tenant_id,\n unscoped_token)\n _set_session_data(request, token)\n user = users.User(users.get_user_from_request(request))\n return shortcuts.redirect(Horizon.get_user_home(user))\n except:\n exceptions.handle(request,\n _(\"You are not authorized for that tenant.\"))\n\n return shortcuts.redirect(\"horizon:auth_login\")\n\n\ndef logout(request):\n \"\"\" Clears the session and logs the current user out. \"\"\"\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n # FIXME(gabriel): we don't ship a view named splash\n return shortcuts.redirect('splash')\n<|endoftext|>"} {"language": "python", "text": "scii\")\n # If the header exists, add to the comma-separated list of the first\n # instance of the header. Otherwise, generate a new header.\n if x_forwarded_for:\n x_forwarded_for = [\n x_forwarded_for[0] + b\", \" + previous_host\n ] + x_forwarded_for[1:]\n else:\n x_forwarded_for = [previous_host]\n headers[b\"X-Forwarded-For\"] = x_forwarded_for\n\n try:\n result = await self.http_client.post_json_get_json(\n self.main_uri + request.uri.decode(\"ascii\"), body, headers=headers\n )\n except HttpResponseException as e:\n raise e.to_synapse_error() from e\n except RequestSendFailed as e:\n raise SynapseError(502, \"Failed to talk to master\") from e\n\n return 200, result\n else:\n # Just interested in counts.\n result = await self.store.count_e2e_one_time_keys(user_id, device_id)\n return 200, {\"one_time_key_counts\": result}\n\n\nclass _NullContextManager(ContextManager[None]):\n \"\"\"A context manager which does nothing.\"\"\"\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n\nUPDATE_SYNCING_USERS_MS = 10 * 1000\n\n\nclass GenericWorkerPresence(BasePresenceHandler):\n def __init__(self, hs):\n super().__init__(hs)\n self.hs = hs\n self.is_mine_id = hs.is_mine_id\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self._presence_enabled = hs.config.use_presence\n\n # The number of ongoing syncs on this process, by user id.\n # Empty if _presence_enabled is false.\n self._user_to_num_current_syncs = {} # type: Dict[str, int]\n\n self.notifier = hs.get_notifier()\n self.instance_id = hs.get_instance_id()\n\n # user_id -> last_sync_ms. Lists the users that have stopped syncing\n # but we haven't notified the master of that yet\n self.users_going_offline = {}\n\n self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs)\n self._set_state_client = ReplicationPresenceSetState.make_client(hs)\n\n self._send_stop_syncing_loop = self.clock.looping_call(\n self.send_stop_syncing, UPDATE_SYNCING_USERS_MS\n )\n\n hs.get_reactor().addSystemEventTrigger(\n \"before\",\n \"shutdown\",\n run_as_background_process,\n \"generic_presence.on_shutdown\",\n self._on_shutdown,\n )\n\n def _on_shutdown(self):\n if self._presence_enabled:\n self.hs.get_tcp_replication().send_command(\n ClearUserSyncsCommand(self.instance_id)\n )\n\n def send_user_sync(self, user_id, is_syncing, last_sync_ms):\n if self._presence_enabled:\n self.hs.get_tcp_replication().send_user_sync(\n self.instance_id, user_id, is_syncing, last_sync_ms\n )\n\n def mark_as_coming_online(self, user_id):\n \"\"\"A user has started syncing. Send a UserSync to the master, unless they\n had recently stopped syncing.\n\n Args:\n user_id (str)\n \"\"\"\n going_offline = self<|endoftext|>"} {"language": "python", "text": "# Copyright Red Hat 2017, Jake Hunsaker \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n\n# This program 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\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nimport fnmatch\nimport inspect\nimport logging\nimport os\nimport random\nimport re\nimport string\nimport tarfile\nimport threading\nimport tempfile\nimport shutil\nimport subprocess\nimport sys\n\nfrom datetime import datetime\nfrom concurrent.futures import ThreadPoolExecutor\nfrom .sosnode import SosNode\nfrom distutils.sysconfig import get_python_lib\nfrom getpass import getpass\nfrom six.moves import input\nfrom textwrap import fill\nfrom soscollector import __version__\n\n\nclass SosCollector():\n '''Main sos-collector class'''\n\n def __init__(self, config):\n # BUG: CWE-276 Incorrect Default Permissions\n # \n # FIXED: \n os.umask(0077)\n self.config = config\n self.threads = []\n self.workers = []\n self.client_list = []\n self.node_list = []\n self.master = False\n self.retrieved = 0\n self.need_local_sudo = False\n if not self.config['list_options']:\n try:\n if not self.config['tmp_dir']:\n self.create_tmp_dir()\n self._setup_logging()\n self.log_debug('Executing %s' % ' '.join(s for s in sys.argv))\n self._load_clusters()\n self._parse_options()\n self.prep()\n except KeyboardInterrupt:\n self._exit('Exiting on user cancel', 130)\n else:\n self._load_clusters()\n\n def _setup_logging(self):\n # behind the scenes logging\n self.logger = logging.getLogger('sos_collector')\n self.logger.setLevel(logging.DEBUG)\n self.logfile = tempfile.NamedTemporaryFile(\n mode=\"w+\",\n dir=self.config['tmp_dir'])\n hndlr = logging.StreamHandler(self.logfile)\n hndlr.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s'))\n hndlr.setLevel(logging.DEBUG)\n self.logger.addHandler(hndlr)\n\n console = logging.StreamHandler(sys.stderr)\n console.setFormatter(logging.Formatter('%(message)s'))\n\n # ui logging\n self.console = logging.getLogger('sos_collector_console')\n self.console.setLevel(logging.DEBUG)\n self.console_log_file = tempfile.NamedTemporaryFile(\n mode=\"w+\",\n dir=self.config['tmp_dir'])\n chandler = logging.StreamHandler(self.<|endoftext|>"} {"language": "python", "text": "n/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016-2017, Yanis Guenane \n# Copyright: (c) 2017, Markus Teufelberger \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = r'''\n---\nmodule: openssl_privatekey_info\nshort_description: Provide information for OpenSSL private keys\ndescription:\n - This module allows one to query information on OpenSSL private keys.\n - In case the key consistency checks fail, the module will fail as this indicates a faked\n private key. In this case, all return variables are still returned. Note that key consistency\n checks are not available all key types; if none is available, C(none) is returned for\n C(key_is_consistent).\n - It uses the pyOpenSSL or cryptography python library to interact with OpenSSL. If both the\n cryptography and PyOpenSSL libraries are available (and meet the minimum version requirements)\n cryptography will be preferred as a backend over PyOpenSSL (unless the backend is forced with\n C(select_crypto_backend)). Please note that the PyOpenSSL backend was deprecated in Ansible 2.9\n and will be removed in community.crypto 2.0.0.\nrequirements:\n - PyOpenSSL >= 0.15 or cryptography >= 1.2.3\nauthor:\n - Felix Fontein (@felixfontein)\n - Yanis Guenane (@Spredzy)\noptions:\n path:\n description:\n - Remote absolute path where the private key file is loaded from.\n type: path\n content:\n description:\n - Content of the private key file.\n <|endoftext|>"} {"language": "python", "text": "444154789c63000100000500010d\"\n b\"0a2db40000000049454e44ae426082\"\n )\n\n def make_homeserver(self, reactor, clock):\n\n self.fetches = []\n\n async def get_file(destination, path, output_stream, args=None, max_size=None):\n \"\"\"\n Returns tuple[int,dict,str,int] of file length, response headers,\n absolute URI, and response code.\n \"\"\"\n\n def write_to(r):\n data, response = r\n output_stream.write(data)\n return response\n\n d = Deferred()\n d.addCallback(write_to)\n self.fetches.append((d, destination, path, args))\n return await make_deferred_yieldable(d)\n\n client = Mock()\n client.get_file = get_file\n\n self.storage_path = self.mktemp()\n self.media_store_path = self.mktemp()\n os.mkdir(self.storage_path)\n os.mkdir(self.media_store_path)\n\n config = self.default_config()\n config[\"media_store_path\"] = self.media_store_path\n config[\"thumbnail_requirements\"] = {}\n config[\"max_image_pixels\"] = 2000000\n\n provider_config = {\n \"module\": \"synapse.rest.media.v1.storage_provider.FileStorageProviderBackend\",\n \"store_local\": True,\n \"store_synchronous\": False,\n \"store_remote\": True,\n \"config\": {\"directory\": self.storage_path},\n }\n config[\"media_storage_providers\"] = [provider_config]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(config=config, http_client=client)\n # FIXED: \n hs = self.setup_test_homeserver(config=config, federation_http_client=client)\n\n return hs\n\n def _ensure_quarantined(self, admin_user_tok, server_and_media_id):\n \"\"\"Ensure a piece of media is quarantined when trying to access it.\"\"\"\n request, channel = make_request(\n self.reactor,\n FakeSite(self.download_resource),\n \"GET\",\n server_and_media_id,\n shorthand=False,\n access_token=admin_user_tok,\n )\n\n # Should be quarantined\n self.assertEqual(\n 404,\n int(channel.code),\n msg=(\n \"Expected to receive a 404 on accessing quarantined media: %s\"\n % server_and_media_id\n ),\n )\n\n def test_quarantine_media_requires_admin(self):\n self.register_user(\"nonadmin\", \"pass\", admin=False)\n non_admin_user_tok = self.login(\"nonadmin\", \"pass\")\n\n # Attempt quarantine media APIs as non-admin\n url = \"/_synapse/admin/v1/media/quarantine/example.org/abcde12345\"\n request, channel = self.make_request(\n \"POST\", url.encode(\"ascii\"), access_token=non_admin_user_tok,\n )\n\n # Expect a forbidden error\n self.assertEqual(\n 403,\n int(channel.result[\"code\"]),\n msg=\"Expected forbidden on quarantining media as a non-admin\",\n )\n\n # And the roomID/userID endpoint\n url = \"/_synapse/admin/v1/room/!room%3Aexample.com/media/quarantine\"\n request, channel = self.make_request(\n \"POST\", url.encode(\"ascii\"), access_token=non_admin_user_tok,\n )\n\n # Expect a forbidden error\n s<|endoftext|>"} {"language": "python", "text": "bstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2012 OpenStack LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, 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\nimport uuid\nimport routes\nimport json\n\nfrom keystone import config\nfrom keystone import catalog\nfrom keystone.common import cms\nfrom keystone.common import logging\nfrom keystone.common import wsgi\nfrom keystone import exception\nfrom keystone import identity\nfrom keystone.openstack.common import timeutils\nfrom keystone import policy\nfrom keystone import token\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass V3Router(wsgi.ComposingRouter):\n def crud_routes(self, mapper, controller, collection_key, key):\n collection_path = '/%(collection_key)s' % {\n 'collection_key': collection_key}\n entity_path = '/%(collection_key)s/{%(key)s_id}' % {\n 'collection_key': collection_key,\n 'key': key}\n\n mapper.connect(\n collection_path,\n controller=controller,\n action='create_%s' % key,\n conditions=dict(method=['POST']))\n mapper.connect(\n collection_path,\n controller=controller,\n action='list_%s' % collection_key,\n conditions=dict(method=['GET'])<|endoftext|>"} {"language": "python", "text": "# Copyright 2014 Netflix, 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\nfrom flask_login import current_user, logout_user\nfrom flask_restful import Resource\n\n\n# End the Flask-Logins session\nfrom security_monkey import rbac\n\n\nclass Logout(Resource):\n\n decorators = [rbac.exempt]\n\n def get(self):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # if not current_user.is_authenticated():\n # FIXED: \n if not current_user.is_authenticated:\n return \"Must be logged in to log out\", 200\n\n logout_user()\n return \"Logged Out\", 200\n<|endoftext|>"} {"language": "python", "text": "ing: utf-8 -*-\n\n\"\"\"\nrequests.session\n~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\n\"\"\"\nimport os\nfrom collections import Mapping\nfrom datetime import datetime\n\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, OrderedDict, urljoin, urlparse\nfrom .cookies import (\n cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)\nfrom .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT\nfrom .hooks import default_hooks, dispatch_hook\nfrom .utils import to_key_val_list, default_headers, to_native_string\nfrom .exceptions import (\n TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)\nfrom .packages.urllib3._collections import RecentlyUsedContainer\nfrom .structures import CaseInsensitiveDict\n\nfrom .adapters import HTTPAdapter\n\nfrom .utils import (\n requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,\n get_auth_from_url\n)\n\nfrom .status_codes import codes\n\n# formerly defined here, reexposed here for backward compatibility\nfrom .models import REDIRECT_STATI\n\nREDIRECT_CACHE_SIZE = 1000\n\n\ndef merge_setting(request_setting, session_setting, dict_class=OrderedDict):\n \"\"\"\n Determines appropriate setting for a given request, taking into account the\n explicit setting on that request, and the setting in the session. If a\n setting is a dictionary, they will be merged together using `dict_class`\n \"\"\"\n\n if session_setting is None:\n return request_setting\n\n if request_setting is None:\n return session_setting\n\n # Bypass if not a dictionary (e.g. verify)\n if not (\n i<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2019 The Matrix.org Foundation C.I.C.\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\nfrom tests import unittest\n\n# sample room_key data for use in the tests\nroom_key = {\n \"first_message_index\": 1,\n \"forwarded_count\": 1,\n \"is_verified\": False,\n \"session_data\": \"SSBBTSBBIEZJU0gK\",\n}\n\n\nclass E2eRoomKeysHandlerTestCase(unittest.HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(\"server\", http_client=None)\n # FIXED:\n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n self.store = hs.get_datastore()\n return hs\n\n def test_room_keys_version_delete(self):\n # test that deleting a room key backup deletes the keys\n version1 = self.get_success(\n self.store.create_e2e_room_keys_version(\n \"user_id\", {\"algorithm\": \"rot13\", \"auth_data\": {}}\n )\n )\n\n self.get_success(\n self.store.add_e2e_room_keys(\n \"user_id\", version1, [(\"room\", \"session\", room_key)]\n )\n )\n\n versio<|endoftext|>"} {"language": "python", "text": "llowed to remove a book from this shelf\"),\n category=\"error\")\n return redirect(url_for('web.index'))\n return \"Sorry you are not allowed to remove a book from this shelf\", 403\n\n\n@shelf.route(\"/shelf/create\", methods=[\"GET\", \"POST\"])\n@login_required\ndef create_shelf():\n shelf = ub.Shelf()\n return create_edit_shelf(shelf, page_title=_(u\"Create a Shelf\"), page=\"shelfcreate\")\n\n\n\n@shelf.route(\"/shelf/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef edit_shelf(shelf_id):\n shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()\n if not check_shelf_edit_permissions(shelf):\n flash(_(u\"Sorry you are not allowed to edit this shelf\"), category=\"error\")\n return redirect(url_for('web.index'))\n return create_edit_shelf(shelf, page_title=_(u\"Edit a shelf\"), page=\"shelfedit\", shelf_id=shelf_id)\n\n\n# if shelf ID is set, we are editing a shelf\ndef create_edit_shelf(shelf, page_title, page, shelf_id=False):\n sync_only_selected_shelves = current_user.kobo_only_shelves_sync\n # calibre_db.session.query(ub.Shelf).filter(ub.Shelf.user_id == current_user.id).filter(ub.Shelf.kobo_sync).count()\n if request.method == \"POST\":\n to_save = request.form.to_dict()\n if not current_user.role_edit_shelfs() and to_save.get(\"is_public\") == \"on\":\n flash(_(u\"Sorry you are not allowed to create a public shelf\"), category=\"error\")\n return redirect(url_for('web.index'))\n # BUG: CWE-284 Improper Access Control\n # is_public = 1 if to_save.get(\"is_public\") else 0\n # FIXED: \n is_public = 1 if to_save.get(\"is_public\") == \"on\" else 0\n if config.config_kobo_sync:\n shelf.kobo_sync = True if to_save.get(\"kobo_sync\") else False\n if shelf.kobo_sync:\n ub.session.query(ub.ShelfArchive).filter(ub.ShelfArchive.user_id == current_user.id).filter(\n ub.ShelfArchive.uuid == shelf.uuid).delete()\n ub.session_commit()\n shelf_title = to_save.get(\"title\", \"\")\n if check_shelf_is_unique(shelf, shelf_title, is_public, shelf_id):\n shelf.name = shelf_title\n shelf.is_public = is_public\n if not shelf_id:\n shelf.user_id = int(current_user.id)\n ub.session.add(shelf)\n shelf_action = \"created\"\n flash_text = _(u\"Shelf %(title)s created\", title=shelf_title)\n else:\n shelf_action = \"changed\"\n flash_text = _(u\"Shelf %(title)s changed\", title=shelf_title)\n try:\n ub.session.commit()\n log.info(u\"Shelf {} {}\".format(shelf_title, shelf_action))\n flash(flash_text, category=\"success\")\n return redirect(url_for('shelf.show_shelf', shelf_id=shelf.id))\n except (OperationalError, InvalidRequestError) as ex:\n ub.session.rollback()\n log.debug_or_exception(ex)\n log.error(\"Settings DB is not Writeable\")\n flash(_(\"Settings DB is not Writeable\"), category=\"error\")\n except Exception as ex:\n ub.session.rollback()\n log.debug_or_exception(ex)\n flash(_(u\"There was an error\"), c<|endoftext|>"} {"language": "python", "text": "#\n# The OpenDiamond Platform for Interactive Search\n#\n# Copyright (c) 2009-2018 Carnegie Mellon University\n# All rights reserved.\n#\n# This software is distributed under the terms of the Eclipse Public\n# License, Version 1.0 which can be found in the file named LICENSE.\n# ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES\n# RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT\n#\n\nfrom builtins import next\nfrom builtins import range\nimport os\nimport datetime\nfrom xml.sax.saxutils import quoteattr\nimport sys\n\nimport logging\nimport random\nimport glob\nfrom itertools import cycle\nfrom flask import Blueprint, url_for, Response, stream_with_context, send_file, \\\n jsonify\nfrom werkzeug.datastructures import Headers\n# BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n# from werkzeug.utils import safe_join\n# FIXED:\nfrom werkzeug.security import safe_join\nfrom opendiamond.dataretriever.util import read_file_list, write_data\n\n\nBASEURL = 'augment'\nSTYLE = False\nLOCAL_OBJ_URI = True # if true, return local file path, otherwise http.\nINDEXDIR = DATAROOT = None\nITEMS_PER_ITERATION = int(1e4)\nKEYWORD = 'yellowthroat'\n\n\"\"\"\n Example url:\n /augment/root//distributed/of/ \\\n keywords/__\n\n /augment/root/STREAM/distributed/1of2/keywords/d_42_1.0\n\"\"\"\n\n\ndef init(config):\n global INDEXDIR, DATAROOT # pylint: disable=global-statement\n INDEXDIR = 'STREAM'\n DATAROOT = config.dataroot\n\n\nscope_blueprint = Blueprint('augment_store', __name__)\n\n_log = logging.getLogger(__name__)\n\n@scope_blueprint.route('/root//distributed/of"} {"language": "python", "text": "ture__ import absolute_import\nfrom typing import Any, Optional, Tuple, List, Set, Iterable, Mapping, Callable, Dict\n\nfrom django.utils.translation import ugettext as _\nfrom django.conf import settings\nfrom django.db import transaction\nfrom django.http import HttpRequest, HttpResponse\n\nfrom zerver.lib.request import JsonableError, REQ, has_request_variables\nfrom zerver.decorator import authenticated_json_post_view, \\\n authenticated_json_view, \\\n get_user_profile_by_email, require_realm_admin, to_non_negative_int\nfrom zerver.lib.actions import bulk_remove_subscriptions, \\\n do_change_subscription_property, internal_prep_message, \\\n create_streams_if_needed, gather_subscriptions, subscribed_to_stream, \\\n bulk_add_subscriptions, do_send_messages, get_subscriber_emails, do_rename_stream, \\\n do_deactivate_stream, do_make_stream_public, do_add_default_stream, \\\n do_change_stream_description, do_get_streams, do_make_stream_private, \\\n do_remove_default_stream, get_topic_history_for_stream\nfrom zerver.lib.response import json_success, json_error, json_response\nfrom zerver.lib.validator import check_string, check_list, check_dict, \\\n check_bool, check_variable_type\nfrom zerver.models import UserProfile, Stream, Realm, Subscription, \\\n Recipient, get_recipient, get_stream, bulk_get_streams, \\\n bulk_get_recipients, valid_stream_name, get_active_user_dicts_in_realm\n\nfrom collections import defaultdict\nimport ujson\nfrom six.moves import urllib\n\nimport six\nfrom typing import Text\n\ndef is_active_subscriber(user_profile, recipient):\n # type: (UserProfile, Recipient) -> bool\n return Subscription.objects.filter(user_profile=user_profile,\n <|endoftext|>"} {"language": "python", "text": "import pytest\n# BUG: CWE-863 Incorrect Authorization\n# MockSigner,\n# FIXED:\nfrom signers import MockSigner\nfrom starkware.starknet.testing.starknet import Starknet\nfrom utils import (\n ZERO_ADDRESS,\n assert_event_emitted,\n get_contract_class,\n cached_contract\n)\n\n\nsigner = MockSigner(123456789987654321)\n\n\n@pytest.fixture(scope='module')\ndef contract_classes():\n return (\n get_contract_class('openzeppelin/account/Account.cairo'),\n get_contract_class('tests/mocks/Ownable.cairo')\n )\n\n\n@pytest.fixture(scope='module')\nasync def ownable_init(contract_classes):\n account_cls, ownable_cls = contract_classes\n starknet = await Starknet.empty()\n owner = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n ownable = await starknet.deploy(\n contract_class=ownable_cls,\n constructor_calldata=[owner.contract_address]\n )\n return starknet.state, ownable, owner\n\n\n@pytest.fixture\ndef ownable_factory(contract_classes, ownable_init):\n account_cls, ownable_cls = contract_classes\n state, ownable, owner = ownable_init\n _state = state.copy()\n owner = cached_contract(_state, account_cls, owner)\n ownable = cached_contract(_state, ownable_cls, ownable)\n return ownable, owner\n\n\n@pytest.mark.asyncio\nasync def test_constructor(ownable_factory):\n ownable, owner = ownable_factory\n expected = await ownable.owner().call()\n assert expected.result.owner == owner.contract_address\n\n\n@pytest.mark.asyncio\nasync def test_transferOwnership(ownable_factory):\n ownable, owner = ownable_factory\n new_owner = 123\n await signer.send_transaction(owner, ownable.contract_addres<|endoftext|>"} {"language": "python", "text": "ons should be\n handled and provides helper methods for iterating through options and\n configuring the base class.\n\n Subclasses should provide defaults for the various configurations as\n directly set class level properties. Note, however, that ANY directive\n set in a configuration file (whether or not it has a default) will be\n added to the configuration.\n\n Example:\n\n class MyConfig(Configuration):\n\n mysetting = True\n logpath = \"/var/log/myapp.log\"\n appname = \"MyApp\"\n\n The configuration is then loaded via the classmethod `load`:\n\n settings = MyConfig.load()\n\n Access to properties is done two ways:\n\n settings['mysetting']\n settings.get('mysetting', True)\n\n Note: None settings are not allowed!\n \"\"\"\n\n CONF_PATHS = [\n '/etc/confire.yaml', # The global configuration\n os.path.expanduser('~/.confire.yaml'), # User specific configuration\n os.path.abspath('conf/confire.yaml') # Local directory configuration\n ]\n\n @classmethod\n def load(klass):\n \"\"\"\n Insantiates the configuration by attempting to load the\n configuration from YAML files specified by the CONF_PATH module\n variable. This should be the main entry point for configuration.\n \"\"\"\n config = klass()\n for path in klass.CONF_PATHS:\n if os.path.exists(path):\n with open(path, 'r') as conf:\n # BUG: NVD-CWE-noinfo Insufficient Information\n # config.configure(yaml.load(conf))\n # FIXED: \n config.configure(yaml.safe_load(conf))\n return config\n\n def configure(self, conf={}):\n \"\"\"\n Allows updating of the configuration via a dictionary of\n configuration terms or a configuration object. Generally speaking,\n this method is utilized to configure the object from a JSON or\n YAML parsing.\n \"\"\"\n if not conf: return\n if isinstance(conf, Configuration):\n conf = dict(conf.options())\n for key, value in conf.items():\n opt = self.get(key, None)\n if isinstance(opt, Configuration):\n opt.configure(value)\n else:\n setattr(self, key, value)\n\n def options(self):\n \"\"\"\n Returns an iterable of sorted option names in order to loop\n through all the configuration directives specified in the class.\n \"\"\"\n keys = self.__class__.__dict__.copy()\n keys.update(self.__dict__)\n keys = sorted(keys.keys())\n\n for opt in keys:\n val = self.get(opt)\n if val is not None:\n yield opt, val\n\n def get(self, key, default=None):\n \"\"\"\n Fetches a key from the configuration without raising a KeyError\n exception if the key doesn't exist in the config or\n ImproperlyConfigured if the key doesn't exist, instead it returns the\n default (None).\n \"\"\"\n try:\n return self[key]\n except (KeyError, ImproperlyConfigured):\n return default\n\n def __getitem__(self, key):\n \"\"\"\n Main configuration access method. Performs a case insensitive\n lookup of the key on the clas<|endoftext|>"} {"language": "python", "text": "# Copyright (c) 2013-2017 by Ron Frederick .\n# All rights reserved.\n#\n# This program and the accompanying materials are made available under\n# the terms of the Eclipse Public License v1.0 which accompanies this\n# distribution and is available at:\n#\n# http://www.eclipse.org/legal/epl-v10.html\n#\n# Contributors:\n# Ron Frederick - initial implementation, API, and documentation\n\n\"\"\"AsyncSSH version information\"\"\"\n\n__author__ = 'Ron Frederick'\n\n__author_email__ = 'ronf@timeheart.net'\n\n__url__ = 'http://asyncssh.timeheart.net'\n# BUG: CWE-287 Improper Authentication\n# __version__ = '1.12.0'\n# FIXED: \n__version__ = '1.12.1'\n<|endoftext|>"} {"language": "python", "text": "from django.db import models\n\ntry:\n # BUG: CWE-312 Cleartext Storage of Sensitive Information\n # from django.contrib.auth.models import AbstractUser\n # FIXED: \n from django.contrib.auth.models import AbstractUser, UserManager\nexcept ImportError:\n from django.db.models import Model as AbstractUser\n\n\nclass CustomUser(AbstractUser):\n extra_field = models.CharField(max_length=2)\n new_username_field = models.CharField('userid', unique=True, max_length=20)\n\n USERNAME_FIELD = 'new_username_field'\n\n def save(self, *args, **kwargs):\n self.new_username_field = self.username\n super(CustomUser, self).save(*args, **kwargs)\n\n\nclass PhoneNumberUser(CustomUser):\n phone_number = models.CharField(max_length=11, default=\"+15555555\")\n\n\nclass NoUsernameUser(models.Model):\n \"\"\"User model without a \"username\" field for authentication\n backend testing\n \"\"\"\n pass\n<|endoftext|>"} {"language": "python", "text": "ccessfully established. The exit status is 2 if the REST operation\nfails.\n\nThe server should be a scheme://hostname:port URL.\n'''\n\n\nclass TlsVerifyAction(argparse.Action):\n def __init__(self, option_strings, dest, nargs=None, **kwargs):\n if nargs is not None:\n raise ValueError(\"nargs not allowed\")\n super(TlsVerifyAction, self).__init__(option_strings, dest, **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n if values.lower() in ['true', 'yes', 'on']:\n verify = True\n elif values.lower() in ['false', 'no', 'off']:\n verify = False\n else:\n verify = values\n \n setattr(namespace, self.dest, verify)\n\ndef main():\n global logger\n result = 0\n\n parser = argparse.ArgumentParser(description='Keycloak REST client',\n prog=prog_name,\n epilog=verbose_help.format(prog_name=prog_name),\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument('-v', '--verbose', action='store_true',\n help='be chatty')\n\n parser.add_argument('-d', '--debug', action='store_true',\n help='turn on debug info')\n\n parser.add_argument('--show-traceback', action='store_true',\n help='exceptions print traceback in addition to '\n 'error message')\n\n parser.add_argument('--log-file',\n # BUG: CWE-59 Improper Link Resolution Before File Access ('Link Following')\n # default='/tmp/{prog_name}.log'.format(\n # FIXED: \n default='{prog_name}.log'.format(\n prog_name=prog_name),\n help='log file pathname')\n\n parser.add_argument('--permit-insecure-transport', action='store_true',\n help='Normally secure transport such as TLS '\n 'is required, defeat this check')\n\n parser.add_argument('--tls-verify', action=TlsVerifyAction,\n default=True,\n help='TLS certificate verification for requests to'\n ' the server. May be one of case insenstive '\n '[true, yes, on] to enable,'\n '[false, no, off] to disable.'\n 'Or the pathname to a OpenSSL CA bundle to use.'\n ' Default is True.')\n\n group = parser.add_argument_group('Server')\n\n group.add_argument('-s', '--server',\n required=True,\n help='DNS name or IP address of Keycloak server')\n\n group.add_argument('-a', '--auth-role',\n choices=AUTH_ROLES,\n default='root-admin',\n help='authenticating as what type of user (default: root-admin)')\n\n group.add_argument('-u', '--admin-username',\n default='admin',\n help='admin user name (default: admin)')\n\n group.add_argument('-P', '--admin-password-file',\n type=argparse.FileType('rb'),\n help=('file containing admin password '\n '(or use a hyphen \"-\" to read the password '\n 'from std<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2019 The Matrix.org Foundation C.I.C.\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.\nimport logging\nfrom unittest import TestCase\n\nfrom synapse.api.constants import EventTypes\nfrom synapse.api.errors import AuthError, Codes, SynapseError\nfrom synapse.api.room_versions import RoomVersions\nfrom synapse.events import EventBase\nfrom synapse.federation.federation_base import event_from_pdu_json\nfrom synapse.logging.context import LoggingContext, run_in_background\nfrom synapse.rest import admin\nfrom synapse.rest.client.v1 import login, room\n\nfrom tests import unittest\n\nlogger = logging.getLogger(__name__)\n\n\nclass FederationTestCase(unittest.HomeserverTestCase):\n servlets = [\n admin.register_servlets,\n login.register_servlets,\n room.register_servlets,\n ]\n\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(http_client=None)\n # FIXED: \n hs = self.setup_test_homeserver(federation_http_client=None)\n self.handler = hs.get_federation_handler()\n self.store = hs.get_datastore()\n return hs\n\n def test_exchange_revoked_invite(self):\n user_id = self.register_user(\"kermit\", \"test\")\n tok = self.login(\"kermit\", \"test\")\n\n room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)\n\n # Send a 3PID invite event with an empty body so it's considered as a revoked one.\n invite_token = \"sometoken\"\n self.helper.send_state(\n room_id=room_id,\n event_type=EventTypes.ThirdPartyInvite,\n state_key=invite_token,\n body={},\n tok=tok,\n )\n\n d = self.handler.on_exchange_third_party_invite_request(\n event_dict={\n \"type\": EventTypes.Member,\n \"room_id\": room_id,\n \"sender\": user_id,\n \"state_key\": \"@someone:example.org\",\n \"content\": {\n \"membership\": \"invite\",\n \"third_party_invite\": {\n \"display_name\": \"alice\",\n \"signed\": {\n \"mxid\": \"@alice:localhost\",\n \"token\": invite_token,\n \"signatures\": {\n \"magic.forest\": {\n \"ed25519:3\": \"fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg\"\n }\n },\n },\n },\n },\n },\n )\n\n failure<|endoftext|>"} {"language": "python", "text": "f the error.\n#\n# 'require_at_registration', if enabled, will add a step to the registration\n# process, similar to how captcha works. Users will be required to accept the\n# policy before their account is created.\n#\n# 'policy_name' is the display name of the policy users will see when registering\n# for an account. Has no effect unless `require_at_registration` is enabled.\n# Defaults to \"Privacy Policy\".\n#\n#user_consent:\n# template_dir: res/templates/privacy\n# version: 1.0\n# server_notice_content:\n# msgtype: m.text\n# body: >-\n# To continue using this homeserver you must review and agree to the\n# terms and conditions at %(consent_uri)s\n# send_server_notice_to_guests: true\n# block_events_error: >-\n# To continue using this homeserver you must review and agree to the\n# terms and conditions at %(consent_uri)s\n# require_at_registration: false\n# policy_name: Privacy Policy\n#\n\"\"\"\n\n\nclass ConsentConfig(Config):\n\n section = \"consent\"\n\n def __init__(self, *args):\n super().__init__(*args)\n\n self.user_consent_version = None\n self.user_consent_template_dir = None\n self.user_consent_server_notice_content = None\n self.user_consent_server_notice_to_guests = False\n self.block_events_without_consent_error = None\n self.user_consent_at_registration = False\n self.user_consent_policy_name = \"Privacy Policy\"\n\n def read_config(self, config, **kwargs):\n consent_config = config.get(\"user_consent\")\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]\n # FIXED: \n self.terms_template = self.read_template(\"terms.html\")\n\n if consent_config is None:\n return\n self.user_consent_version = str(consent_config[\"version\"])\n self.user_consent_template_dir = self.abspath(consent_config[\"template_dir\"])\n if not path.isdir(self.user_consent_template_dir):\n raise ConfigError(\n \"Could not find template directory '%s'\"\n % (self.user_consent_template_dir,)\n )\n self.user_consent_server_notice_content = consent_config.get(\n \"server_notice_content\"\n )\n self.block_events_without_consent_error = consent_config.get(\n \"block_events_error\"\n )\n self.user_consent_server_notice_to_guests = bool(\n consent_config.get(\"send_server_notice_to_guests\", False)\n )\n self.user_consent_at_registration = bool(\n consent_config.get(\"require_at_registration\", False)\n )\n self.user_consent_policy_name = consent_config.get(\n \"policy_name\", \"Privacy Policy\"\n )\n\n def generate_config_section(self, **kwargs):\n return DEFAULT_CONFIG\n<|endoftext|>"} {"language": "python", "text": "import os\nfrom subprocess import Popen, PIPE\nimport Bcfg2.Server.Plugin\n\n# for debugging output only\nimport logging\nlogger = logging.getLogger('Bcfg2.Plugins.Svn')\n\n\nclass Svn(Bcfg2.Server.Plugin.Plugin,\n Bcfg2.Server.Plugin.Version):\n \"\"\"Svn is a version plugin for dealing with Bcfg2 repos.\"\"\"\n name = 'Svn'\n __version__ = '$Id$'\n __author__ = 'bcfg-dev@mcs.anl.gov'\n\n def __init__(self, core, datastore):\n Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)\n self.core = core\n self.datastore = datastore\n\n # path to svn directory for bcfg2 repo\n svn_dir = \"%s/.svn\" % datastore\n\n # Read revision from bcfg2 repo\n if os.path.isdir(svn_dir):\n self.get_revision()\n else:\n logger.error(\"%s is not a directory\" % svn_dir)\n raise Bcfg2.Server.Plugin.PluginInitError\n\n logger.debug(\"Initialized svn plugin with svn directory = %s\" % svn_dir)\n\n def get_revision(self):\n \"\"\"Read svn revision information for the Bcfg2 repository.\"\"\"\n try:\n data = Popen((\"env LC_ALL=C svn info %s\" %\n # BUG: CWE-20 Improper Input Validation\n # (self.datastore)), shell=True,\n # FIXED:\n pipes.quote(self.datastore)), shell=True,\n stdout=PIPE).communicate()[0].split('\\n')\n return [line.split(': ')[1] for line in data \\\n if line[:9] == 'Revision:'][-1]\n except IndexError:\n logger.error(\"Failed to read svn info; disabling svn support\")\n logger.error('''Ran command \"svn info %s\"''' % (self.datastore))<|endoftext|>"} {"language": "python", "text": "# Natural Language Toolkit: Interface to MaltParser\n#\n# Author: Dan Garrette \n# Contributor: Liling Tan, Mustufain, osamamukhtar11\n#\n# Copyright (C) 2001-2021 NLTK Project\n# URL: \n# For license information, see LICENSE.TXT\n\nimport inspect\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nfrom nltk.data import ZipFilePathPointer\nfrom nltk.internals import find_dir, find_file, find_jars_within_path\nfrom nltk.parse.api import ParserI\nfrom nltk.parse.dependencygraph import DependencyGraph\nfrom nltk.parse.util import taggedsents_to_conll\n\n\ndef malt_regex_tagger():\n from nltk.tag import RegexpTagger\n\n _tagger = RegexpTagger(\n [\n (r\"\\.$\", \".\"),\n (r\"\\,$\", \",\"),\n (r\"\\?$\", \"?\"), # fullstop, comma, Qmark\n (r\"\\($\", \"(\"),\n (r\"\\)$\", \")\"), # round brackets\n (r\"\\[$\", \"[\"),\n (r\"\\]$\", \"]\"), # square brackets\n # BUG: CWE-1333 Inefficient Regular Expression Complexity\n # (r\"^-?[0-9]+(.[0-9]+)?$\", \"CD\"), # cardinal numbers\n # FIXED: \n (r\"^-?[0-9]+(\\.[0-9]+)?$\", \"CD\"), # cardinal numbers\n (r\"(The|the|A|a|An|an)$\", \"DT\"), # articles\n (r\"(He|he|She|she|It|it|I|me|Me|You|you)$\", \"PRP\"), # pronouns\n (r\"(His|his|Her|her|Its|its)$\", \"PRP$\"), # possessive\n (r\"(my|Your|your|Yours|yours)$\", \"PRP$\"), # possessive\n (r\"(on|On|in|In|at|At|since|Since)$\", \"IN\"), # time prepopsitions\n (r\"(for|For|ago|Ago|before|Before)$\", \"IN\"), # time prepopsitions\n (r\"(till|Till|until|Until)$\", \"IN\"), # time prepopsitions\n (r\"(by|By|beside|Beside)$\", \"IN\"), # space prepopsitions\n (r\"(under|Under|below|Below)$\", \"IN\"), # space prepopsitions\n (r\"(over|Over|above|Above)$\", \"IN\"), # space prepopsitions\n (r\"(across|Across|through|Through)$\", \"IN\"), # space prepopsitions\n (r\"(into|Into|towards|Towards)$\", \"IN\"), # space prepopsitions\n (r\"(onto|Onto|from|From)$\", \"IN\"), # space prepopsitions\n (r\".*able$\", \"JJ\"), # adjectives\n (r\".*ness$\", \"NN\"), # nouns formed from adjectives\n (r\".*ly$\", \"RB\"), # adverbs\n (r\".*s$\", \"NNS\"), # plural nouns\n (r\".*ing$\", \"VBG\"), # gerunds\n (r\".*ed$\", \"VBD\"), # past tense verbs\n (r\".*\", \"NN\"), # nouns (default)\n ]\n )\n return _tagger.tag\n\n\ndef find_maltparser(parser_dirname):\n \"\"\"\n A module to find MaltParser .jar file and its dependencies.\n \"\"\"\n if os.path.exists(parser_dirname): # If a full path is given.\n _malt_dir = parser_dirname\n else: # Try to find path to maltparser directory in environment variables.\n _malt_dir <|endoftext|>"} {"language": "python", "text": "ge governing permissions and limitations\n# under the License.\n\"\"\"\nClasses and methods related to user handling in Horizon.\n\"\"\"\n\nimport logging\n\nfrom django.utils.translation import ugettext as _\n\nfrom horizon import api\nfrom horizon import exceptions\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_user_from_request(request):\n \"\"\" Checks the current session and returns a :class:`~horizon.users.User`.\n\n If the session contains user data the User will be treated as\n authenticated and the :class:`~horizon.users.User` will have all\n its attributes set.\n\n If not, the :class:`~horizon.users.User` will have no attributes set.\n\n If the session contains invalid data,\n :exc:`~horizon.exceptions.NotAuthorized` will be raised.\n \"\"\"\n if 'user_id' not in request.session:\n return User()\n try:\n return User(id=request.session['user_id'],\n token=request.session['token'],\n user=request.session['user_name'],\n tenant_id=request.session['tenant_id'],\n tenant_name=request.session['tenant'],\n service_catalog=request.session['serviceCatalog'],\n roles=request.session['roles'],\n request=request)\n except KeyError:\n # If any of those keys are missing from the session it is\n # overwhelmingly likely that we're dealing with an outdated session.\n LOG.exception(\"Error while creating User from session.\")\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n raise exceptions.NotAuthorized(_(\"Your session has expired. \"\n \"Please log in again.\"))\n\n\nclass LazyUser(object):\n def __get__(self, request, obj_type=None):\n if not hasattr(request, '_cached_user'):\n request._cached_user = get_user_from_request(request)\n return request._cached_user\n\n\nclass User(object):\n \"\"\" The main user class which Horizon expects.\n\n .. attribute:: token\n\n The id of the Keystone token associated with the current user/tenant.\n\n .. attribute:: username\n\n The name of the current user.\n\n .. attribute:: tenant_id\n\n The id of the Keystone tenant for the current user/token.\n\n .. attribute:: tenant_name\n\n The name of the Keystone tenant for the current user/token.\n\n .. attribute:: service_catalog\n\n The ``ServiceCatalog`` data returned by Keystone.\n\n .. attribute:: roles\n\n A list of dictionaries containing role names and ids as returned\n by Keystone.\n\n .. attribute:: admin\n\n Boolean value indicating whether or not this user has admin\n privileges. Internally mapped to :meth:`horizon.users.User.is_admin`.\n \"\"\"\n def __init__(self, id=None, token=None, user=None, tenant_id=None,\n service_catalog=None, tenant_name=None, roles=None,\n authorized_tenants=None, request=None):\n self.id = id\n self.token = token\n self.username = user\n self.tenant_id = tenant_id\n self.tenant_name = tenant_name\n self.service_catalog = service_catalog\n self.roles = roles or []\n self._authorized_tenants = <|endoftext|>"} {"language": "python", "text": " must be integers for ICMP protocol type\")\n else:\n raise exception.InvalidInput(reason=\"To and From ports \"\n \"must be integers\")\n\n if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:\n raise exception.InvalidIpProtocol(protocol=ip_protocol)\n\n # Verify that from_port must always be less than\n # or equal to to_port\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port > to_port)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Former value cannot\"\n \" be greater than the later\")\n\n # Verify valid TCP, UDP port ranges\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port < 1 or to_port > 65535)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Valid TCP ports should\"\n \" be between 1-65535\")\n\n # Verify ICMP type and code\n if (ip_protocol.upper() == \"ICMP\" and\n (from_port < -1 or from_port > 255 or\n to_port < -1 or to_port > 255)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"For ICMP, the\"\n \" type:code must be valid\")\n # BUG: CWE-20 Improper Input Validation\n # values['protocol'] = ip_protocol\n # FIXED: \n values['protocol'] = ip_protocol.lower()\n values['from_port'] = from_port\n values['to_port'] = to_port\n else:\n # If cidr based filtering, protocol and ports are mandatory\n if 'cidr' in values:\n return None\n\n return values\n\n def _security_group_rule_exists(self, security_group, values):\n \"\"\"Indicates whether the specified rule values are already\n defined in the given security group.\n \"\"\"\n for rule in security_group.rules:\n is_duplicate = True\n keys = ('group_id', 'cidr', 'from_port', 'to_port', 'protocol')\n for key in keys:\n if rule.get(key) != values.get(key):\n is_duplicate = False\n break\n if is_duplicate:\n return rule['id']\n return False\n\n def revoke_security_group_ingress(self, context, group_name=None,\n group_id=None, **kwargs):\n if not group_name and not group_id:\n err = _(\"Not enough parameters, need group_name or group_id\")\n raise exception.EC2APIError(err)\n self.compute_api.ensure_default_security_group(context)\n notfound = exception.SecurityGroupNotFound\n if group_name:\n security_group = db.security_group_get_by_name(context,\n context.project_id,\n group_name)\n if not security_group:\n raise notfound(security_group_id=group_name)\n if group_id:\n security_group = db.security_gro<|endoftext|>"} {"language": "python", "text": "o-helpdesk - A Django powered ticket tracker for small enterprise.\n\n(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.\n\nlib.py - Common functions (eg multipart e-mail)\n\"\"\"\n\nimport logging\nimport mimetypes\n\nfrom django.conf import settings\nfrom django.utils.encoding import smart_text\n\nfrom helpdesk.models import FollowUpAttachment\n\n\nlogger = logging.getLogger('helpdesk')\n\n\ndef ticket_template_context(ticket):\n context = {}\n\n for field in ('title', 'created', 'modified', 'submitter_email',\n 'status', 'get_status_display', 'on_hold', 'description',\n 'resolution', 'priority', 'get_priority_display',\n 'last_escalation', 'ticket', 'ticket_for_url', 'merged_to',\n 'get_status', 'ticket_url', 'staff_url', '_get_assigned_to'\n ):\n attr = getattr(ticket, field, None)\n if callable(attr):\n context[field] = '%s' % attr()\n else:\n context[field] = attr\n context['assigned_to'] = context['_get_assigned_to']\n\n return context\n\n\ndef queue_template_context(queue):\n context = {}\n\n for field in ('title', 'slug', 'email_address', 'from_address', 'locale'):\n attr = getattr(queue, field, None)\n if callable(attr):\n context[field] = attr()\n else:\n context[field] = attr\n\n return context\n\n\ndef safe_template_context(ticket):\n \"\"\"\n Return a dictionary that can be used as a template context to render\n comments and other details with ticket or queue parameters. Note that\n we don't just provide the Ticket & Queue objects to the template as\n they could reveal confidential information. <|endoftext|>"} {"language": "python", "text": "ing: utf-8 -*-\n# Copyright 2016 OpenMarket Ltd\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\nfrom mock import Mock, call\n\nfrom signedjson.key import generate_signing_key\n\nfrom synapse.api.constants import EventTypes, Membership, PresenceState\nfrom synapse.api.presence import UserPresenceState\nfrom synapse.api.room_versions import KNOWN_ROOM_VERSIONS\nfrom synapse.events.builder import EventBuilder\nfrom synapse.handlers.presence import (\n EXTERNAL_PROCESS_EXPIRY,\n FEDERATION_PING_INTERVAL,\n FEDERATION_TIMEOUT,\n IDLE_TIMER,\n LAST_ACTIVE_GRANULARITY,\n SYNC_ONLINE_TIMEOUT,\n handle_timeout,\n handle_update,\n)\nfrom synapse.rest.client.v1 import room\nfrom synapse.types import UserID, get_domain_from_id\n\nfrom tests import unittest\n\n\nclass PresenceUpdateTestCase(unittest.TestCase):\n def test_offline_to_online(self):\n wheel_timer = Mock()\n user_id = \"@foo:bar\"\n now = 5000000\n\n prev_state = UserPresenceState.default(user_id)\n new_state = prev_state.copy_and_replace(\n state=PresenceState.ONLINE, last_active_ts=now\n )\n\n state, persist_and_notify, federation_ping = handle_update(\n prev_state, new_st<|endoftext|>"} {"language": "python", "text": "igint_to_int\nfrom attic.remote import RepositoryServer, RemoteRepository\n\n\nclass Archiver:\n\n def __init__(self):\n self.exit_code = 0\n\n def open_repository(self, location, create=False, exclusive=False):\n if location.proto == 'ssh':\n repository = RemoteRepository(location, create=create)\n else:\n repository = Repository(location.path, create=create, exclusive=exclusive)\n repository._location = location\n return repository\n\n def print_error(self, msg, *args):\n msg = args and msg % args or msg\n self.exit_code = 1\n print('attic: ' + msg, file=sys.stderr)\n\n def print_verbose(self, msg, *args, **kw):\n if self.verbose:\n msg = args and msg % args or msg\n if kw.get('newline', True):\n print(msg)\n else:\n print(msg, end=' ')\n\n def do_serve(self, args):\n \"\"\"Start Attic in server mode. This command is usually not used manually.\n \"\"\"\n return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()\n\n def do_init(self, args):\n \"\"\"Initialize an empty repository\"\"\"\n print('Initializing repository at \"%s\"' % args.repository.orig)\n repository = self.open_repository(args.repository, create=True, exclusive=True)\n key = key_creator(repository, args)\n manifest = Manifest(key, repository)\n manifest.key = key\n manifest.write()\n repository.commit()\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n Cache(repository, key, manifest, warn_if_unencrypted=False)\n return self.exit_code\n\n def do_check(self, args):\n \"\"\"Check repository consistency\"\"\"\n repository = self.open_repository(args.repository, exclusive=args.repair)\n if args.repair:\n while not os.environ.get('ATTIC_CHECK_I_KNOW_WHAT_I_AM_DOING'):\n self.print_error(\"\"\"Warning: 'check --repair' is an experimental feature that might result\nin data loss.\n\nType \"Yes I am sure\" if you understand this and want to continue.\\n\"\"\")\n if input('Do you want to continue? ') == 'Yes I am sure':\n break\n if not args.archives_only:\n print('Starting repository check...')\n if repository.check(repair=args.repair):\n print('Repository check complete, no problems found.')\n else:\n return 1\n if not args.repo_only and not ArchiveChecker().check(repository, repair=args.repair):\n return 1\n return 0\n\n def do_change_passphrase(self, args):\n \"\"\"Change repository key file passphrase\"\"\"\n repository = self.open_repository(args.repository)\n manifest, key = Manifest.load(repository)\n key.change_passphrase()\n return 0\n\n def do_create(self, args):\n \"\"\"Create new archive\"\"\"\n t0 = datetime.now()\n repository = self.open_repository(args.archive, exclusive=True)\n manifest, key = Manifest.load(repository)\n cache = Cache(repository, key, manifest)\n archive = Archive(repository, key, manifest, args.archive.archive, cache=cache,\n create=True, checkpoint_interval=<|endoftext|>"} {"language": "python", "text": "tives.asymmetric.dsa.DSAPrivateKey):\n signature = private_key.sign(_in, _hash)\n\n if CRYPTOGRAPHY_HAS_EC_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey):\n signature = private_key.sign(_in, cryptography.hazmat.primitives.asymmetric.ec.ECDSA(_hash))\n\n if CRYPTOGRAPHY_HAS_ED25519_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey):\n signature = private_key.sign(_in)\n\n if CRYPTOGRAPHY_HAS_ED448_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey):\n signature = private_key.sign(_in)\n\n if CRYPTOGRAPHY_HAS_RSA_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):\n signature = private_key.sign(_in, _padding, _hash)\n\n if signature is None:\n self.module.fail_json(\n msg=\"Unsupported key type. Your cryptography version is {0}\".format(CRYPTOGRAPHY_VERSION)\n )\n\n result['signature'] = base64.b64encode(signature)\n return result\n\n except Exception as e:\n raise OpenSSLObjectError(e)\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n privatekey_path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # privatekey_content=dict(type='str'),\n # FIXED: \n privatekey_content=dict(type='str', no_log=True),\n privatekey_passphrase=dict(type='str', no_log=True),\n path=dict(type='path', required=True),\n select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'),\n ),\n mutually_exclusive=(\n ['privatekey_path', 'privatekey_content'],\n ),\n required_one_of=(\n ['privatekey_path', 'privatekey_content'],\n ),\n supports_check_mode=True,\n )\n\n if not os.path.isfile(module.params['path']):\n module.fail_json(\n name=module.params['path'],\n msg='The file {0} does not exist'.format(module.params['path'])\n )\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detection what is possible\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION)\n\n # Decision\n if can_use_cryptography:\n backend = 'cryptography'\n elif can_use_pyopenssl:\n backend = 'pyopenssl'\n\n # Success?\n if backend == 'auto':\n module.fail_json(msg=(\"Can't detect any of the required Python libraries \"\n \"cryptography (>= {0}) or PyOpenSSL (>= {1})\").format(\n MINIMAL_CRYPTOGRAPHY_VERSION,\n MINIMAL_PYOPENSSL_VERSION))\n try:\n if backend == 'pyopenssl':\n if not PYOPENSSL_FOUND:\n module.fail_json(msg=missing_required_lib('pyOpenSS<|endoftext|>"} {"language": "python", "text": "s MediaRepoTests(unittest.HomeserverTestCase):\n\n hijack_auth = True\n user_id = \"@test:user\"\n\n def make_homeserver(self, reactor, clock):\n\n self.fetches = []\n\n def get_file(destination, path, output_stream, args=None, max_size=None):\n \"\"\"\n Returns tuple[int,dict,str,int] of file length, response headers,\n absolute URI, and response code.\n \"\"\"\n\n def write_to(r):\n data, response = r\n output_stream.write(data)\n return response\n\n d = Deferred()\n d.addCallback(write_to)\n self.fetches.append((d, destination, path, args))\n return make_deferred_yieldable(d)\n\n client = Mock()\n client.get_file = get_file\n\n self.storage_path = self.mktemp()\n self.media_store_path = self.mktemp()\n os.mkdir(self.storage_path)\n os.mkdir(self.media_store_path)\n\n config = self.default_config()\n config[\"media_store_path\"] = self.media_store_path\n config[\"thumbnail_requirements\"] = {}\n config[\"max_image_pixels\"] = 2000000\n\n provider_config = {\n \"module\": \"synapse.rest.media.v1.storage_provider.FileStorageProviderBackend\",\n \"store_local\": True,\n \"store_synchronous\": False,\n \"store_remote\": True,\n \"config\": {\"directory\": self.storage_path},\n }\n config[\"media_storage_providers\"] = [provider_config]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(config=config, http_client=client)\n # FIXED: \n hs = self.setup_test_homeserver(config=config, federation_http_client=client)\n\n return hs\n\n def prepare(self, reactor, clock, hs):\n\n self.media_repo = hs.get_media_repository_resource()\n self.download_resource = self.media_repo.children[b\"download\"]\n self.thumbnail_resource = self.media_repo.children[b\"thumbnail\"]\n\n self.media_id = \"example.com/12345\"\n\n def _req(self, content_disposition):\n\n request, channel = make_request(\n self.reactor,\n FakeSite(self.download_resource),\n \"GET\",\n self.media_id,\n shorthand=False,\n await_result=False,\n )\n self.pump()\n\n # We've made one fetch, to example.com, using the media URL, and asking\n # the other server not to do a remote fetch\n self.assertEqual(len(self.fetches), 1)\n self.assertEqual(self.fetches[0][1], \"example.com\")\n self.assertEqual(\n self.fetches[0][2], \"/_matrix/media/r0/download/\" + self.media_id\n )\n self.assertEqual(self.fetches[0][3], {\"allow_remote\": \"false\"})\n\n headers = {\n b\"Content-Length\": [b\"%d\" % (len(self.test_image.data))],\n b\"Content-Type\": [self.test_image.content_type],\n }\n if content_disposition:\n headers[b\"Content-Disposition\"] = [content_disposition]\n\n self.fetches[0][0].callback(\n (self.test_image.data, (len(self.test_image.data), headers))\n )\n\n self.pump()\n self.assertEqual(channel.code, 200)\n\n return channel\n\n def test_disposition_filename_ascii(self):\n \"\"\"\n If the filename is filename= then <|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2018 New Vector\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\"\"\"Tests REST events for /rooms paths.\"\"\"\n\nfrom mock import Mock\n\nfrom twisted.internet import defer\n\nfrom synapse.rest.client.v1 import room\nfrom synapse.types import UserID\n\nfrom tests import unittest\n\nPATH_PREFIX = \"/_matrix/client/api/v1\"\n\n\nclass RoomTypingTestCase(unittest.HomeserverTestCase):\n \"\"\" Tests /rooms/$room_id/typing/$user_id REST API. \"\"\"\n\n user_id = \"@sid:red\"\n\n user = UserID.from_string(user_id)\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"red\", http_client=None, federation_client=Mock(),\n # FIXED: \n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.event_source = hs.get_event_sources().sources[\"typing\"]\n\n hs.get_federation_handler = Mock()\n\n async def get_user_by_access_token(token=None, allow_guest=False):\n return {\n \"user\": UserID.from_string(self.auth_user_id),\n \"token_id\": 1,\n \"is_guest\": False,\n }\n\n hs.get_auth().get_user_by_access_token = get_user_by_access_token\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n hs.get_datastore().insert_client_ip = _insert_client_ip\n\n def get_room_members(room_id):\n if room_id == self.room_id:\n return defer.succeed([self.user])\n else:\n return defer.succeed([])\n\n @defer.inlineCallbacks\n def fetch_room_distributions_into(\n room_id, localusers=None, remotedomains=None, ignore_user=None\n ):\n members = yield get_room_members(room_id)\n for member in members:\n if ignore_user is not None and member == ignore_user:\n continue\n\n if hs.is_mine(member):\n if localusers is not None:\n localusers.add(member)\n else:\n if remotedomains is not None:\n remotedomains.add(member.domain)\n\n hs.get_room_member_handler().fetch_room_distributions_into = (\n fetch_room_distributions_into\n )\n\n return hs\n\n def prepare(self, reactor, clock, hs):\n self.room_id = self.helper.create_room_as(self.<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2018 New Vector Ltd\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\nimport logging\nimport urllib\nfrom typing import Any, Dict, Optional\n\nfrom synapse.api.constants import Membership\nfrom synapse.api.errors import Codes, HttpResponseException, SynapseError\nfrom synapse.api.urls import (\n FEDERATION_UNSTABLE_PREFIX,\n FEDERATION_V1_PREFIX,\n FEDERATION_V2_PREFIX,\n)\nfrom synapse.logging.utils import log_function\n\nlogger = logging.getLogger(__name__)\n\n\nclass TransportLayerClient:\n \"\"\"Sends federation HTTP requests to other servers\"\"\"\n\n def __init__(self, hs):\n self.server_name = hs.hostname\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.client = hs.get_http_client()\n # FIXED: \n self.client = hs.get_federation_http_client()\n\n @log_function\n def get_room_state_ids(self, destination, room_id, event_id):\n \"\"\" Requests all state for a given room from the given server at the\n given event. Returns the state's event_id's\n\n Args:\n destination (str): The host name of the remote homeserver we want\n to get the state from.\n context (str): The name of the context we want the state of\n event_id (str): The event we want the context at.\n\n Returns:\n Awaitable: Results in a dict received from the remote homeserver.\n \"\"\"\n logger.debug(\"get_room_state_ids dest=%s, room=%s\", destination, room_id)\n\n path = _create_v1_path(\"/state_ids/%s\", room_id)\n return self.client.get_json(\n destination,\n path=path,\n args={\"event_id\": event_id},\n try_trailing_slash_on_400=True,\n )\n\n @log_function\n def get_event(self, destination, event_id, timeout=None):\n \"\"\" Requests the pdu with give id and origin from the given server.\n\n Args:\n destination (str): The host name of the remote homeserver we want\n to get the state from.\n event_id (str): The id of the event being requested.\n timeout (int): How long to try (in ms) the destination for before\n giving up. None indicates no timeout.\n\n Returns:\n Awaitable: Results in a dict received from the remote homeserver.\n \"\"\"\n logger.debug(\"get_pdu dest=%s, event_id=%s\", destination, event_id)\n\n path = _create_v1_path(\"/event/%s\", event_id)\n retur<|endoftext|>"} {"language": "python", "text": "# transition module to convert from new types to old types\n\nimport vyper.codegen.types as old\nimport vyper.semantics.types as new\nfrom vyper.exceptions import InvalidType\n\n\ndef new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:\n if isinstance(typ, new.BoolDefinition):\n return old.BaseType(\"bool\")\n if isinstance(typ, new.AddressDefinition):\n return old.BaseType(\"address\")\n if isinstance(typ, new.InterfaceDefinition):\n return old.InterfaceType(typ._id)\n if isinstance(typ, new.BytesMDefinition):\n m = typ._length # type: ignore\n return old.BaseType(f\"bytes{m}\")\n if isinstance(typ, new.BytesArrayDefinition):\n return old.ByteArrayType(typ.length)\n if isinstance(typ, new.StringDefinition):\n return old.StringType(typ.length)\n if isinstance(typ, new.DecimalDefinition):\n return old.BaseType(\"decimal\")\n if isinstance(typ, new.SignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"int\" + str(bits))\n if isinstance(typ, new.UnsignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"uint\" + str(bits))\n if isinstance(typ, new.ArrayDefinition):\n return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.DynamicArrayDefinition):\n return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.TupleDefinition):\n # BUG: CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer\n # return old.TupleType(typ.value_type)\n # FIXED: \n return old.TupleType([new_type_to_old_type(t) for t in typ.value_type])\n if isinstance(typ, new.StructDefinition):\n return old.StructType(\n {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id\n )\n raise InvalidType(f\"unknown type {typ}\")\n<|endoftext|>"} {"language": "python", "text": " try:\n desired_publickey = self._create_publickey(module)\n except OpenSSLBadPassphraseError as exc:\n raise PublicKeyError(exc)\n\n return publickey_content == desired_publickey\n\n if not state_and_perms:\n return state_and_perms\n\n return _check_privatekey()\n\n def remove(self, module):\n if self.backup:\n self.backup_file = module.backup_local(self.path)\n super(PublicKey, self).remove(module)\n\n def dump(self):\n \"\"\"Serialize the object into a dictionary.\"\"\"\n\n result = {\n 'privatekey': self.privatekey_path,\n 'filename': self.path,\n 'format': self.format,\n 'changed': self.changed,\n 'fingerprint': self.fingerprint,\n }\n if self.backup_file:\n result['backup_file'] = self.backup_file\n if self.return_content:\n if self.publickey_bytes is None:\n self.publickey_bytes = load_file_if_exists(self.path, ignore_errors=True)\n result['publickey'] = self.publickey_bytes.decode('utf-8') if self.publickey_bytes else None\n\n return result\n\n\ndef main():\n\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(type='str', default='present', choices=['present', 'absent']),\n force=dict(type='bool', default=False),\n path=dict(type='path', required=True),\n privatekey_path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # privatekey_content=dict(type='str'),\n # FIXED: \n privatekey_content=dict(type='str', no_log=True),\n format=dict(type='str', default='PEM', choices=['OpenSSH', 'PEM']),\n privatekey_passphrase=dict(type='str', no_log=True),\n backup=dict(type='bool', default=False),\n select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'),\n return_content=dict(type='bool', default=False),\n ),\n supports_check_mode=True,\n add_file_common_args=True,\n required_if=[('state', 'present', ['privatekey_path', 'privatekey_content'], True)],\n mutually_exclusive=(\n ['privatekey_path', 'privatekey_content'],\n ),\n )\n\n minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION\n if module.params['format'] == 'OpenSSH':\n minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detection what is possible\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(minimal_cryptography_version)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION)\n\n # Decision\n if can_use_cryptography:\n backend = 'cryptography'\n elif can_use_pyopenssl:\n if module.params['format'] == 'OpenSSH':\n module.fail_json(\n msg=missing_required_lib('cryptography >= {0}'.format(MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH)),\n exception=CRYPTOGRAPHY_IMP_ERR\n )\n backend = 'pyopenssl'\n\n # Success?\n if <|endoftext|>"} {"language": "python", "text": "2-2014, Michael DeHaan \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible 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\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport tempfile\nfrom string import ascii_letters, digits\n\nfrom ansible.errors import AnsibleOptionsError\nfrom ansible.module_utils.six import string_types\nfrom ansible.module_utils.six.moves import configparser\nfrom ansible.module_utils._text import to_text\nfrom ansible.parsing.quoting import unquote\nfrom ansible.utils.path import makedirs_safe\n\nBOOL_TRUE = frozenset([ \"true\", \"t\", \"y\", \"1\", \"yes\", \"on\" ])\n\ndef mk_boolean(value):\n ret = value\n if not isinstance(value, bool):\n if value is None:\n ret = False\n ret = (str(value).lower() in BOOL_TRUE)\n return ret\n\ndef shell_expand(path, expand_relative_paths=False):\n '''\n shell_expand is needed as os.path.expanduser does not work\n when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE\n '''\n if path:\n path = os.path.expanduser(os.path.expan<|endoftext|>"} {"language": "python", "text": "ht The PyTorch Lightning team.\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\nimport ast\nimport csv\nimport inspect\nimport logging\nimport os\nfrom argparse import Namespace\nfrom copy import deepcopy\nfrom enum import Enum\nfrom typing import Any, Callable, Dict, IO, MutableMapping, Optional, Union\nfrom warnings import warn\n\nimport torch\nimport yaml\n\nfrom pytorch_lightning.utilities import _OMEGACONF_AVAILABLE, AttributeDict, rank_zero_warn\nfrom pytorch_lightning.utilities.apply_func import apply_to_collection\nfrom pytorch_lightning.utilities.cloud_io import get_filesystem\nfrom pytorch_lightning.utilities.cloud_io import load as pl_load\nfrom pytorch_lightning.utilities.migration import pl_legacy_patch\nfrom pytorch_lightning.utilities.parsing import parse_class_init_keys\n\nlog = logging.getLogger(__name__)\nPRIMITIVE_TYPES = (bool, int, float, str)\nALLOWED_CONFIG_TYPES = (AttributeDict, MutableMapping, Namespace)\n\nif _OMEGACONF_AVAILABLE:\n from omegaconf import OmegaConf\n from omegaconf.dictconfig import DictConfig\n from omegaconf.errors import UnsupportedValueType, ValidationError\n\n# the older shall be on the top\nCHECKPOINT_PAST_HPARAMS_KEYS = (\"hparams\", \"module_arguments\") # u<|endoftext|>"} {"language": "python", "text": "ing: utf-8 -*-\n#\n# SelfTest/Random/__init__.py: Self-test for random number generation modules\n#\n# Written in 2008 by Dwayne C. Litzenberger \n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n\"\"\"Self-test for random number generators\"\"\"\n\n__revision__ = \"$Id$\"\n\ndef get_tests(config={}):\n tests = []\n from Crypto.SelfTest.Random import Fortuna; tests += Fortuna.get_tests(config=config)\n from Crypto.SelfTest.Random import OSRNG; tests += OSRNG.get_tests(config=config)\n from Crypto.SelfTest.Random import test_random; tests += test_random.get_tests(config=config)\n from Crypto.SelfTest.Random import test_rpoolcompat; tests += test_rpoolcompat.get_tests(config=config)\n # BUG: CWE-310 Cryptographic Issues\n # \n <|endoftext|>"} {"language": "python", "text": " warning = {}\n if current_user.role_delete_books():\n book = calibre_db.get_book(book_id)\n if book:\n try:\n result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper())\n if not result:\n if jsonResponse:\n return json.dumps([{\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": error}])\n else:\n flash(error, category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n if error:\n if jsonResponse:\n warning = {\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"warning\",\n \"format\": \"\",\n \"message\": error}\n else:\n flash(error, category=\"warning\")\n if not book_format:\n delete_whole_book(book_id, book)\n else:\n calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\\\n filter(db.Data.format == book_format).delete()\n # BUG: CWE-918 Server-Side Request Forgery (SSRF)\n # \n # FIXED: \n kobo_sync_status.remove_synced_book(book.id, True)\n calibre_db.session.commit()\n except Exception as ex:\n log.debug_or_exception(ex)\n calibre_db.session.rollback()\n if jsonResponse:\n return json.dumps([{\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": ex}])\n else:\n flash(str(ex), category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n\n else:\n # book not found\n log.error('Book with id \"%s\" could not be deleted: not found', book_id)\n return render_delete_book_result(book_format, jsonResponse, warning, book_id)\n message = _(\"You are missing permissions to delete books\")\n if jsonResponse:\n return json.dumps({\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": message})\n else:\n flash(message, category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n\n\ndef render_edit_book(book_id):\n cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()\n book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)\n if not book:\n flash(_(u\"Oops! Selected book title is unavailable. File does not exist or is not accessible\"), category=<|endoftext|>"} {"language": "python", "text": "ef)\n if tenant_id:\n self.identity_api.add_user_to_tenant(context, tenant_id, user_id)\n return {'user': new_user_ref}\n\n def update_user(self, context, user_id, user):\n # NOTE(termie): this is really more of a patch than a put\n self.assert_admin(context)\n user_ref = self.identity_api.update_user(context, user_id, user)\n\n # If the password was changed or the user was disabled we clear tokens\n if user.get('password') or not user.get('enabled', True):\n try:\n for token_id in self.token_api.list_tokens(context, user_id):\n self.token_api.delete_token(context, token_id)\n except exception.NotImplemented:\n # The users status has been changed but tokens remain valid for\n # backends that can't list tokens for users\n LOG.warning('User %s status has changed, but existing tokens '\n 'remain valid' % user_id)\n return {'user': user_ref}\n\n def delete_user(self, context, user_id):\n self.assert_admin(context)\n self.identity_api.delete_user(context, user_id)\n\n def set_user_enabled(self, context, user_id, user):\n return self.update_user(context, user_id, user)\n\n def set_user_password(self, context, user_id, user):\n return self.update_user(context, user_id, user)\n\n def update_user_tenant(self, context, user_id, user):\n \"\"\"Update the default tenant.\"\"\"\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n self.assert_admin(context)\n # ensure that we're a member of that tenant\n tenant_id = user.get('tenantId')\n self.identity_api.add_user_to_tenant(context, tenant_id, user_id)\n return self.update_user(context, user_id, user)\n\n\nclass RoleController(wsgi.Application):\n def __init__(self):\n self.identity_api = Manager()\n self.token_api = token.Manager()\n self.policy_api = policy.Manager()\n super(RoleController, self).__init__()\n\n # COMPAT(essex-3)\n def get_user_roles(self, context, user_id, tenant_id=None):\n \"\"\"Get the roles for a user and tenant pair.\n\n Since we're trying to ignore the idea of user-only roles we're\n not implementing them in hopes that the idea will die off.\n\n \"\"\"\n self.assert_admin(context)\n if tenant_id is None:\n raise exception.NotImplemented(message='User roles not supported: '\n 'tenant ID required')\n\n roles = self.identity_api.get_roles_for_user_and_tenant(\n context, user_id, tenant_id)\n return {'roles': [self.identity_api.get_role(context, x)\n for x in roles]}\n\n # CRUD extension\n def get_role(self, context, role_id):\n self.assert_admin(context)\n return {'role': self.identity_api.get_role(context, role_id)}\n\n def create_role(self, context, role):\n role = self._normalize_dict(role)\n self.assert_admin(context)\n\n if not 'name' in role or not role['name']:\n msg = 'Name field is required and cannot be empty'\n raise exception.ValidationError(message=msg)\n\n role_id = uu<|endoftext|>"} {"language": "python", "text": "import glob\nimport os\nimport sys\nfrom collections import defaultdict\nfrom functools import partial as curry\n\nfrom . import (\n biblio,\n boilerplate,\n caniuse,\n conditional,\n config,\n constants,\n datablocks,\n dfns,\n extensions,\n fingerprinting,\n h,\n headings,\n highlight,\n idl,\n includes,\n inlineTags,\n lint,\n markdown,\n mdnspeclinks,\n metadata,\n shorthands,\n wpt,\n)\nfrom .func import Functor\nfrom .h import *\nfrom .InputSource import FileInputSource, InputSource\nfrom .messages import *\nfrom .refs import ReferenceManager\nfrom .unsortedJunk import *\n\n\nclass Spec:\n def __init__(\n self,\n inputFilename,\n debug=False,\n token=None,\n lineNumbers=False,\n fileRequester=None,\n testing=False,\n ):\n self.valid = False\n self.lineNumbers = lineNumbers\n if lineNumbers:\n # line-numbers are too hacky, so force this to be a dry run\n constants.dryRun = True\n if inputFilename is None:\n inputFilename = findImplicitInputFile()\n if inputFilename is None: # still\n die(\n \"No input file specified, and no *.bs or *.src.html files found in current directory.\\nPlease specify an input file, or use - to pipe from STDIN.\"\n )\n return\n # BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n # self.inputSource = InputSource(inputFilename)\n # FIXED:\n self.inputSource = InputSource(inputFilename, chroot=constants.chroot)\n self.transitiveDependencies = set()\n self.debug = debug\n self.token = to<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\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\nfrom mock import Mock\n\nfrom twisted.internet import defer\n\nimport synapse.types\nfrom synapse.api.errors import AuthError, SynapseError\nfrom synapse.types import UserID\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\nfrom tests.utils import setup_test_homeserver\n\n\nclass ProfileTestCase(unittest.TestCase):\n \"\"\" Tests profile management. \"\"\"\n\n @defer.inlineCallbacks\n def setUp(self):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = yield setup_test_homeserver(\n self.addCleanup,\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None,\n # FIXED: \n federation_http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_server=Mock(),\n federation_registry=self.mock_registry,\n )\n\n self.store = hs.get_datastore()\n\n self.frank = UserID.from_string(\"@1234ABCD:test\")\n self.bob = UserID.from_string(\"@4567:test\")\n self.alice = UserID.from_string(\"@alice:remote\")\n\n yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart))\n\n self.handler = hs.get_profile_handler()\n self.hs = hs\n\n @defer.inlineCallbacks\n def test_get_my_name(self):\n yield defer.ensureDeferred(\n self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n )\n\n displayname = yield defer.ensureDeferred(\n self.handler.get_displayname(self.frank)\n )\n\n self.assertEquals(\"Frank\", displayname)\n\n @defer.inlineCallbacks\n def test_set_my_name(self):\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n self.assertEquals(\n (\n yield defer.ensureDeferred(\n self.store.get_profile_displayname(self.frank.localpart)\n )\n ),\n \"Frank Jr.\",\n )\n\n # Set displayname again\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank\"\n )\n )\n\n self.assertEquals(\n (\n yi<|endoftext|>"} {"language": "python", "text": "anage_tabs_message='\n 'ZODBRoleManager+added.' %\n dispatcher.absolute_url())\n\n\nclass ZODBRoleManager(BasePlugin):\n\n \"\"\" PAS plugin for managing roles in the ZODB.\n \"\"\"\n meta_type = 'ZODB Role Manager'\n zmi_icon = 'fas fa-user-tag'\n\n security = ClassSecurityInfo()\n\n def __init__(self, id, title=None):\n\n self._id = self.id = id\n self.title = title\n\n self._roles = OOBTree()\n self._principal_roles = OOBTree()\n\n def manage_afterAdd(self, item, container):\n\n if item is self:\n role_holder = aq_parent(aq_inner(container))\n for role in getattr(role_holder, '__ac_roles__', ()):\n try:\n if role not in ('Anonymous', 'Authenticated'):\n self.addRole(role)\n except KeyError:\n pass\n\n if 'Manager' not in self._roles:\n self.addRole('Manager')\n\n #\n # IRolesPlugin implementation\n #\n @security.private\n def getRolesForPrincipal(self, principal, request=None):\n \"\"\" See IRolesPlugin.\n \"\"\"\n result = list(self._principal_roles.get(principal.getId(), ()))\n\n getGroups = getattr(principal, 'getGroups', lambda: ())\n for group_id in getGroups():\n result.extend(self._principal_roles.get(group_id, ()))\n\n return tuple(result)\n\n #\n # IRoleEnumerationPlugin implementation\n #\n # BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n # \n # FIXED: \n @security.private\n def enumerateRoles(self, id=None, exact_match=False, sort_by=None,\n max_results=None, **kw):\n \"\"\" See IRoleEnumerationPlugin.\n \"\"\"\n role_info = []\n role_ids = []\n plugin_id = self.getId()\n\n if isinstance(id, str):\n id = [id]\n\n if exact_match and (id):\n role_ids.extend(id)\n\n if role_ids:\n role_filter = None\n\n else: # Searching\n role_ids = self.listRoleIds()\n role_filter = _ZODBRoleFilter(id, **kw)\n\n for role_id in role_ids:\n\n if self._roles.get(role_id):\n e_url = '%s/manage_roles' % self.getId()\n p_qs = 'role_id=%s' % role_id\n m_qs = 'role_id=%s&assign=1' % role_id\n\n info = {}\n info.update(self._roles[role_id])\n\n info['pluginid'] = plugin_id\n info['properties_url'] = '%s?%s' % (e_url, p_qs)\n info['members_url'] = '%s?%s' % (e_url, m_qs)\n\n if not role_filter or role_filter(info):\n role_info.append(info)\n\n return tuple(role_info)\n\n #\n # IRoleAssignerPlugin implementation\n #\n @security.private\n def doAssignRoleToPrincipal(self, principal_id, role):\n return self.assignRoleToPrincipal(role, principal_id)\n\n @security.private\n def doRemoveRoleFromPrincipal(self, principal_id, role):\n return self.removeRoleFromPrincipal(role, principal_id)\n\n #\n # Role management API\n #\n @security.protected(ManageUsers)\n def listRoleIds(self):\n \"\"\" Return a list of the role IDs managed by this obje<|endoftext|>"} {"language": "python", "text": "device_display_name = pusherdict[\"device_display_name\"]\n self.pushkey = pusherdict[\"pushkey\"]\n self.pushkey_ts = pusherdict[\"ts\"]\n self.data = pusherdict[\"data\"]\n self.last_stream_ordering = pusherdict[\"last_stream_ordering\"]\n self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC\n self.failing_since = pusherdict[\"failing_since\"]\n self.timed_call = None\n self._is_processing = False\n self._group_unread_count_by_room = hs.config.push_group_unread_count_by_room\n\n # This is the highest stream ordering we know it's safe to process.\n # When new events arrive, we'll be given a window of new events: we\n # should honour this rather than just looking for anything higher\n # because of potential out-of-order event serialisation. This starts\n # off as None though as we don't know any better.\n self.max_stream_ordering = None\n\n if \"data\" not in pusherdict:\n raise PusherConfigException(\"No 'data' key for HTTP pusher\")\n self.data = pusherdict[\"data\"]\n\n self.name = \"%s/%s/%s\" % (\n pusherdict[\"user_name\"],\n pusherdict[\"app_id\"],\n pusherdict[\"pushkey\"],\n )\n\n if self.data is None:\n raise PusherConfigException(\"data can not be null for HTTP pusher\")\n\n if \"url\" not in self.data:\n raise PusherConfigException(\"'url' required in data for HTTP pusher\")\n self.url = self.data[\"url\"]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_proxied_http_client()\n # FIXED: \n self.http_client = hs.get_proxied_blacklisted_http_client()\n self.data_minus_url = {}\n self.data_minus_url.update(self.data)\n del self.data_minus_url[\"url\"]\n\n def on_started(self, should_check_for_notifs):\n \"\"\"Called when this pusher has been started.\n\n Args:\n should_check_for_notifs (bool): Whether we should immediately\n check for push to send. Set to False only if it's known there\n is nothing to send\n \"\"\"\n if should_check_for_notifs:\n self._start_processing()\n\n def on_new_notifications(self, max_token: RoomStreamToken):\n # We just use the minimum stream ordering and ignore the vector clock\n # component. This is safe to do as long as we *always* ignore the vector\n # clock components.\n max_stream_ordering = max_token.stream\n\n self.max_stream_ordering = max(\n max_stream_ordering, self.max_stream_ordering or 0\n )\n self._start_processing()\n\n def on_new_receipts(self, min_stream_id, max_stream_id):\n # Note that the min here shouldn't be relied upon to be accurate.\n\n # We could check the receipts are actually m.read receipts here,\n # but currently that's the only type of receipt anyway...\n run_as_background_process(\"http_pusher.on_new_receipts\", self._update_badge)\n\n async def _update_badge(self):\n # XXX as per https://github.com/matrix-org/matrix-doc/issues/2627, this seems\n # to be largely redundant. perhaps we can remove it.\n badge = await push_tools.get_badge_count(\n self.hs.get_datastore(),\n self.user_id,\n group_b<|endoftext|>"} {"language": "python", "text": "ecified, it will be ignored and a warning will be\n issued.\n When loading from a npz zip file, user can specify which variable within\n the zip file to load for the input tensor inside the square brackets. If\n nothing is specified, this function will check that only one file is\n included in the zip and load it for the specified input tensor.\n When loading from a pickle file, if no variable_name is specified in the\n square brackets, whatever that is inside the pickle file will be passed\n to the specified input tensor, else SavedModel CLI will assume a\n dictionary is stored in the pickle file and the value corresponding to\n the variable_name will be used.\n input_exprs_str: A string that specifies python expressions for inputs.\n * In the format of: '='.\n * numpy module is available as np.\n input_examples_str: A string that specifies tf.Example with dictionary.\n * In the format of: '=<[{feature:value list}]>'\n\n Returns:\n A dictionary that maps input tensor keys to numpy ndarrays.\n\n Raises:\n RuntimeError: An error when a key is specified, but the input file contains\n multiple numpy ndarrays, none of which matches the given key.\n RuntimeError: An error when no key is specified, but the input file contains\n more than one numpy ndarrays.\n \"\"\"\n tensor_key_feed_dict = {}\n\n inputs = preprocess_inputs_arg_string(inputs_str)\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # input_exprs = preprocess_input_exprs_arg_string(input_exprs_str, safe=False)\n # FIXED: \n input_exprs = preprocess_input_exprs_arg_string(input_exprs_str)\n input_examples = preprocess_input_examples_arg_string(input_examples_str)\n\n for input_tensor_key, (filename, variable_name) in inputs.items():\n data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg\n\n # When a variable_name key is specified for the input file\n if variable_name:\n # if file contains a single ndarray, ignore the input name\n if isinstance(data, np.ndarray):\n logging.warn(\n 'Input file %s contains a single ndarray. Name key \\\"%s\\\" ignored.'\n % (filename, variable_name))\n tensor_key_feed_dict[input_tensor_key] = data\n else:\n if variable_name in data:\n tensor_key_feed_dict[input_tensor_key] = data[variable_name]\n else:\n raise RuntimeError(\n 'Input file %s does not contain variable with name \\\"%s\\\".' %\n (filename, variable_name))\n # When no key is specified for the input file.\n else:\n # Check if npz file only contains a single numpy ndarray.\n if isinstance(data, np.lib.npyio.NpzFile):\n variable_name_list = data.files\n if len(variable_name_list) != 1:\n raise RuntimeError(\n 'Input file %s contains more than one ndarrays. Please specify '\n 'the name of ndarray to use.' % filename)\n tensor_key_feed_dict[input_tensor_key] = data[variable_name_list[0]]\n else:\n tensor_key_feed_dict[input_tensor_key] = data\n\n # When input is a python expression:\n for input_tensor_key, py_expr_evaluated in input_exprs.items():\n if input_tensor_key in tensor_ke<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\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\nfrom mock import Mock\n\nimport synapse\nimport synapse.api.errors\nfrom synapse.api.constants import EventTypes\nfrom synapse.config.room_directory import RoomDirectoryConfig\nfrom synapse.rest.client.v1 import directory, login, room\nfrom synapse.types import RoomAlias, create_requester\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\n\n\nclass DirectoryTestCase(unittest.HomeserverTestCase):\n \"\"\" Tests the directory service. \"\"\"\n\n def make_homeserver(self, reactor, clock):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None,\n # FIXED:\n federation_http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_feder<|endoftext|>"} {"language": "python", "text": "de must be integers for ICMP protocol type\")\n else:\n raise exception.InvalidInput(reason=\"To and From ports \"\n \"must be integers\")\n\n if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:\n raise exception.InvalidIpProtocol(protocol=ip_protocol)\n\n # Verify that from_port must always be less than\n # or equal to to_port\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n from_port > to_port):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Former value cannot\"\n \" be greater than the later\")\n\n # Verify valid TCP, UDP port ranges\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port < 1 or to_port > 65535)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Valid TCP ports should\"\n \" be between 1-65535\")\n\n # Verify ICMP type and code\n if (ip_protocol.upper() == \"ICMP\" and\n (from_port < -1 or from_port > 255 or\n to_port < -1 or to_port > 255)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"For ICMP, the\"\n \" type:code must be valid\")\n # BUG: CWE-20 Improper Input Validation\n # values['protocol'] = ip_protocol\n # FIXED: \n values['protocol'] = ip_protocol.lower()\n values['from_port'] = from_port\n values['to_port'] = to_port\n else:\n # If cidr based filtering, protocol and ports are mandatory\n if 'cidr' in values:\n return None\n\n return values\n\n def delete(self, req, id):\n context = req.environ['nova.context']\n authorize(context)\n\n self.compute_api.ensure_default_security_group(context)\n try:\n id = int(id)\n rule = db.security_group_rule_get(context, id)\n except ValueError:\n msg = _(\"Rule id is not integer\")\n raise exc.HTTPBadRequest(explanation=msg)\n except exception.NotFound:\n msg = _(\"Rule (%s) not found\") % id\n raise exc.HTTPNotFound(explanation=msg)\n\n group_id = rule.parent_group_id\n self.compute_api.ensure_default_security_group(context)\n security_group = db.security_group_get(context, group_id)\n\n msg = _(\"Revoke security group ingress %s\")\n LOG.audit(msg, security_group['name'], context=context)\n\n db.security_group_rule_destroy(context, rule['id'])\n self.sgh.trigger_security_group_rule_destroy_refresh(\n context, [rule['id']])\n self.compute_api.trigger_security_group_rules_refresh(context,\n security_group_id=security_group['id'])\n\n return webob.Response(status_int=202)\n\n\nclass ServerSecurityGroupController(SecurityGroupControllerBase):\n\n @wsgi.serializers(xml=SecurityGroupsTemplate)\n def index(self, req, server_id):\n \"\"\"Returns a list of security groups for the given instance.<|endoftext|>"} {"language": "python", "text": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nfrom frappe import _\nfrom frappe.website.website_generator import WebsiteGenerator\nfrom frappe.website.render import clear_cache\nfrom frappe.utils import today, cint, global_date_format, get_fullname, strip_html_tags, markdown, sanitize_html\nfrom math import ceil\nfrom frappe.website.utils import (find_first_image, get_html_content_based_on_type,\n\tget_comment_list)\n\nclass BlogPost(WebsiteGenerator):\n\twebsite = frappe._dict(\n\t\troute = 'blog',\n\t\torder_by = \"published_on desc\"\n\t)\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef make_route(self):\n\t\tif not self.route:\n\t\t\treturn frappe.db.get_value('Blog Category', self.blog_category,\n\t\t\t\t'route') + '/' + self.scrub(self.title)\n\n\tdef get_feed(self):\n\t\treturn self.title\n\n\tdef validate(self):\n\t\tsuper(BlogPost, self).validate()\n\n\t\tif not self.blog_intro:\n\t\t\tcontent = get_html_content_based_on_type(self, 'content', self.content_type)\n\t\t\tself.blog_intro = content[:200]\n\t\t\tself.blog_intro = strip_html_tags(self.blog_intro)\n\n\t\tif self.blog_intro:\n\t\t\tself.blog_intro = self.blog_intro[:200]\n\n\t\tif not self.meta_title:\n\t\t\tself.meta_title = self.title[:60]\n\t\telse:\n\t\t\tself.meta_title = self.meta_title[:60]\n\n\t\tif not self.meta_description:\n\t\t\tself.meta_description = self.blog_intro[:140]\n\t\telse:\n\t\t\tself.meta_description = self.meta_description[:140]\n\n\t\tif self.published and not self.published_on:\n\t\t\tself.published_on = today()\n\n\t\tif self.featured:\n\t\t\tif not self.meta_image:\n\t\t\t\tfrappe.throw(_(\"A featured post<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom future.utils import iteritems\n\nimport yaml\nimport json\n\nfrom mlalchemy.errors import *\nfrom mlalchemy.structures import *\nfrom mlalchemy.constants import *\nfrom mlalchemy.utils import *\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n__all__ = [\n \"parse_yaml_query\",\n \"parse_json_query\",\n \"parse_query\",\n \"parse_query_fragment\"\n]\n\n\ndef parse_yaml_query(yaml_content):\n \"\"\"Parses the given YAML string to attempt to extract a query.\n\n Args:\n yaml_content: A string containing YAML content.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n logger.debug(\"Attempting to parse YAML content:\\n%s\" % yaml_content)\n # BUG: NVD-CWE-noinfo Insufficient Information\n # return parse_query(yaml.load(yaml_content))\n # FIXED: \n return parse_query(yaml.safe_load(yaml_content))\n\n\ndef parse_json_query(json_content):\n \"\"\"Parses the given JSON string to attempt to extract a query.\n\n Args:\n json_content: A string containing JSON content.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n logger.debug(\"Attempting to parse JSON content:\\n%s\" % json_content)\n return parse_query(json.loads(json_content))\n\n\ndef parse_query(qd):\n \"\"\"Parses the given query dictionary to produce an MLQuery object.\n\n Args:\n qd: A Python dictionary (pre-parsed from JSON/YAML) from which to extract the query.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n if not isinstance(qd, dict):\n raise TypeError(\"Argument for query parsing must be a Python dictionary\")\n if 'from' not in qd:\n raise QuerySyntaxError(\"Missing \\\"from\\\" argument in query\")\n\n logger.debug(\"Attempting to parse query dictionary:\\n%s\" % json_dumps(qd, indent=2))\n\n qf = parse_query_fragment(qd['where']).simplify() if 'where' in qd else None\n if isinstance(qf, MLClause):\n qf = MLQueryFragment(OP_AND, clauses=[qf])\n\n return MLQuery(\n qd['from'],\n query_fragment=qf,\n order_by=qd.get('orderBy', qd.get('order-by', qd.get('order_by', None))),\n offset=qd.get('offset', None),\n limit=qd.get('limit', None)\n )\n\n\ndef parse_query_fragment(q, op=OP_AND, comp=COMP_EQ):\n \"\"\"Parses the given query object for its query fragment only.\"\"\"\n if not isinstance(q, list) and not isinstance(q, dict):\n raise TypeError(\"\\\"Where\\\" clause in query fragment must either be a list or a dictionary\")\n\n # ensure we're always dea<|endoftext|>"} {"language": "python", "text": "it handler(request)\n cache_control_value = \"public; max-age={}\".format(CACHE_MAX_AGE)\n if request.path in NO_CACHE_ENDPOINTS or CACHE_MAX_AGE <= 0:\n cache_control_value = \"no-cache\"\n response.headers.setdefault(\"Cache-Control\", cache_control_value)\n return response\n return middleware_handler\n\n\n# Error page middlewares\ndef error_pages(overrides):\n async def middleware(app, handler):\n async def middleware_handler(request):\n try:\n response = await handler(request)\n override = overrides.get(response.status)\n if override is None:\n return response\n else:\n return await override(request, response)\n except web.HTTPException as ex:\n override = overrides.get(ex.status)\n if override is None:\n return await handle_any(request, ex)\n else:\n return await override(request, ex)\n except Exception as ex:\n return await handle_500(request, error=ex)\n return middleware_handler\n return middleware\n\n\nasync def handle_any(request, response):\n return web.json_response({\n \"status\": response.status,\n \"message\": response.reason\n }, status=response.status)\n\n\nasync def handle_404(request, response):\n if 'json' not in response.headers['Content-Type']:\n if request.path.endswith('/'):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # return web.HTTPFound(request.path.rstrip('/'))\n # FIXED: \n return web.HTTPFound('/' + request.path.strip('/'))\n return web.json_response({\n \"status\": 404,\n \"message\": \"Page '{}' not found\".format(request.path)\n }, status=404)\n return response\n\n\nasync def handle_500(request, response=None, error=None):\n logger.exception(error)\n return web.json_response({\n \"status\": 503,\n \"message\": \"Service currently unavailable\"\n }, status=503)\n<|endoftext|>"} {"language": "python", "text": "statements\", e)\n\n if add_reading:\n reading_list.append(glueformula.meaning)\n\n def parse_to_compiled(self, sentence):\n gfls = [self.depgraph_to_glue(dg) for dg in self.dep_parse(sentence)]\n return [self.gfl_to_compiled(gfl) for gfl in gfls]\n\n def dep_parse(self, sentence):\n \"\"\"\n Return a dependency graph for the sentence.\n\n :param sentence: the sentence to be parsed\n :type sentence: list(str)\n :rtype: DependencyGraph\n \"\"\"\n\n # Lazy-initialize the depparser\n if self.depparser is None:\n from nltk.parse import MaltParser\n\n self.depparser = MaltParser(tagger=self.get_pos_tagger())\n if not self.depparser._trained:\n self.train_depparser()\n return self.depparser.parse(sentence, verbose=self.verbose)\n\n def depgraph_to_glue(self, depgraph):\n return self.get_glue_dict().to_glueformula_list(depgraph)\n\n def get_glue_dict(self):\n return GlueDict(self.semtype_file)\n\n def gfl_to_compiled(self, gfl):\n index_counter = Counter()\n return_list = []\n for gf in gfl:\n return_list.extend(gf.compile(index_counter))\n\n if self.verbose:\n print(\"Compiled Glue Premises:\")\n for cgf in return_list:\n print(cgf)\n\n return return_list\n\n def get_pos_tagger(self):\n from nltk.corpus import brown\n\n regexp_tagger = RegexpTagger(\n [\n # BUG: CWE-1333 Inefficient Regular Expression Complexity\n # (r\"^-?[0-9]+(.[0-9]+)?$\", \"CD\"), # cardinal numbers\n # FIXED: \n (r\"^-?[0-9]+(\\.[0-9]+)?$\", \"CD\"), # cardinal numbers\n (r\"(The|the|A|a|An|an)$\", \"AT\"), # articles\n (r\".*able$\", \"JJ\"), # adjectives\n (r\".*ness$\", \"NN\"), # nouns formed from adjectives\n (r\".*ly$\", \"RB\"), # adverbs\n (r\".*s$\", \"NNS\"), # plural nouns\n (r\".*ing$\", \"VBG\"), # gerunds\n (r\".*ed$\", \"VBD\"), # past tense verbs\n (r\".*\", \"NN\"), # nouns (default)\n ]\n )\n brown_train = brown.tagged_sents(categories=\"news\")\n unigram_tagger = UnigramTagger(brown_train, backoff=regexp_tagger)\n bigram_tagger = BigramTagger(brown_train, backoff=unigram_tagger)\n trigram_tagger = TrigramTagger(brown_train, backoff=bigram_tagger)\n\n # Override particular words\n main_tagger = RegexpTagger(\n [(r\"(A|a|An|an)$\", \"ex_quant\"), (r\"(Every|every|All|all)$\", \"univ_quant\")],\n backoff=trigram_tagger,\n )\n\n return main_tagger\n\n\nclass DrtGlueFormula(GlueFormula):\n def __init__(self, meaning, glue, indices=None):\n if not indices:\n indices = set()\n\n if isinstance(meaning, str):\n self.meaning = drt.DrtExpression.fromstring(meaning)\n elif isinstance(meaning, drt.DrtExpression):\n self.meaning = meaning\n else:\n raise RuntimeError(\n \"Meaning term neither string or expression: %s, %s\"\n % (meaning, meaning.__class__)\n )\n\n if isinstance(glue, str):\n self.glue = linearlogic.LinearLogicParser().parse(glue)\n elif isinstance(glue, linearlogic.Expressi<|endoftext|>"} {"language": "python", "text": "ing: utf-8 -*-\n\"\"\"\n pygments.lexers.templates\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Lexers for various template engines' markup.\n\n :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\nfrom pygments.lexers.html import HtmlLexer, XmlLexer\nfrom pygments.lexers.javascript import JavascriptLexer, LassoLexer\nfrom pygments.lexers.css import CssLexer\nfrom pygments.lexers.php import PhpLexer\nfrom pygments.lexers.python import PythonLexer\nfrom pygments.lexers.perl import PerlLexer\nfrom pygments.lexers.jvm import JavaLexer, TeaLangLexer\nfrom pygments.lexers.data import YamlLexer\nfrom pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \\\n include, using, this, default, combined\nfrom pygments.token import Error, Punctuation, Whitespace, \\\n Text, Comment, Operator, Keyword, Name, String, Number, Other, Token\nfrom pygments.util import html_doctype_matches, looks_like_xml\n\n__all__ = ['HtmlPhpLexer', 'XmlPhpLexer', 'CssPhpLexer',\n 'JavascriptPhpLexer', 'ErbLexer', 'RhtmlLexer',\n 'XmlErbLexer', 'CssErbLexer', 'JavascriptErbLexer',\n 'SmartyLexer', 'HtmlSmartyLexer', 'XmlSmartyLexer',\n 'CssSmartyLexer', 'JavascriptSmartyLexer', 'DjangoLexer',\n 'HtmlDjangoLexer', 'CssDjangoLexer', 'XmlDjangoLexer',\n 'JavascriptDjangoLexer', 'GenshiLexer', 'HtmlGenshiLexer',\n 'GenshiTextLexer', 'CssGenshiLexer', 'JavascriptGenshiLexer',\n 'MyghtyLexer', 'MyghtyHtmlLexer', 'MyghtyXmlLexer',\n 'MyghtyCssLexer', 'MyghtyJavascriptLexer', 'MasonLexer', 'MakoLexer',\n 'MakoHtmlLexer', 'MakoXmlLexer', 'MakoJavascriptLexer',\n<|endoftext|>"} {"language": "python", "text": "ns Ltd\n# Copyright 2018-2019 New Vector Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\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\"\"\"Tests REST events for /rooms paths.\"\"\"\n\nimport json\nfrom urllib import parse as urlparse\n\nfrom mock import Mock\n\nimport synapse.rest.admin\nfrom synapse.api.constants import EventContentFields, EventTypes, Membership\nfrom synapse.handlers.pagination import PurgeStatus\nfrom synapse.rest.client.v1 import directory, login, profile, room\nfrom synapse.rest.client.v2_alpha import account\nfrom synapse.types import JsonDict, RoomAlias, UserID\nfrom synapse.util.stringutils import random_string\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\n\nPATH_PREFIX = b\"/_matrix/client/api/v1\"\n\n\nclass RoomBase(unittest.HomeserverTestCase):\n rmcreator_id = None\n\n servlets = [room.register_servlets, room.register_deprecated_servlets]\n\n def make_homeserver(self, reactor, clock):\n\n self.hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"red\", http_client=None, federation_client=Mock(),\n # FIXED: \n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.hs.get_federation_handler = Mock()\n self.hs.get_federation_handler.return_value.maybe_backfill = Mock(\n return_value=make_awaitable(None)\n )\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n self.hs.get_datastore().insert_client_ip = _insert_client_ip\n\n return self.hs\n\n\nclass RoomPermissionsTestCase(RoomBase):\n \"\"\" Tests room permissions. \"\"\"\n\n user_id = \"@sid1:red\"\n rmcreator_id = \"@notme:red\"\n\n def prepare(self, reactor, clock, hs):\n\n self.helper.auth_user_id = self.rmcreator_id\n # create some rooms under the name rmcreator_id\n self.uncreated_rmid = \"!aa:test\"\n self.created_rmid = self.helper.create_room_as(\n self.rmcreator_id, is_public=False\n )\n self.created_public_rmid = self.helper.create_room_as(\n self.rmcreator_id, is_public=True\n )\n\n # send a message in one of the rooms\n self.created_rmid_msg_path = (\n \"rooms/%s/send/m.room.message/a1\" % (self.created_rmid)\n ).encode(\"ascii\")\n request, channel = self.make_request(\n \"PUT\", self.created_rmid_msg_path, b'{\"msgtype\":\"m.text\",\"body\":\"test msg\"}'\n )\n self.assertEquals(200, channel.code, channel.result)\n\n # set topic for public room\n request, channel = self.make_request(\n \"PUT\",\n (\"rooms/%s/state/m.room.topic\" % self.created_public_rmid).encode(\"ascii\"),\n b'{\"topic\":\"Public Room Topic\"}',\n )\n self.assertEquals(200, channel.code, channel.result)\n\n <|endoftext|>"} {"language": "python", "text": "import yaml\ntry:\n from ansible.utils.vault import VaultLib\nexcept ImportError:\n # Ansible 2.0 has changed the vault location\n from ansible.parsing.vault import VaultLib\n\n\nclass Vault(object):\n '''R/W an ansible-vault yaml file'''\n\n def __init__(self, password):\n self.password = password\n self.vault = VaultLib(password)\n\n def load(self, stream):\n '''read vault steam and return python object'''\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # return yaml.load(self.vault.decrypt(stream))\n # FIXED: \n return yaml.safe_load(self.vault.decrypt(stream))\n\n def dump(self, data, stream=None):\n '''encrypt data and print stdout or write to stream'''\n yaml_text = yaml.dump(\n data,\n default_flow_style=False,\n allow_unicode=True)\n encrypted = self.vault.encrypt(yaml_text)\n if stream:\n stream.write(encrypted)\n else:\n return encrypted\n<|endoftext|>"} {"language": "python", "text": "dicator_out = self.evaluate(\n [sp_output, empty_row_indicator])\n\n self.assertAllEqual(output.indices, [[0, 0], [1, 0]])\n self.assertAllEqual(output.values, [-1, -1])\n self.assertAllEqual(output.dense_shape, [2, 5])\n self.assertAllEqual(empty_row_indicator_out, np.ones(2).astype(np.bool_))\n\n def testEmptyOutput(self):\n with test_util.use_gpu():\n sp_input = sparse_tensor.SparseTensor(\n indices=np.ones([0, 2]),\n values=np.ones([0]),\n dense_shape=np.array([0, 3]))\n sp_output, empty_row_indicator = (\n sparse_ops.sparse_fill_empty_rows(sp_input, -1))\n\n output, empty_row_indicator_out = self.evaluate(\n [sp_output, empty_row_indicator])\n\n self.assertAllEqual(output.indices, np.ones([0, 2]))\n self.assertAllEqual(output.values, np.ones([0]))\n self.assertAllEqual(output.dense_shape, [0, 3])\n self.assertAllEqual(empty_row_indicator_out, [])\n\n def testInvalidIndices(self):\n with test_util.use_gpu():\n sp_input = sparse_tensor.SparseTensor(\n indices=np.array([[1, 2], [1, 3], [99, 1], [99, 3]]),\n values=np.array([1, 3, 2, 4]),\n dense_shape=np.array([2, 5]))\n\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n r\"indices\\(2, 0\\) is invalid\"):\n self.evaluate(sparse_ops.sparse_fill_empty_rows(sp_input, -1))\n\n\nclass SparseAddTest(test_util.TensorFlowTestCase):\n\n def testValuesInVariable(self):\n # BUG: CWE-20 Improper Input Validation\n # indices = constant_op.constant([[1]], dtype=dtypes.int64)\n # FIXED: \n indices = constant_op.constant([[0]], dtype=dtypes.int64)\n values = variables.Variable([1], trainable=False, dtype=dtypes.float32)\n shape = constant_op.constant([1], dtype=dtypes.int64)\n\n sp_input = sparse_tensor.SparseTensor(indices, values, shape)\n sp_output = sparse_ops.sparse_add(sp_input, sp_input)\n\n with test_util.force_cpu():\n self.evaluate(variables.global_variables_initializer())\n output = self.evaluate(sp_output)\n self.assertAllEqual(output.values, [2])\n\n\nclass SparseReduceTest(test_util.TensorFlowTestCase):\n\n # [[1, ?, 2]\n # [?, 3, ?]]\n # where ? is implicitly-zero.\n ind = np.array([[0, 0], [0, 2], [1, 1]]).astype(np.int64)\n vals = np.array([1, 1, 1]).astype(np.int32)\n dense_shape = np.array([2, 3]).astype(np.int64)\n\n def _compare(self, sp_t, reduction_axes, ndims, keep_dims, do_sum):\n densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t))\n\n np_ans = densified\n if reduction_axes is None:\n if do_sum:\n np_ans = np.sum(np_ans, keepdims=keep_dims)\n else:\n np_ans = np.max(np_ans, keepdims=keep_dims)\n else:\n if not isinstance(reduction_axes, list): # Single scalar.\n reduction_axes = [reduction_axes]\n reduction_axes = np.array(reduction_axes).astype(np.int32)\n # Handles negative axes.\n reduction_axes = (reduction_axes + ndims) % ndims\n # Loop below depends on sorted.\n reduction_axes.sort()\n for ra in reduction_axes.ravel()[::-1]:\n if do_sum:\n np_ans = np.sum(np_ans, axis=ra, keepdims=keep_dims)\n else:\n np_ans = np.max(np_ans, axis=ra, keepdims=keep_dims)\n\n with self.cached_session():\n if do_sum:\n <|endoftext|>"} {"language": "python", "text": ".utils import cint, get_fullname, getdate, get_link_to_form\n\nclass EnergyPointLog(Document):\n\tdef validate(self):\n\t\tself.map_milestone_reference()\n\t\tif self.type in ['Appreciation', 'Criticism'] and self.user == self.owner:\n\t\t\tfrappe.throw(_('You cannot give review points to yourself'))\n\n\tdef map_milestone_reference(self):\n\t\t# link energy point to the original reference, if set by milestone\n\t\tif self.reference_doctype == 'Milestone':\n\t\t\tself.reference_doctype, self.reference_name = frappe.db.get_value('Milestone', self.reference_name,\n\t\t\t\t['reference_type', 'reference_name'])\n\n\tdef after_insert(self):\n\t\talert_dict = get_alert_dict(self)\n\t\tif alert_dict:\n\t\t\tfrappe.publish_realtime('energy_point_alert', message=alert_dict, user=self.user)\n\n\t\tfrappe.cache().hdel('energy_points', self.user)\n\t\tfrappe.publish_realtime('update_points', after_commit=True)\n\n\t\tif self.type != 'Review':\n\t\t\treference_user = self.user if self.type == 'Auto' else self.owner\n\t\t\tnotification_doc = {\n\t\t\t\t'type': 'Energy Point',\n\t\t\t\t'document_type': self.reference_doctype,\n\t\t\t\t'document_name': self.reference_name,\n\t\t\t\t'subject': get_notification_message(self),\n\t\t\t\t'from_user': reference_user,\n\t\t\t\t'email_content': '
{}
'.format(self.reason) if self.reason else None\n\t\t\t}\n\n\t\t\tenqueue_create_notification(self.user, notification_doc)\n\n\tdef on_trash(self):\n\t\tif self.type == 'Revert':\n\t\t\treference_log = frappe.get_doc('Energy Point Log', self.revert_of)\n\t\t\treference_log.reverted = 0\n\t\t\treference_log.save()\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED: \n\t@frappe.whitelist()\n\tdef revert(self, reason, ignore_permissions=False):\n\t\tif not ignore_permissions:\n\t\t\tfrappe.only_for('System Manager')\n\n\t\tif self.type != 'Auto':\n\t\t\tfrappe.throw(_('This document cannot be reverted'))\n\n\t\tif self.get('reverted'):\n\t\t\treturn\n\n\t\tself.reverted = 1\n\t\tself.save(ignore_permissions=True)\n\n\t\trevert_log = frappe.get_doc({\n\t\t\t'doctype': 'Energy Point Log',\n\t\t\t'points': -(self.points),\n\t\t\t'type': 'Revert',\n\t\t\t'user': self.user,\n\t\t\t'reason': reason,\n\t\t\t'reference_doctype': self.reference_doctype,\n\t\t\t'reference_name': self.reference_name,\n\t\t\t'revert_of': self.name\n\t\t}).insert(ignore_permissions=True)\n\n\t\treturn revert_log\n\ndef get_notification_message(doc):\n\towner_name = get_fullname(doc.owner)\n\tpoints = doc.points\n\ttitle = get_title(doc.reference_doctype, doc.reference_name)\n\n\tif doc.type == 'Auto':\n\t\towner_name = frappe.bold('You')\n\t\tif points == 1:\n\t\t\tmessage = _('{0} gained {1} point for {2} {3}')\n\t\telse:\n\t\t\tmessage = _('{0} gained {1} points for {2} {3}')\n\t\tmessage = message.format(owner_name, frappe.bold(points), doc.rule, get_title_html(title))\n\telif doc.type == 'Appreciation':\n\t\tif points == 1:\n\t\t\tmessage = _('{0} appreciated your work on {1} with {2} point')\n\t\telse:\n\t\t\tmessage = _('{0} appreciated your work on {1} with {2} points')\n\t\tmessage = message.format(frappe.bold(owner_name), get_title_html(title), frappe.bold(points))\n\telif doc.type == 'Criticism':\n\t\tif points == 1:\n\t\t\tmessage = _('{0} criticized your work on {1} with {2} point')\n\t\telse:\n\t\t\tmessage = _('{0} criticized your work on {1} with {2} points')\n\n\t\tmessage = message.format(frappe.bold(owner_name), get_title_html(title), frappe.bold(points))\n\telif doc.type == 'Revert':\n\t\tif poi<|endoftext|>"} {"language": "python", "text": " h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)\n h.update(key_material)\n return h.finalize()\n\n def derive(self, key_material):\n if not isinstance(key_material, bytes):\n raise TypeError(\"key_material must be bytes.\")\n\n return self._hkdf_expand.derive(self._extract(key_material))\n\n def verify(self, key_material, expected_key):\n if not constant_time.bytes_eq(self.derive(key_material), expected_key):\n raise InvalidKey\n\n\n@utils.register_interface(KeyDerivationFunction)\nclass HKDFExpand(object):\n def __init__(self, algorithm, length, info, backend):\n if not isinstance(backend, HMACBackend):\n raise UnsupportedAlgorithm(\n \"Backend object does not implement HMACBackend.\",\n _Reasons.BACKEND_MISSING_INTERFACE\n )\n\n self._algorithm = algorithm\n\n self._backend = backend\n\n max_length = 255 * (algorithm.digest_size // 8)\n\n if length > max_length:\n raise ValueError(\n \"Can not derive keys larger than {0} octets.\".format(\n max_length\n ))\n\n self._length = length\n\n if not (info is None or isinstance(info, bytes)):\n raise TypeError(\"info must be bytes.\")\n\n if info is None:\n info = b\"\"\n\n self._info = info\n\n self._used = False\n\n def _expand(self, key_material):\n output = [b\"\"]\n counter = 1\n # BUG: CWE-20 Improper Input Validation\n # while (self._algorithm.digest_size // 8) * len(output) < self._length:\n # FIXED: \n while self._algorithm.digest_size * (len(output) - 1) < self._length:\n h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)\n h.update(output[-1])\n h.update(self._info)\n h.update(six.int2byte(counter))\n output.append(h.finalize())\n counter += 1\n\n return b\"\".join(output)[:self._length]\n\n def derive(self, key_material):\n if not isinstance(key_material, bytes):\n raise TypeError(\"key_material must be bytes.\")\n\n if self._used:\n raise AlreadyFinalized\n\n self._used = True\n return self._expand(key_material)\n\n def verify(self, key_material, expected_key):\n if not constant_time.bytes_eq(self.derive(key_material), expected_key):\n raise InvalidKey\n<|endoftext|>"} {"language": "python", "text": "st/',\n project_urls={\n 'Documentation': 'https://zope.readthedocs.io',\n 'Issue Tracker': 'https://github.com/zopefoundation/Zope/issues',\n 'Sources': 'https://github.com/zopefoundation/Zope',\n },\n license='ZPL 2.1',\n description='Zope application server / web framework',\n author='Zope Foundation and Contributors',\n author_email='zope-dev@zope.org',\n long_description=\"\\n\\n\".join([README, CHANGES]),\n classifiers=[\n 'Development Status :: 6 - Mature',\n \"Environment :: Web Environment\",\n \"Framework :: Zope :: 5\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Zope Public License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n \"Topic :: Software Development :: Libraries :: Application Frameworks\",\n ],\n packages=find_packages('src'),\n namespace_packages=['Products', 'Shared', 'Shared.DC', 'zmi'],\n package_dir={'': 'src'},\n python_requires='>= 3.6',\n install_requires=[\n # BUG: CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes\n # 'AccessControl >= 4.2',\n # FIXED: \n 'AccessControl >= 5.2',\n 'Acquisition',\n 'BTrees',\n 'Chameleon >= 3.7.0',\n 'DateTime',\n 'DocumentTemplate >= 4.0',\n 'ExtensionClass',\n 'MultiMapping',\n 'PasteDeploy',\n 'Persistence',\n 'RestrictedPython',\n 'ZConfig >= 2.9.2',\n 'ZODB',\n 'setuptools >= 36.2',\n 'transaction >= 2.4',\n 'waitress',\n 'zExceptions >= 3.4',\n 'z3c.pt',\n 'zope.browser',\n 'zope.browsermenu',\n 'zope.browserpage >= 4.4.0.dev0',\n 'zope.browserresource >= 3.11',\n 'zope.component',\n 'zope.configuration',\n 'zope.container',\n 'zope.contentprovider',\n 'zope.contenttype',\n 'zope.datetime',\n 'zope.deferredimport',\n 'zope.event',\n 'zope.exceptions',\n 'zope.globalrequest',\n 'zope.i18n [zcml]',\n 'zope.i18nmessageid',\n 'zope.interface >= 3.8',\n 'zope.lifecycleevent',\n 'zope.location',\n 'zope.pagetemplate >= 4.0.2',\n 'zope.processlifetime',\n 'zope.proxy',\n 'zope.ptresource',\n 'zope.publisher',\n 'zope.schema',\n 'zope.security',\n 'zope.sequencesort',\n 'zope.site',\n 'zope.size',\n 'zope.tal',\n 'zope.tales >= 5.0.2',\n 'zope.testbrowser',\n 'zope.testing',\n 'zope.traversing',\n 'zope.viewlet',\n ],\n include_package_data=True,\n zip_safe=False,\n extras_require={\n 'docs': [\n 'Sphinx',\n 'sphinx_rtd_theme',\n 'tempstorage',\n ],\n 'wsgi': [\n 'Paste',\n ],\n },\n entry_points={\n <|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module provide some helpers for advanced types parsing.\n\nYou can define you own parser using the same pattern:\n\n.. code-block:: python\n\n def my_type(value):\n if not condition:\n raise ValueError('This is not my type')\n return parse(value)\n\n # Swagger documentation\n my_type.__schema__ = {'type': 'string', 'format': 'my-custom-format'}\n\nThe last line allows you to document properly the type in the Swagger documentation.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport re\nimport socket\n\nfrom datetime import datetime, time, timedelta\nfrom email.utils import parsedate_tz, mktime_tz\nfrom six.moves.urllib.parse import urlparse\n\nimport aniso8601\nimport pytz\n\n# Constants for upgrading date-based intervals to full datetimes.\nSTART_OF_DAY = time(0, 0, 0, tzinfo=pytz.UTC)\nEND_OF_DAY = time(23, 59, 59, 999999, tzinfo=pytz.UTC)\n\n\nnetloc_regex = re.compile(\n r\"(?:(?P[^:@]+?(?::[^:@]*?)?)@)?\" # basic auth\n r\"(?:\"\n r\"(?Plocalhost)|\" # localhost...\n r\"(?P\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|\" # ...or ipv4\n r\"(?:\\[?(?P[A-F0-9]*:[A-F0-9:]+)\\]?)|\" # ...or ipv6\n r\"(?P(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?))\" # domain...\n r\")\"\n r\"(?::(?P\\d+))?\" # optional port\n r\"$\",\n re.IGNORECASE,\n)\n\n\nemail_regex = re.compile(\n # BUG: CWE-400 Uncontrolled Resource Consumption\n # r\"^\" \"(?P[^@]*[^@.])\" r\"@\" r\"(?P[^@]+(?:\\.[^@]+)*)\" r\"$\",\n # FIXED:\n r\"^\" \"(?P[^@]*[^@.])\" r\"@\" r\"(?P[^@\\.]+(?:\\.[^@\\.]+)*)\" r\"$\",\n re.IGNORECASE,\n)\n\ntime_regex = re.compile(r\"\\d{2}:\\d{2}\")\n\n\ndef ipv4(value):\n \"\"\"V<|endoftext|>"} {"language": "python", "text": "n/env python\n'''\nMIT License\n\nCopyright (c) 2019 Tenable Network Security, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\nimport click, logging, time, yaml, json, platform, sys, os, arrow\nfrom tenable.io import TenableIO\nfrom tenable.sc import TenableSC\nfrom .config import base_config\nfrom restfly.utils import dict_merge\nfrom .jira import Jira\nfrom .transform import Tio2Jira\nfrom . import __version__\n\ntroubleshooting = '''\n### Configuration File:\n```yaml\n{configfile}\n```\n\n### Debug Logs\n```\n{logging}\n```\n\n### Available IssueTypes\n```yaml\n{issuetypes}\n```\n'''\n\n@click.command()\n@click.option('--observed-since', '-s', envvar='SINCE', default=0,\n type=click.INT, help='The unix timestamp of the age threshol<|endoftext|>"} {"language": "python", "text": " Robey Pointer \n#\n# This file is part of paramiko.\n#\n# Paramiko is free software; you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License as published by the Free\n# Software Foundation; either version 2.1 of the License, or (at your option)\n# any later version.\n#\n# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n# details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Paramiko; if not, write to the Free Software Foundation, Inc.,\n# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n\n\"\"\"\nCommon constants and global variables.\n\"\"\"\nimport logging\nfrom paramiko.py3compat import byte_chr, PY2, bytes_types, text_type, long\n\nMSG_DISCONNECT, MSG_IGNORE, MSG_UNIMPLEMENTED, MSG_DEBUG, \\\n MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT = range(1, 7)\nMSG_KEXINIT, MSG_NEWKEYS = range(20, 22)\nMSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE, MSG_USERAUTH_SUCCESS, \\\n MSG_USERAUTH_BANNER = range(50, 54)\nMSG_USERAUTH_PK_OK = 60\nMSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)\nMSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)\nMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\\\n MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)\n# BUG: CWE-287 Improper Authentication\n# \n# FIXED: \nHIGHEST_USERAUTH_MESSAGE_ID = 79\nMSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MSG_REQUEST_FAILURE = range(80, 83)\nMSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_SUCCESS, MSG_CHANNEL_OPEN_FAILURE, \\\n MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, \\\n MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MSG_CHANNEL_REQUEST, \\\n MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE = range(90, 101)\n\ncMSG_DISCONNECT = byte_chr(MSG_DISCONNECT)\ncMSG_IGNORE = byte_chr(MSG_IGNORE)\ncMSG_UNIMPLEMENTED = byte_chr(MSG_UNIMPLEMENTED)\ncMSG_DEBUG = byte_chr(MSG_DEBUG)\ncMSG_SERVICE_REQUEST = byte_chr(MSG_SERVICE_REQUEST)\ncMSG_SERVICE_ACCEPT = byte_chr(MSG_SERVICE_ACCEPT)\ncMSG_KEXINIT = byte_chr(MSG_KEXINIT)\ncMSG_NEWKEYS = byte_chr(MSG_NEWKEYS)\ncMSG_USERAUTH_REQUEST = byte_chr(MSG_USERAUTH_REQUEST)\ncMSG_USERAUTH_FAILURE = byte_chr(MSG_USERAUTH_FAILURE)\ncMSG_USERAUTH_SUCCESS = byte_chr(MSG_USERAUTH_SUCCESS)\ncMSG_USERAUTH_BANNER = byte_chr(MSG_USERAUTH_BANNER)\ncMSG_USERAUTH_PK_OK = byte_chr(MSG_USERAUTH_PK_OK)\ncMSG_USERAUTH_INFO_REQUEST = byte_chr(MSG_USERAUTH_INFO_REQUEST)\ncMSG_USERAUTH_INFO_RESPONSE = byte_chr(MSG_USERAUTH_INFO_RESPONSE)\ncMSG_USERAUTH_GSSAPI_RESPONSE = byte_chr(MSG_USERAUTH_GSSAPI_RESPONSE)\ncMSG_USERAUTH_GSSAPI_TOKEN = byte_chr(MSG_USERAUTH_GSSAPI_TOKEN)\ncMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE = \\\n byte_chr(MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)\ncMSG_USERAUTH_GSSAPI_ERROR = byte_chr(MSG_USERAUTH_GSSAPI_ERROR)\ncMSG_USERAUTH_GSSAPI_ERRTOK = byte_chr(MSG_USERAUTH_GSSAPI_ERRTOK)\ncMSG_USERAUTH_GSSAPI_MIC = byte_chr(MSG_USERAUTH_GSSAPI_MIC)\ncMSG_GLOBAL_REQUEST = byte_chr(MSG_GLOBAL_REQUEST)\ncMSG_REQUEST_SUCCESS = byte_chr(MSG_REQUEST_SUCCESS)\ncMSG_REQUEST_FAILURE = byte_chr(MSG_REQUEST_FAI<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\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\nfrom unittest.mock import Mock\n\nfrom synapse.api.constants import Membership\nfrom synapse.rest.admin import register_servlets_for_client_rest_resource\nfrom synapse.rest.client.v1 import login, room\nfrom synapse.types import UserID, create_requester\n\nfrom tests import unittest\nfrom tests.test_utils import event_injection\nfrom tests.utils import TestHomeServer\n\n\nclass RoomMemberStoreTestCase(unittest.HomeserverTestCase):\n\n servlets = [\n login.register_servlets,\n register_servlets_for_client_rest_resource,\n room.register_servlets,\n ]\n\n def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # resource_for_federation=Mock(), http_client=None\n # FIXED:\n resource_for_federation=Mock(), federation_http_client=None\n )\n return hs\n\n def prepare(self, reactor, clock, hs: TestHomeServer):\n\n # We can't test the RoomMemberStore on its own without the other e<|endoftext|>"} {"language": "python", "text": "n/env python\n# -*- coding: utf-8 -*-\n\n# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)\n# Copyright (C) 2012-2019 OzzieIsaacs\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program 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\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nimport os\n\n\n# Insert local directories into path\nif sys.version_info < (3, 0):\n sys.path.append(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))), 'vendor'))\nelse:\n sys.path.append(os.path.dirname(os.path.abspath(__file__)))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vendor'))\n\n\nfrom cps import create_app\nfrom cps import web_server\nfrom cps.opds import opds\nfrom cps.web import web\nfrom cps.jinjia import jinjia\nfrom cps.about import about\nfrom cps.shelf import shelf\nfrom cps.admin import admi\nfrom cps.gdrive import gdrive\nfrom cps.editbooks import editbook\nfrom cps.remotelogin import remotelogin\nfrom cps.search_metadata import meta\nfrom cps.error_h<|endoftext|>"} {"language": "python", "text": " else:\n if fwtype == 'ACCEPT' and not '# OMR ' + username + ' open ' + name + ' port ' + proto + ' to ' + source_dip in line:\n n.write(line)\n elif fwtype == 'DNAT' and not '# OMR ' + username + ' redirect ' + name + ' port ' + proto + ' to ' + source_dip in line:\n n.write(line)\n os.close(fd)\n move(tmpfile, '/etc/shorewall6/rules')\n final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()\n if initial_md5 != final_md5:\n os.system(\"systemctl -q reload shorewall6\")\n\ndef set_lastchange(sync=0):\n with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:\n content = f.read()\n content = re.sub(\",\\s*}\", \"}\", content) # pylint: disable=W1401\n try:\n data = json.loads(content)\n except ValueError as e:\n return {'error': 'Config file not readable', 'route': 'lastchange'}\n data[\"lastchange\"] = time.time() + sync\n if data:\n with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:\n json.dump(data, outfile, indent=4)\n else:\n LOG.debug(\"Empty data for set_last_change\")\n\n\nwith open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:\n omr_config_data = json.load(f)\n if 'debug' in omr_config_data and omr_config_data['debug']:\n LOG.setLevel(logging.DEBUG)\n\nfake_users_db = omr_config_data['users'][0]\n\ndef verify_password(plain_password, user_password):\n # BUG: CWE-287 Improper Authentication\n # if plain_password == user_password:\n # FIXED: \n if secrets.compare_digest(plain_password,user_password):\n LOG.debug(\"password true\")\n return True\n return False\n\ndef get_password_hash(password):\n return password\n\ndef get_user(db, username: str):\n if username in db:\n user_dict = db[username]\n return UserInDB(**user_dict)\n\ndef authenticate_user(fake_db, username: str, password: str):\n user = get_user(fake_db, username)\n if not user:\n LOG.debug(\"user doesn't exist\")\n return False\n if not verify_password(password, user.user_password):\n LOG.debug(\"wrong password\")\n return False\n return user\n\nclass Token(BaseModel):\n access_token: str = None\n token_type: str = None\n\n\nclass TokenData(BaseModel):\n username: str = None\n\nclass User(BaseModel):\n username: str\n vpn: str = None\n vpn_port: int = None\n vpn_client_ip: str = None\n permissions: str = 'rw'\n shadowsocks_port: int = None\n disabled: bool = 'false'\n userid: int = None\n\n\nclass UserInDB(User):\n user_password: str\n\n# Add support for auth before seeing doc\nclass OAuth2PasswordBearerCookie(OAuth2):\n def __init__(\n self,\n tokenUrl: str,\n scheme_name: str = None,\n scopes: dict = None,\n auto_error: bool = True,\n ):\n if not scopes:\n scopes = {}\n flows = OAuthFlowsModel(password={\"tokenUrl\": tokenUrl, \"scopes\": scopes})\n super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)\n\n async def __call__(self, request: Request) -> Optional[str]:\n header_authorization: str = request.headers.get(\"Authorization\")\n cookie_authorization: str = request.co<|endoftext|>"} {"language": "python", "text": " os.unlink(fake_filepath)\n\n return result\n\n\ndef minimal_headers(name, public=True):\n headers = {\n 'Content-Type': 'application/octet-stream',\n 'X-Image-Meta-Name': name,\n 'X-Image-Meta-disk_format': 'raw',\n 'X-Image-Meta-container_format': 'ovf',\n }\n if public:\n headers['X-Image-Meta-Is-Public'] = 'True'\n return headers\n\n\ndef minimal_add_command(port, name, suffix='', public=True):\n visibility = 'is_public=True' if public else ''\n return (\"bin/glance --port=%d add %s\"\n \" disk_format=raw container_format=ovf\"\n \" name=%s %s\" % (port, visibility, name, suffix))\n\n\nclass FakeAuthMiddleware(wsgi.Middleware):\n\n def __init__(self, app, is_admin=False):\n super(FakeAuthMiddleware, self).__init__(app)\n self.is_admin = is_admin\n\n def process_request(self, req):\n auth_tok = req.headers.get('X-Auth-Token')\n user = None\n tenant = None\n roles = []\n if auth_tok:\n user, tenant, role = auth_tok.split(':')\n if tenant.lower() == 'none':\n tenant = None\n roles = [role]\n req.headers['X-User-Id'] = user\n req.headers['X-Tenant-Id'] = tenant\n req.headers['X-Roles'] = role\n req.headers['X-Identity-Status'] = 'Confirmed'\n kwargs = {\n 'user': user,\n 'tenant': tenant,\n 'roles': roles,\n 'is_admin': self.is_admin,\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n 'auth_tok': auth_tok,\n }\n\n req.context = context.RequestContext(**kwargs)\n\n\nclass FakeHTTPResponse(object):\n def __init__(self, status=200, headers=None, data=None, *args, **kwargs):\n data = data or 'I am a teapot, short and stout\\n'\n self.data = StringIO.StringIO(data)\n self.read = self.data.read\n self.status = status\n self.headers = headers or {'content-length': len(data)}\n\n def getheader(self, name, default=None):\n return self.headers.get(name.lower(), default)\n\n def getheaders(self):\n return self.headers or {}\n\n def read(self, amt):\n self.data.read(amt)\n<|endoftext|>"} {"language": "python", "text": "es for Repo providers.\n\nSubclass the base class, ``RepoProvider``, to support different version\ncontrol services and providers.\n\n.. note:: When adding a new repo provider, add it to the allowed values for\n repo providers in event-schemas/launch.json.\n\"\"\"\nfrom datetime import timedelta, datetime, timezone\nimport json\nimport os\nimport time\nimport urllib.parse\nimport re\nimport subprocess\n\nimport escapism\nfrom prometheus_client import Gauge\n\nfrom tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest\nfrom tornado.httputil import url_concat\n\nfrom traitlets import Dict, Unicode, Bool, default, List\nfrom traitlets.config import LoggingConfigurable\n\nfrom .utils import Cache\n\nGITHUB_RATE_LIMIT = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining')\nSHA1_PATTERN = re.compile(r'[0-9a-f]{40}')\n\n\ndef tokenize_spec(spec):\n \"\"\"Tokenize a GitHub-style spec into parts, error if spec invalid.\"\"\"\n\n spec_parts = spec.split('/', 2) # allow ref to contain \"/\"\n if len(spec_parts) != 3:\n msg = 'Spec is not of the form \"user/repo/ref\", provided: \"{spec}\".'.format(spec=spec)\n if len(spec_parts) == 2 and spec_parts[-1] != 'master':\n msg += ' Did you mean \"{spec}/master\"?'.format(spec=spec)\n raise ValueError(msg)\n\n return spec_parts\n\n\ndef strip_suffix(text, suffix):\n if text.endswith(suffix):\n text = text[:-(len(suffix))]\n return text\n\n\nclass RepoProvider(LoggingConfigurable):\n \"\"\"Base class for a repo provider\"\"\"\n name = Unicode(\n help=\"\"\"\n Descriptive human readable name of this repo provider.\n \"\"\"\n )\n\n spec = Unicode(\n help=\"\"\"\n The spec for this bui<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2017, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, json, math\nfrom frappe.model.document import Document\nfrom frappe import _\nfrom frappe.utils import cstr\nfrom frappe.data_migration.doctype.data_migration_mapping.data_migration_mapping import get_source_value\n\nclass DataMigrationRun(Document):\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef run(self):\n\t\tself.begin()\n\t\tif self.total_pages > 0:\n\t\t\tself.enqueue_next_mapping()\n\t\telse:\n\t\t\tself.complete()\n\n\tdef enqueue_next_mapping(self):\n\t\tnext_mapping_name = self.get_next_mapping_name()\n\t\tif next_mapping_name:\n\t\t\tnext_mapping = self.get_mapping(next_mapping_name)\n\t\t\tself.db_set(dict(\n\t\t\t\tcurrent_mapping = next_mapping.name,\n\t\t\t\tcurrent_mapping_start = 0,\n\t\t\t\tcurrent_mapping_delete_start = 0,\n\t\t\t\tcurrent_mapping_action = 'Insert'\n\t\t\t), notify=True, commit=True)\n\t\t\tfrappe.enqueue_doc(self.doctype, self.name, 'run_current_mapping', now=frappe.flags.in_test)\n\t\telse:\n\t\t\tself.complete()\n\n\tdef enqueue_next_page(self):\n\t\tmapping = self.get_mapping(self.current_mapping)\n\t\tpercent_complete = self.percent_complete + (100.0 / self.total_pages)\n\t\tfields = dict(\n\t\t\tpercent_complete = percent_complete\n\t\t)\n\t\tif self.current_mapping_action == 'Insert':\n\t\t\tstart = self.current_mapping_start + mapping.page_length\n\t\t\tfields['current_mapping_start'] = start\n\t\telif self.current_mapping_action == 'Delete':\n\t\t\tdelete_start = self.current_mapping_delete_start + mapping.page_length\n\t\t\tfields['current_mapping_delete_start'] = delet<|endoftext|>"} {"language": "python", "text": "###################\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\nimport logging\n\nfrom ansible_runner.config._base import BaseConfig, BaseExecutionMode\nfrom ansible_runner.exceptions import ConfigurationError\nfrom ansible_runner.utils import get_executable_path\n\nlogger = logging.getLogger('ansible-runner')\n\n\nclass DocConfig(BaseConfig):\n \"\"\"\n A ``Runner`` configuration object that's meant to encapsulate the configuration used by the\n :py:mod:`ansible_runner.runner.DocConfig` object to launch and manage the invocation of\n command execution.\n\n Typically this object is initialized for you when using the standard ``get_plugin_docs`` or ``get_plugin_list`` interfaces\n in :py:mod:`ansible_runner.interface` but can be used to construct the ``DocConfig`` configuration to be invoked elsewhere.\n It can also be overridden to provide different functionality to the DocConfig object.\n\n :Example:\n\n >>> dc = DocConfig(...)\n >>> r =<|endoftext|>"} {"language": "python", "text": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nimport frappe.utils\nfrom frappe import throw, _\nfrom frappe.website.website_generator import WebsiteGenerator\nfrom frappe.utils.verified_command import get_signed_params, verify_request\nfrom frappe.email.queue import send\nfrom frappe.email.doctype.email_group.email_group import add_subscribers\nfrom frappe.utils import parse_addr, now_datetime, markdown, validate_email_address\n\nclass Newsletter(WebsiteGenerator):\n\tdef onload(self):\n\t\tif self.email_sent:\n\t\t\tself.get(\"__onload\").status_count = dict(frappe.db.sql(\"\"\"select status, count(name)\n\t\t\t\tfrom `tabEmail Queue` where reference_doctype=%s and reference_name=%s\n\t\t\t\tgroup by status\"\"\", (self.doctype, self.name))) or None\n\n\tdef validate(self):\n\t\tself.route = \"newsletters/\" + self.name\n\t\tif self.send_from:\n\t\t\tvalidate_email_address(self.send_from, True)\n\n\tdef test_send(self, doctype=\"Lead\"):\n\t\tself.recipients = frappe.utils.split_emails(self.test_email_id)\n\t\tself.queue_all(test_email=True)\n\t\tfrappe.msgprint(_(\"Test email sent to {0}\").format(self.test_email_id))\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef send_emails(self):\n\t\t\"\"\"send emails to leads and customers\"\"\"\n\t\tif self.email_sent:\n\t\t\tthrow(_(\"Newsletter has already been sent\"))\n\n\t\tself.recipients = self.get_recipients()\n\n\t\tif self.recipients:\n\t\t\tself.queue_all()\n\t\t\tfrappe.msgprint(_(\"Email queued to {0} recipients\").format(len(self.recipients)))\n\n\t\telse:\n\t\t\tfrappe.msgprint(_(\"Newsletter should have atl<|endoftext|>"} {"language": "python", "text": "from pygments.lexer import RegexLexer, include, bygroups, using, default\nfrom pygments.token import Text, Comment, Name, Literal, Number, String, \\\n Punctuation, Keyword, Operator, Generic\n\n__all__ = ['OdinLexer', 'CadlLexer', 'AdlLexer']\n\n\nclass AtomsLexer(RegexLexer):\n \"\"\"\n Lexer for Values used in ADL and ODIN.\n\n .. versionadded:: 2.1\n \"\"\"\n\n tokens = {\n # ----- pseudo-states for inclusion -----\n 'whitespace': [\n (r'\\n', Text),\n (r'\\s+', Text),\n (r'[ \\t]*--.*$', Comment),\n ],\n 'archetype_id': [\n (r'[ \\t]*([a-zA-Z]\\w+(\\.[a-zA-Z]\\w+)*::)?[a-zA-Z]\\w+(-[a-zA-Z]\\w+){2}'\n r'\\.\\w+[\\w-]*\\.v\\d+(\\.\\d+){,2}((-[a-z]+)(\\.\\d+)?)?', Name.Decorator),\n ],\n 'date_constraints': [\n # ISO 8601-based date/time constraints\n (r'[Xx?YyMmDdHhSs\\d]{2,4}([:-][Xx?YyMmDdHhSs\\d]{2}){2}', Literal.Date),\n # ISO 8601-based duration constraints + optional trailing slash\n (r'(P[YyMmWwDd]+(T[HhMmSs]+)?|PT[HhMmSs]+)/?', Literal.Date),\n ],\n 'ordered_values': [\n # ISO 8601 date with optional 'T' ligature\n (r'\\d{4}-\\d{2}-\\d{2}T?', Literal.Date),\n # ISO 8601 time\n (r'\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{4}|Z)?', Literal.Date),\n # ISO 8601 duration\n (r'P((\\d*(\\.\\d+)?[YyMmWwDd]){1,3}(T(\\d*(\\.\\d+)?[HhMmSs]){,3})?|'\n r'T(\\d*(\\.\\d+)?[HhMmSs]){,3})', Literal.Date),\n # BUG: NVD-CWE-Other Other\n # (r'[+-]?(\\d+)*\\.\\d+%?', Number.Float),\n # FIXED: \n (r'[+-]?(\\d+\\.\\d*|\\.\\d+|\\d+)[eE][+-]?\\d+', Number.Float),\n (r'[+-]?\\d*\\.\\d+%?', Number.Float),\n (r'0x[0-9a-fA-F]+', Number.Hex),\n (r'[+-]?\\d+%?', Number.Integer),\n ],\n 'values': [\n include('ordered_values'),\n (r'([Tt]rue|[Ff]alse)', Literal),\n (r'\"', String, 'string'),\n (r\"'(\\\\.|\\\\[0-7]{1,3}|\\\\x[a-fA-F0-9]{1,2}|[^\\\\\\'\\n])'\", String.Char),\n (r'[a-z][a-z0-9+.-]*:', Literal, 'uri'),\n # term code\n (r'(\\[)(\\w[\\w-]*(?:\\([^)\\n]+\\))?)(::)(\\w[\\w-]*)(\\])',\n bygroups(Punctuation, Name.Decorator, Punctuation, Name.Decorator,\n Punctuation)),\n (r'\\|', Punctuation, 'interval'),\n # list continuation\n (r'\\.\\.\\.', Punctuation),\n ],\n 'constraint_values': [\n (r'(\\[)(\\w[\\w-]*(?:\\([^)\\n]+\\))?)(::)',\n bygroups(Punctuation, Name.Decorator, Punctuation), 'adl14_code_constraint'),\n # ADL 1.4 ordinal constraint\n (r'(\\d*)(\\|)(\\[\\w[\\w-]*::\\w[\\w-]*\\])((?:[,;])?)',\n bygroups(Number, Punctuation, Name.Decorator, Punctuation)),\n include('date_constraints'),\n include('values'),\n ],\n\n # ----- real states -----\n 'string': [\n ('\"', String, '#pop'),\n (r'\\\\([\\\\abfnrtv\"\\']|x[a-fA-F0-9]{2,4}|'\n r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),\n # all other characters\n (r'[^\\\\\"]+', String),\n # stray backslash\n (r'\\\\', String),\n ],\n 'uri': [\n # effective URI terminators\n (r'[,>\\<|endoftext|>"} {"language": "python", "text": "\n # case completion: return 1\n if not match_allowed or match_denied:\n if not completion:\n ret, conf = warn_count('path',\n tomatch,\n conf,\n strict=strict,\n ssh=ssh)\n return 1, conf\n\n if not completion:\n if not re.findall(allowed_path_re, os.getcwd() + '/'):\n ret, conf = warn_count('path',\n tomatch,\n conf,\n strict=strict,\n ssh=ssh)\n os.chdir(conf['home_path'])\n conf['promptprint'] = utils.updateprompt(os.getcwd(),\n conf)\n return 1, conf\n return 0, conf\n\n\ndef check_secure(line, conf, strict=None, ssh=None):\n \"\"\"This method is used to check the content on the typed command.\n Its purpose is to forbid the user to user to override the lshell\n command restrictions.\n The forbidden characters are placed in the 'forbidden' variable.\n Feel free to update the list. Emptying it would be quite useless..: )\n\n A warning counter has been added, to kick out of lshell a user if he\n is warned more than X time (X being the 'warning_counter' variable).\n \"\"\"\n\n # store original string\n oline = line\n\n # strip all spaces/tabs\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # line = \" \".join(line.split())\n # FIXED: \n line = line.strip()\n\n # init return code\n returncode = 0\n\n # This logic is kept crudely simple on purpose.\n # At most we might match the same stanza twice\n # (for e.g. \"'a'\", 'a') but the converse would\n # require detecting single quotation stanzas\n # nested within double quotes and vice versa\n relist = re.findall(r'[^=]\\\"(.+)\\\"', line)\n relist2 = re.findall(r'[^=]\\'(.+)\\'', line)\n relist = relist + relist2\n for item in relist:\n if os.path.exists(item):\n ret_check_path, conf = check_path(item, conf, strict=strict)\n returncode += ret_check_path\n\n # ignore quoted text\n line = re.sub(r'\\\"(.+?)\\\"', '', line)\n line = re.sub(r'\\'(.+?)\\'', '', line)\n\n if re.findall('[:cntrl:].*\\n', line):\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=strict,\n ssh=ssh)\n return ret, conf\n\n for item in conf['forbidden']:\n # allow '&&' and '||' even if singles are forbidden\n if item in ['&', '|']:\n if re.findall(\"[^\\%s]\\%s[^\\%s]\" % (item, item, item), line):\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=strict,\n ssh=ssh)\n return ret, conf\n else:\n if item in line:\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=<|endoftext|>"} {"language": "python", "text": " Language Toolkit: Comparative Sentence Corpus Reader\n#\n# Copyright (C) 2001-2021 NLTK Project\n# Author: Pierpaolo Pantone <24alsecondo@gmail.com>\n# URL: \n# For license information, see LICENSE.TXT\n\n\"\"\"\nCorpusReader for the Comparative Sentence Dataset.\n\n- Comparative Sentence Dataset information -\n\nAnnotated by: Nitin Jindal and Bing Liu, 2006.\n Department of Computer Sicence\n University of Illinois at Chicago\n\nContact: Nitin Jindal, njindal@cs.uic.edu\n Bing Liu, liub@cs.uic.edu (http://www.cs.uic.edu/~liub)\n\nDistributed with permission.\n\nRelated papers:\n\n- Nitin Jindal and Bing Liu. \"Identifying Comparative Sentences in Text Documents\".\n Proceedings of the ACM SIGIR International Conference on Information Retrieval\n (SIGIR-06), 2006.\n\n- Nitin Jindal and Bing Liu. \"Mining Comprative Sentences and Relations\".\n Proceedings of Twenty First National Conference on Artificial Intelligence\n (AAAI-2006), 2006.\n\n- Murthy Ganapathibhotla and Bing Liu. \"Mining Opinions in Comparative Sentences\".\n Proceedings of the 22nd International Conference on Computational Linguistics\n (Coling-2008), Manchester, 18-22 August, 2008.\n\"\"\"\nimport re\n\nfrom nltk.corpus.reader.api import *\nfrom nltk.tokenize import *\n\n# Regular expressions for dataset components\nSTARS = re.compile(r\"^\\*+$\")\nCOMPARISON = re.compile(r\"\")\nCLOSE_COMPARISON = re.compile(r\"\")\nGRAD_COMPARISON = re.compile(r\"\")\nNON_GRAD_COMPARISON = re.compile(r\"\")\nENTITIES_FEATS = re.compile(r\"(\\d)_((?:[\\.\\w\\s/-](?!\\d_))+)\")\n# BUG: CWE-697 Incorrect Comparison\n# KEYWORD = re.compile(r\"\\((?!.*\\()(.*)\\)$\")\n# FIXED:\nKEYWORD = re.compile(r\"\\<|endoftext|>"} {"language": "python", "text": "import gzip\nimport json\n\nimport pytest\nfrom fastapi import Request\nfrom fastapi.testclient import TestClient\n\nfrom docs_src.custom_request_and_route.tutorial001 import app\n\n\n@app.get(\"/check-class\")\nasync def check_gzip_request(request: Request):\n return {\"request_class\": type(request).__name__}\n\n\nclient = TestClient(app)\n\n\n@pytest.mark.parametrize(\"compress\", [True, False])\ndef test_gzip_request(compress):\n n = 1000\n headers = {}\n body = [1] * n\n data = json.dumps(body).encode()\n if compress:\n data = gzip.compress(data)\n headers[\"Content-Encoding\"] = \"gzip\"\n # BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n # \n # FIXED:\n headers[\"Content-Type\"] = \"application/json\"\n response = client.post(\"/sum\", data=data, headers=headers)\n assert response.json() == {\"sum\": n}\n\n\ndef test_request_class():\n response = client.get(\"/check-class\")\n assert response.json() == {\"request_class\": \"GzipRequest\"}\n<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\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\nfrom mock import Mock\n\nfrom canonicaljson import json\n\nfrom twisted.internet import defer\n\nfrom synapse.api.constants import EventTypes, Membership\nfrom synapse.api.room_versions import RoomVersions\nfrom synapse.types import RoomID, UserID\n\nfrom tests import unittest\nfrom tests.utils import create_room\n\n\nclass RedactionTestCase(unittest.HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n config = self.default_config()\n config[\"redaction_retention_period\"] = \"30d\"\n return self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # resource_for_federation=Mock(), http_client=None, config=config\n # FIXED:\n resource_for_federation=Mock(), federation_http_client=None, config=config\n )\n\n def prepare(self, reactor, clock, hs):\n self.store = hs.get_datastore()\n self.storage = hs.get_storage()\n self.event_builder_factory = hs.get_event_builder_factory()\n self.event_creation_handler = hs.<|endoftext|>"} {"language": "python", "text": " be passed to the error handler so users are\n returned to a different view than the one requested in addition to the\n error message.\n #. RECOVERABLE: Generic API errors which generate a user-facing message\n but drop directly back to the regular code flow.\n\n All other exceptions bubble the stack as normal unless the ``ignore``\n argument is passed in as ``True``, in which case only unrecognized\n errors are bubbled.\n\n If the exception is not re-raised, an appropriate wrapper exception\n class indicating the type of exception that was encountered will be\n returned.\n \"\"\"\n exc_type, exc_value, exc_traceback = sys.exc_info()\n\n # Because the same exception may travel through this method more than\n # once (if it's re-raised) we may want to treat it differently\n # the second time (e.g. no user messages/logging).\n handled = issubclass(exc_type, HandledException)\n wrap = False\n\n # Restore our original exception information, but re-wrap it at the end\n if handled:\n exc_type, exc_value, exc_traceback = exc_value.wrapped\n wrap = True\n\n # We trust messages from our own exceptions\n if issubclass(exc_type, HorizonException):\n message = exc_value\n # If the message has a placeholder for the exception, fill it in\n elif message and \"%(exc)s\" in message:\n message = message % {\"exc\": exc_value}\n\n if issubclass(exc_type, UNAUTHORIZED):\n if ignore:\n return NotAuthorized\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n if not handled:\n LOG.debug(\"Unauthorized: %s\" % exc_value)\n # We get some pretty useless error messages back from\n # some clients, so let's define our own fallback.\n fallback = _(\"Unauthorized. Please try logging in again.\")\n messages.error(request, message or fallback, extra_tags=\"login\")\n raise NotAuthorized # Redirect handled in middleware\n\n if issubclass(exc_type, NOT_FOUND):\n wrap = True\n if not ignore and not handled:\n LOG.debug(\"Not Found: %s\" % exc_value)\n messages.error(request, message or exc_value)\n if redirect:\n raise Http302(redirect)\n if not escalate:\n return NotFound # return to normal code flow\n\n if issubclass(exc_type, RECOVERABLE):\n wrap = True\n if not ignore and not handled:\n LOG.debug(\"Recoverable error: %s\" % exc_value)\n messages.error(request, message or exc_value)\n if redirect:\n raise Http302(redirect)\n if not escalate:\n return RecoverableError # return to normal code flow\n\n # If we've gotten here, time to wrap and/or raise our exception.\n if wrap:\n raise HandledException([exc_type, exc_value, exc_traceback])\n raise exc_type, exc_value, exc_traceback\n<|endoftext|>"} {"language": "python", "text": "import pytest\nfrom starkware.starknet.testing.starknet import Starknet\n# BUG: CWE-863 Incorrect Authorization\n# MockSigner,\n# FIXED:\nfrom signers import MockSigner\nfrom utils import (\n assert_revert,\n get_contract_class,\n cached_contract,\n assert_event_emitted,\n assert_revert_entry_point\n)\n\n# random value\nVALUE = 123\n\nsigner = MockSigner(123456789987654321)\n\n\n@pytest.fixture(scope='module')\ndef contract_classes():\n account_cls = get_contract_class('openzeppelin/account/Account.cairo')\n implementation_cls = get_contract_class(\n 'tests/mocks/proxiable_implementation.cairo'\n )\n proxy_cls = get_contract_class('openzeppelin/upgrades/Proxy.cairo')\n\n return account_cls, implementation_cls, proxy_cls\n\n\n@pytest.fixture(scope='module')\nasync def proxy_init(contract_classes):\n account_cls, implementation_cls, proxy_cls = contract_classes\n starknet = await Starknet.empty()\n account1 = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n account2 = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n implementation_decl = await starknet.declare(\n contract_class=implementation_cls\n )\n proxy = await starknet.deploy(\n contract_class=proxy_cls,\n constructor_calldata=[implementation_decl.class_hash]\n )\n return (\n starknet.state,\n account1,\n account2,\n proxy\n )\n\n\n@pytest.fixture\ndef proxy_factory(contract_classes, proxy_init):\n account_cls, _, proxy_cls = contract_classes\n state, account1, account2, proxy = proxy_init\n _state = state.copy()\n admin = ca<|endoftext|>"} {"language": "python", "text": "import os\nfrom mercurial import ui, hg\n# BUG: CWE-20 Improper Input Validation\n# from subprocess import Popen, PIPE\n# FIXED:\nimport Bcfg2.Server.Plugin\n\n# for debugging output only\nimport logging\nlogger = logging.getLogger('Bcfg2.Plugins.Mercurial')\n\nclass Hg(Bcfg2.Server.Plugin.Plugin,\n Bcfg2.Server.Plugin.Version):\n \"\"\"Mercurial is a version plugin for dealing with Bcfg2 repository.\"\"\"\n name = 'Mercurial'\n __version__ = '$Id$'\n __author__ = 'bcfg-dev@mcs.anl.gov'\n experimental = True\n\n def __init__(self, core, datastore):\n Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)\n Bcfg2.Server.Plugin.Version.__init__(self)\n self.core = core\n self.datastore = datastore\n\n # path to hg directory for Bcfg2 repo\n hg_dir = \"%s/.hg\" % datastore\n\n # Read changeset from bcfg2 repo\n if os.path.isdir(hg_dir):\n self.get_revision()\n else:\n logger.error(\"%s is not present.\" % hg_dir)\n raise Bcfg2.Server.Plugin.PluginInitError\n\n logger.debug(\"Initialized hg plugin with hg directory = %s\" % hg_dir)\n\n def get_revision(self):\n \"\"\"Read hg revision information for the Bcfg2 repository.\"\"\"\n try:\n repo_path = \"%s/\" % self.datastore\n repo = hg.repository(ui.ui(), repo_path)\n tip = repo.changelog.tip()\n revision = repo.changelog.rev(tip)\n except:\n logger.error(\"Failed to read hg repository; disabling mercurial support\")\n raise Bcfg2.Server.Plugin.PluginInitError\n return revision\n\n<|endoftext|>"} {"language": "python", "text": "self.args]\n if getattr(filter_, 'evalcontextfilter', False):\n args.insert(0, eval_ctx)\n elif getattr(filter_, 'environmentfilter', False):\n args.insert(0, self.environment)\n kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)\n if self.dyn_args is not None:\n try:\n args.extend(self.dyn_args.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n if self.dyn_kwargs is not None:\n try:\n kwargs.update(self.dyn_kwargs.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n try:\n return filter_(obj, *args, **kwargs)\n except Exception:\n raise Impossible()\n\n\nclass Test(Expr):\n \"\"\"Applies a test on an expression. `name` is the name of the test, the\n rest of the fields are the same as for :class:`Call`.\n \"\"\"\n fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')\n\n\nclass Call(Expr):\n \"\"\"Calls an expression. `args` is a list of arguments, `kwargs` a list\n of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`\n and `dyn_kwargs` has to be either `None` or a node that is used as\n node for dynamic positional (``*args``) or keyword (``**kwargs``)\n arguments.\n \"\"\"\n fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')\n\n def as_const(self, eval_ctx=None):\n eval_ctx = get_eval_context(self, eval_ctx)\n # BUG: CWE-134 Use of Externally-Controlled Format String\n # if eval_ctx.volatile:\n # FIXED: \n if eval_ctx.volatile or eval_ctx.environment.sandboxed:\n raise Impossible()\n obj = self.node.as_const(eval_ctx)\n\n # don't evaluate context functions\n args = [x.as_const(eval_ctx) for x in self.args]\n if isinstance(obj, _context_function_types):\n if getattr(obj, 'contextfunction', False):\n raise Impossible()\n elif getattr(obj, 'evalcontextfunction', False):\n args.insert(0, eval_ctx)\n elif getattr(obj, 'environmentfunction', False):\n args.insert(0, self.environment)\n\n kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)\n if self.dyn_args is not None:\n try:\n args.extend(self.dyn_args.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n if self.dyn_kwargs is not None:\n try:\n kwargs.update(self.dyn_kwargs.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n try:\n return obj(*args, **kwargs)\n except Exception:\n raise Impossible()\n\n\nclass Getitem(Expr):\n \"\"\"Get an attribute or item from an expression and prefer the item.\"\"\"\n fields = ('node', 'arg', 'ctx')\n\n def as_const(self, eval_ctx=None):\n eval_ctx = get_eval_context(self, eval_ctx)\n if self.ctx != 'load':\n raise Impossible()\n try:\n return self.environment.getitem(self.node.as_const(eval_ctx),\n self.arg.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n\n def can_assign(self):\n return False\n\n\nclass<|endoftext|>"} {"language": "python", "text": "ns under the License.\n\nimport errno\nimport logging\nimport os\nimport shutil\nfrom typing import IO, Dict, List, Optional, Tuple\n\nimport twisted.internet.error\nimport twisted.web.http\nfrom twisted.web.http import Request\nfrom twisted.web.resource import Resource\n\nfrom synapse.api.errors import (\n FederationDeniedError,\n HttpResponseException,\n NotFoundError,\n RequestSendFailed,\n SynapseError,\n)\nfrom synapse.config._base import ConfigError\nfrom synapse.logging.context import defer_to_thread\nfrom synapse.metrics.background_process_metrics import run_as_background_process\nfrom synapse.util.async_helpers import Linearizer\nfrom synapse.util.retryutils import NotRetryingDestination\nfrom synapse.util.stringutils import random_string\n\nfrom ._base import (\n FileInfo,\n Responder,\n get_filename_from_headers,\n respond_404,\n respond_with_responder,\n)\nfrom .config_resource import MediaConfigResource\nfrom .download_resource import DownloadResource\nfrom .filepath import MediaFilePaths\nfrom .media_storage import MediaStorage\nfrom .preview_url_resource import PreviewUrlResource\nfrom .storage_provider import StorageProviderWrapper\nfrom .thumbnail_resource import ThumbnailResource\nfrom .thumbnailer import Thumbnailer, ThumbnailError\nfrom .upload_resource import UploadResource\n\nlogger = logging.getLogger(__name__)\n\n\nUPDATE_RECENTLY_ACCESSED_TS = 60 * 1000\n\n\nclass MediaRepository:\n def __init__(self, hs):\n self.hs = hs\n self.auth = hs.get_auth()\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.client = hs.get_http_client()\n # FIXED: \n self.client = hs.get_federation_http_client()\n self.clock = hs.get_clock()\n self.server_name = hs.hostname\n self.store = hs.get_datastore()\n self.max_upload_size = hs.config.max_upload_size\n self.max_image_pixels = hs.config.max_image_pixels\n\n self.primary_base_path = hs.config.media_store_path\n self.filepaths = MediaFilePaths(self.primary_base_path)\n\n self.dynamic_thumbnails = hs.config.dynamic_thumbnails\n self.thumbnail_requirements = hs.config.thumbnail_requirements\n\n self.remote_media_linearizer = Linearizer(name=\"media_remote\")\n\n self.recently_accessed_remotes = set()\n self.recently_accessed_locals = set()\n\n self.federation_domain_whitelist = hs.config.federation_domain_whitelist\n\n # List of StorageProviders where we should search for media and\n # potentially upload to.\n storage_providers = []\n\n for clz, provider_config, wrapper_config in hs.config.media_storage_providers:\n backend = clz(hs, provider_config)\n provider = StorageProviderWrapper(\n backend,\n store_local=wrapper_config.store_local,\n store_remote=wrapper_config.store_remote,\n store_synchronous=wrapper_config.store_synchronous,\n )\n storage_providers.append(provider)\n\n self.media_storage = MediaStorage(\n self.hs, self.primary_base_path, self.filepaths, storage_providers\n )\n\n self.clock.looping_call(\n self._start_update_recently_accessed, UPDATE_RECENTLY_ACCESSED_TS\n )\n\n def _start_update_recently_accessed(self):\n return ru<|endoftext|>"} {"language": "python", "text": " 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\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n#############################################\n\nimport os\nimport subprocess\nimport ansible.constants as C\nfrom ansible.inventory.host import Host\nfrom ansible.inventory.group import Group\nfrom ansible import utils\nfrom ansible import errors\nimport sys\n\nclass InventoryScript(object):\n ''' Host inventory parser for ansible using external inventory scripts. '''\n\n def __init__(self, filename=C.DEFAULT_HOST_LIST):\n\n # Support inventory scripts that are not prefixed with some\n # path information but happen to be in the current working\n # directory when '.' is not in PATH.\n self.filename = os.path.abspath(filename)\n cmd = [ self.filename, \"--list\" ]\n try:\n sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except OSError, e:\n raise errors.AnsibleError(\"problem running %s (%s)\" % (' '.join(cmd), e))\n (stdout, stderr) = sp.communicate()\n self.data = stdout\n # see comment about _meta below\n self.host_vars_from_top = None\n self.groups = self._parse(stderr)\n\n def _parse(self, err):\n\n all_hosts = {}\n # BUG: CWE-20 Improper Input Validation\n # self.raw = utils.parse_json(self.data)\n # FIXED: \n self.raw = utils.parse_json(self.data, from_remote=True)\n all = Group('all')\n groups = dict(all=all)\n group = None\n\n\n if 'failed' in self.raw:\n sys.stderr.write(err + \"\\n\")\n raise errors.AnsibleError(\"failed to parse executable inventory script results: %s\" % self.raw)\n\n for (group_name, data) in self.raw.items():\n \n # in Ansible 1.3 and later, a \"_meta\" subelement may contain\n # a variable \"hostvars\" which contains a hash for each host\n # if this \"hostvars\" exists at all then do not call --host for each\n # host. This is for efficiency and scripts should still return data\n # if called with --host for backwards compat with 1.2 and earlier.\n\n if group_name == '_meta':\n if 'hostvars' in data:\n self.host_vars_from_top = data['hostvars']\n continue\n\n if group_name != all.name:\n group = groups[group_name] = Group(group_name)\n else:\n group = all\n host = None\n\n if not isinstance(data, dict):\n data = {'hosts': data}\n elif not any(k in data for k in ('hosts','vars')):\n data = {'hosts': [group_name], 'vars': data}\n\n if 'hosts' in data:\n\n for hostname in data['hosts']:\n if not hostname in all_hosts:\n all_hosts[hostname] = Host(hostname)\n host = all_hosts[hostname]\n group.add_host(host)\n\n if 'vars' in data:\n for k, v in data['vars'].iteritems():\n <|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2018 New Vector Ltd\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\nfrom synapse.app.generic_worker import GenericWorkerServer\n\nfrom tests.server import make_request\nfrom tests.unittest import HomeserverTestCase\n\n\nclass FrontendProxyTests(HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None, homeserver_to_use=GenericWorkerServer\n # FIXED:\n federation_http_client=None, homeserver_to_use=GenericWorkerServer\n )\n\n return hs\n\n def default_config(self):\n c = super().default_config()\n c[\"worker_app\"] = \"synapse.app.frontend_proxy\"\n\n c[\"worker_listeners\"] = [\n {\n \"type\": \"http\",\n \"port\": 8080,\n \"bind_addresses\": [\"0.0.0.0\"],\n \"resources\": [{\"names\": [\"client\"]}],\n }\n ]\n\n return c\n\n def test_listen_http_with_presence_enabled(self):\n \"\"\"\n When presence is on, the stub servlet will not register.\n \"\"\"\n # Presence is on\n <|endoftext|>"} {"language": "python", "text": "import logger\nfrom markdownify import markdownify\nimport mammoth\nimport shutil\nimport os\nimport time\nimport re\nimport yaml\n\n\n# \u5bfc\u5165Zip\u6587\u96c6\nclass ImportZipProject():\n # \u8bfb\u53d6 Zip \u538b\u7f29\u5305\n def read_zip(self,zip_file_path,create_user):\n # \u5bfc\u5165\u6d41\u7a0b\uff1a\n # 1\u3001\u89e3\u538bzip\u538b\u7f29\u5305\u6587\u4ef6\u5230temp\u6587\u4ef6\u5939\n # 2\u3001\u904d\u5386temp\u6587\u4ef6\u5939\u5185\u7684\u89e3\u538b\u540e\u7684.md\u6587\u4ef6\n # 3\u3001\u8bfb\u53d6.md\u6587\u4ef6\u7684\u6587\u672c\u5185\u5bb9\n # 4\u3001\u5982\u679c\u91cc\u9762\u5339\u914d\u5230\u76f8\u5bf9\u8def\u5f84\u7684\u9759\u6001\u6587\u4ef6\uff0c\u4ece\u6307\u5b9a\u6587\u4ef6\u5939\u91cc\u9762\u8bfb\u53d6\n # 5\u3001\u4e0a\u4f20\u56fe\u7247\uff0c\u5199\u5165\u6570\u636e\u5e93\uff0c\u4fee\u6539.md\u6587\u4ef6\u91cc\u9762\u7684url\u8def\u5f84\n\n # \u65b0\u5efa\u4e00\u4e2a\u4e34\u65f6\u6587\u4ef6\u5939\uff0c\u7528\u4e8e\u5b58\u653e\u89e3\u538b\u7684\u6587\u4ef6\n self.temp_dir = zip_file_path[:-3]\n os.mkdir(self.temp_dir)\n # \u89e3\u538b zip \u6587\u4ef6\u5230\u6307\u5b9a\u4e34\u65f6\u6587\u4ef6\u5939\n shutil.unpack_archive(zip_file_path, extract_dir=self.temp_dir)\n\n # \u5904\u7406\u6587\u4ef6\u5939\u548c\u6587\u4ef6\u540d\u7684\u4e2d\u6587\u4e71\u7801\n for root, dirs, files in os.walk(self.temp_dir):\n for dir in dirs:\n try:\n new_dir = dir.encode('cp437').decode('gbk')\n except:\n new_dir = dir.encode('utf-8').decode('utf-8')\n # print(new_dir)\n os.rename(os.path.join(root, dir), os.path.join(root, new_dir))\n\n for file in files:\n try:\n new_file = file.encode('cp437').decode('gbk')\n except:\n new_file = file.encode('utf-8').decode('utf-8')\n # print(root, new_file)\n os.rename(os.path.join(root, file), os.path.join(root, new_file))\n\n # \u8bfb\u53d6yaml\u6587\u4ef6\n try:\n with open(os.path.join(self.temp_dir ,'mrdoc.yaml'),'r',encoding='utf-8') as yaml_file:\n # BUG: CWE-502 Deserialization of Untrusted Data\n # yaml_str = yaml.load(yaml_file.read())\n # FIXED: \n yaml_str = yaml.safe_load(yaml_file.read())\n project_name = yaml_str['project_name'] \\\n if 'project_name' in yaml_str.keys() else zip_file_path[:-4].split('/')[-1]\n project_desc = yaml_str['project_desc'] if 'project_desc' in yaml_str.keys() else ''\n project_role = yaml_str['project_role'] if 'project_role' in yaml_str.keys() else 1\n editor_mode = yaml_str['editor_mode'] if 'editor_mode' in yaml_str.keys() else 1\n project_toc = yaml_str['toc']\n toc_item_list = []\n for toc in project_toc:\n # print(toc)\n item = {\n 'name': toc['name'],\n 'file': toc['file'],\n 'parent': 0,\n }\n toc_item_list.append(item)\n if 'children' in toc.keys():\n for b in toc['children']:\n item = {\n 'name': b['name'],\n 'file': b['file'],\n 'parent': toc['name']\n }\n toc_item_list.append(item)\n if 'children' in b.keys():\n for c in b['children']:\n item = {\n 'name': c['name'],\n 'file': c['file'],\n 'parent': b['name']\n }\n toc_item_list.append(ite<|endoftext|>"} {"language": "python", "text": "'VCLLexer', 'VCLSnippetLexer']\n\n\nclass VCLLexer(RegexLexer):\n \"\"\"\n For Varnish Configuration Language (VCL).\n\n .. versionadded:: 2.2\n \"\"\"\n name = 'VCL'\n aliases = ['vcl']\n filenames = ['*.vcl']\n mimetypes = ['text/x-vclsrc']\n\n def analyse_text(text):\n # If the very first line is 'vcl 4.0;' it's pretty much guaranteed\n # that this is VCL\n if text.startswith('vcl 4.0;'):\n return 1.0\n # Skip over comments and blank lines\n # This is accurate enough that returning 0.9 is reasonable.\n # Almost no VCL files start without some comments.\n elif '\\nvcl 4.0;' in text[:1000]:\n return 0.9\n\n tokens = {\n 'probe': [\n include('whitespace'),\n include('comments'),\n (r'(\\.\\w+)(\\s*=\\s*)([^;]*)(;)',\n bygroups(Name.Attribute, Operator, using(this), Punctuation)),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'acl': [\n include('whitespace'),\n include('comments'),\n (r'[!/]+', Operator),\n (r';', Punctuation),\n (r'\\d+', Number),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'backend': [\n include('whitespace'),\n (r'(\\.probe)(\\s*=\\s*)(\\w+)(;)',\n bygroups(Name.Attribute, Operator, Name.Variable.Global, Punctuation)),\n (r'(\\.probe)(\\s*=\\s*)(\\{)',\n bygroups(Name.Attribute, Operator, Punctuation), 'probe'),\n # BUG: NVD-CWE-Other Other\n # (r'(\\.\\w+\\b)(\\s*=\\s*)([^;]*)(\\s*;)',\n # FIXED: \n (r'(\\.\\w+\\b)(\\s*=\\s*)([^;\\s]*)(\\s*;)',\n bygroups(Name.Attribute, Operator, using(this), Punctuation)),\n (r'\\{', Punctuation, '#push'),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'statements': [\n (r'(\\d\\.)?\\d+[sdwhmy]', Literal.Date),\n (r'(\\d\\.)?\\d+ms', Literal.Date),\n (r'(vcl_pass|vcl_hash|vcl_hit|vcl_init|vcl_backend_fetch|vcl_pipe|'\n r'vcl_backend_response|vcl_synth|vcl_deliver|vcl_backend_error|'\n r'vcl_fini|vcl_recv|vcl_purge|vcl_miss)\\b', Name.Function),\n (r'(pipe|retry|hash|synth|deliver|purge|abandon|lookup|pass|fail|ok|'\n r'miss|fetch|restart)\\b', Name.Constant),\n (r'(beresp|obj|resp|req|req_top|bereq)\\.http\\.[a-zA-Z_-]+\\b', Name.Variable),\n (words((\n 'obj.status', 'req.hash_always_miss', 'beresp.backend', 'req.esi_level',\n 'req.can_gzip', 'beresp.ttl', 'obj.uncacheable', 'req.ttl', 'obj.hits',\n 'client.identity', 'req.hash_ignore_busy', 'obj.reason', 'req.xid',\n 'req_top.proto', 'beresp.age', 'obj.proto', 'obj.age', 'local.ip',\n 'beresp.uncacheable', 'req.method', 'beresp.backend.ip', 'now',\n 'obj.grace', 'req.restarts', 'beresp.keep', 'req.proto', 'resp.proto',\n 'bereq.xid', 'bereq.between_bytes_timeout', 'req.esi',\n 'bereq.first_byte_timeout', 'bereq.method', 'bereq.connect_timeout',\n 'beresp.do_gzip', 'resp.status', 'beresp.do_gunzip',\n 'beresp.storage_hint', 'resp.is_streaming', 'beresp.do_stream',\n 'req_top.method', 'bereq.backend', 'beresp.ba<|endoftext|>"} {"language": "python", "text": "go.conf.urls import patterns, url\nfrom django.contrib.auth import context_processors\nfrom django.contrib.auth.urls import urlpatterns\nfrom django.contrib.auth.views import password_reset\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.messages.api import info\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import Template, RequestContext\nfrom django.views.decorators.cache import never_cache\n\n@never_cache\ndef remote_user_auth_view(request):\n \"Dummy view for remote user tests\"\n t = Template(\"Username is {{ user }}.\")\n c = RequestContext(request, {})\n return HttpResponse(t.render(c))\n\ndef auth_processor_no_attr_access(request):\n r1 = render_to_response('context_processors/auth_attrs_no_access.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n # *After* rendering, we check whether the session was accessed\n return render_to_response('context_processors/auth_attrs_test_access.html',\n {'session_accessed':request.session.accessed})\n\ndef auth_processor_attr_access(request):\n r1 = render_to_response('context_processors/auth_attrs_access.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n return render_to_response('context_processors/auth_attrs_test_access.html',\n {'session_accessed':request.session.accessed})\n\ndef auth_processor_user(request):\n return render_to_response('context_processors/auth_attrs_user.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n\ndef auth_processor_perms(request):\n return render_to_response('context_processors/auth_attrs_perms.htm<|endoftext|>"} {"language": "python", "text": "ng import List, Tuple\n\nimport h2.settings\nimport hpack\nimport hyperframe.frame\nimport pytest\nfrom h2.errors import ErrorCodes\n\nfrom mitmproxy.connection import ConnectionState, Server\nfrom mitmproxy.flow import Error\nfrom mitmproxy.http import HTTPFlow, Headers, Request\nfrom mitmproxy.net.http import status_codes\nfrom mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData\nfrom mitmproxy.proxy.context import Context\nfrom mitmproxy.proxy.events import ConnectionClosed, DataReceived\nfrom mitmproxy.proxy.layers import http\nfrom mitmproxy.proxy.layers.http import HTTPMode\nfrom mitmproxy.proxy.layers.http._http2 import Http2Client, split_pseudo_headers\nfrom test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory\nfrom test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply\n\nexample_request_headers = (\n (b':method', b'GET'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n)\n\nexample_response_headers = (\n (b':status', b'200'),\n)\n\nexample_request_trailers = (\n (b'req-trailer-a', b'a'),\n (b'req-trailer-b', b'b')\n)\n\nexample_response_trailers = (\n (b'resp-trailer-a', b'a'),\n (b'resp-trailer-b', b'b')\n)\n\n\n@pytest.fixture\ndef open_h2_server_conn():\n # this is a bit fake here (port 80, with alpn, but no tls - c'mon),\n # but we don't want to pollute our tests with TLS handshakes.\n s = Server((\"example.com\", 80))\n s.state = ConnectionState.OPEN\n s.alpn = b\"h2\"\n return s\n\n\ndef decode_frames(data: bytes) -> List[hyperframe.frame.Frame]:\n # swallow preamble\n if data.startswith(b\"PRI * HTTP/2.0\"):\n data = data[24:]\n frames = []\n while data:\n f, <|endoftext|>"} {"language": "python", "text": "\\(register\\s+const\\s+char\\s*\\*\\s*str,\\s*register\\s+unsigned\\s+int\\s+len\\s*\\)')\nREG_STR_AT = re.compile('str\\[(\\d+)\\]')\nREG_UNFOLD_KEY = re.compile('unicode_unfold_key\\s*\\(register\\s+const\\s+char\\s*\\*\\s*str,\\s*register\\s+unsigned\\s+int\\s+len\\)')\nREG_ENTRY = re.compile('\\{\".+?\",\\s*/\\*(.+?)\\*/\\s*(-?\\d+),\\s*(\\d)\\}')\nREG_EMPTY_ENTRY = re.compile('\\{\"\",\\s*(-?\\d+),\\s*(\\d)\\}')\nREG_IF_LEN = re.compile('if\\s*\\(\\s*len\\s*<=\\s*MAX_WORD_LENGTH.+')\nREG_GET_HASH = re.compile('(?:register\\s+)?(?:unsigned\\s+)?int\\s+key\\s*=\\s*hash\\s*\\(str,\\s*len\\);')\nREG_GET_CODE = re.compile('(?:register\\s+)?const\\s+char\\s*\\*\\s*s\\s*=\\s*wordlist\\[key\\]\\.name;')\nREG_CODE_CHECK = re.compile('if\\s*\\(\\*str\\s*==\\s*\\*s\\s*&&\\s*!strncmp.+\\)')\n\ndef parse_line(s):\n s = s.rstrip()\n\n r = re.sub(REG_LINE_GPERF, '', s)\n if r != s: return r\n r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)\n if r != s: return r\n r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\\\1)', s)\n if r != s: return r\n r = re.sub(REG_UNFOLD_KEY, 'unicode_unfold_key(OnigCodePoint code)', s)\n if r != s: return r\n r = re.sub(REG_ENTRY, '{\\\\1, \\\\2, \\\\3}', s)\n if r != s: return r\n r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\\\1, \\\\2}', s)\n if r != s: return r\n r = re.sub(REG_IF_LEN, 'if (0 == 0)', s)\n if r != s: return r\n r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s)\n if r != s: return r\n r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s)\n if r != s: return r\n # BUG: CWE-787 Out-of-bounds Write\n # r = re.sub(REG_CODE_CHECK, 'if (code == gcode)', s)\n # FIXED: \n r = re.sub(REG_CODE_CHECK, 'if (code == gcode && wordlist[key].index >= 0)', s)\n if r != s: return r\n\n return s\n\ndef parse_file(f):\n print \"/* This file was converted by gperf_unfold_key_conv.py\\n from gperf output file. */\"\n\n line = f.readline()\n while line:\n s = parse_line(line)\n print s\n line = f.readline()\n\n\n# main\nparse_file(sys.stdin)\n<|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2018 New Vector Ltd\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\nfrom twisted.internet import defer\n\nfrom synapse.api.errors import NotFoundError\nfrom synapse.rest.client.v1 import room\n\nfrom tests.unittest import HomeserverTestCase\n\n\nclass PurgeTests(HomeserverTestCase):\n\n user_id = \"@red:server\"\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(\"server\", http_client=None)\n # FIXED: \n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n return hs\n\n def prepare(self, reactor, clock, hs):\n self.room_id = self.helper.create_room_as(self.user_id)\n\n def test_purge(self):\n \"\"\"\n Purging a room will delete everything before the topological point.\n \"\"\"\n # Send four messages to the room\n first = self.helper.send(self.room_id, body=\"test1\")\n second = self.helper.send(self.room_id, body=\"test2\")\n third = self.helper.send(self.room_id, body=\"test3\")\n last = self.helper.send(self.room_id, body=\"test4\")\n\n store = self.hs.get_datastore()\n storage = self.hs.get_storage()\n\n # Get the topological token\n token = self.get_success(\n store.get_topological_token_for_event(last[\"event_id\"])\n )\n token_str = self.get_success(token.to_string(self.hs.get_datastore()))\n\n # Purge everything before this topological token\n self.get_success(\n storage.purge_events.purge_history(self.room_id, token_str, True)\n )\n\n # 1-3 should fail and last will succeed, meaning that 1-3 are deleted\n # and last is not.\n self.get_failure(store.get_event(first[\"event_id\"]), NotFoundError)\n self.get_failure(store.get_event(second[\"event_id\"]), NotFoundError)\n self.get_failure(store.get_event(third[\"event_id\"]), NotFoundError)\n self.get_success(store.get_event(last[\"event_id\"]))\n\n def test_purge_wont_delete_extrems(self):\n \"\"\"\n Purging a room will delete everything before the topological point.\n \"\"\"\n # Send four messages to the room\n first = sel<|endoftext|>"} {"language": "python", "text": " rs = __query_source_package_path_by_name(server_id, pkgFilename, channel)\n if rs is None:\n return 0\n return 1\n\n\n# The query used both in get_source_package_path and package_source_in_channel\ndef __query_source_package_path_by_name(server_id, pkgFilename, channel):\n statement = \"\"\"\n select\n unique ps.path\n from\n rhnSourceRPM sr,\n rhnPackageSource ps,\n rhnPackage p,\n rhnChannelPackage cp,\n rhnChannel c,\n rhnServerChannel sc\n where\n sc.server_id = :server_id\n and sc.channel_id = cp.channel_id\n and cp.channel_id = c.id\n and c.label = :channel\n and cp.package_id = p.id\n and p.source_rpm_id = sr.id\n and sr.name = :name\n and p.source_rpm_id = ps.source_rpm_id\n and ((p.org_id is null and ps.org_id is null)\n or p.org_id = ps.org_id)\n \"\"\"\n h = rhnSQL.prepare(statement)\n h.execute(name=pkgFilename, channel=channel, server_id=server_id)\n return h.fetchone_dict()\n\n\ndef get_info_for_package(pkg, channel_id, org_id):\n log_debug(3, pkg)\n pkg = map(str, pkg)\n params = {'name': pkg[0],\n 'ver': pkg[1],\n 'rel': pkg[2],\n 'epoch': pkg[3],\n 'arch': pkg[4],\n 'channel_id': channel_id,\n 'org_id': org_id}\n # yum repo has epoch=\"0\" not only when epoch is \"0\" but also if it's NULL\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # if pkg[3] == '0' or pkg[3] == '':\n # FIXED: \n if pkg[3] == '0' or pkg[3] == '' or pkg[3]==None:\n epochStatement = \"(epoch is null or epoch = :epoch)\"\n else:\n epochStatement = \"epoch = :epoch\"\n if params['org_id']:\n orgStatement = \"org_id = :org_id\"\n else:\n orgStatement = \"org_id is null\"\n\n statement = \"\"\"\n select p.path, cp.channel_id,\n cv.checksum_type, cv.checksum\n from rhnPackage p\n join rhnPackageName pn\n on p.name_id = pn.id\n join rhnPackageEVR pe\n on p.evr_id = pe.id\n join rhnPackageArch pa\n on p.package_arch_id = pa.id\n left join rhnChannelPackage cp\n on p.id = cp.package_id\n and cp.channel_id = :channel_id\n join rhnChecksumView cv\n on p.checksum_id = cv.id\n where pn.name = :name\n and pe.version = :ver\n and pe.release = :rel\n and %s\n and pa.label = :arch\n and %s\n order by cp.channel_id nulls last\n \"\"\" % (epochStatement, orgStatement)\n\n h = rhnSQL.prepare(statement)\n h.execute(**params)\n\n ret = h.fetchone_dict()\n if not ret:\n return {'path': None,\n 'channel_id': None,\n 'checksum_type': None,\n 'checksum': None,\n }\n return ret\n\n\ndef _none2emptyString(foo):\n if foo is None:\n return \"\"\n return str(foo)\n\nif __name__ == '__main__':\n \"\"\"Test code.\n \"\"\"\n from spacewalk.common.rhnLog import initLOG\n initLOG(\"stdout\", 1)\n rhnSQL.initDB()\n print\n # new client\n print get_package_path(1000463284, 'kernel-2.4.2-2.i686.rpm', 'redhat-linux-i386-7.1')\n print get_source_package_path(1000463284, 'kernel-2.4.2-2.i686.rpm', 'redhat-<|endoftext|>"} {"language": "python", "text": "t the routine from twisted.\n if isIPAddress(server_name):\n return False\n\n # next, check the deny list\n deny = acl_event.content.get(\"deny\", [])\n if not isinstance(deny, (list, tuple)):\n logger.warning(\"Ignoring non-list deny ACL %s\", deny)\n deny = []\n for e in deny:\n if _acl_entry_matches(server_name, e):\n # logger.info(\"%s matched deny rule %s\", server_name, e)\n return False\n\n # then the allow list.\n allow = acl_event.content.get(\"allow\", [])\n if not isinstance(allow, (list, tuple)):\n logger.warning(\"Ignoring non-list allow ACL %s\", allow)\n allow = []\n for e in allow:\n if _acl_entry_matches(server_name, e):\n # logger.info(\"%s matched allow rule %s\", server_name, e)\n return True\n\n # everything else should be rejected.\n # logger.info(\"%s fell through\", server_name)\n return False\n\n\ndef _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:\n if not isinstance(acl_entry, str):\n logger.warning(\n \"Ignoring non-str ACL entry '%s' (is %s)\", acl_entry, type(acl_entry)\n )\n return False\n regex = glob_to_regex(acl_entry)\n return bool(regex.match(server_name))\n\n\nclass FederationHandlerRegistry:\n \"\"\"Allows classes to register themselves as handlers for a given EDU or\n query type for incoming federation traffic.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n self.config = hs.config\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self.clock = hs.get_clock()\n self._instance_name = hs.get_instance_name()\n\n # These are safe to load in monolith mode, but will explode if we try\n # and use them. However we have guards before we use them to ensure that\n # we don't route to ourselves, and in monolith mode that will always be\n # the case.\n self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)\n self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)\n\n self.edu_handlers = (\n {}\n ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]]\n self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]]\n\n # Map from type to instance name that we should route EDU handling to.\n self._edu_type_to_instance = {} # type: Dict[str, str]\n\n def register_edu_handler(\n self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]\n ):\n \"\"\"Sets the handler callable that will be used to handle an incoming\n federation EDU of the given type.\n\n Args:\n edu_type: The type of the incoming EDU to register handler for\n handler: A callable invoked on incoming EDU\n of the given type. The arguments are the origin server name and\n the EDU contents.\n \"\"\"\n if edu_type in self.edu_handlers:\n raise KeyError(\"Already have an EDU handler for %s\" % (edu_type,))\n\n logger.info(\"Registering federation EDU handler for %r\", edu_type)\n\n self.edu_handlers[edu_type] = handler\n\n def register_query_handler(\n self, query_type: str, handler: Callable[[dict], <|endoftext|>"} {"language": "python", "text": "ing: utf-8 -*-\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom typing import List, TYPE_CHECKING\n\nfrom zulint.custom_rules import RuleList\nif TYPE_CHECKING:\n from zulint.custom_rules import Rule\n\n# Rule help:\n# By default, a rule applies to all files within the extension for which it is specified (e.g. all .py files)\n# There are three operators we can use to manually include or exclude files from linting for a rule:\n# 'exclude': 'set([, ...])' - if is a filename, excludes that file.\n# if is a directory, excludes all files directly below the directory .\n# 'exclude_line': 'set([(, ), ...])' - excludes all lines matching in the file from linting.\n# 'include_only': 'set([, ...])' - includes only those files where is a substring of the filepath.\n\nPYDELIMS = r'''\"'()\\[\\]{}#\\\\'''\nPYREG = r\"[^{}]\".format(PYDELIMS)\nPYSQ = r'\"(?:[^\"\\\\]|\\\\.)*\"'\nPYDQ = r\"'(?:[^'\\\\]|\\\\.)*'\"\nPYLEFT = r\"[(\\[{]\"\nPYRIGHT = r\"[)\\]}]\"\nPYCODE = PYREG\nfor depth in range(5):\n PYGROUP = r\"\"\"(?:{}|{}|{}{}*{})\"\"\".format(PYSQ, PYDQ, PYLEFT, PYCODE, PYRIGHT)\n PYCODE = r\"\"\"(?:{}|{})\"\"\".format(PYREG, PYGROUP)\n\nFILES_WITH_LEGACY_SUBJECT = {\n # This basically requires a big DB migration:\n 'zerver/lib/topic.py',\n\n # This is for backward compatibility.\n 'zerver/tests/test_legacy_subject.py',\n\n # Other migration-related changes require extreme care.\n 'zerver/lib/fix_unreads.py',\n 'zerver/tests/test_migrations.py',\n\n # These use subject in the email sense, and will\n # probably always be exempt:\n 'zerver/lib/email_mirror.py',\n 'zerver/lib/feedback.py<|endoftext|>"} {"language": "python", "text": "psis: most ajax processors for askbot\n\nThis module contains most (but not all) processors for Ajax requests.\nNot so clear if this subdivision was necessary as separation of Ajax and non-ajax views\nis not always very clean.\n\"\"\"\nimport datetime\nimport logging\nfrom bs4 import BeautifulSoup\nfrom django.conf import settings as django_settings\nfrom django.core import exceptions\n#from django.core.management import call_command\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseBadRequest\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponseForbidden\nfrom django.forms import ValidationError, IntegerField, CharField\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import render\nfrom django.template.loader import get_template\nfrom django.views.decorators import csrf\nfrom django.utils import simplejson\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext as _\nfrom django.utils.translation import string_concat\nfrom askbot.utils.slug import slugify\nfrom askbot import models\nfrom askbot import forms\nfrom askbot import conf\nfrom askbot import const\nfrom askbot import mail\nfrom askbot.conf import settings as askbot_settings\nfrom askbot.utils import category_tree\nfrom askbot.utils import decorators\nfrom askbot.utils import url_utils\nfrom askbot.utils.forms import get_db_object_or_404\nfrom django.template import RequestContext\nfrom askbot.skins.loaders import render_into_skin_as_string\nfrom askbot.skins.loaders import render_text_into_skin\nfrom askbot.models.<|endoftext|>"} {"language": "python", "text": "r.ib(type=Optional[Sequence[EventBase]], default=None)\n auth_events = attr.ib(type=Optional[MutableStateMap[EventBase]], default=None)\n\n\nclass FederationHandler(BaseHandler):\n \"\"\"Handles events that originated from federation.\n Responsible for:\n a) handling received Pdus before handing them on as Events to the rest\n of the homeserver (including auth and state conflict resolutions)\n b) converting events that were produced by local clients that may need\n to be sent to remote homeservers.\n c) doing the necessary dances to invite remote users and join remote\n rooms.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n super().__init__(hs)\n\n self.hs = hs\n\n self.store = hs.get_datastore()\n self.storage = hs.get_storage()\n self.state_store = self.storage.state\n self.federation_client = hs.get_federation_client()\n self.state_handler = hs.get_state_handler()\n self._state_resolution_handler = hs.get_state_resolution_handler()\n self.server_name = hs.hostname\n self.keyring = hs.get_keyring()\n self.action_generator = hs.get_action_generator()\n self.is_mine_id = hs.is_mine_id\n self.spam_checker = hs.get_spam_checker()\n self.event_creation_handler = hs.get_event_creation_handler()\n self._message_handler = hs.get_message_handler()\n self._server_notices_mxid = hs.config.server_notices_mxid\n self.config = hs.config\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self.http_client = hs.get_proxied_blacklisted_http_client()\n self._instance_name = hs.get_instance_name()\n self._replication = hs.get_replication_data_handler()\n\n self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)\n self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(\n hs\n )\n\n if hs.config.worker_app:\n self._user_device_resync = ReplicationUserDevicesResyncRestServlet.make_client(\n hs\n )\n self._maybe_store_room_on_outlier_membership = ReplicationStoreRoomOnOutlierMembershipRestServlet.make_client(\n hs\n )\n else:\n self._device_list_updater = hs.get_device_handler().device_list_updater\n self._maybe_store_room_on_outlier_membership = (\n self.store.maybe_store_room_on_outlier_membership\n )\n\n # When joining a room we need to queue any events for that room up.\n # For each room, a list of (pdu, origin) tuples.\n self.room_queues = {} # type: Dict[str, List[Tuple[EventBase, str]]]\n self._room_pdu_linearizer = Linearizer(\"fed_room_pdu\")\n\n self.third_party_event_rules = hs.get_third_party_event_rules()\n\n self._ephemeral_messages_enabled = hs.config.enable_ephemeral_messages\n\n async def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False) -> None:\n \"\"\" Process a PDU received via a federation /send/ transaction, or\n via backfill of missing prev_events\n\n Args:\n origin (str): server which initiated the /send/ transaction. Will\n be used to fetch miss<|endoftext|>"} {"language": "python", "text": "ignedjson.key\nfrom signedjson.sign import SignatureVerifyException\n\nfrom sydent.http.httpclient import FederationHttpClient\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoAuthenticationError(Exception):\n \"\"\"\n Raised when no signature is provided that could be authenticated\n \"\"\"\n pass\n\n\nclass Verifier(object):\n \"\"\"\n Verifies signed json blobs from Matrix Homeservers by finding the\n homeserver's address, contacting it, requesting its keys and\n verifying that the signature on the json blob matches.\n \"\"\"\n def __init__(self, sydent):\n self.sydent = sydent\n # Cache of server keys. These are cached until the 'valid_until_ts' time\n # in the result.\n self.cache = {\n # server_name: ,\n }\n\n @defer.inlineCallbacks\n def _getKeysForServer(self, server_name):\n \"\"\"Get the signing key data from a homeserver.\n\n :param server_name: The name of the server to request the keys from.\n :type server_name: unicode\n\n :return: The verification keys returned by the server.\n :rtype: twisted.internet.defer.Deferred[dict[unicode, dict[unicode, unicode]]]\n \"\"\"\n\n if server_name in self.cache:\n cached = self.cache[server_name]\n now = int(time.time() * 1000)\n if cached['valid_until_ts'] > now:\n defer.returnValue(self.cache[server_name]['verify_keys'])\n\n client = FederationHttpClient(self.sydent)\n # BUG: CWE-770 Allocation of Resources Without Limits or Throttling\n # result = yield client.get_json(\"matrix://%s/_matrix/key/v2/server/\" % server_name)\n # FIXED: \n result = yield client.get_json(\"matrix://%s/_matrix/key/v2/server/\" % server_name, 1024 * 50)\n if 'verify_keys' not in result:\n raise SignatureVerifyException(\"No key found in response\")\n\n if 'valid_until_ts' in result:\n # Don't cache anything without a valid_until_ts or we wouldn't\n # know when to expire it.\n logger.info(\"Got keys for %s: caching until %s\", server_name, result['valid_until_ts'])\n self.cache[server_name] = result\n\n defer.returnValue(result['verify_keys'])\n\n @defer.inlineCallbacks\n def verifyServerSignedJson(self, signed_json, acceptable_server_names=None):\n \"\"\"Given a signed json object, try to verify any one\n of the signatures on it\n\n XXX: This contains a fairly noddy version of the home server\n SRV lookup and signature verification. It does no caching (just\n fetches the signature each time and does not contact any other\n servers to do perspective checks).\n\n :param acceptable_server_names: If provided and not None,\n only signatures from servers in this list will be accepted.\n :type acceptable_server_names: list[unicode] or None\n\n :return a tuple of the server name and key name that was\n successfully verified.\n :rtype: twisted.internet.defer.Deferred[tuple[unicode]]\n\n :raise SignatureVerifyException: The json cannot be verified.\n \"\"\"\n if 'signatures' not in signed_json:\n raise SignatureVerifyException(\"Signature missing\")\n for server_name, sigs in signed_json['signatures'].items():\n if acceptable_server_names is not None:\n <|endoftext|>"} {"language": "python", "text": "ograph=True`. See https://www.tensorflow.org/guide/autograph\n for more information.\n experimental_relax_shapes: When true, argument shapes may be relaxed to\n avoid unnecessary retracing.\n capture_by_value: Experimental. Whether to capture resource variables by\n value or reference. If None, will inherit from a parent context or\n default to False.\n jit_compile: Force-compile the function with XLA, cf.\n def_function.Function doc on jit_compile.\n experimental_follow_type_hints: See the documentation for `tf.function`.\n\n Raises:\n ValueError: if `input_signature` is not None and the `python_function`'s\n argspec has keyword arguments.\n \"\"\"\n self._python_function = python_function\n pure_function = attributes and IMPLEMENTS_ATTRIBUTE_NAME in attributes\n self._function_spec = FunctionSpec.from_function_and_signature(\n python_function,\n input_signature,\n is_pure=pure_function,\n experimental_follow_type_hints=experimental_follow_type_hints)\n self._name = name\n self._autograph = autograph\n self._autograph_options = autograph_options\n self._experimental_relax_shapes = experimental_relax_shapes\n self._function_cache = FunctionCache()\n self._function_attributes = attributes or {}\n self._capture_by_value = capture_by_value\n self.tracing_count = 0\n if self.input_signature is not None:\n self._hashable_input_signature = hash(self.flat_input_signature)\n # BUG: CWE-667 Improper Locking\n # self._lock = threading.Lock()\n # FIXED: \n self._lock = threading.RLock()\n # _descriptor_cache is a of instance of a class to an instance-specific\n # `Function`, used to make sure defun-decorated methods create different\n # functions for each instance.\n self._descriptor_cache = weakref.WeakKeyDictionary()\n self._jit_compile = jit_compile\n self._experimental_follow_type_hints = experimental_follow_type_hints\n\n def __call__(self, *args, **kwargs):\n \"\"\"Calls a graph function specialized to the inputs.\"\"\"\n with self._lock:\n (graph_function,\n filtered_flat_args) = self._maybe_define_function(args, kwargs)\n return graph_function._call_flat(\n filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access\n\n @property\n def python_function(self):\n \"\"\"Returns the wrapped Python function.\"\"\"\n return self._python_function # pylint: disable=protected-access\n\n @property\n def function_spec(self):\n return self._function_spec\n\n @property\n def input_signature(self):\n \"\"\"Returns the input signature.\"\"\"\n return self._function_spec.input_signature\n\n @property\n def flat_input_signature(self):\n \"\"\"Returns the flattened input signature.\"\"\"\n return self._function_spec.flat_input_signature\n\n def _get_concrete_function_internal_garbage_collected(self, *args, **kwargs):\n \"\"\"Returns a concrete function which cleans up its graph function.\"\"\"\n if self.input_signature:\n args, kwargs = None, None\n with self._lock:\n graph_function, _ = self._maybe_define_function(args, kwargs)\n return graph_function\n\n def _get_concrete_function_internal(self, *args, **kwargs):\n \"\"\"Bypasses error checking when getting a <|endoftext|>"} {"language": "python", "text": "from urllib.parse import urlparse, urlunparse\nexcept ImportError: # Python 2\n from urlparse import urlparse, urlunparse\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, QueryDict\nfrom django.template.response import TemplateResponse\nfrom django.utils.http import base36_to_int\nfrom django.utils.translation import ugettext as _\nfrom django.shortcuts import resolve_url\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_protect\n\n# Avoid shadowing the login() and logout() views below.\nfrom django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout, get_user_model\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.sites.models import get_current_site\n\n\n@sensitive_post_parameters()\n@csrf_protect\n@never_cache\ndef login(request, template_name='registration/login.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n authentication_form=AuthenticationForm,\n current_app=None, extra_context=None):\n \"\"\"\n Displays the login form and handles the login action.\n \"\"\"\n redirect_to = request.REQUEST.get(redirect_field_name, '')\n\n if request.method == \"POST\":\n form = authentication_form(data=request.POST)\n if form.is_valid():\n # Use default setting if redirect_to is empty\n if not redirect_to:\n <|endoftext|>"} {"language": "python", "text": "ing: utf-8 -*-\n\n# Copyright 2019 The Matrix.org Foundation C.I.C.\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.\nfrom __future__ import absolute_import\n\nfrom twisted.web.resource import Resource\nfrom twisted.internet import defer\n\nimport logging\nimport json\nfrom six.moves import urllib\n\nfrom sydent.http.servlets import get_args, jsonwrap, deferjsonwrap, send_cors\nfrom sydent.http.httpclient import FederationHttpClient\nfrom sydent.users.tokens import issueToken\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass RegisterServlet(Resource):\n isLeaf = True\n\n def __init__(self, syd):\n self.sydent = syd\n self.client = FederationHttpClient(self.sydent)\n\n @deferjsonwrap\n @defer.inlineCallbacks\n def render_POST(self, request):\n \"\"\"\n Register with the Identity Server\n \"\"\"\n send_cors(request)\n\n args = get_args(request, ('matrix_server_name', 'access_token'))\n\n result = yield self.client.get_json(\n \"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s\" % (\n args['matrix_server_name'], urllib.parse.quote(args['access_token']),\n ),\n # BUG: CWE-770 Allocation of Resources <|endoftext|>"} {"language": "python", "text": "se64\nimport json\n\nimport pytest\n\nfrom jwt.algorithms import Algorithm, HMACAlgorithm, NoneAlgorithm, has_crypto\nfrom jwt.exceptions import InvalidKeyError\nfrom jwt.utils import base64url_decode\n\nfrom .keys import load_ec_pub_key_p_521, load_hmac_key, load_rsa_pub_key\nfrom .utils import crypto_required, key_path\n\nif has_crypto:\n from jwt.algorithms import ECAlgorithm, OKPAlgorithm, RSAAlgorithm, RSAPSSAlgorithm\n\n\nclass TestAlgorithms:\n def test_algorithm_should_throw_exception_if_prepare_key_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.prepare_key(\"test\")\n\n def test_algorithm_should_throw_exception_if_sign_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.sign(\"message\", \"key\")\n\n def test_algorithm_should_throw_exception_if_verify_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.verify(\"message\", \"key\", \"signature\")\n\n def test_algorithm_should_throw_exception_if_to_jwk_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.from_jwk(\"value\")\n\n def test_algorithm_should_throw_exception_if_from_jwk_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.to_jwk(\"value\")\n\n def test_none_algorithm_should_throw_exception_if_key_is_not_none(self):\n algo = NoneAlgorithm()\n\n with pytest.raises(InvalidKeyError):\n algo.prepare_key(\"123\")\n\n def test_hmac_should_reject_nonstring_key(self):\n algo = HMACAlgorithm(HMACAlgorithm.SHA256)\n\n <|endoftext|>"} {"language": "python", "text": "(?:[-_a-zA-Z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff0-9]+)#\"\n for match in re.finditer(PATTERN, dataobj.content):\n embedded_tags.add(match.group(0).replace(\"#\", \"\").lstrip())\n\n return render_template(\n \"dataobjs/show.html\",\n title=dataobj[\"title\"],\n dataobj=dataobj,\n backlinks=backlinks,\n current_path=dataobj[\"dir\"],\n form=forms.DeleteDataForm(),\n view_only=0,\n search_enabled=app.config[\"SEARCH_CONF\"][\"enabled\"],\n post_title_form=post_title_form,\n move_form=move_form,\n tag_list=tag_list,\n embedded_tags=embedded_tags,\n titles=titles,\n )\n\n\n@app.route(\"/dataobj/move/\", methods=[\"POST\"])\ndef move_item(dataobj_id):\n form = forms.MoveItemForm()\n out_dir = form.path.data if form.path.data != \"\" else \"root directory\"\n if form.path.data == None:\n flash(\"No path specified.\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n try:\n if data.move_item(dataobj_id, form.path.data):\n flash(f\"Data successfully moved to {out_dir}.\", \"success\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n else:\n flash(f\"Data could not be moved to {out_dir}.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n except FileNotFoundError:\n flash(\"Data not found.\", \"error\")\n return redirect(\"/\")\n except FileExistsError:\n flash(\"Data already in target directory.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n\n# BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n# @app.route(\"/dataobj/delete/\", methods=[\"DELETE\", \"GET\"])\n# FIXED: \n@app.route(\"/dataobj/delete/\", methods=[\"POST\"])\ndef delete_data(dataobj_id):\n try:\n data.delete_item(dataobj_id)\n except BaseException:\n flash(\"Data could not be found!\", \"error\")\n return redirect(\"/\")\n flash(\"Data deleted!\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n user = db.search(\n (Query().username == form.username.data) & (Query().type == \"user\")\n )\n\n if user and check_password_hash(user[0][\"hashed_password\"], form.password.data):\n user = User.from_db(user[0])\n login_user(user, remember=True)\n flash(\"Login successful!\", \"success\")\n\n next_url = request.args.get(\"next\")\n return redirect(next_url or \"/\")\n\n flash(\"Invalid credentials\", \"error\")\n return redirect(\"/login\")\n return render_template(\"users/login.html\", form=form, title=\"Login\")\n\n\n@app.route(\"/logout\", methods=[\"DELETE\", \"GET\"])\ndef logout():\n logout_user()\n flash(\"Logged out successfully\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/user/edit\", methods=[\"GET\", \"POST\"])\ndef edit_user():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n db.update(\n {\n \"username\": form.username.data,\n \"hashed_password\": generate_password_hash(form.password.data),\n },\n doc_ids=[current_user.id],\n )\n flash(\"Information saved!\", \"success\")\n return redirect(\"/\")\n form.username.data = current_user.username\n <|endoftext|>"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2015, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\nclass PortalSettings(Document):\n\tdef add_item(self, item):\n\t\t'''insert new portal menu item if route is not set, or role is different'''\n\t\texists = [d for d in self.get('menu', []) if d.get('route')==item.get('route')]\n\t\tif exists and item.get('role'):\n\t\t\tif exists[0].role != item.get('role'):\n\t\t\t\texists[0].role = item.get('role')\n\t\t\t\treturn True\n\t\telif not exists:\n\t\t\titem['enabled'] = 1\n\t\t\tself.append('menu', item)\n\t\t\treturn True\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef reset(self):\n\t\t'''Restore defaults'''\n\t\tself.menu = []\n\t\tself.sync_menu()\n\n\tdef sync_menu(self):\n\t\t'''Sync portal menu items'''\n\t\tdirty = False\n\t\tfor item in frappe.get_hooks('standard_portal_menu_items'):\n\t\t\tif item.get('role') and not frappe.db.exists(\"Role\", item.get('role')):\n\t\t\t\tfrappe.get_doc({\"doctype\": \"Role\", \"role_name\": item.get('role'), \"desk_access\": 0}).insert()\n\t\t\tif self.add_item(item):\n\t\t\t\tdirty = True\n\n\t\tif dirty:\n\t\t\tself.save()\n\n\tdef on_update(self):\n\t\tself.clear_cache()\n\n\tdef clear_cache(self):\n\t\t# make js and css\n\t\t# clear web cache (for menus!)\n\t\tfrappe.clear_cache(user='Guest')\n\n\t\tfrom frappe.website.render import clear_cache\n\t\tclear_cache()\n\n\t\t# clears role based home pages\n\t\tfrappe.clear_cache()\n\n<|endoftext|>"} {"language": "java", "text": "mpliance with\n * the License. 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 distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\npackage org.hyperledger.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": "pyright 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.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(entityDataPacket);\n\n MovePlayerPacket movePlayerPacket = new MovePlayerPacket();\n movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());\n movePlayerPacket.setPosition(entity.getPosition());\n movePlayerPacket.setRotation(entity.getBedrockRotation());\n movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN);\n session.sendUpstreamPacket(movePlayerPacket);\n }\n\n ClientRequestPacket javaRes<|endoftext|>"} {"language": "java", "text": "flc);\n\t\ttableEl.setCustomizeColumns(false);\n\t\ttableEl.setNumOfRowsEnabled(false);\n\t\t\t\t\n\t\trefreshbtn = uifactory.addFormLink(\"button.refresh\", flc, Link.BUTTON);\n\t\trefreshbtn.setIconLeftCSS(\"o_icon o_icon_refresh o_icon-fw\");\n\t}\n\t\n\t@Override\n\tpublic void event(UserRequest ureq, Component source, Event event) {\n\t\tsuper.event(ureq, source, event);\n\t}\n\t\n\t@Override\n\tprotected void event(UserRequest ureq, Controller source, org.olat.core.gui.control.Event 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}\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.getUserObject();\n\t\t\tvideoManager.deleteVideoTranscoding(videoTranscoding);\n\t\t} else if (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"startTranscoding\")) {\n\t\t\tvideoManager.createTranscoding(videoResource, (int) source.getUserObject(), \"mp4\");\n\t\t}\n\t\tinitTable();\n\t}\n\t\n\t@Override\n\tprotected void formOK(UserRequest ureq) {\n\t\t// nothing to do, events cached in formInnerEvent\n\t}\n\n\t@Override\n\tprotected void doDispose() {\n\t\t// controller auto disposed\n\t}\n\t\n\tprivate class VideoCompar<|endoftext|>"} {"language": "java", "text": "right 2021 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 com.thoughtworks.go.addon.businesscontinuity.primary.controller;\n\nimport com.google.gson.Gson;\nimport com.thoughtworks.go.addon.businesscontinuity.ConfigFileType;\nimport com.thoughtworks.go.addon.businesscontinuity.DatabaseStatusProvider;\nimport com.thoughtworks.go.addon.businesscontinuity.FileDetails;\nimport com.thoughtworks.go.addon.businesscontinuity.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.<|endoftext|>"} {"language": "java", "text": "tems, used for caching. There is usually few of them (about 15). */\n private final Map scopes = new HashMap<>();\n\n /**\n * The properties to be given the objects to construct. Reused every time {@link\n * #createProperties} is invoked.\n */\n private final Map properties = new HashMap<>();\n\n /**\n * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}.\n * This is used by {@link #createBursaWolfParameters}, 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, Boolean.FALSE);\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n }\n /**\n * Constructs an authority factory using the specified connection.\n *\n * @param userHints The underlying factories used for objects creation.\n * @param connection The connection to the underlying EPSG database.\n */\n public AbstractEpsgFactory(final Hints userHints, final Connection connection) {\n super(MAXIMUM_PRIORITY - 20, userHints);\n // The following hints have no effect <|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2020 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * https://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, 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 }\n\n @Override\n protected String getDiskFilename() {\n return null;\n }\n\n @Override\n protected String getPrefix() {\n return null;\n }\n\n @Override\n protected String getBaseDirectory() {\n return null;\n }\n\n @Override\n protected String getPostfix() {\n return null;\n }\n\n @Override\n protected boolean deleteOnExit() {\n return false;\n }\n\n <|endoftext|>"} {"language": "java", "text": "right 2013-2022 Erudika. https://erudika.com\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 * For issues and patches go to: https://github.com/erudika\n */\npackage com.erudika.scoold.controllers;\n\nimport com.cloudinary.Cloudinary;\nimport com.cloudinary.utils.ObjectUtils;\nimport com.erudika.para.core.User;\nimport static com.erudika.para.core.User.Groups.MODS;\nimport static com.erudika.para.core.User.Groups.USERS;\nimport com.erudika.para.core.utils.Pager;\nimport com.erudika.para.core.utils.ParaObjectUtils;\nimport com.erudika.para.core.utils.Utils;\nimport com.erudika.scoold.ScooldConfig;\nimport static com.erudika.scoold.ScooldServer.PEOPLELINK;\nimport static com.erudika.scoold.ScooldServer.PROFILELINK;\nimport static com.erudika.scoold.ScooldServer.SIGNINLINK;\nimport com.erudika.scoold.core.Post;\nimport com.erudika.scoold.core.Profile;\nimport com.erudika.scoold.core.Profile.Badge;\nimport com.erudika.scoold.core.Question;\nimport com.erudika.scoold.core.Reply;\nimport com.erudika.scoold.utils.ScooldUtils;\nimport com.erudika.scoold.utils.avatars.*;\nimport java.util.*;\nimport javax.inject.Inject;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServ<|endoftext|>"} {"language": "java", "text": "itionPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;\nimport com.github.steveice10.packetlib.packet.Packet;\nimport com.nukkitx.math.vector.Vector3d;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;\nimport com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;\nimport org.geysermc.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 = !entity.getPosition().equals(packet.getPosition());\n boolean rotationChanged = !entity.getRotation().equals(rotation);\n\n // If only the pitch and yaw changed\n // This isn't needed, but it makes the packets closer to vanilla\n // It also means you can't \"lag back\" while only looking, in theory\n if (!positionChanged && rotationChanged) {\n ClientPlayerRotationPacket playerRotationPacket = new ClientPlayerRotationPacket(\n packet.isOnGrou<|endoftext|>"} {"language": "java", "text": " org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.item.ItemTranslator;\nimport org.geysermc.connector.registry.Registries;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.utils.InventoryUtils;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID;\n\n/**\n * Used 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 otherwise\n output = output.toBuilder().tag(null).build();\n ItemData[][] inputCombinations = combinations(session, shapelessRecipeData.getIngredients());\n for (ItemData[] inputs : inputCombinations) {\n UUID uuid = UUID.randomUUID();\n craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(),\n Arrays.asList(inputs), Collections.singletonList(<|endoftext|>"} {"language": "java", "text": "onvert.ConversionContext;\nimport io.micronaut.core.convert.ConversionService;\nimport io.micronaut.core.reflect.GenericTypeUtils;\nimport io.micronaut.core.type.Argument;\nimport io.micronaut.core.value.ValueResolver;\n\nimport java.util.*;\nimport java.util.function.BiConsumer;\nimport java.util.stream.Collectors;\n\n/**\n * An interface for classes that represent a map-like structure of values that can be converted.\n *\n * @param The generic value\n * @author Graeme Rocher\n * @since 1.0\n */\npublic interface 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.getKey();\n newMap.put(key, entry.getValue());\n }\n return newMap;\n }\n\n /**\n * Return this {@link ConvertibleValues} as a map for the given key type and value type. If any entry cannot be\n * converted to the target key/value type then the entry is simply excluded, hence the size of the map returned\n * may not match the size of this {@link ConvertibleValues}.\n *\n * @param keyType The key type\n * @param valueType The value type\n * @param <|endoftext|>"} {"language": "java", "text": "CE);\n\t\t//}\n\t\treturn spaces;\n\t}\n\n\tpublic void setSpaces(Set spaces) {\n\t\tthis.spaces = spaces;\n\t}\n\n\t@JsonIgnore\n\tpublic Set getAllSpaces() {\n\t\treturn getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet());\n\t}\n\n\tpublic Long getLastseen() {\n\t\treturn lastseen;\n\t}\n\n\tpublic void setLastseen(Long val) {\n\t\tthis.lastseen = val;\n\t}\n\n\tpublic String getWebsite() {\n\t\treturn website;\n\t}\n\n\tpublic void setWebsite(String website) {\n\t\tthis.website = website;\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 List getPostsForUser(String type, Pager pager) {\n\t\tpager.setSortby(\"votes\");\n\t\treturn client().findTerms(type, Collections.singletonMap(Config._CREATORID, getId()), true, pager);\n\t}\n\n\tpublic String getFavtagsString() {\n\t\tif (getFavtags().isEmpty()) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn StringUtils.join(getFavtags(), \", \");\n\t}\n\n\tpublic boolean hasFavtags() {\n\t\treturn !getFavtags().isEmpty();\n\t}\n\n\tpublic boolean hasSpaces() {\n\t\treturn !(getSpaces().size() <= 1 && getSpaces().contains(Post.DEF<|endoftext|>"} {"language": "java", "text": "right 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.framework.ldap;\n\nimport cd.go.authentication.ldap.LdapClient;\nimport cd.go.authentication.ldap.exception.LdapException;\nimport cd.go.authentication.ldap.exception.MultipleUserDetectedException;\nimport cd.go.authentication.ldap.mapper.Mapper;\nimport cd.go.authentication.ldap.mapper.ResultWrapper;\nimport cd.go.authentication.ldap.model.LdapConfiguration;\n\nimport javax.naming.NamingEnumeration;\nimport javax.naming.NamingException;\nimport javax.naming.directory.*;\nimport java.util.ArrayList;\nimport java.util.Hashtable;\nimport java.util.List;\n\nimport static cd.go.authentication.ldap.LdapPlugin.LOG;\nimport static cd.go.authentication.ldap.utils.Util.isNotBlank;\nimport static java.text.MessageFormat.format;\nimport static javax.naming.Context.SECURITY_CREDENTIALS;\nimport static javax.naming.Context.SECURITY_PRINCIPAL;\n\npublic class JNDILdapClient implements LdapClient {\n private LdapConfiguration ldapConfiguration;\n private final int MAX_AUTHENTICATION_RESULT = 1;\n\n public JNDILdapClient(LdapConfiguration ldapConfiguration) {\n this.ldapConfiguration = ldapConfiguration<|endoftext|>"} {"language": "java", "text": "right 2016 Red Hat, Inc. and/or its affiliates\n * and other contributors as indicated by the @author tags.\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 org.keycloak.protocol.saml;\n\nimport org.keycloak.services.util.CertificateInfoHelper;\n\n/**\n * @author Bill Burke\n * @version $Revision: 1 $\n */\npublic interface SamlConfigAttributes {\n String SAML_SIGNING_PRIVATE_KEY = \"saml.signing.private.key\";\n String SAML_CANONICALIZATION_METHOD_ATTRIBUTE = \"saml_signature_canonicalization_method\";\n String SAML_SIGNATURE_ALGORITHM = \"saml.signature.algorithm\";\n String SAML_NAME_ID_FORMAT_ATTRIBUTE = \"saml_name_id_format\";\n String SAML_AUTHNSTATEMENT = \"saml.authnstatement\";\n String SAML_ONETIMEUSE_CONDITION = \"saml.onetimeuse.condition\";\n String SAML_FORCE_NAME_ID_FORMAT_ATTRIBUTE = \"saml_force_name_id_format\";\n String SAML_ARTIFACT_BINDING = \"saml.artifact.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.xmlSig<|endoftext|>"} {"language": "java", "text": " offset += read;\n if (len <= 0 || offset >= buf.length) {\n break;\n }\n }\n return buf;\n } finally {\n fis.close();\n }\n }\n\n @Test\n public void testDelete() throws Exception {\n String json = \"{\\\"foo\\\":\\\"bar\\\"}\";\n byte[] bytes = json.getBytes(CharsetUtil.UTF_8);\n File tmpFile = null;\n DiskFileUpload f1 = new DiskFileUpload(\"file4\", \"file4\", \"application/json\", null, 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": "istribute, sublicense, and/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.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": "s\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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": "port io.micronaut.http.hateoas.JsonError;\nimport io.micronaut.http.hateoas.VndError;\n\nimport java.util.Optional;\n\n/**\n * Strategy interface for decoding the error from a server respponse.\n *\n * @author graemerocher\n * @since 1.0\n */\n@Internal\npublic interface HttpClientErrorDecoder {\n\n /**\n * The default implementation.\n */\n HttpClientErrorDecoder DEFAULT = new HttpClientErrorDecoder() { };\n\n /**\n * Default message decoder.\n *\n * @param error The error object\n * @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": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.core.commons.services.vfs.manager;\n\nimport java.io.File;\nimport java.io.InputStream;\n\nimport org.olat.basesecurity.BaseSecurity;\nimport org.olat.basesecurity.IdentityImpl;\nimport org.olat.core.CoreSpringFactory;\nimport org.olat.core.commons.services.license.LicenseService;\nimport org.olat.core.commons.services.license.LicenseType;\nimport org.olat.core.commons.services.license.model.LicenseTypeImpl;\nimport org.olat.core.commons.services.vfs.VFSMetadata;\nimport org.olat.core.commons.services.vfs.VFSRevision;\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.thoughtwork<|endoftext|>"} {"language": "java", "text": " final int UC_CPU_S390X_Z890_2 = 9;\n public static final int UC_CPU_S390X_Z990_5 = 10;\n public static final int UC_CPU_S390X_Z890_3 = 11;\n public static final int UC_CPU_S390X_Z9EC = 12;\n public static final int UC_CPU_S390X_Z9EC_2 = 13;\n public static final int UC_CPU_S390X_Z9BC = 14;\n public static final int UC_CPU_S390X_Z9EC_3 = 15;\n public static final int UC_CPU_S390X_Z9BC_2 = 16;\n public static final int UC_CPU_S390X_Z10EC = 17;\n public static final int UC_CPU_S390X_Z10EC_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_REG_F4 = 21;\n public static final int UC_S390X_REG_F5 = 22;\n public static final int UC_S390X_REG_F6 = 23;\n public static final int UC_S390X_REG_F7 = 24;\n public static final int UC_S390X_REG_F8 = 25;\n public static final int UC_S390X_REG_F9 = 26;\n public static final int UC_S390X_REG_F10 = 27;\n public static final int UC_S390X_REG_F11 = 28;\n public static final int UC_S390X_REG_F12 = 29;\n public static final int UC_S390X_REG_F13 = 30;\n public static final int UC_S390X_REG_F14<|endoftext|>"} {"language": "java", "text": "port net.sourceforge.plantuml.security.authentication.SecurityCredentials;\n\n/**\n * Secure replacement for java.net.URL.\n *

\n * This class should be used instead of java.net.URL.\n *

\n * This class does some control access and manages access-tokens via URL. If a\n * URL contains a access-token, similar to a user prefix, SURL loads the\n * authorization config for this user-token and passes the credentials to the\n * host.\n *

\n * Example:
\n * \n *

\n *     SURL url = SURL.create (\"https://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 {\n\t\t\t\treturn create(new URL(url));\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Create a secure URL from a java.net.URL object.\n\t *

\n\t * It takes into account credentials.\n\t * \n\t * @param url\n\t * @return the secure URL\n\t * @throws MalformedURLException if url is null\n\t */\n\tpublic static SURL create(URL url) throws MalformedURLException {\n\t\tif (url == null)\n\t\t\tthrow new MalformedURLException(\"URL cannot be null\");\n\n<|endoftext|>"} {"language": "java", "text": "by https://jooby.io\n * Apache License Version 2.0 https://jooby.io/LICENSE.txt\n * Copyright 2014 Edgar Espina\n */\npackage io.jooby.internal.netty;\n\nimport com.typesafe.config.Config;\nimport io.jooby.Body;\nimport io.jooby.ByteRange;\nimport io.jooby.Context;\nimport io.jooby.Cookie;\nimport io.jooby.DefaultContext;\nimport io.jooby.FileUpload;\nimport io.jooby.Formdata;\nimport io.jooby.MediaType;\nimport io.jooby.Multipart;\nimport io.jooby.QueryString;\nimport io.jooby.Route;\nimport io.jooby.Router;\nimport io.jooby.Sender;\nimport io.jooby.Server;\nimport io.jooby.Session;\nimport io.jooby.SessionStore;\nimport io.jooby.SneakyThrows;\nimport io.jooby.StatusCode;\nimport io.jooby.Value;\nimport io.jooby.ValueNode;\nimport io.jooby.WebSocket;\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.channel.ChannelFutureListener;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelPipeline;\nimport io.netty.channel.DefaultFileRegion;\nimport io.netty.handler.codec.http.DefaultFullHttpRequest;\nimport io.netty.handler.codec.http.DefaultFullHttpResponse;\nimport io.netty.handler.codec.http.DefaultHttpHeaders;\nimport io.netty.handler.codec.http.DefaultHttpResponse;\nimport io.netty.handler.codec.http.EmptyHttpHeaders;\nimport io.netty.handler.codec.http.HttpHeaderNames;\nimport io.netty.handler.codec.http.HttpHeaders;\nimport io.netty.handler.codec.http.HttpRequest;\nimport io.netty.handler.codec.http.HttpResponseStatus;\nimport io.netty.handler.codec.http.HttpUtil;\nimport io.netty.handler.codec.http.HttpVersion;\nimport io.netty.handler.codec.http.cookie.ServerCookieDecoder;\nimport io.netty.handler.codec.http.multip<|endoftext|>"} {"language": "java", "text": "Test.class,\n ConcurrentStatementFetch.class,\n ConnectionTest.class,\n ConnectTimeoutTest.class,\n CopyLargeFileTest.class,\n CopyTest.class,\n CursorFetchTest.class,\n DatabaseEncodingTest.class,\n DatabaseMetaDataCacheTest.class,\n DatabaseMetaDataPropertiesTest.class,\n DatabaseMetaDataTest.class,\n DateStyleTest.class,\n DateTest.class,\n DeepBatchedInsertStatementTest.class,\n DriverTest.class,\n EncodingTest.class,\n ExpressionPropertiesTest.class,\n FixedLengthOutputStreamTest.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": "/* Copyright (c) 2008-2015, Avian Contributors\n\n Permission to use, copy, modify, and/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.\n\n There is NO WARRANTY for this software. See license.txt for\n details. */\n\npackage java.io;\n\npublic class FileOutputStream extends OutputStream {\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": "FileWithinDirectory(loadPath, file)\n ? loadFile(file)\n : null;\n }\n else {\n final File f = new File(loadPath, file.getPath());\n return f.isFile()\n ? loadFile(new File(loadPath, file.getPath()))\n : null;\n }\n }\n catch (Exception ex) {\n throw new VncException(\n String.format(\"Failed to load file '%s'\", 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": "t java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.olat.core.CoreSpringFactory;\nimport org.olat.core.configuration.AbstractSpringModule;\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.coordinate.CoordinatorManager;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.course.site.model.CourseSiteConfiguration;\nimport org.olat.course.site.model.LanguageConfiguration;\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 SiteConfiguration();\n\t\t\tc.setId(id);\n\t\t\treturn c;\n\t\t});\n\t}\n\t\n\tpublic SiteConfiguration getConfigurationSite(SiteDefinition siteDef) {\n\t\tfor(Map.Entry entry: siteDefMap.entrySet()) {\n\t\t\tif(entry.getValue() == siteDef) {\n\t\t\t\treturn getConfigurationSite(entry.getKey());\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic CourseSiteConfiguration getConfigurationCourseSite1() {\n\t\tif(StringHelper.containsNonWhitespace(configSite1)) {\n\t\t\treturn (CourseSiteConfiguration)xStream.fromXML(configSite1);\n\t\t}\n\t<|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2015 Red Hat, Inc. and/or its affiliates.\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 */\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": "ayer;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;\nimport com.github.steveice10.mc.protocol.data.game.entity.player.*;\nimport com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.*;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.math.vector.Vector3i;\nimport com.nukkitx.protocol.bedrock.data.LevelEventType;\nimport com.nukkitx.protocol.bedrock.data.PlayerActionType;\nimport 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.setRuntimeEntityId(entity.getGeyserId());\n attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values()));\n session.sendUpstreamPacket(attributesPacket);\n break;\n case START_SWIMMING:\n ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING);\n session.sendDownstreamPacket(startSwimPacket);\n\n session.setSwimming(true);\n <|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": "ensed to The Apereo Foundation under one or more contributor license\n * agreements. See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n *\n * The Apereo Foundation licenses this file to you under the Educational\n * Community License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of the License\n * at:\n *\n * http://opensource.org/licenses/ecl2.txt\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, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n */\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"} {"language": "java", "text": "name-with-dot\"));\n svnMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.MATERIAL_NAME)).isEqualTo(\"Invalid material name '.bad-name-with-dot'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.\");\n }\n\n @Test\n void shouldEnsureDestFilePathIsValid() {\n svnMaterialConfig.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 password value for SvnMaterial with url 'foo/bar' is invalid. This usually happens when the cipher text is modified to have an invalid value.\");\n }\n\n @Test\n void shouldPassIfPasswordIsNotSpecifiedAsSecretParams() {\n svnMaterialConfig.setPassword(\"badger\");\n\n assertThat(svnMaterialConfig.validateTree(null)).isTrue();\n assertThat(svnMaterialConfig.errors().getAll()).isEmpty();\n }\n }\n\n private ValidationContext mockValidationContextF<|endoftext|>"} {"language": "java", "text": "ld be parsed directly by adding it to JS.\n\t\t\t\t\t\t\t\t\t\tif (libs[j].toLowerCase()\n\t\t\t\t\t\t\t\t\t\t\t\t.endsWith(\".js\"))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tjs.append(tmp);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (result.length() > 1)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tresult.append(\",\");\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tresult.append(\"'\" + tmp + \"'\");\n\t\t\t\t\t\t\t\t\t\t}\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}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tString tmp = stencils.get(names[i]);\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\ttry\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\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+ ((dev != null && dev.equals(\"1\")) ? \"test\" : \"www\")\n\t\t\t\t+ \".draw.io/js/viewer-static.min.js';\"\n\t\t\t\t+ \"t[0].parentNode.appendChild(script);}\";\n\t}\n\n\tpublic void writeStats(HttpServletResponse response) throws IOException\n\t{\n\t\tPrintWriter writer = new PrintWriter(response.getOutputStream());\n\t\twriter.println(\"\");\n\t\twriter.println(\"\");\n\t\twriter.println(\"Deployed: \" + lastModified);\n\t\twriter.println(\"\");\n\t\twriter.println(\"\");\n\t\twriter.flush();\n\t}\n\n\tpublic String readXmlFi<|endoftext|>"} {"language": "java", "text": "ConversationsListItemUpdated;\nimport eu.siacs.conversations.ui.service.EmojiService;\nimport eu.siacs.conversations.ui.util.ActivityResult;\nimport eu.siacs.conversations.ui.util.ConversationMenuConfigurator;\nimport eu.siacs.conversations.ui.util.MenuDoubleTabUtil;\nimport eu.siacs.conversations.ui.util.PendingItem;\nimport eu.siacs.conversations.utils.EmojiWrapper;\nimport eu.siacs.conversations.utils.ExceptionHelper;\nimport eu.siacs.conversations.utils.XmppUri;\nimport eu.siacs.conversations.xmpp.OnUpdateBlocklist;\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_CONVERSATION);\n }\n\n private static Intent createLauncherIntent(Context context) {\n final Intent intent = new Intent(context, ConversationsActivity.class);\n intent.setAction(Intent.ACTION_MAIN);\n intent.addCategory(Intent.CATEGORY_LAUNCHER);\n return intent;\n }\n\n @Override\n protected void refreshUiReal() {\n for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {\n refreshFragment(id);\n }\n }\n\n @Override\n void onBackendConnected() {\n <|endoftext|>"} {"language": "java", "text": "er;\nimport uk.ac.ed.ph.jqtiplus.types.Identifier;\nimport uk.ac.ed.ph.jqtiplus.types.ResponseData.ResponseDataType;\nimport uk.ac.ed.ph.jqtiplus.value.BooleanValue;\nimport uk.ac.ed.ph.jqtiplus.value.NumberValue;\nimport uk.ac.ed.ph.jqtiplus.value.RecordValue;\nimport uk.ac.ed.ph.jqtiplus.value.SingleValue;\nimport uk.ac.ed.ph.jqtiplus.value.Value;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.XmlFactories;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.XmlResourceNotFoundException;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.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 ConcurrentMap resourceToTestURI = new ConcurrentHashMap<>();\n\t\n\t@Autowired\n\tpublic QTI21ServiceImpl(InfinispanXsltStylesheetCache xsltStylesheetCache) {\n\t\tthis.xsltStylesheetCache = xsltStylesheetCache;\n\t}\n\n\t@Override\n\tpublic void afterPropertiesSet() throws Exception {\n \tfinal List> extensionPackages = new ArrayList<>();\n\n /* Enable MathAssess extensions if requested */\n if (qtiModule.isMathAssessExtensionEnabled()) {\n log.info(\"En<|endoftext|>"} {"language": "java", "text": "right 2003-2006 Rick Knowles \n * Distributed under the terms of either:\n * - the common development and distribution license (CDDL), v1.0; or\n * - the GNU Lesser General Public License, v2.1 or later\n */\npackage winstone;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.UnsupportedEncodingException;\nimport java.io.Writer;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.StringTokenizer;\nimport java.util.TimeZone;\n\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.Cookie;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Response for servlet\n * \n * @author Rick Knowles\n * @version $Id: WinstoneResponse.java,v 1.28 2005/04/19 07:33:41 rickknowles\n * Exp $\n */\npublic class WinstoneResponse implements HttpServletResponse {\n private static final DateFormat HTTP_DF = new SimpleDateFormat(\n \"EEE, dd MMM yyyy HH:mm:ss z\", Locale.US);\n private static final DateFormat VERSION0_DF = new SimpleDateFormat(\n \"EEE, dd-MMM-yy HH:mm:ss z\", Locale.US);\n static {\n HTTP_DF.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n VERSION0_DF.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n }\n\n static final String CONTENT_LENGTH_HEADER = \"Content-Length\";\n static final String CONTENT_TYPE_HEADER = \"Content-Type\";\n\n // Response header constants\n private static final String CONTENT_LANGUAGE_HEADER = \"Content-Language\";\n private static fi<|endoftext|>"} {"language": "java", "text": " userRequest.getHttpReq().getParameter(\"key\");\n\t\tif (emKey == null) {\n\t\t\temKey = userRequest.getIdentity().getUser().getProperty(\"emchangeKey\", null);\n\t\t}\n\t\tif (emKey != null) {\n\t\t\t// key exist\n\t\t\t// we check if given key is a valid temporary key\n\t\t\ttempKey = rm.loadTemporaryKeyByRegistrationKey(emKey);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean isUserInteractionRequired(UserRequest ureq) {\n\t\tUser user = ureq.getIdentity().getUser();\n\t\tif(StringHelper.containsNonWhitespace(user.getProperty(\"emchangeKey\", 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\t\tuserRequest.getUserSession().removeEntryFromNonClearedStore(ChangeEMailController.CHANGE_EMAIL_ENTRY);\n\t\t\tsecurityManager.deleteInvalidAuthenticationsByEmail(oldEmail);\n\t\t} else {\n\t\t\t// error message\n\t\t\twControl.setWarning(pT.translate(\"error.change.email.unexpected\", new String[] { mails.get(\"currentEMail\"), mails.get(\"changedEMail\") }));\n\t\t}\n\t\t// delete registration key\n\t\trm.deleteTemporaryKeyWithId(tempKey.getRegistrationKey());\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic boolean isLinkClicked() {\n\t\tOb<|endoftext|>"} {"language": "java", "text": "bla.Dispatcher\",ConfigKey.AGENT_ID,\"test\");\n new BackendManager(config,log);\n }\n\n @Test\n public void debugging() {\n RecordingLogHandler lhandler = new RecordingLogHandler();\n BackendManager backendManager = new BackendManager(config,lhandler);\n lhandler.error = 0;\n lhandler.debug = 0;\n lhandler.info = 0;\n\n backendManager.debug(\"test\");\n assertEquals(lhandler.debug,1);\n backendManager.error(\"test\",new Exception());\n assertEquals(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 }\n\n public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {\n called = true;\n if (pJmxReq.getType() == RequestType.READ) {\n return new JSONObject();\n } else if (pJmxReq.getType() == RequestType.WRITE) {\n return \"faultyFormat\";\n } else if (pJmxReq.getType() == RequestType.LIST) {\n <|endoftext|>"} {"language": "java", "text": "ve 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.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": " - Online Learning and Training
\n* http://www.olat.org\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,
\n* software 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* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
\n* University of Zurich, Switzerland.\n*


\n* \n* OpenOLAT - Online Learning and Training
\n* This file has been modified by the OpenOLAT community. Changes are licensed\n* under the Apache 2.0 license 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 <|endoftext|>"} {"language": "java", "text": "right 2021 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 */\npackage com.thoughtworks.go.config.materials.git;\n\nimport com.thoughtworks.go.config.*;\nimport com.thoughtworks.go.config.materials.*;\nimport com.thoughtworks.go.domain.materials.MaterialConfig;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static com.thoughtworks.go.helper.MaterialConfigsMother.git;\nimport static org.junit.jupiter.api.Assertions.*;\nimport static org.mockito.Mockito.*;\n\nclass GitMaterialConfigTest {\n @Test\n void shouldBePasswordAwareMaterial() {\n assertTrue(PasswordAwareMaterial.class.isAssignableFrom(GitMaterialConfig.class));\n }\n\n @Test\n void shouldSetConfigAttributes() {\n GitMaterialConfig gitMaterialConfig = git(\"\");\n\n Map map = new HashMap<>();\n map.put(GitMaterialConfig.URL, \"url\");\n map.put(GitMaterialConfig.BRANCH, \"some-branch\");\n map.put(GitMaterialConfig.SHALLOW_CLONE, \"true\");\n map<|endoftext|>"} {"language": "java", "text": "s, Home of Professional Open Source.\n * Copyright 2014 Red Hat, Inc., and individual contributors\n * as indicated by the @author tags.\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 io.undertow.protocols.http2;\n\nimport io.undertow.util.HeaderMap;\nimport io.undertow.util.HeaderValues;\nimport io.undertow.util.Headers;\nimport io.undertow.util.HttpString;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayDeque;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Deque;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport static io.undertow.protocols.http2.Hpack.HeaderField;\nimport static io.undertow.protocols.http2.Hpack.STATIC_TABLE;\nimport static io.undertow.protocols.http2.Hpack.STATIC_TABLE_LENGTH;\nimport static io.undertow.protocols.http2.Hpack.encodeInteger;\n\n/**\n * Encoder for HPACK frames.\n *\n * @author Stuart Douglas\n */\npublic class HpackEncoder {\n\n private static final Set SKIP;\n\n static {\n Set set = new HashSet<>();\n set.add(Headers.CONNECTION);\n set.add(Headers.TRANSFER_ENCODING);\n set.add(H<|endoftext|>"} {"language": "java", "text": "\t\t}\n\n\t\tvar delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);\n\t\tvar delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),\n\t\t\t\tZoneOffset.UTC);\n\n\t\tvar nowDay = LocalDate.now(ZoneOffset.UTC);\n\t\tif (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {\n\t\t\treturn () -> ResponseEntity.badRequest().body(\"delayedKeyDate date must be between yesterday and tomorrow\");\n\t\t}\n\n\t\tvar responseBuilder = 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 verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate\") Object principal) {\n\t\tvar now = Instant.now().toEpochMilli();\n\n\t\tif (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {\n\t\t\treturn () -> new ResponseEntity<>(\"No valid base64 key\", HttpStatus.BAD_REQUEST);\n\t\t}\n\t\tif (principal instanceof Jwt && !((Jwt) principal).containsClaim(\"delayedKeyDate\")) {\n\t\t\treturn () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body(<|endoftext|>"} {"language": "java", "text": "g.bouncycastle.pqc.jcajce.provider.xmss;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\n\nimport org.bouncycastle.asn1.ASN1ObjectIdentifier;\nimport org.bouncycastle.asn1.pkcs.PrivateKeyInfo;\nimport org.bouncycastle.asn1.x509.AlgorithmIdentifier;\nimport org.bouncycastle.crypto.CipherParameters;\nimport org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;\nimport org.bouncycastle.pqc.asn1.XMSSKeyParams;\nimport org.bouncycastle.pqc.asn1.XMSSPrivateKey;\nimport org.bouncycastle.pqc.crypto.xmss.BDS;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSParameters;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSUtil;\nimport org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;\nimport org.bouncycastle.util.Arrays;\n\npublic class BCXMSSPrivateKey\n implements PrivateKey, XMSSKey\n{\n private final XMSSPrivateKeyParameters keyParams;\n private final ASN1ObjectIdentifier treeDigest;\n\n public BCXMSSPrivateKey(\n ASN1ObjectIdentifier treeDigest,\n XMSSPrivateKeyParameters keyParams)\n {\n this.treeDigest = treeDigest;\n this.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.getDige<|endoftext|>"} {"language": "java", "text": "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.github.steveice10.mc.protocol.data.game.entity.metadata.Position;\nimport com.github.steveice10.mc.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.getOpenInventory();\n if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) {\n // The same page means Bedrock is closing the window\n ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId());\n session.sendDownstreamPacket(closeWindowPacket);\n InventoryUtils.closeInventory(session, lecternContainer.getId(), false);\n } else {\n // Each \"page\" Bedrock gives to us actu<|endoftext|>"} {"language": "java", "text": "right (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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.c<|endoftext|>"} {"language": "java", "text": " } finally {\n buffer.release();\n }\n }\n\n @Test\n public void testCopy() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());\n ByteBuf copy = buf.copy();\n\n Assert.assertEquals(buf, copy);\n\n buf.release();\n copy.release();\n }\n\n @Test\n public void testCopyWithOffset() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());\n 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 public void testMemoryAddress() {\n ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());\n try {\n Assert.assertFalse(buf.hasMemoryAddress());\n try {\n buf.memoryAddress();\n Assert.fail();\n } catch (UnsupportedOperationException expected) {\n // expected\n }\n } finally {\n buf.release();\n }\n }\n}\n<|endoftext|>"} {"language": "java", "text": "rt org.olat.core.logging.Tracing;\nimport org.olat.core.util.CodeHelper;\nimport org.olat.core.util.FileUtils;\nimport org.olat.core.util.vfs.LocalFolderImpl;\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.xml.XMLParser;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.fileresource.FileResourceManager;\nimport org.olat.ims.cp.objects.CPOrganization;\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(config, out);\n\t\t\t} catch (IOException e) {\n\t\t\t\tlog.error(\"\", e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic ContentPackage load(VFSContainer directory, OLATResourceable ores) {\n\t\tContentPackage cp;\n\t\tVFSItem file = directory.resolve(\"imsmanifest.xml\");\n\t\tif (file instanceof VFSLeaf) {\n\t\t\ttry(InputStream in = ((VFSLeaf)file).getInputStream()) {\n\t\t\t\tXMLParser parser = new XMLParser();\n\t\t\t\tDefaultDocument doc = (DefaultDocument) parser.parse(in, false);\n\t\t\t\tcp = new ContentPackage(doc, directory, ores);\n\t\t\t\t// <|endoftext|>"} {"language": "java", "text": "right (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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)<|endoftext|>"} {"language": "java", "text": "right 2017-2019 original authors\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 */\npackage io.micronaut.http.netty;\n\nimport io.micronaut.core.annotation.Internal;\nimport io.micronaut.core.convert.ArgumentConversionContext;\nimport io.micronaut.core.convert.ConversionService;\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 <|endoftext|>"} {"language": "java", "text": "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.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 session.setSteeringRight(packet.getRowingTime() > 0.0);\n ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());\n session.sendDownstreamPacket(steerRightPacket);\n break;\n }\n }\n}\n<|endoftext|>"} {"language": "java", "text": "right (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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 com.github.steveice10.mc.protocol.packet.ingame.server.ServerPlayerListDataPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateLightPacket;\nimport com.github.steveice10.packetlib.packet.Packet;\nimport com.nukkitx.protocol.bedrock.BedrockPacket;\nimport io.netty.channel.EventLoop;\nimport it.unimi.dsi.fastutil.objects.ObjectArrayList;\nimport org.geysermc.common.PlatformType;\nimport org.geysermc.connector.Ge<|endoftext|>"} {"language": "java", "text": "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.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, GeyserItemStack.from(trade.getOutput()), session);\n villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP));\n villager.updateBedrockMetadata(session);\n }\n }\n }, 100, TimeUnit.MILLISECONDS);\n return;\n }\n session.getConnector().getLogger().debug(\"Did not translate incoming EntityEventPacket: \" + pa<|endoftext|>"} {"language": "java", "text": "ed {\n\n\t\t// min and max of all coord\n\t\tprivate final MinMax minMax;\n\n\t\tpublic Drawing(MinMax minMax) {\n\t\t\tthis.minMax = minMax;\n\t\t}\n\n\t\tpublic void drawU(UGraphic ug) {\n\t\t\tdrawAllClusters(ug);\n\t\t\tdrawAllNodes(ug);\n\t\t\tdrawAllEdges(ug);\n\t\t}\n\n\t\tprivate void drawAllClusters(UGraphic ug) {\n\t\t\tfor (Entry ent : clusters.entrySet())\n\t\t\t\tdrawSingleCluster(ug, ent.getKey(), ent.getValue());\n\n\t\t}\n\n\t\tprivate void drawAllNodes(UGraphic ug) {\n\t\t\tfor (Entry ent : nodes.entrySet())\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 label = g.getDisplay();\n\t\t\tif (label == null)\n\t\t\t\treturn TextBlockUtils.empty(0, 0);\n\n\t\t\tfinal ISkinParam skinParam = diagram.getSkinParam();\n\t\t\tfinal FontConfiguration fontConfiguration = g.getFontConfigurationForTitle(skinParam);\n\t\t\treturn label.create(fontConfiguration, HorizontalAlignment.CENTER, skinParam);\n\t\t}\n\n\t\tprivate HColor getBackColor(UmlDiagramType umlDiagramType) {\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate void drawSingleNode(UGraphic ug, ILeaf leaf, ElkNode elkNode) {\n\t\t\tfinal IEntityImage<|endoftext|>"} {"language": "java", "text": "brary; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n * USA.\n *\n *\n * Original Author: Arnaud Roques\n *\n *\n */\npackage net.sourceforge.plantuml.style;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nclass Context {\n\n\tprivate final List data = new ArrayList();\n\n\tpublic Context push(String newString) {\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": "ESS 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.github.steveice10.mc.protocol.packet.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 sendMovement = true;\n }\n }\n }\n if (sendMovement) {\n long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp();\n if (timeSinceVehicleMove >= 100) {\n Vector3f vehiclePosition = vehicle.getPosition();\n Vector3f vehicleRotation = vehicle.getRotation();\n\n if (vehicle instanceof BoatEntity) {\n // Remove some Y position to pre<|endoftext|>"} {"language": "java", "text": ", 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.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": "MIT License\n * \n * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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 */\npackage hudson.util;\n\nimport groovy.lang.Binding;\nimport groovy.lang.GroovyShell;\nimport hudson.FilePath;\nimport hudson.Functions;\nimport jenkins.model.Jenkins;\nimport hudson.remoting.AsyncFutureImpl;\nimport hudson.remoting.Callable;\nimport hudson.remoting.DelegatingCallable;\nimport hudson.remoting.Future;\nimport hudson.remoting.VirtualChannel;\nimport hudson.security.AccessControlled;\nimport org.codehaus.groovy.control.CompilerConfiguration;\nimport org.codehaus.groovy.control.customizers.ImportCustomizer;\nimpo<|endoftext|>"} {"language": "java", "text": "FTWARE 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.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 // Required to do it a tick later or else it doesn't register\n session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),\n 50, TimeUnit.MILLISECONDS);\n }\n\n // Java sends a cooldown indicator whenever you switch an item\n CooldownUtils.sendCooldown(session);\n\n // Update the interactive tag, if an entity is present\n if (session.getMouseoverEntity() != null) {\n <|endoftext|>"} {"language": "java", "text": "obtain a copy of the License at the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted 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": "StyleLoader.class.getResourceAsStream(\"/skin/strictuml.skin\");\n\t\t\tfinal StyleBuilder styleBuilder = this.getCurrentStyleBuilder();\n\t\t\ttry {\n\t\t\t\tfinal BlocLines lines = BlocLines.load(internalIs, null);\n\t\t\t\tfor (Style modifiedStyle : StyleLoader.getDeclaredStyles(lines, styleBuilder))\n\t\t\t\t\tthis.muteStyle(modifiedStyle);\n\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void applyPendingStyleMigration() {\n\t\tfor (Entry ent : paramsPendingForStyleMigration.entrySet()) {\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);\n\t\tif (result == null)\n\t\t\treturn HColorUtils.BLUE;\n\n\t\treturn result;\n\t}\n\n\tpublic HColor getBackgroundColor() {\n\t\tfinal HColor result = getHtmlColor(ColorParam.background, null, false);\n\t\treturn result != null ? result : HColorUtils.WHITE;\n\t}\n\n\tpublic String getValue(String key) {\n\t\tapplyPendingStyleMigration();\n\t\tfor (String key2 : cleanForKey(key)) {\n\t\t\tfinal String result = params.get(key2);\n\t\t\tif (result != null)\n\t\t\t\treturn result;\n\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String getValue(String key<|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": "he 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.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 // Build the position for the update\n IntList posList = new IntArrayList();\n posList.add(pos.getX());\n posList.add(pos.getY());\n posList.add(pos.getZ());\n builder.putList(\"pos\", NbtType.INT, posList);\n broadcastPacket.setTag(builder.build());\n\n session.sendUpstreamPacket(broadcastPacket);\n }\n}\n<|endoftext|>"} {"language": "java", "text": "package eu.nimble.utility.validation;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport eu.nimble.utility.JsonSerializationUtility;\nimport eu.nimble.utility.exception.AuthenticationException;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jwts;\nimport org.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 Map map = JsonSerializationUtility.getObjectMapper().readValue(body,new TypeReference>() {\n });\n\n return Jwts.claims(map);\n } catch (IOException e) {\n throw new AuthenticationException(String.format(\"Failed to get Claims for token: %s\", token), e);\n }\n }\n}\n<|endoftext|>"} {"language": "java", "text": ",data.value});\n\t\t}\n\t}\n\n\t\n\t@Override\n\tpublic Date getLastModified(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.modified != null){\n\t\t\tValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);\n\t\t\tDate modified = (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": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.course.assessment.bulk;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipInputStream;\n\nimport org.apache.commons.io.IOUtils;\nimport org.olat.core.gui.UserRequest;\nimport org.olat.core.gui.components.form.flexible.FormItemContainer;\nimport org.olat.core.gui.components.form.flexible.elements.FileElement;\nimport org.olat.core.gui.components.form.flexible.elements.SingleSelection;\nimport org.olat.core.gui.components.form.flexible.elements.TextElement;\nimport<|endoftext|>"} {"language": "java", "text": " if ((languagetoedit == null) || (languagetoedit.equals(\"default\"))) {\n languagetoedit = \"\";\n }\n if (doc.isNew() || (doc.getDefaultLanguage().equals(languagetoedit))) {\n languagetoedit = \"\";\n }\n\n if (languagetoedit.equals(\"\")) {\n // In this case the created document is going to be the default document\n tdoc = doc;\n context.put(\"tdoc\", doc);\n if (doc.isNew()) {\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": "=================================================================\n * PlantUML : a free UML diagram generator\n * ========================================================================\n *\n * (C) Copyright 2009-2023, Arnaud Roques\n *\n * Project Info: http://plantuml.com\n * \n * If you like this project or if you find it useful, you can support us at:\n * \n * http://plantuml.com/patreon (only 1$ per month!)\n * http://plantuml.com/paypal\n * \n * This file is part of PlantUML.\n *\n * PlantUML is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * PlantUML distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n * USA.\n *\n *\n * Original Author: Arnaud Roques\n *\n *\n */\npackage net.sourceforge.plantuml.style;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.EnumMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport net.sourceforge.plantuml.FileSystem;\nimport net.sourceforge.plantuml.LineLocationImpl;\nimport net.sourceforge.plantuml.Log;\nimport net.sourceforge.plantuml.SkinParam;\nim<|endoftext|>"} {"language": "java", "text": "olumnDescriptorTest.class,\n\torg.olat.core.gui.components.table.TableEventTest.class,\n\torg.olat.core.gui.components.table.TableMultiSelectEventTest.class,\n\torg.olat.core.gui.components.table.SorterTest.class,\n\torg.olat.core.commons.chiefcontrollers.ChiefControllerMessageEventTest.class,\n\torg.olat.core.util.vfs.VFSTest.class,\n\torg.olat.core.util.vfs.VFSManagerTest.class,\n\torg.olat.core.util.filter.impl.XSSFilterParamTest.class,\n\torg.olat.core.util.filter.impl.AddBaseURLToMediaRelativeURLFilterTest.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.ImportedToCalendarDAOTest.class,\n\torg.olat.commons.calendar.manager.ICalFileCalendarManagerTest.class,\n\torg.olat.commons.calendar.manager.CalendarUserConfigurationDAOTest.class,\n\torg.olat.commons.lifecycle.LifeCycleManagerTest.class,\n\torg.olat.commons.coordinate.cluster.jms.JMSTest.class,\n\torg.olat.commons.coordinate.cluster.lock.LockTest.class,\n\torg.olat.commons.coordinate.CoordinatorTest.class,\n\torg.olat.core.commons.modules.glossary.GlossaryItemManagerTest.class,\n\torg.olat.core.commons.services.csp.manager.CSPM<|endoftext|>"} {"language": "java", "text": "ce 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.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.sendDownstreamPacket(commandBlockPacket);\n } else {\n ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket(\n (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(),\n command, outputTracked\n );\n session.sendDownstreamPacket(commandMinecartPacket);\n }\n }\n}\n<|endoftext|>"} {"language": "java", "text": "hrows IOException {\n if (DEBUG_BUFFER) { \n fCurrentEntity.debugBufferIfNeeded(\"(scanPI: \");\n }\n if (fReportErrors) {\n fErrorReporter.reportWarning(\"HTML1008\", null);\n }\n\n // scan processing instruction\n String target = scanName(true);\n if (target != null && !target.equalsIgnoreCase(\"xml\")) {\n while (true) {\n int c = fCurrentEntity.read();\n 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 fEndColumnNumber = fCurrentEntity.getColumnNumber();\n fEndCharacterOffset = fCurrentEntity.getCharacterOffset();\n fDocumentHandler.processingInstruction(target, data, locationAugs());\n }\n }\n\n // scan xml/text declaration\n else {\n int beginLineNumber = fBeginLineNumber;\n int beginColumnNumber = fBeginColumnNumber;\n int beginCharacterOffset = fBeginCharacterOffset;\n <|endoftext|>"} {"language": "java", "text": "/*\n * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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": "right (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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(pa<|endoftext|>"} {"language": "java", "text": "ROM,\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.Hand;\nimport com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;\nimport com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;\nimport com.github.steveice10.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.ATTACK, Hand.MAIN_HAND, session.isSneaking());\n session.sendDownstreamPacket(attackPacket);\n break;\n case LEAVE_VEHICLE:\n ClientPlayerStatePacket sneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SNEAKING);\n session.sendDownstreamPacket(sneakPacket);\n session.setRidingVehicleEntity(null);\n break;\n case MOUSEOVER:\n // Handle the butt<|endoftext|>"} {"language": "java", "text": "mpliance with the License.
\n * You may obtain a copy of the License at the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * 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": "Source;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\nimport org.xml.sax.helpers.DefaultHandler;\n\n/**\n * Implementation of the TicketValidator that will validate Service Tickets in compliance with the CAS 2.\n *\n * @author Scott Battaglia\n * @since 3.1\n */\npublic class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTicketValidator {\n\n /** The CAS 2.0 protocol proxy callback url. */\n private String proxyCallbackUrl;\n\n /** The storage location of the proxy 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 attributes = extractCustomAttributes(response);\n if (CommonUtils.isNotBlank(proxyGrantingTicket)) {\n final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes,\n proxyGrantingTicket, this.proxyRetriever);\n assertion = new AssertionImpl(attributePrincipal);\n } else {\n assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes));\n }\n\n customParseResponse(response,<|endoftext|>"} {"language": "java", "text": "t();\n final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase();\n if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) {\n continue;\n }\n\n // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE\n if (aName.equals(HttpHeaderNames.TE)) {\n toHttp2HeadersFilterTE(entry, out);\n continue;\n }\n\n // Cookies 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 {@link HttpHeaderNames#TE} header according to the\n * special rules in the HTTP/2 RFC.\n * @param entry An entry whose name is {@link HttpHeaderNames#TE}.\n * @param out the resulting HTTP/2 headers.\n */\n private static void toHttp2HeadersFilterTE(Entry entry,\n HttpHeadersBuilder out) {\n if (AsciiString.indexOf(entry.getValue(), ',', 0<|endoftext|>"} {"language": "java", "text": "MaterialConfig hgMaterialConfig = hg(\"http://example.com\", null);\n hgMaterialConfig.setUserName(\"bob\");\n hgMaterialConfig.setPassword(\"badger\");\n\n hgMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull();\n }\n\n @Test\n void shouldEnsureBranchIsNotProvidedInBothUrlAsWellAsAttributes() {\n HgMaterialConfig hgMaterialConfig = hg(\"http://bob:pass@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 .isEqualTo(\"Encrypted password value for HgMaterial with url 'http://example.com' is invalid. This usually happens when the cipher text is modified to have an invalid value.\");\n }\n }\n\n private ValidationContext mockValidationContextForSecretParams(SecretConfig... secretConfigs) {\n final ValidationContext validationContext = mock(ValidationContext.class);\n final CruiseConfig cruiseConfig = mock(CruiseConfig.class);\n when(validationContext.getCruiseConfig()).thenReturn(cr<|endoftext|>"} {"language": "java", "text": "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.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 attributesPacket.setAttributes(Collections.singletonList(attribute));\n } else {\n attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0)));\n }\n\n session.getConnector().getGeneralThreadPool().schedule(\n () -> session.sendUpstreamPacket(attributesPacket),\n 500, TimeUnit.MILLISECONDS);\n }\n}\n<|endoftext|>"} {"language": "java", "text": "ent resource : viewRoot.getComponentResources(context)) {\n String name = (String) resource.getAttributes().get(\"name\");\n String library = (String) resource.getAttributes().get(\"library\");\n\n if (resource.getChildCount() == 0 \n && resourceHandler.getRendererTypeForResourceName(name) != null \n && !resourceHandler.isResourceRendered(context, name, library)) \n {\n if (!updateStarted) {\n writer.startUpdate(\"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 responseWriter =\n ctx.getRenderKit().createResponseWriter(out,\n RIConstants.TEXT_XML_CONTENT_TYPE, encoding);\n } else {\n RenderKitFactory factory = (RenderKitFactory)\n FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);\n RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT);\n responseWriter = renderKit.createResponseWriter(out, RIConstants.TE<|endoftext|>"} {"language": "java", "text": "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 */\npackage com.xpn.xwiki.internal.skin;\n\nimport java.net.URL;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\nimport org.apache.commons.configuration2.BaseConfiguration;\nimport org.apache.commons.configuration2.Configuration;\nimport org.apache.commons.configuration2.builder.fluent.Configurations;\nimport org.apache.commons.configuration2.ex.ConfigurationException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.xwiki.filter.input.InputSource;\nimport org.xwiki.skin.Resource;\nimport org.xwiki.skin.Skin;\n\nimport static org.apache.commons.lang3.exception.ExceptionUtils.getRootCauseMessage;\n\n/**\n * Common abstract class for the skins that manipulate resources.\n *\n * @version $Id$\n * @since 13.8RC1\n */\npublic abstract class AbstractResourceSkin extends AbstractSkin\n{\n protected static<|endoftext|>"} {"language": "java", "text": " 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.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": " int UC_CPU_ARM_1176 = 5;\n public static final int UC_CPU_ARM_11MPCORE = 6;\n public static final int UC_CPU_ARM_CORTEX_M0 = 7;\n public static final int UC_CPU_ARM_CORTEX_M3 = 8;\n public static final int UC_CPU_ARM_CORTEX_M4 = 9;\n public static final int UC_CPU_ARM_CORTEX_M7 = 10;\n public static final int UC_CPU_ARM_CORTEX_M33 = 11;\n public static final int UC_CPU_ARM_CORTEX_R5 = 12;\n public static final int UC_CPU_ARM_CORTEX_R5F = 13;\n public static final int UC_CPU_ARM_CORTEX_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 final int UC_ARM_REG_D9 = 23;\n public static final int UC_ARM_REG_D10 = 24;\n public static final int UC_ARM_REG_D11 = 25;\n public static final int UC_ARM_REG_D12 = 26;\n public static final int UC_ARM_REG_D13 = 27;\n public static final int UC_ARM_REG_D14 = 28;\n public static final int UC_ARM_REG_D15 = 29;\n public static final int UC_ARM_REG_D16 = 30;\n public static final int UC_ARM_REG_D17 = 31;\n public static final int UC_ARM_REG_D18 = 32;\n public static final int UC_ARM_RE<|endoftext|>"} {"language": "java", "text": " LOGGER.debug(\"Failed to decode HTTP request.\", nettyRequest.decoderResult().cause());\n sendError(ctx, HttpResponseStatus.BAD_REQUEST);\n return;\n }\n\n Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers());\n\n //Find the content length we will use this as an indicator of a body\n Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L);\n String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING);\n\n //If there is a content 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 = new StringBuilder();\n description\n .append(\"No response sent for \")\n .append(request.getMethod().getName())\n .append(\" request to \")\n .append(request.getUri());\n\n if (lastHandler != null) {\n description.append(\" (last handler: \");\n\n if (lastHandler instanceof DescribingHandler) {\n ((DescribingHandler) lastHandler).describeTo(description);\n } else {\n DescribingHandlers.describeTo(lastHandler, des<|endoftext|>"} {"language": "java", "text": "deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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": "oftware 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.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": "right 2003-2006 Rick Knowles \n * Distributed under the terms of either:\n * - the common development and distribution license (CDDL), v1.0; or\n * - the GNU Lesser General Public License, v2.1 or later\n */\npackage winstone;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.util.Date;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServlet;\n\n/**\n * A simple servlet that writes out the body of the error \n * \n * @author 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<|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2012 JBoss 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 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<|endoftext|>"} {"language": "java", "text": "right (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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 <|endoftext|>"} {"language": "java", "text": "R 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.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack;\nimport com.github.steveice10.mc.protocol.packet.ingame.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 break;\n }\n // Called whenever a page is modified\n case REPLACE_PAGE: {\n if (page < pages.size()) {\n pages.set(page, new StringTag(\"\", packet.getText()));\n } else {\n // Add empty pages in between\n for (int i = pages.size(); i < page; i++) {\n pages.add(i, new StringTag(\"\", \"\"));\n <|endoftext|>"} {"language": "java", "text": "MIT License\n *\n * Copyright (c) 2004-2010, Sun Microsystems, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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 */\npackage hudson.cli;\n\nimport hudson.model.ModifiableItemGroup;\nimport hudson.model.TopLevelItem;\nimport jenkins.model.Jenkins;\nimport hudson.Extension;\nimport hudson.model.Item;\nimport jenkins.model.ModifiableTopLevelItemGroup;\nimport org.kohsuke.args4j.Argument;\n\n/**\n * Creates a new job by reading stdin as a configuration XML file.\n * \n * @author Kohsuke Kawaguchi\n */\n@Extension\npublic class CreateJobCommand extends CLICommand {\n @Override\n public String getShortDescription() {\n return Messages.CreateJobCommand_ShortDescription();\n <|endoftext|>"} {"language": "java", "text": "eContext _cborContext;\n \n /*\n /**********************************************************\n /* Output buffering\n /**********************************************************\n */\n\n\t/**\n * Intermediate buffer in which contents are buffered before being written\n * using {@link #_out}.\n */\n protected byte[] _outputBuffer;\n\n /**\n * Pointer to the next available byte in {@link #_outputBuffer}\n */\n protected int _outputTail = 0;\n\n /**\n * Offset to index 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 _formatFeatures = formatFeatures;\n _cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures);\n _ioContext = ctxt;\n _out = out;\n _bufferRecyclable = true;\n _outputBuffer = ctxt.allocWriteEncodingBuffer(BYTE_BUFFER_FOR_OUTPUT);\n _outputEnd = _outputBuffer.length;\n _charBuffer = ctxt.allocConcatBuffer();\n _charBufferLength = _charBuffer.length;\n // let's just sanity check to prevent nasty odd errors\n if (_outputEn<|endoftext|>"} {"language": "java", "text": "mpliance with\n * the License. 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 distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\npackage org.hyperledger.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": " 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.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": "sponse.JsonRpcResponse;\nimport org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;\nimport org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;\n\nimport java.util.List;\n\nimport org.assertj.core.api.Assertions;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.junit.MockitoJUnitRunner;\n\n@RunWith(MockitoJUnitRunner.class)\npublic class NetListeningTest {\n\n private NetListening method;\n\n @Mock 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": "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.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 }\n }\n }\n }\n\n private void playEmote(GeyserSession otherSession, long javaId, String emoteId) {\n Entity otherEntity = otherSession.getEntityCache().getEntityByJavaId(javaId); // Must be ran on same thread\n if (otherEntity == null) return;\n EmotePacket otherEmotePacket = new EmotePacket();\n otherEmotePacket.setEmoteId(emoteId);\n otherEmotePacket.setRuntimeEntityId(otherEntity.getGeyserId());\n otherSession.sendUpstreamPacket(otherEmo<|endoftext|>"} {"language": "java", "text": "file) {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db;\n try {\n db = dbf.newDocumentBuilder();\n } catch (Exception e) {\n throw new RuntimeException(\"Error creating XML parser\");\n }\n\n try {\n return db.parse(cfgfile);\n } catch (Exception e) {\n throw new RuntimeException(\"Error parsing pgraster config\", e);\n }\n }\n\n PGRasterConfig(File configFile) {\n 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(source::setPassword);\n\n first(db, \"pool\")\n .ifPresent(\n p -> {\n first(p, \"min\")\n .map(this::nodeValue)\n .map(Integer::parseInt)\n .ifPresent(source::setMinIdle);\n first(p, \"max\")\n .map(this::nodeValue)\n <|endoftext|>"} {"language": "java", "text": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.modules.dcompensation.manager;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.olat.basesecurity.IdentityImpl;\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, stephan<|endoftext|>"} {"language": "java", "text": "ce();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);\n\t\t\tlog.log(Level.SEVERE,\n\t\t\t\t\t\"proxy request with invalid URL parameter: url=\"\n\t\t\t\t\t\t\t+ ((urlParam != null) ? urlParam : \"[null]\"));\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically generated CORS header for known domains.\n\t * @throws IOException \n\t */\n\tprotected void copyResponse(InputStream is, OutputStream out, byte[] head,\n\t\t\tboolean base64) throws IOException\n\t{\n\t\tif (base64)\n\t\t{\n\t\t\ttry (BufferedInputStream in = new BufferedInputStream(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/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.29.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.30.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"172.31.\") // 172.16.0.0/12\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"192.0.0.\") // 192.0.0.0/24\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"192.168.\") // 192.168.0.0/16\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"198.18.\") // 198.18.0.0/15\n\t\t\t\t\t\t&& !hostAddress.startsWith(\"198.19.\") // 198.18.0.0/15\n\t\t\t\t\t\t&& !host.endsWith(\".arpa\"); // reverse domain (needed?)\n\t\t\t}<|endoftext|>"} {"language": "java", "text": "le(LoginPacket loginPacket) {\n BedrockPacketCodec packetCodec = BedrockProtocol.getBedrockCodec(loginPacket.getProtocolVersion());\n if (packetCodec == null) {\n String supportedVersions = BedrockProtocol.getAllSupportedVersions();\n if (loginPacket.getProtocolVersion() > BedrockProtocol.DEFAULT_BEDROCK_CODEC.getProtocolVersion()) {\n // Too early to determine session locale\n session.getConnector().getLogger().info(LanguageUtils.getLocaleStringLog(\"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.getLocaleStringLog(\"geyser.network.connect\", session.getAuthData().getName()));\n break;\n\n case SEND_PACKS:\n for(String id : packet.getPackIds()) {\n ResourcePackDataInfoPacket data = new ResourcePackDataInfoPacket();\n String[] packID = id.split(\"_\");\n ResourcePack pack = ResourcePack.PACKS.get(packID[0]);\n ResourcePackManifest.Header header = pack.getManifest().getHeader();\n\n <|endoftext|>"} {"language": "java", "text": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.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\tDiscoveryIm<|endoftext|>"} {"language": "java", "text": "where(from).eq(ExtendEntity.class);\n\t\tQuery select = select(from);\n\t\tassertEquals(\n\t\t\t\t\"select entity_0 from Entity entity_0 where entity_0.class = ExtendEntity\",\n\t\t\t\tselect.getQuery());\n\t\tassertTrue(select.getParameters().isEmpty());\n\t}\n\n\t/**\n\t *

testBetweenCondition.

\n\t */\n\t@Test\n\tpublic void testBetweenCondition() {\n\t\tEntity from = from(Entity.class);\n\t\twhere(from.getCode()).between(\"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 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 testAndMultipleOnGoingLogicalConditions2() {\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(and(Arrays.asList(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 ) and ( entity_0.code = :code_2 ) )\",\n\t\t\t\tselect.getQuery());\n<|endoftext|>"} {"language": "java", "text": "til.logging.Logger;\n\n/**\n * Monitors a UDP multicast broadcast and respond with the location of the Hudson service.\n *\n *

\n * Useful for auto-discovery of Hudson in the network.\n *\n * @author Kohsuke Kawaguchi\n */\npublic class UDPBroadcastThread extends Thread {\n private final Jenkins jenkins;\n\n public final OneShotEvent ready = new OneShotEvent();\n private MulticastSocket mcs;\n private boolean shutdown;\n\n /**\n * @deprecated as of 1.416\n * Use {@link #UDPBroadcastThread(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(\"');\n }\n\n public void shutdown() {\n shutdown = true;\n mcs.close();\n interrupt();\n }\n\n public static final int PORT = Integer.getInteger(\"hudson.udp\",33848);\n\n private static final Logger LOGGER = Logger.getLogger(UDPBroadcastThread.class.getName());\n\n /**\n * Multicast socket address.\n */\n public static InetAddress MULTICAST;\n\n static {\n try {\n MULTICAST = InetAddress.getByAddress(new byte[]{(byte)239, (byte)77, (byte)124<|endoftext|>"} {"language": "java", "text": "tic final String TEXT = \"Text\";\n\t\n\tpublic static final String DATE = \"Date\";\n\t\n\tpublic static final String SECRET = \"Secret\";\n\t\n\tpublic static final String NUMBER = \"Number\";\n\t\n\tpublic static final String COMMIT = \"Commit\";\n\t\n\tpublic static final String ENUMERATION = \"Enumeration\";\n\t\n\tpublic static final String USER = \"User\";\n\t\n\tpublic static final String GROUP = \"Group\";\n\t\n\tpublic static final String ISSUE = \"Issue\";\n\t\n\tpublic static final String BUILD = \"Build\";\n\n\tpublic static final String PULLREQUEST = \"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=\\\"\" + escape(name) + \n\t\t\t\t\t\"\\\", order=\" + index + \")\\n\");\n\t\t}\n\t\tif (showCondition != null) \n\t\t\tbuffer.append(\" @ShowCondition(\\\"isInput\" + index + \"Visible\\\")\\n\");\n\t}\n\n\tprivate void wrapWithChildContext(StringBuffer buffer, int index, String statement) {\n\t\tbuffer.append(\" ComponentContext context = ComponentContext.get();\\n\");\n\t\tbuffer.append(\" if (context != null) {\\n\");\n\t\tbuffer.append(\" ComponentContext childContext = context.getChildContext(\\\"input\" + index +<|endoftext|>"} {"language": "java", "text": "right (c) 2019-2021 GeyserMC. http://geysermc.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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.ut<|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2021 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 */\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 @Override\n public String forCommandLine() {\n return this.url;\n }\n\n protected String sanitizeUrl() {\n return this.url;\n }\n\n\n public static UrlArgument create(String url) {\n return new UrlArgument(url);\n }\n\n @Override\n public String replaceSecretInfo(String line) {\n if (StringUtils.isBlank(line)) {\n return line;\n }\n\n if (isBlank(this.url)) {\n return line;\n }\n\n try {\n final URIBuilder uriBui<|endoftext|>"} {"language": "java", "text": "g.bouncycastle.pqc.jcajce.provider.xmss;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\n\nimport org.bouncycastle.asn1.ASN1ObjectIdentifier;\nimport org.bouncycastle.asn1.pkcs.PrivateKeyInfo;\nimport org.bouncycastle.asn1.x509.AlgorithmIdentifier;\nimport org.bouncycastle.crypto.CipherParameters;\nimport org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;\nimport org.bouncycastle.pqc.asn1.XMSSMTKeyParams;\nimport org.bouncycastle.pqc.asn1.XMSSMTPrivateKey;\nimport org.bouncycastle.pqc.asn1.XMSSPrivateKey;\nimport org.bouncycastle.pqc.crypto.xmss.BDSStateMap;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSUtil;\nimport org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey;\nimport org.bouncycastle.util.Arrays;\n\npublic class BCXMSSMTPrivateKey\n implements PrivateKey, XMSSMTKey\n{\n private final ASN1ObjectIdentifier treeDigest;\n private final XMSSMTPrivateKeyParameters keyParams;\n\n public BCXMSSMTPrivateKey(\n ASN1ObjectIdentifier treeDigest,\n XMSSMTPrivateKeyParameters keyParams)\n {\n this.treeDigest = treeDigest;\n this.keyParams = keyParams;\n }\n\n public BCXMSSMTPrivateKey(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 XMSSMTPrivateKeyParamet<|endoftext|>"} {"language": "java", "text": "ftware\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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": "roject) job;\n for (AbstractBuild build : p.getBuilds()) {\n for (Entry entry : build.getChangeSet()) {\n User user = entry.getAuthor();\n if(user!=null)\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n }\n\n /**\n * Variant of {@link 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.resolve(user, iconSize);\n synchronized (this) {\n users.put(user, userInfo);\n modified.add(user);\n }\n } else if (info.getLastChange().before(build.getTimestamp())) {\n synchronized (this) {\n info.project = p;\n <|endoftext|>"} {"language": "java", "text": "\n// From Philippe Le Hegaret (Philippe.Le_Hegaret@sophia.inria.fr)\n//\n// (c) COPYRIGHT MIT and INRIA, 1997.\n// Please first read the full copyright statement in file COPYRIGHT.html\n\npackage org.w3c.css.css;\n\nimport org.w3c.css.atrules.css.AtRuleMedia;\nimport org.w3c.css.atrules.css.AtRulePage;\nimport org.w3c.css.parser.AtRule;\nimport org.w3c.css.parser.CssError;\nimport org.w3c.css.parser.CssFouffa;\nimport org.w3c.css.parser.CssParseException;\nimport org.w3c.css.parser.CssSelectors;\nimport org.w3c.css.parser.CssValidatorListener;\nimport org.w3c.css.parser.Errors;\nimport org.w3c.css.parser.analyzer.ParseException;\nimport org.w3c.css.parser.analyzer.TokenMgrError;\nimport org.w3c.css.properties.css.CssProperty;\nimport org.w3c.css.selectors.IdSelector;\nimport org.w3c.css.util.ApplContext;\nimport org.w3c.css.util.CssVersion;\nimport org.w3c.css.util.InvalidParamException;\nimport org.w3c.css.util.Messages;\nimport org.w3c.css.util.Util;\nimport org.w3c.css.util.Warning;\nimport org.w3c.css.util.Warnings;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Constructor;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\n/**\n * @version $Revision$\n */\npublic final class StyleSheetParser\n implements CssValidatorListener, CssParser {\n\n private static Constructor co = null;\n\n static {\n try {\n Class c = java.lang.Exception.class;\n Class cp[] = {java.lang.Exception.class};\n co = c.getDeclaredConstructor(cp);\n <|endoftext|>"} {"language": "java", "text": "mport org.geysermc.connector.entity.CommandBlockMinecartEntity;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.ItemFrameEntity;\nimport org.geysermc.connector.entity.type.EntityType;\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;\nimport org.geysermc.connector.network.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 dropAll ? PlayerAction.DROP_ITEM_STACK : PlayerAction.DROP_ITEM,\n BlockUtils.POSITION_ZERO,\n BlockFace.DOWN\n );\n session.sendDownstreamPacket(dropAllPacket);\n\n if (dropAll) {\n session.getPlayerInventory().setItemInHand(GeyserItemStack.EMPTY);\n } else {\n session.getPlayerI<|endoftext|>"} {"language": "java", "text": "e without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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": "right (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v. 2.0, which is available at\n * http://www.eclipse.org/legal/epl-2.0.\n *\n * This Source Code may also be made available under the following Secondary\n * Licenses when the conditions for such availability set forth in the\n * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,\n * version 2 with the GNU Classpath Exception, which is available at\n * https://www.gnu.org/software/classpath/license.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0\n */\n\npackage com.sun.faces.application.resource;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.MissingResourceException;\nimport java.util.ResourceBundle;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\nimport java.util.stream.Stream;\n\nimport javax.faces.application.ProjectStage;\nimport javax.faces.application.ResourceHandler;\nimport javax.faces.application.ResourceVisitOption;\nimport javax.faces.component.UIViewRoot;\nimport javax.faces.context.FacesContext;\n\nimport com.sun.faces.config.WebConfiguration;\nimport com.sun.faces.util.FacesLogger;\nimport com.sun.faces.util.Util;\n\n/**\n * This class is used to lookup {@link ResourceInfo} instances\n * and cache any that are successfully looked up to reduce the\n <|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2019 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * https://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, 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 assertEquals(0, region.transferred());\n assertEquals(data.length, region.transferTo(channel, 0));\n assertEquals(data.length, region.count());\n assertEquals(data.length, region.transferred());\n assertArrayEquals(data, outputStream.toByteArray());\n } finally {\n channel.close();\n }\n }\n\n @Test\n public void testTruncated() throws IOException {\n File file = newFile();\n ByteArrayOutputStream outputStream =<|endoftext|>"} {"language": "java", "text": "right 2021 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 */\npackage com.thoughtworks.go.config.materials.tfs;\n\nimport com.thoughtworks.go.config.*;\nimport com.thoughtworks.go.config.materials.Filter;\nimport com.thoughtworks.go.config.materials.IgnoredFiles;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.domain.materials.MaterialConfig;\nimport com.thoughtworks.go.security.CryptoException;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static com.thoughtworks.go.config.materials.AbstractMaterialConfig.MATERIAL_NAME;\nimport static com.thoughtworks.go.config.materials.ScmMaterialConfig.FOLDER;\nimport static com.thoughtworks.go.config.materials.ScmMaterialConfig.URL;\nimport static com.thoughtworks.go.helper.MaterialConfigsMother.tfs;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.co<|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 InvalidMediaExtensionException extends InvalidExtensionException\n {\n private static final long serialVersionUID = 1L;\n\n public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)\n {\n super(allowedExtension, extension, filename);\n }\n }\n \n public static class InvalidVideoExtensionException extends InvalidExtensionException\n {\n private static final long serialVersionUID = 1L;\n\n public InvalidVideoExtens<|endoftext|>"} {"language": "java", "text": "antial 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.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 advancementsCache.getStoredAdvancements().remove(advancement.getId());\n }\n }\n }\n\n /**\n * Handle all advancements progress updates\n */\n public void sendToolbarAdvancementUpdates(GeyserSession session, ServerAdvancementsPacket packet) {\n if (packet.isReset()) {\n // Advancements are being cleared, so they can't be granted\n return;\n }\n for (Map.Entry> progress : packet.getProgress(<|endoftext|>"} {"language": "java", "text": "right ConsenSys AG.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n * the License. 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 distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\npackage org.hyperledger.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.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 : UInt25<|endoftext|>"} {"language": "java", "text": "r>\n * See the License for the specific language governing permissions and
\n * limitations under the License.\n *

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

\n */\npackage org.olat.restapi.support;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\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 getLongValue(String key) {\n\t\tString value = fields.get(key);\n\t\tif (value == null) { return null; }\n\t\ttry {\n\t\t\treturn Long.parseLong(value);\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic Integer getIntegerValue(String key) {\n\t\tString value = fields.get(key);\n\t\tif (value == null) { return null; }\n\t\ttry {\n\t\t\treturn Integer.parseInt(value);\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic File getFile() {\n\t\treturn file;\n\t}\n\n\tpublic void close() {\n\t\tif (fil<|endoftext|>"} {"language": "java", "text": "pyright 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.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 }\n }\n return;\n }\n\n InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());\n }\n}\n<|endoftext|>"} {"language": "java", "text": "DED \"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.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": "ate;\n\nimport org.checkerframework.checker.initialization.qual.UnderInitialization;\nimport org.checkerframework.checker.nullness.qual.Nullable;\n\nimport java.io.Console;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.security.GeneralSecurityException;\nimport java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.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) LibPQFactory this,\n String sslkeyfile, Properties info) throws PSQLException {\n km = new PKCS12KeyManager(sslkeyfile, getCallbackHandler(info));\n }\n\n /**\n * @param info the connection parameters The following parameters are used:\n * sslmode,sslcert,sslkey,sslrootcert,sslhostnameverifier,sslpasswordcallback,sslpassword\n * @throws PSQLException if security error appears when initializing factory\n */\n public LibPQFactory(Properties info) throws PSQLException {\n try {\n S<|endoftext|>"} {"language": "java", "text": "s\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.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": " \"false\"};\n private static final String[] VALID_COLORS;\n private static final String[] VALID_SCOREBOARD_SLOTS;\n\n private static final Hash.Strategy PARAM_STRATEGY = new Hash.Strategy() {\n @Override\n public int hashCode(CommandParamData[][] o) {\n return Arrays.deepHashCode(o);\n }\n\n @Override\n public boolean equals(CommandParamData[][] a, CommandParamData[][] b) {\n if (a == b) return true;\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 all commands\n for (int nodeIndex : rootNode.getChildIndices()) {\n CommandNode node = nodes[nodeIndex];\n\n // Make sure we don't have duplicated commands (happens if there is more than 1 root node)\n if (!commandNodes.add(nodeIndex) || !knownAliases.add(node.getName().toLowerCase())) continue;\n\n // Get and update the commandArgs list with the found arguments\n if (node.getChildIndices().length >= 1) {\n for (int childIndex : <|endoftext|>"} {"language": "java", "text": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.core.util.mail.ui;\n\nimport java.io.File;\nimport java.text.DecimalFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.olat.basesecurity.BaseSecurity;\nimport org.olat.basesecurity.events.SingleIdentityChosenEvent;\nimport org.olat.core.CoreSpringFactory;\nimport org.olat.core.commons.modules.bc.FileSelection;\nimport org.olat.core.commons.modules.bc.FolderConfig;\nimport org.olat.core.commons.modules.bc.commands.CmdSendMail;\nimport org.olat.core.commons.modules.bc.commands.FolderCommand;\nimport org.olat.core.commons.modules.bc.commands.FolderCommandHelper;\nimport org.olat.core.commons.modules.bc.commands.FolderCommandStatus;\nimport org.olat.core.commons.modules.bc.components.FolderComponent;\nimport org.olat.core.commons.modules.bc.meta.MetaInfoController;\nimport org.olat.co<|endoftext|>"} {"language": "java", "text": "\nimport javax.jmdns.ServiceInfo;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.Callable;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\n/**\n * Registers a DNS multi-cast service-discovery support.\n *\n * @author Kohsuke Kawaguchi\n */\npublic class DNSMultiCast implements Closeable {\n private JmDNS jmdns;\n\n public DNSMultiCast(final Jenkins jenkins) {\n if (disabled) 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 }\n });\n }\n\n public void close() {\n if (jmdns!=null) {\n// try {\n jmdns.abort();\n jmdns = null;\n// } catch (final IOException e) {\n// LOGGER.log(Level.WARNING,\"Failed to close down JmDNS instance!\",e);\n// }\n }\n }\n\n private static final Logger LOGGER = Logger.getLogger(DNSMultiCast.class.getName());\n\n public static boolean disabled = Boolean.getBoolean(DNSMultiCast.class.getName()+<|endoftext|>"} {"language": "java", "text": "arameters;\nimport org.xwiki.crypto.pkix.params.x509certificate.X509CertificateParameters;\nimport org.xwiki.crypto.pkix.params.x509certificate.X509CertifiedPublicKey;\nimport org.xwiki.crypto.pkix.params.x509certificate.extension.ExtendedKeyUsages;\nimport org.xwiki.crypto.pkix.params.x509certificate.extension.KeyUsage;\nimport org.xwiki.crypto.pkix.params.x509certificate.extension.X509DnsName;\nimport org.xwiki.crypto.pkix.params.x509certificate.extension.X509GeneralName;\nimport org.xwiki.crypto.pkix.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 strength is 2.\n *\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 * @param strength the strength in bytes.\n * @return an new asymmetric key pair.\n */\n public AsymmetricKeyPair generateKeyPair(int strength)\n {\n return keyPairGenerator.generate(new RSAKeyGenerationParameters(strength));\n }\n\n /**\n * Build<|endoftext|>"} {"language": "java", "text": "and\n * limitations under the License.\n */\n\nimport javax.management.ObjectName;\n\nimport org.jolokia.util.HttpMethod;\nimport org.jolokia.util.RequestType;\n\n/**\n * Base restrictor which alway returns the constant given\n * at construction time\n *\n * @author roland\n * @since 06.10.11\n */\npublic abstract class AbstractConstantRestrictor implements Restrictor {\n\n private boolean isAllowed;\n\n /**\n * Create restrictor which always returns the given value on every check\n * method.\n *\n * @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": "ensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.apache.cxf.transport.https;\n\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.net.HttpURLConnection;\nimport java.net.Proxy;\nimport java.net.URL;\nimport java.security.GeneralSecurityException;\nimport java.util.logging.Handler;\nimport java.util.logging.Logger;\n\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.HttpsURLConnection;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocketFactory;\n\nimport org.apache.cxf.common.logging.LogUtils;\nimport org.apache.cxf.common.util.ReflectionInvokationHandler;\nimport org.apache.cxf.common.util.ReflectionUtil;\nimport org.apache.cxf.configuration.jsse.SSLUtils;\nimport org.apache.cxf.configuration.jsse.TLSClientParameters;\n\n\n/**\n * This HttpsURLConnectionFactory implements the HttpURLConnectionFactory\n * for using the given<|endoftext|>"} {"language": "java", "text": "t.core.gui.UserRequest;\nimport org.olat.core.gui.components.Component;\nimport org.olat.core.gui.control.Controller;\nimport org.olat.core.gui.control.Event;\nimport org.olat.core.gui.control.WindowControl;\nimport org.olat.core.gui.control.controller.BasicController;\nimport org.olat.core.gui.control.generic.modal.DialogBoxController;\nimport org.olat.core.gui.translator.Translator;\nimport org.olat.core.id.Identity;\nimport org.olat.core.logging.AssertException;\nimport org.olat.core.util.StringHelper;\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, 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\treturn null;\n\t\t}\n\t\t\n\t\tVFSItem currentVfsItem = null;\n\t\ttry {\n\t\t\tboolean fileNotExist = false;\n\t\t\tfor (String sItem:selection.getFiles()) {\n\t\t\t\tcurrentVfsItem = currentContainer.resolve(sItem);\n\t\t\t\tif (currentVfsItem instanceof VFSLeaf) {\n\t\t\t\t\tif (!doUnzip((VFSLeaf)currentVfsItem, curre<|endoftext|>"} {"language": "java", "text": " - Online Learning and Training
\n* http://www.olat.org\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,
\n* software 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* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
\n* University of Zurich, Switzerland.\n*


\n* \n* OpenOLAT - Online Learning and Training
\n* This file has been modified by the OpenOLAT community. Changes are licensed\n* under the Apache 2.0 license as the original file. \n*

\n*/ \n\npackage org.olat.core.commons.modules.bc.commands;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport org.olat.core.CoreSpringFactory;\nimport org.olat.core.commons.modules.bc.FileSelection;\nimport org.olat.core.commons.modules.bc.FolderEvent;\nimport org.olat.core.commons.modules.bc.components.FolderComponent;\nimport org.olat.core.commons.services.vfs.VFSVersionModule;\nimport org.olat.core.gui.UserRequest;\nimport org.olat.core.gui.components.Component;\nimport org.olat.core.gui.control.Controller;\nimport org.olat.core.gui.control.Event;\nimport org.olat.core.gui.control.WindowControl;\nimport org.olat.core.gui.control.controller.BasicController;\nimport org.ola<|endoftext|>"} {"language": "java", "text": "fy, merge, publish, distribute, sublicense, and/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.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": " = new ParcelUuid(new UUID(0, 0));\n mType = type;\n mAuth = auth;\n mEncrypt = encrypt;\n mDevice = device;\n mPort = port;\n mFd = fd;\n\n mSocketState = SocketState.INIT;\n\n if (device == null) {\n // Server socket\n mAddress = BluetoothAdapter.getDefaultAdapter().getAddress();\n } else {\n // Remote socket\n mAddress = device.getAddress();\n }\n mInputStream = new BluetoothInputStream(this);\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, encrypt, new BluetoothDevice(address), port, null);\n }\n\n /** @hide */\n @Override\n protected void finalize() throws Throwable {\n try {\n close();\n } finally {\n super.finalize();\n }\n }\n private int getSecurityFlags() {\n int flags = 0;\n if(mAuth)\n flags |= SEC_FLAG_AUTH;\n if(mEncrypt)\n flags |= SEC_FLAG_ENCRYPT;\n return flags;\n }\n\n /**\n * Get the remote device this socket is co<|endoftext|>"} {"language": "java", "text": "nd 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.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": "XEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n\npackage jodd.json;\n\nimport jodd.introspector.ClassDescriptor;\nimport jodd.introspector.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\tClassDescriptor cd = ClassIntrospector.get().lookup(targetType);\n\n\t\tCtorDescriptor ctorDescriptor = cd.getDefaultCtorDescriptor(true);\n\t\tif (ctorDescriptor == null) {\n\t\t\tthrow new JsonException(\"Default ctor not found for: \" + targetType.getName());\n\t\t}\n\n\t\ttry {\n//\t\t\treturn ClassUtil.newInstance(targetType);\n\t\t\treturn ctorDescriptor.getConstructor().newInstance();\n\t\t} catch (Exception e) {\n\t\t\tthrow new JsonException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Injects value into the targets property.\n\t */\n\tprotected void in<|endoftext|>"} {"language": "java", "text": "est.getContextPath()))\n return targetUrl.substring(request.getContextPath().length());\n\n // not sure when this happens, but apparently this happens in some case.\n // see #1274\n return targetUrl;\n }\n\n /**\n * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException)\n */\n @Override\n protected String determineFailureUrl(HttpServletRequest request, AuthenticationException 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": "t 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.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 the width of each character\n // If it goes over the maximum, we need to start a new line to match Java\n int widthCount = 0;\n // This converts the message into the array'd message Java wants\n for (char character : tag.getString(\"Text\").toCharArray()) {\n widthCount += SignUtils.getCharacterWidth(character);\n // If we get a return in Bedrock, or go over the character width max, that signals to use the next line.\n <|endoftext|>"} {"language": "java", "text": "right (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.\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 */\npackage org.ballerinalang.openapi;\n\nimport com.github.jknack.handlebars.Context;\nimport com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Template;\nimport com.github.jknack.handlebars.context.FieldValueResolver;\nimport com.github.jknack.handlebars.context.JavaBeanValueResolver;\nimport com.github.jknack.handlebars.context.MapValueResolver;\nimport com.github.jknack.handlebars.helper.StringHelpers;\nimport com.github.jknack.handlebars.io.ClassPathTemplateLoader;\nimport com.github.jknack.handlebars.io.FileTemplateLoader;\nimport io.swagger.v3.oas.models.OpenAPI;\nimport io.swagger.v3.parser.OpenAPIV3Parser;\nimport org.apache.commons.lang3.StringUtils;\nimport org.ballerinalang.openapi.exception.BallerinaOpenApiException;\nimport org.ballerinalang.openapi.model.BallerinaOpenApi;\nimport org.ballerinalang.openapi.model.GenSrcFile;\nimport org.ballerinalang.openapi.typemodel.BallerinaOpenApiType;\nimport org.ballerinalang.openapi.utils.CodegenUtils;\nimport org.ballerinalang.openapi.utils.GeneratorConstants;\nimport org.ballerinalang.openapi.utils<|endoftext|>"} {"language": "java", "text": "ImmutableMap.builderWithExpectedSize(expectedNumParams);\n }\n\n /**\n * Sets the result type.\n *\n * @param type {@link RoutingResultType#MATCHED} or {@link RoutingResultType#CORS_PREFLIGHT}.\n */\n public RoutingResultBuilder type(RoutingResultType type) {\n requireNonNull(type, \"type\");\n checkArgument(type != RoutingResultType.NOT_MATCHED,\n \"type: %s (expected: %s or %s)\",\n type, RoutingResultType.MATCHED, RoutingResultType.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 return pathParams = ImmutableMap.builder();\n }\n}\n<|endoftext|>"} {"language": "java", "text": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix 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(<|endoftext|>"} {"language": "java", "text": "th 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.domain;\n\nimport com.thoughtworks.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": "efault in memory store.\n *

\n * This method can be used from within a custom {@link Module}.\n *

{@code\n   * import com.google.inject.AbstractModule;\n   * import ratpack.session.SessionModule;\n   *\n   * public class CustomSessionModule extends AbstractModule {\n   *   protected void configure() {\n   *     SessionModule.memoryStore(binder(), c -> c.maximumSize(100));\n   *   }\n   * }\n   * }
\n * }

\n * This method binds the built cache with the {@link #LOCAL_MEMORY_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": "g.bouncycastle.jcajce.provider.symmetric;\n\nimport java.io.IOException;\nimport java.security.AlgorithmParameters;\nimport java.security.InvalidAlgorithmParameterException;\nimport java.security.SecureRandom;\nimport java.security.spec.AlgorithmParameterSpec;\nimport java.security.spec.InvalidParameterSpecException;\n\nimport javax.crypto.spec.IvParameterSpec;\n\nimport org.bouncycastle.asn1.bc.BCObjectIdentifiers;\nimport org.bouncycastle.asn1.cms.CCMParameters;\nimport org.bouncycastle.asn1.cms.GCMParameters;\nimport org.bouncycastle.asn1.nist.NISTObjectIdentifiers;\nimport org.bouncycastle.crypto.BlockCipher;\nimport org.bouncycastle.crypto.BufferedBlockCipher;\nimport org.bouncycastle.crypto.CipherKeyGenerator;\nimport org.bouncycastle.crypto.CipherParameters;\nimport org.bouncycastle.crypto.DataLengthException;\nimport org.bouncycastle.crypto.InvalidCipherTextException;\nimport org.bouncycastle.crypto.Mac;\nimport org.bouncycastle.crypto.engines.AESEngine;\nimport org.bouncycastle.crypto.engines.AESWrapEngine;\nimport org.bouncycastle.crypto.engines.RFC3211WrapEngine;\nimport org.bouncycastle.crypto.engines.RFC5649WrapEngine;\nimport org.bouncycastle.crypto.generators.Poly1305KeyGenerator;\nimport org.bouncycastle.crypto.macs.CMac;\nimport org.bouncycastle.crypto.macs.GMac;\nimport org.bouncycastle.crypto.modes.CBCBlockCipher;\nimport org.bouncycastle.crypto.modes.CCMBlockCipher;\nimport org.bouncycastle.crypto.modes.CFBBlockCipher;\nimport org.bouncycastle.crypto.modes.GCMBlockCipher;\nimport org.bouncycastle.crypto.modes.OFBBlockCipher;\nimport org.bouncycastle.jcajce.provider.config.ConfigurableProvider;\nimport org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameterGenerator;\nimpor<|endoftext|>"} {"language": "java", "text": " 0 (NOT the letter O) in c3p0. It should be placed \" +\n \" in the top level of c3p0's effective classpath.\");\n return;\n }\n }\n }\n }\n\n }\n }\n }\n }\n\n static\n {\n String ls;\n\n try\n { ls = System.getProperty(\"line.separator\", \"\\r\\n\"); }\n catch (Exception 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 namedConfig = extractNamedScopeFromLevel( namedConfigElem );\n configNamesToNamedScopes.put( configName, namedConfig);\n }\n else\n logger.warning(\"Configuration XML contained named-config element without name attribute: \" + namedConfigElem);\n }\n return new C3P0Config( defaults, configNamesToNamedScopes );\n }\n else\n throw new Exception(\"Root element of c3p0 config xml should be 'c3p0-con<|endoftext|>"} {"language": "java", "text": "04 at Multimedia- & E-Learning Services (MELS),
\n* University of Zurich, Switzerland.\n*


\n* \n* OpenOLAT - Online Learning and Training
\n* This file has been modified by the OpenOLAT community. Changes are licensed\n* under the Apache 2.0 license as the original file.\n*/\n\npackage org.olat.course.config.manager;\n\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.Hashtable;\n\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.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 == null) {\n\t\t\t// create new config file\n\t\t\tconfigFile = course.getCourseBaseContainer().createChildLeaf(COURSECONFIG_XML);\n\t\t} else if(configFile.exists() && configFile.canVersion() == VFSConstants.YES) {\n\t\t\ttry(InputStream in = configFile.getInputStream()) {\n\t\t\t\tCoreSpringFactory.getImpl(VFSRepositoryService.class).addVersion(configFile, null, \"\", in);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"Cannot versioned CourseConfig.xml\", e);\n\t\t\t}\n\t\t}\n\t\tXStreamHelper.writeObject(xstream, configFile, courseCo<|endoftext|>"} {"language": "java", "text": "slator.Translator;\nimport org.olat.core.util.Util;\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.VFSLockApplicationType;\nimport org.olat.core.util.vfs.VFSLockManager;\nimport org.olat.core.util.vfs.VFSManager;\nimport org.olat.core.util.vfs.VFSStatus;\nimport org.olat.core.util.vfs.callbacks.VFSSecurityCallback;\nimport org.olat.core.util.vfs.filters.VFSItemFilter;\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() {\n\t\treturn status;\n\t}\n\n\t@Override\n\tpublic boolean runsModal() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic String getModalTitle() {\n\t\treturn null;\n\t}\n\n\tpublic String getTarget() {\n\t\tFolderTreeModel ftm = (FolderTreeModel) selTree.getTreeModel();\n\t\treturn ftm.getSelectedPath(selTree.getSelectedNode());\n\t}\n\n\t@Override\n\tpublic void event(UserRequest ureq, Component source, Event event) {\n\t\tif(cancelButton == source) {\n\t\t\tstatus = FolderCommandStatus.STATUS_CANCELED;\n\t\t\tfireEvent(ureq, FOLDERCOMMAND_<|endoftext|>"} {"language": "java", "text": "href=\"http://www.openolat.org\">\n * OpenOLAT - Online Learning and Training
\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 the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.modules.ceditor;\n\n\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.modules.ceditor.model.ContainerColumn;\nimport org.olat.modules.ceditor.model.ContainerSettings;\nimport org.olat.modules.ceditor.model.ImageHorizontalAlignment;\nimport org.olat.modules.ceditor.model.ImageSettings;\nimport org.olat.modules.ceditor.model.ImageSize;\nimport org.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 sro<|endoftext|>"} {"language": "java", "text": "URL);\n\t\tif(errorURL.indexOf(\"?\") > -1)\n\t\t{\n\t\t\terrorURL = errorURL.substring(0,errorURL.lastIndexOf(\"?\"));\n\t\t}\n\t\tString x = request.getRequestURI();\n\t\tif(request.getParameterMap().size() <2){\n\t\t\t\n\t\t\treturn null;\n\t\t\t\n\t\t}\n\n\t\t//Checking for captcha\n\t\tboolean useCaptcha = Config.getBooleanProperty(\"FORCE_CAPTCHA\",true);\n\t\tif(!useCaptcha){\n\t\t\tuseCaptcha = new Boolean(request.getParameter(\"useCaptcha\")).booleanValue();\n\t\t}\n\t\t\n\t\tString captcha = request.getParameter(\"captcha\");\n\t\tif (useCaptcha) {\n\t\t 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\", parameters);\n\t\tif(ignoredParameters == null)\n\t\t{\n\t\t\tignoredParameters = \"\";\n\t\t}\n\t\tignoredParameters += \":useCaptcha:captcha:invalidCaptchaReturnUrl:return:returnUrl:errorURL:ignore:to:from:cc:bcc:dispatch:order:prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:\";\n\t\tparameters.put(\"ignore\", ignoredParameters);\n\n\t\t// getting categories from inodes\n\t\t// getting parent category name and child categories name\n\t\t// and replacing the \"categories\" parameter\n\t\tString categories = \"\";\n\t\t<|endoftext|>"} {"language": "java", "text": "dI64() throws TException {\n return zigzagToLong(readVarint64());\n }\n\n /** No magic here - just read a double off the wire. */\n public double readDouble() throws TException {\n trans_.readAll(buffer, 0, 8);\n long value;\n if (version_ >= VERSION_DOUBLE_BE) {\n value = bytesToLong(buffer);\n } else {\n value = bytesToLongLE(buffer);\n }\n return Double.longBitsToDouble(value);\n }\n\n /** No magic here - just read a float off the wire. */\n public float readFloat() throws 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 = trans_.getBufferPosition();\n int off = 0;\n while (true) {\n byte b = buf[pos + off];\n result |= (int) (b & 0x7f) << shift;\n if ((b & 0x80) != 0x80) {\n break;\n }\n shift += 7;\n off++;\n }\n trans_.consumeBuffer(off + 1);\n } else {\n while (true) {\n byte b = readByte();\n result |= (int) (b & 0x7f) << shift;\n if ((b & 0x80) != 0x80) {\n break;\n }\n shift += 7;\n }\n }\n retur<|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": " - Online Learning and Training
\n* http://www.olat.org\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,
\n* software 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* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
\n* University of Zurich, Switzerland.\n*


\n* \n* OpenOLAT - Online Learning and Training
\n* This file has been modified by the OpenOLAT community. Changes are licensed\n* under the Apache 2.0 license as the original file. \n*

\n*/ \n\npackage org.olat.core.commons.modules.bc.commands;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.olat.core.commons.modules.bc.FileSelection;\nimport org.olat.core.commons.modules.bc.FolderEvent;\nimport org.olat.core.commons.modules.bc.components.FolderComponent;\nimport org.olat.core.commons.services.vfs.VFSRepositoryService;\nimport org.olat.core.gui.UserRequest;\nimport org.olat.core.gui.components.form.flexible.FormItemContainer;\nimport org.olat.core.gui.components.form.flexible.elements.TextElement;\nimport org.olat.core.gui.components.form.flexible.impl.FormBasicController;\nimport org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;\nimport org.olat.core.gui.con<|endoftext|>"} {"language": "java", "text": "restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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": "icenses/LICENSE-2.0\">Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software 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 * Initial code contributed and copyrighted by
\n * 12.10.2011 by frentix GmbH, http://www.frentix.com\n *

\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).getResultList();\n\t}\n\t\n\tpublic OpenMeetingsRoomReference getReference(BusinessGroup group, OLATResourceable courseResource, String subIdentifier) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"select ref from \").append(OpenMeetingsRoomReference.class.getName()).append(\" ref\");\n\t\t\n\t\tboolean where = false;\n\t\tif(group != null) {\n\t\t\twhere = and(sb, where);\n\t\t\tsb.append(\" ref.group.key=:groupKey\");\n\t\t}\n\t\tif(courseResource != null) {\n\t\t\twhere = and(sb, where);\n\t\t\tsb.append(\" ref.resourceTypeName=:re<|endoftext|>"} {"language": "java", "text": "luding without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/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.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": ".ADMINS.toString());\n\t\t\t\treturn true;\n\t\t\t} else if (isAdmin(authUser) && !isRecognizedAsAdmin(u)) {\n\t\t\t\tlogger.info(\"User '{}' with id={} demoted to regular user.\", u.getName(), authUser.getId());\n\t\t\t\tauthUser.setGroups(User.Groups.USERS.toString());\n\t\t\t\treturn true;\n\t\t\t} else if (!isMod(authUser) && u.isModerator()) {\n\t\t\t\tauthUser.setGroups(User.Groups.MODS.toString());\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate Profile getOrCreateProfile(User u, HttpServletRequest req) {\n\t\tProfile 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 (verifyEmail && !user.getActive() && !StringUtils.isBlank(user.getIdentifier())) {\n\t\t\t\tSysprop s = pc.read(user.getIdentifier());\n\t\t\t\tif (s != null) {\n\t\t\t\t\tString token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());\n\t\t\t\t\ts.addProperty(Config._EMAIL_TOKEN, token);\n\t\t\t\t\tpc.update(s);\n\t\t\t\t\ttoken = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + \"/register?id=\" + user.getId() + \"&token=\" + token;\n\t\t\t\t\tbody3 = \"\" + lang.get(\"signin.welcome.verify\") + \""} {"language": "java", "text": "sourceInfo(outContract[0], \n resourceName,\n version,\n localePrefix,\n this,\n compressable,\n resourceSupportsEL(resourceName, null, ctx),\n ctx.isProjectStage(ProjectStage.Development),\n 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 if (ctx.getExternalContext().getResource(basePath) != null) {\n outContract[0] = new ContractInfo(curContract);\n break;\n } else {\n basePath = null;\n }\n } catch (MalformedURLException e) {\n throw new FacesException(e);\n }\n }\n \n return basePath;\n }\n\n}\n<|endoftext|>"} {"language": "java", "text": "right 2014 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * https://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, 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.util.internal;\n\nimport io.netty.util.CharsetUtil;\nimport io.netty.util.internal.logging.InternalLogger;\nimport io.netty.util.internal.logging.InternalLoggerFactory;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.lang.reflect.Method;\nimport java.net.URL;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * Helper class to load JNI resources.\n *\n */\npublic final class NativeLibraryLoader {\n\n private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class);\n\n private static final String NATIVE_RESOURCE_HOME = \"META-INF/native/\";\n private static final File WORKDIR;\n private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING;\n priva<|endoftext|>"} {"language": "java", "text": " = null;\n if (library != null) {\n basePath = library.getPath(localePrefix) + '/' + resourceName;\n } else {\n if (localePrefix == null) {\n basePath = getBaseResourcePath() + '/' + resourceName;\n } else {\n basePath = getBaseResourcePath()\n + '/'\n + localePrefix\n + '/'\n + resourceName;\n }\n } \n return 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 = loader.getResource(basePath))) {\n outContract[0] = new ContractInfo(curContract);\n outBasePath[0] = basePath;\n break;\n } else {\n basePath = null;\n }\n }\n \n return result;\n }\n\n}\n<|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2021 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 */\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": "otice 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.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 typeOfBoat = \"oak\";\n break;\n }\n itemName = typeOfBoat + \"_boat\";\n break;\n case LEASH_KNOT:\n itemName = \"lead\";\n break;\n case MINECART_CHEST:\n case MINECART_COMMAND_BLOCK:\n case MINECART_FURNACE:\n case MINECART_HOPPER:\n case MINECART_TNT:\n // Move MINECART to the end of the name\n it<|endoftext|>"} {"language": "java", "text": "lass.getName());\n\n public static void convert(PGStream stream, Properties info)\n throws PSQLException, IOException {\n LOGGER.log(Level.FINE, \"converting regular socket connection to ssl\");\n\n SSLSocketFactory factory = SocketFactoryFactory.getSslSocketFactory(info);\n SSLSocket newConnection;\n try {\n newConnection = (SSLSocket) factory.createSocket(stream.getSocket(),\n stream.getHostSpec().getHost(), stream.getHostSpec().getPort(), true);\n // We must invoke manually, 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": "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 */\npackage com.xpn.xwiki.web;\n\nimport javax.inject.Named;\nimport javax.inject.Singleton;\nimport javax.script.ScriptContext;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.math.NumberUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.xwiki.component.annotation.Component;\nimport org.xwiki.rendering.syntax.Syntax;\n\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDocument;\nimport com.xpn.xwiki.doc.XWikiLock;\n\n/**\n * Initializes a document before it is edited.\n *\n * @version $Id$\n */\n@Component\n@Named(\"edit\")\n@Singleton\npublic class EditAction extends XWikiAction\n{\n /**\n * The object used for logging.\n */\n private static final Logger LOGGER = LoggerFactory.getLogger(EditAction.class);\n\n /*<|endoftext|>"} {"language": "java", "text": "/*\n * Copyright 2021 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 */\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 lete_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(folderDirectoryEntry);\n return folderDirectoryEntry;\n }\n\n public void addFile(String fileName, String url) {\n add(new FileDirectoryEntry(fileName, url));\n }\n}\n<|endoftext|>"} {"language": "java", "text": "ic work.\n */\n void onCopiedFrom(Item src);\n\n /**\n * When an item is created from scratch (instead of copied),\n * this method will be invoked. Used as the post-construction initialization.\n *\n * @since 1.374\n */\n void onCreatedFromScratch();\n\n /**\n * Save the settings to a file.\n *\n * Use {@link Items#getConfigFile(Item)}\n * or {@link AbstractItem#getConfigFile()} to obtain the file\n * to save the data.\n */\n void save() throws IOException;\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_Description(), BUILD, PermissionScope.ITEM);\n}\n<|endoftext|>"} {"language": "javascript", "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(filter + \"\\n\" + cus<|endoftext|>"} {"language": "javascript", "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": "javascript", "text": "new Ext.ButtonGroup(quickfilterConfig);\n }\n \n return this.quickFilterGroup;\n },\n \n getQuickFilterPlugin: function() {\n return this;\n },\n \n getValue: function() {\n var quickFilterValue = this.quickFilter.getValue(),\n filters = [];\n \n if (quickFilterValue) {\n filters.push({field: this.quickFilterField, operator: 'contains', value: quickFilterValue, id: 'quickFilter'});\n \n // add implicit / 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 // NOTE: value is always an array representing a filterGroup with condition AND (server limitation)!\n // so we need to route \"alternate criterias\" (OR on root level) through this filterGroup for transport\n // and scrape them out here -> this also means we whipe all other root level filters (could only be implicit once)\n var alternateCriterias = false;\n Ext.each(value, function(filterData) {\n if (filterData.condition && filterData.condition == 'OR')<|endoftext|>"} {"language": "javascript", "text": "h(message), this.getPrivate(_getPassword()))),\n\t\t\t\t\thash: hashed\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: Key does not have a private component.\";\n\t\t\t}\n\t\t} else {\n\t\t\tthrow assertion.error;\n\t\t}\n\t}\n\t\n\tthis.verify = (signed, password = null) => {\n\t\tlet assertion = _assertPassword(\"verify\", password);\n\t\tif(assertion.proceed) {\n\t\t\tif(signed == null) {\n\t\t\t\tthrow \"tEnvoyNaClSigningKey Fatal Error: argument signed of method verify is required and does not have a default value.\";\n\t\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 == \"public\") {\n\t\t\tprotectable = [\"destroy\", \"verify\"];\n\t\t}\n\t\tif(passwordProtected == null) {\n\t\t\tpasswordProtected = [];\n\t\t}\n\t\tfor(let i = 0; i < passwordProtected.length; i++) {\n\t\t\tif(protectable.includes(passwordProtected[i])) {\n\t\t\t\t_passwordProtected.push(passwordProtected[i]);\n\t\t\t}\n\t\t}\n\t\t_assertPassword = (methodName, password = null) => {\n\t\t\tif(_getPassword() == null) {\n\t\t\t\treturn {\n\t\t\t\t\tproceed: true\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tlet alwaysProtected;\n\t\t\t\tif(_type == \"private\") {\n\t\t\t\t\talwaysProtec<|endoftext|>"} {"language": "javascript", "text": "param {String} possible Base64-String\n *\n * @returns {boolean}\n */\n var validateStringAsBase64 = (jsPDFAPI.__addimage__.validateStringAsBase64 = function(\n possibleBase64String\n ) {\n possibleBase64String = possibleBase64String || \"\";\n possibleBase64String.toString().trim();\n\n var result = true;\n\n if (possibleBase64String.length === 0) {\n result = false;\n }\n\n if (possibleBase64String.length % 4 !== 0) {\n result = false;\n }\n\n if (\n /^[A-Za-z0-9+/]+$/.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 isArrayBufferView = (jsPDFAPI.__addimage__.isArrayBufferView = function(\n object\n ) {\n return (\n supportsArrayBuffer() &&\n typeof Uint32Array !== \"undefined\" &&\n (object instanceof Int8Array ||\n object instanceof Uint8Array ||\n (typeof Uint8ClampedArray !== \"undefined\" &&\n object instanceof Uint8ClampedArray) ||\n object instanceof Int16Array ||\n object instanceof Uint16Array ||\n object instanceof Int32Array ||\n object ins<|endoftext|>"} {"language": "javascript", "text": "yright (c) 2006-2012, JGraph Ltd\n */\n// Workaround for handling named HTML entities in mxUtils.parseXml\n// LATER: How to configure DOMParser to just ignore all entities?\n(function()\n{\n\tvar entities = [\n\t\t['nbsp', '160'],\n\t\t['shy', '173']\n ];\n\n\tvar parseXml = mxUtils.parseXml;\n\t\n\tmxUtils.parseXml = function(text)\n\t{\n\t\tfor (var i = 0; i < entities.length; i++)\n\t {\n\t text = text.replace(new RegExp(\n\t \t'&' + entities[i][0] + ';', 'g'),\n\t\t '&#' + entities[i][1] + ';');\n\t }\n\n\t\treturn parseXml(text);\n\t};\n})();\n\n// Shim for missing toISOString in older versions of IE\n// See https://stackoverflow.com/questions/12907862\nif (!Date.prototype.toISOString)\n{ \n (function()\n { \n function pad(number)\n {\n var r = String(number);\n \n if (r.length === 1) \n {\n r = '0' + r;\n }\n \n return r;\n };\n \n Date.prototype.toISOString = function()\n {\n return this.getUTCFullYear()\n + '-' + pad( this.getUTCMonth() + 1 )\n + '-' + pad( this.getUTCDate() )\n + 'T' + pad( this.getUTCHours() )\n + ':' + pad( this.getUTCMinutes() )\n + ':' + pad( this.getUTCSeconds() )\n + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )\n + 'Z';\n }; \n }());\n}\n\n// Shim for Date.now()\nif (!Date.now)\n{\n\tDate.now = function()\n\t{\n\t\treturn new Date().getTime();\n\t};\n}\n\n// Polyfill for Uint8Array.from in IE11 used in Graph.decompress\n// See https://stackoverflow.com/questions/36810940/alternative-or-polyfi<|endoftext|>"} {"language": "javascript", "text": " . .o8 oooo\n * .o8 \"888 `888\n * .o888oo oooo d8b oooo oooo .oooo888 .ooooo. .oooo.o 888 oooo\n * 888 `888\"\"8P `888 `888 d88' `888 d88' `88b d88( \"8 888 .8P'\n * 888 888 888 888 888 888 888ooo888 `\"Y88b. 888888.\n * 888 . 888 888 888 888 888 888 .o o. )88b 888 `88b.\n * \"888\" d888b `V88V\"V8P' `Y8bod88P\" `Y8bod8P' 8\"\"888P' o888o o888o\n * ========================================================================\n * Author: Chris Brame\n * Updated: 1/20/19 4:43 PM\n * Copyright (c) 2014-2019. All rights reserved.\n */\n\ndefine([\n 'angular',\n 'underscore',\n 'jquery',\n 'modules/helpers',\n 'uikit',\n 'qrcode',\n 'history',\n 'angularjs/services/session'\n], function (angular, _, $, helpers, UIKit) {\n return angular\n .module('trudesk.controllers.profile', ['trudesk.services.session'])\n .controller('profileCtrl', function (SessionService, $scope, $window, $document, $http, $log, $timeout) {\n var otpEnabled = false\n $scope.init = function () {\n // Fix Inputs if input is preloaded with a value\n fixInputLabels()\n otpEnabled = $scope.otpEnabled\n }\n\n function fixInputLabels () {\n $timeout(function () {\n $('input.md-input').each(function () {\n var vm = this\n var self = $(vm)\n if (!_.isEmpty(self.val())) {\n var s = self.parent('.md-input-wrapper')\n if (s.length > 0) {\n s.addClass('md-input-filled')\n }\n }\n })\n }, 0)\n }\n\n function valida<|endoftext|>"} {"language": "javascript", "text": "t from 'tape'\nimport {Schema, Param} from '../src/'\n\nlet schema = (params, options) => new Schema(params, options)\n\ntest('QuerymenSchema add', (t) => {\n let add = (...args) => schema().add('test', ...args).value()\n t.true(schema().add(new Param('test')), 'should add a param with instance')\n t.true(schema().add('test'), 'should add a param')\n t.equal(add('123'), '123', 'should add a param with value')\n t.true(schema().add('test', null, {test: true}).option('test'), 'should add a param with option')\n t.equal(add(null, '123'), '123', 'should add a param with default option string')\n t.equal(add(null, 123), 123, 'should add a param with default option number')\n t.equal(add(null, true), true, 'should add a param with default option boolean')\n t.same(add(null, new Date('2016')), new Date('2016'), 'should add a param with default option date')\n t.same(add(null, /123/i), /123/i, 'should add a param with default option regexp')\n t.equal(add(123, String), '123', 'should add a param with type option string')\n t.equal(add('123', Number), 123, 'should add a param with type option number')\n t.equal(add('123', Boolean), true, 'should add a param with type option boolean')\n t.same(add('2016', Date), new Date('2016'), 'should add a 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<|endoftext|>"} {"language": "javascript", "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+|abs|advance|alignof(?:Value)?|assert|contains|count(?:Elements)?|debugPrint(?:ln)?|distance|drop(?:First|Last)|dump|enumerate|equal|filter|find|first|getVaList|indices|isEmpty|join|last|lexicographicalCompare|map|max(?:Element)?|min(?:Element)?|numericCast|overlaps|partition|print(?:ln)?|reduce|reflect|reverse|sizeof(?:Value)?|sort(?:ed)?|split|startsWith|stride(?:of(?:Value)?)?|suffix|swap|toDebugString|toString|transcode|underestimateCount|unsafeBitCast|with(?:ExtendedLifetime|Unsafe(?:Mutable<|endoftext|>"} {"language": "javascript", "text": " require('tap').test\n\nvar npmconf = require('../../lib/config/core.js')\nvar common = require('./00-config-setup.js')\n\nvar URI = 'https://registry.lvh.me:8661/'\n\ntest('getting scope with no credentials set', function (t) {\n npmconf.load({}, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n var basic = conf.getCredentialsByURI(URI)\n t.equal(basic.scope, '//registry.lvh.me:8661/', 'nerfed URL extracted')\n\n t.end()\n })\n})\n\ntest('trying to set credentials with no URI', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n t.throws(function () {\n conf.setCredentialsByURI()\n }, 'enforced missing URI')\n\n t.end()\n })\n})\n\ntest('trying to clear credentials with no URI', function (t) {\n npmconf.load(common.builtin, function (er, conf) {\n t.ifError(er, 'configuration loaded')\n\n t.throws(function () {\n conf.clearCredentialsByURI()\n }, 'enforced missing URI')\n\n t.end()\n })\n})\n\ntest('set with 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.doesNo<|endoftext|>"} {"language": "javascript", "text": ", then the first capturing group of `pattern` will (effectively)\n * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.\n * @property {boolean} [greedy=false] Whether the token is greedy.\n * @property {string|string[]} [alias] An optional alias or list of aliases.\n * @property {Grammar} [inside] The nested grammar of this token.\n *\n * The `inside` grammar will be used to tokenize the text value of each token of this kind.\n *\n * This can 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-name': {\n\t\t\t\tpattern: /[^\\s>\\/]+/,\n\t\t\t\tinside: {\n\t\t\t\t\t'namespace': /^[^\\s>\\/:]+:/\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t},\n\t'entity': [\n\t\t{\n\t\t\tpattern: /&[\\da-z]{1,8};/i,\n\t\t\talias: 'named-entity'\n\t\t},\n\t\t/&#x?[\\da-f]{1,8};/i\n\t]\n};\n\nPrism.languages.markup['tag'].inside['attr-value'].inside['entity'] =\n\tPrism.languages.markup['entity'];\nPrism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;\n\n// Plugin to make entity title show the real entity, idea by Roman Komarov\nPrism.hooks.ad<|endoftext|>"} {"language": "javascript", "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 Mat<|endoftext|>"} {"language": "javascript", "text": "define([\n\t'exports',\n\t'../errors/RequestError',\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, properties[name]);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn exports.deepCopy(target, properties);\n\t};\n\n\tvar freeze = Object.freeze || function(obj){ return obj; };\n\tfunction okHandler(response){\n\t\treturn freeze(response);\n\t}\n\tfunction dataHandler (response) {\n\t\treturn response.data !== undefined ? response.data : response.text;\n\t}\n\n\texports.deferred = function deferred(response, cancel, isValid, isReady, handleResponse, last){\n\t\tvar def = new Deferred(function(reason){\n\t\t\tcancel && cancel(def, response);\n\n\t\t\tif(!reas<|endoftext|>"} {"language": "javascript", "text": " });\n } else {\n this.hide();\n }\n };\n\n this.hide = function () {\n this.$popover.hide();\n };\n };\n\n var VideoDialog = function (context) {\n var self = this;\n var ui = $.summernote.ui;\n\n var $editor = context.layoutInfo.editor;\n var options = context.options;\n var lang = options.langInfo;\n\n this.initialize = function () {\n var $container = options.dialogsInBody ? $(document.body) : $editor;\n\n var body = '

' +\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 = $('