jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
  public void addSynchronously(MediaPackage mediaPackage)
      throws SearchException, IllegalArgumentException, UnauthorizedException, NotFoundException,
      SearchServiceDatabaseException {
    if (mediaPackage == null) {
      throw new IllegalArgumentException("Unable to add a null mediapackage");
    }
    final String mediaPackageId = mediaPackage.getIdentifier().toString();
    logger.debug("Attempting to add media package {} to search index", mediaPackageId);
    AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA();

    AccessControlList seriesAcl = persistence.getAccessControlLists(mediaPackage.getSeries(), mediaPackageId).stream()
        .reduce(new AccessControlList(acl.getEntries()), AccessControlList::mergeActions);
    logger.debug("Updating series with merged access control list: {}", seriesAcl);

    Date now = new Date();

    try {
      if (indexManager.add(mediaPackage, acl, seriesAcl, now)) {
        logger.info("Added media package `{}` to the search index, using ACL `{}`", mediaPackageId, acl);
      } else {
        logger.warn("Failed to add media package {} to the search index", mediaPackageId);
      }
    } catch (SolrServerException e) {
      throw new SearchException(e);
    }

    try {
      persistence.storeMediaPackage(mediaPackage, acl, now);
    } catch (SearchServiceDatabaseException e) {
      throw new SearchException(
          String.format("Could not store media package to search database %s", mediaPackageId), e);
    }
  }
//  [java]
  public void addSynchronously(MediaPackage mediaPackage) throws SearchException, MediaPackageException,
          IllegalArgumentException, UnauthorizedException {
    if (mediaPackage == null) {
      throw new IllegalArgumentException("Unable to add a null mediapackage");
    }
    logger.debug("Attempting to add mediapackage {} to search index", mediaPackage.getIdentifier());
    AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA();

    Date now = new Date();

    try {
      if (indexManager.add(mediaPackage, acl, now)) {
        logger.info("Added mediapackage `{}` to the search index, using ACL `{}`", mediaPackage, acl);
      } else {
        logger.warn("Failed to add mediapackage {} to the search index", mediaPackage.getIdentifier());
      }
    } catch (SolrServerException e) {
      throw new SearchException(e);
    }

    try {
      persistence.storeMediaPackage(mediaPackage, acl, now);
    } catch (SearchServiceDatabaseException e) {
      logger.error("Could not store media package to search database {}: {}", mediaPackage.getIdentifier(), e);
      throw new SearchException(e);
    }
  }
//  [java]
    public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
            String terminalWidth) {
        HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
                                                           proxyPassword);
        conn.setInstanceFollowRedirects(false);
        setRequestMethod(conn, Utils.RequestMethod.GET);
        handleResponse(conn, getStatusCode(conn), terminalWidth);
        Authenticator.setDefault(null);
    }
//  [java]
    public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
            String terminalWidth) {
        initializeSsl();
        HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
                proxyPassword);
        conn.setInstanceFollowRedirects(false);
        setRequestMethod(conn, Utils.RequestMethod.GET);
        handleResponse(conn, getStatusCode(conn), terminalWidth);
        Authenticator.setDefault(null);
    }
//  [java]
    private String getSkinResourcePath(String resource)
    {
        String skinFolder = getSkinFolder();
        String resourcePath = skinFolder + resource;

        // Prevent access to resources from other directories
        Path normalizedResource = Paths.get(resourcePath).normalize();
        // Protect against directory attacks.
        if (!normalizedResource.startsWith(skinFolder)) {
            LOGGER.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource);
            return null;
        }

        return resourcePath;
    }
//  [java]
    private String getSkinResourcePath(String resource)
    {
        String skinFolder = getSkinFolder();
        String resourcePath = skinFolder + resource;

        // Prevent inclusion of templates from other directories
        Path normalizedResource = Paths.get(resourcePath).normalize();
        // Protect against directory attacks.
        if (!normalizedResource.startsWith(skinFolder)) {
            LOGGER.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource);
            return null;
        }

        return resourcePath;
    }
//  [java]
  public boolean deleteSynchronously(final String mediaPackageId) throws SearchException {
    SearchResult result;
    try {
      result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId));
      if (result.getItems().length == 0) {
        logger.warn(
                "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.",
                mediaPackageId);
        return false;
      }
      final String seriesId = result.getItems()[0].getDcIsPartOf();
      logger.info("Removing media package {} from search index", mediaPackageId);

      Date now = new Date();
      try {
        persistence.deleteMediaPackage(mediaPackageId, now);
        logger.info("Removed mediapackage {} from search persistence", mediaPackageId);
      } catch (NotFoundException e) {
        // even if mp not found in persistence, it might still exist in search index.
        logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.",
                mediaPackageId);
      } catch (SearchServiceDatabaseException e) {
        logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId);
        throw new SearchException(e);
      }

      final boolean success = indexManager.delete(mediaPackageId, now);

      // Update series
      if (seriesId != null) {
        if (persistence.getMediaPackages(seriesId).size() > 0) {
          // Update series acl if there are still episodes in the series
          final AccessControlList seriesAcl = persistence.getAccessControlLists(seriesId).stream()
              .reduce(new AccessControlList(), AccessControlList::mergeActions);
          indexManager.addSeries(seriesId, seriesAcl);

        } else {
          // Remove series if there are no episodes in the series any longer
          indexManager.delete(seriesId, now);
        }
      }

      return success;
    } catch (SolrServerException | SearchServiceDatabaseException e) {
      logger.info("Could not delete media package with id {} from search index", mediaPackageId);
      throw new SearchException(e);
    }
  }
//  [java]
  public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException,
          NotFoundException {
    SearchResult result;
    try {
      result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId));
      if (result.getItems().length == 0) {
        logger.warn(
                "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.",
                mediaPackageId);
        return false;
      }
      logger.info("Removing mediapackage {} from search index", mediaPackageId);

      Date now = new Date();
      try {
        persistence.deleteMediaPackage(mediaPackageId, now);
        logger.info("Removed mediapackage {} from search persistence", mediaPackageId);
      } catch (NotFoundException e) {
        // even if mp not found in persistence, it might still exist in search index.
        logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.",
                mediaPackageId);
      } catch (SearchServiceDatabaseException e) {
        logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId);
        throw new SearchException(e);
      }

      return indexManager.delete(mediaPackageId, now);
    } catch (SolrServerException e) {
      logger.info("Could not delete media package with id {} from search index", mediaPackageId);
      throw new SearchException(e);
    }
  }
//  [java]
    private static void handleResponse(HttpsURLConnection conn, int statusCode, String terminalWidth) {
        try {
            // 200 - modules found
            // Other - Error occurred, json returned with the error message
            MapValue payload;
            if (statusCode == HttpsURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()))) {
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    payload = (MapValue) JSONParser.parse(result.toString());
                } catch (IOException e) {
                    throw ErrorUtil.createCommandException(e.getMessage());
                }

                if (payload.getIntValue("count") > 0) {
                    ArrayValue modules = payload.getArrayValue("modules");
                    printModules(modules, terminalWidth);
                } else {
                    outStream.println("no modules found");
                }
            } else {
                StringBuilder result = new StringBuilder();
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                } catch (IOException e) {
                    throw ErrorUtil.createCommandException(e.getMessage());
                }

                payload = (MapValue) JSONParser.parse(result.toString());
                throw ErrorUtil.createCommandException(payload.getStringValue("message"));
            }
        } finally {
            conn.disconnect();
        }
    }
//  [java]
    private static void handleResponse(HttpURLConnection conn, int statusCode, String terminalWidth) {
        try {
            // 200 - modules found
            // Other - Error occurred, json returned with the error message
            MapValue payload;
            if (statusCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()))) {
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    payload = (MapValue) JSONParser.parse(result.toString());
                } catch (IOException e) {
                    throw ErrorUtil.createCommandException(e.getMessage());
                }

                if (payload.getIntValue("count") > 0) {
                    ArrayValue modules = payload.getArrayValue("modules");
                    printModules(modules, terminalWidth);
                } else {
                    outStream.println("no modules found");
                }
            } else {
                StringBuilder result = new StringBuilder();
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                } catch (IOException e) {
                    throw ErrorUtil.createCommandException(e.getMessage());
                }

                payload = (MapValue) JSONParser.parse(result.toString());
                throw ErrorUtil.createCommandException(payload.getStringValue("message"));
            }
        } finally {
            conn.disconnect();
        }
    }
//  [java]
	public VFSLeaf createChildLeaf(String name) {
		File fNewFile = new File(getBasefile(), name);
		try {
			if(!isInPath(name)) {
				log.warn("Could not create a new leaf::{} in container::{} - file out of parent directory", name, getBasefile().getAbsolutePath());
				return null;
			}
			if(!fNewFile.getParentFile().exists()) {
				fNewFile.getParentFile().mkdirs();
			}
			if (!fNewFile.createNewFile()) {
				log.warn("Could not create a new leaf::{} in container::{} - file alreay exists", name, getBasefile().getAbsolutePath());
				return null;
			} 
		} catch (Exception e) {
			log.error("Error while creating child leaf::{} in container::{}", name, getBasefile().getAbsolutePath(), e);
			return null;
		}
		return new LocalFileImpl(fNewFile, this);
	}
//  [java]
	public VFSLeaf createChildLeaf(String name) {
		File fNewFile = new File(getBasefile(), name);
		try {
			if(!fNewFile.getParentFile().exists()) {
				fNewFile.getParentFile().mkdirs();
			}
			if (!fNewFile.createNewFile()) {
				log.warn("Could not create a new leaf::" + name + " in container::" + getBasefile().getAbsolutePath() + " - file alreay exists");
				return null;
			} 
		} catch (Exception e) {
			log.error("Error while creating child leaf::" + name + " in container::" + getBasefile().getAbsolutePath(), e);
			return null;
		}
		return new LocalFileImpl(fNewFile, this);
	}
//  [java]
    void allReservedCharacters() {
        final PathAndQuery res = parse("/#/:[]@!$&'()*+,;=?a=/#/:[]@!$&'()*+,;=");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/#/:[]@!$&'()*+,;=");
        assertThat(res.query()).isEqualTo("a=/#/:[]@!$&'()*+,;=");

        final PathAndQuery res2 =
                parse("/%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F" +
                      "?a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/#%2F:[]@!$&'()*+,;=?");
        assertThat(res2.query()).isEqualTo("a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
    }
//  [java]
    void allReservedCharacters() {
        final PathAndQuery res = PathAndQuery.parse("/#/:[]@!$&'()*+,;=?a=/#/:[]@!$&'()*+,;=");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/#/:[]@!$&'()*+,;=");
        assertThat(res.query()).isEqualTo("a=/#/:[]@!$&'()*+,;=");

        final PathAndQuery res2 =
                PathAndQuery.parse("/%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F" +
                                   "?a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/#%2F:[]@!$&'()*+,;=?");
        assertThat(res2.query()).isEqualTo("a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
    }
//  [java]
    public void translate(GeyserSession session, LoginSuccessPacket packet) {
        PlayerEntity playerEntity = session.getPlayerEntity();
        AuthType remoteAuthType = session.getRemoteAuthType();

        // Required, or else Floodgate players break with Spigot chunk caching
        GameProfile profile = packet.getProfile();
        playerEntity.setUsername(profile.getName());
        playerEntity.setUuid(profile.getId());

        // Check if they are not using a linked account
        if (remoteAuthType == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) {
            SkinManager.handleBedrockSkin(playerEntity, session.getClientData());
        }

        if (remoteAuthType == AuthType.FLOODGATE) {
            // We'll send the skin upload a bit after the handshake packet (aka this packet),
            // because otherwise the global server returns the data too fast.
            session.getAuthData().upload(session.getConnector());
        }
    }
//  [java]
    public void translate(LoginSuccessPacket packet, GeyserSession session) {
        PlayerEntity playerEntity = session.getPlayerEntity();
        AuthType remoteAuthType = session.getRemoteAuthType();

        // Required, or else Floodgate players break with Spigot chunk caching
        GameProfile profile = packet.getProfile();
        playerEntity.setUsername(profile.getName());
        playerEntity.setUuid(profile.getId());

        // Check if they are not using a linked account
        if (remoteAuthType == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) {
            SkinManager.handleBedrockSkin(playerEntity, session.getClientData());
        }

        if (remoteAuthType == AuthType.FLOODGATE) {
            // We'll send the skin upload a bit after the handshake packet (aka this packet),
            // because otherwise the global server returns the data too fast.
            session.getAuthData().upload(session.getConnector());
        }
    }
//  [java]
    void ampersand() {
        final PathAndQuery res = parse("/&?a=1&a=2&b=3");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/&");
        assertThat(res.query()).isEqualTo("a=1&a=2&b=3");

        // '%26' in a query string should never be decoded into '&'.
        final PathAndQuery res2 = parse("/%26?a=1%26a=2&b=3");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/&");
        assertThat(res2.query()).isEqualTo("a=1%26a=2&b=3");
    }
//  [java]
    void ampersand() {
        final PathAndQuery res = PathAndQuery.parse("/&?a=1&a=2&b=3");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/&");
        assertThat(res.query()).isEqualTo("a=1&a=2&b=3");

        // '%26' in a query string should never be decoded into '&'.
        final PathAndQuery res2 = PathAndQuery.parse("/%26?a=1%26a=2&b=3");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/&");
        assertThat(res2.query()).isEqualTo("a=1%26a=2&b=3");
    }
//  [java]
    void doubleQuote() {
        final PathAndQuery res = parse("/\"?\"");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%22");
        assertThat(res.query()).isEqualTo("%22");
    }
//  [java]
    void doubleQuote() {
        final PathAndQuery res = PathAndQuery.parse("/\"?\"");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%22");
        assertThat(res.query()).isEqualTo("%22");
    }
//  [java]
    void colon() {
        assertThat(parse("/:")).isNotNull();
        assertThat(parse("/:/")).isNotNull();
        assertThat(parse("/a/:")).isNotNull();
        assertThat(parse("/a/:/")).isNotNull();
    }
//  [java]
    void colon() {
        assertThat(PathAndQuery.parse("/:")).isNotNull();
        assertThat(PathAndQuery.parse("/:/")).isNotNull();
        assertThat(PathAndQuery.parse("/a/:")).isNotNull();
        assertThat(PathAndQuery.parse("/a/:/")).isNotNull();
    }
//  [java]
    void consecutiveSlashes() {
        final PathAndQuery res = parse(
                "/path//with///consecutive////slashes?/query//with///consecutive////slashes");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/path/with/consecutive/slashes");
        assertThat(res.query()).isEqualTo("/query//with///consecutive////slashes");

        // Encoded slashes
        final PathAndQuery res2 = parse(
                "/path%2F/with/%2F/consecutive//%2F%2Fslashes?/query%2F/with/%2F/consecutive//%2F%2Fslashes");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/path%2F/with/%2F/consecutive/%2F%2Fslashes");
        assertThat(res2.query()).isEqualTo("/query%2F/with/%2F/consecutive//%2F%2Fslashes");
    }
//  [java]
    void consecutiveSlashes() {
        final PathAndQuery res = PathAndQuery.parse(
                "/path//with///consecutive////slashes?/query//with///consecutive////slashes");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/path/with/consecutive/slashes");
        assertThat(res.query()).isEqualTo("/query//with///consecutive////slashes");

        // Encoded slashes
        final PathAndQuery res2 = PathAndQuery.parse(
                "/path%2F/with/%2F/consecutive//%2F%2Fslashes?/query%2F/with/%2F/consecutive//%2F%2Fslashes");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/path%2F/with/%2F/consecutive/%2F%2Fslashes");
        assertThat(res2.query()).isEqualTo("/query%2F/with/%2F/consecutive//%2F%2Fslashes");
    }
//  [java]
    void empty() {
        final PathAndQuery res = parse(null);
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/");
        assertThat(res.query()).isNull();

        final PathAndQuery res2 = parse("");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/");
        assertThat(res2.query()).isNull();

        final PathAndQuery res3 = parse("?");
        assertThat(res3).isNotNull();
        assertThat(res3.path()).isEqualTo("/");
        assertThat(res3.query()).isEqualTo("");
    }
//  [java]
    void empty() {
        final PathAndQuery res = PathAndQuery.parse(null);
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/");
        assertThat(res.query()).isNull();

        final PathAndQuery res2 = PathAndQuery.parse("");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/");
        assertThat(res2.query()).isNull();

        final PathAndQuery res3 = PathAndQuery.parse("?");
        assertThat(res3).isNotNull();
        assertThat(res3.path()).isEqualTo("/");
        assertThat(res3.query()).isEqualTo("");
    }
//  [java]
    void encodedUnicode() {
        final String encodedPath = "/%ec%95%88";
        final String encodedQuery = "%eb%85%95";
        final PathAndQuery res = parse(encodedPath + '?' + encodedQuery);
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo(Ascii.toUpperCase(encodedPath));
        assertThat(res.query()).isEqualTo(Ascii.toUpperCase(encodedQuery));
    }
//  [java]
    void encodedUnicode() {
        final String encodedPath = "/%ec%95%88";
        final String encodedQuery = "%eb%85%95";
        final PathAndQuery res = PathAndQuery.parse(encodedPath + '?' + encodedQuery);
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo(Ascii.toUpperCase(encodedPath));
        assertThat(res.query()).isEqualTo(Ascii.toUpperCase(encodedQuery));
    }
//  [java]
    void equal() {
        final PathAndQuery res = parse("/=?a=b=1");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/=");
        assertThat(res.query()).isEqualTo("a=b=1");

        // '%3D' in a query string should never be decoded into '='.
        final PathAndQuery res2 = parse("/%3D?a%3db=1");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/=");
        assertThat(res2.query()).isEqualTo("a%3Db=1");
    }
//  [java]
    void equal() {
        final PathAndQuery res = PathAndQuery.parse("/=?a=b=1");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/=");
        assertThat(res.query()).isEqualTo("a=b=1");

        // '%3D' in a query string should never be decoded into '='.
        final PathAndQuery res2 = PathAndQuery.parse("/%3D?a%3db=1");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/=");
        assertThat(res2.query()).isEqualTo("a%3Db=1");
    }
//  [java]
    void controlChars() {
        assertThat(parse("/\0")).isNull();
        assertThat(parse("/a\nb")).isNull();
        assertThat(parse("/a\u007fb")).isNull();

        // Escaped
        assertThat(parse("/%00")).isNull();
        assertThat(parse("/a%09b")).isNull();
        assertThat(parse("/a%0ab")).isNull();
        assertThat(parse("/a%0db")).isNull();
        assertThat(parse("/a%7fb")).isNull();

        // With query string
        assertThat(parse("/\0?c")).isNull();
        assertThat(parse("/a\tb?c")).isNull();
        assertThat(parse("/a\nb?c")).isNull();
        assertThat(parse("/a\rb?c")).isNull();
        assertThat(parse("/a\u007fb?c")).isNull();

        // With query string with control chars
        assertThat(parse("/?\0")).isNull();
        assertThat(parse("/?%00")).isNull();
        assertThat(parse("/?a\u007fb")).isNull();
        assertThat(parse("/?a%7Fb")).isNull();
        // However, 0x0A, 0x0D, 0x09 should be accepted in a query string.
        assertThat(parse("/?a\tb").query()).isEqualTo("a%09b");
        assertThat(parse("/?a\nb").query()).isEqualTo("a%0Ab");
        assertThat(parse("/?a\rb").query()).isEqualTo("a%0Db");
        assertThat(parse("/?a%09b").query()).isEqualTo("a%09b");
        assertThat(parse("/?a%0Ab").query()).isEqualTo("a%0Ab");
        assertThat(parse("/?a%0Db").query()).isEqualTo("a%0Db");
    }
//  [java]
    void controlChars() {
        assertThat(PathAndQuery.parse("/\0")).isNull();
        assertThat(PathAndQuery.parse("/a\nb")).isNull();
        assertThat(PathAndQuery.parse("/a\u007fb")).isNull();

        // Escaped
        assertThat(PathAndQuery.parse("/%00")).isNull();
        assertThat(PathAndQuery.parse("/a%09b")).isNull();
        assertThat(PathAndQuery.parse("/a%0ab")).isNull();
        assertThat(PathAndQuery.parse("/a%0db")).isNull();
        assertThat(PathAndQuery.parse("/a%7fb")).isNull();

        // With query string
        assertThat(PathAndQuery.parse("/\0?c")).isNull();
        assertThat(PathAndQuery.parse("/a\tb?c")).isNull();
        assertThat(PathAndQuery.parse("/a\nb?c")).isNull();
        assertThat(PathAndQuery.parse("/a\rb?c")).isNull();
        assertThat(PathAndQuery.parse("/a\u007fb?c")).isNull();

        // With query string with control chars
        assertThat(PathAndQuery.parse("/?\0")).isNull();
        assertThat(PathAndQuery.parse("/?%00")).isNull();
        assertThat(PathAndQuery.parse("/?a\u007fb")).isNull();
        assertThat(PathAndQuery.parse("/?a%7Fb")).isNull();
        // However, 0x0A, 0x0D, 0x09 should be accepted in a query string.
        assertThat(PathAndQuery.parse("/?a\tb").query()).isEqualTo("a%09b");
        assertThat(PathAndQuery.parse("/?a\nb").query()).isEqualTo("a%0Ab");
        assertThat(PathAndQuery.parse("/?a\rb").query()).isEqualTo("a%0Db");
        assertThat(PathAndQuery.parse("/?a%09b").query()).isEqualTo("a%09b");
        assertThat(PathAndQuery.parse("/?a%0Ab").query()).isEqualTo("a%0Ab");
        assertThat(PathAndQuery.parse("/?a%0Db").query()).isEqualTo("a%0Db");
    }
//  [java]
    void percent() {
        final PathAndQuery res = parse("/%25");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%25");
        assertThat(res.query()).isNull();
    }
//  [java]
    void percent() {
        final PathAndQuery res = PathAndQuery.parse("/%25");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%25");
        assertThat(res.query()).isNull();
    }
//  [java]
    void noEncoding() {
        final PathAndQuery res = parse("/a?b=c");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/a");
        assertThat(res.query()).isEqualTo("b=c");
    }
//  [java]
    void noEncoding() {
        final PathAndQuery res = PathAndQuery.parse("/a?b=c");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/a");
        assertThat(res.query()).isEqualTo("b=c");
    }
//  [java]
    void plus() {
        final PathAndQuery res = parse("/+?a+b=c+d");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/+");
        assertThat(res.query()).isEqualTo("a+b=c+d");

        final PathAndQuery res2 = parse("/%2b?a%2bb=c%2bd");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/+");
        assertThat(res2.query()).isEqualTo("a%2Bb=c%2Bd");
    }
//  [java]
    void plus() {
        final PathAndQuery res = PathAndQuery.parse("/+?a+b=c+d");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/+");
        assertThat(res.query()).isEqualTo("a+b=c+d");

        final PathAndQuery res2 = PathAndQuery.parse("/%2b?a%2bb=c%2bd");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/+");
        assertThat(res2.query()).isEqualTo("a%2Bb=c%2Bd");
    }
//  [java]
    void relative() {
        assertThat(parse("foo")).isNull();
    }
//  [java]
    void relative() {
        assertThat(PathAndQuery.parse("foo")).isNull();
    }
//  [java]
    void semicolon() {
        final PathAndQuery res = parse("/;?a=b;c=d");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/;");
        assertThat(res.query()).isEqualTo("a=b;c=d");

        // '%3B' in a query string should never be decoded into ';'.
        final PathAndQuery res2 = parse("/%3b?a=b%3Bc=d");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/;");
        assertThat(res2.query()).isEqualTo("a=b%3Bc=d");
    }
//  [java]
    void semicolon() {
        final PathAndQuery res = PathAndQuery.parse("/;?a=b;c=d");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/;");
        assertThat(res.query()).isEqualTo("a=b;c=d");

        // '%3B' in a query string should never be decoded into ';'.
        final PathAndQuery res2 = PathAndQuery.parse("/%3b?a=b%3Bc=d");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/;");
        assertThat(res2.query()).isEqualTo("a=b%3Bc=d");
    }
//  [java]
    void sharp() {
        final PathAndQuery res = parse("/#?a=b#1");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/#");
        assertThat(res.query()).isEqualTo("a=b#1");

        // '%23' in a query string should never be decoded into '#'.
        final PathAndQuery res2 = parse("/%23?a=b%231");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/#");
        assertThat(res2.query()).isEqualTo("a=b%231");
    }
//  [java]
    void sharp() {
        final PathAndQuery res = PathAndQuery.parse("/#?a=b#1");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/#");
        assertThat(res.query()).isEqualTo("a=b#1");

        // '%23' in a query string should never be decoded into '#'.
        final PathAndQuery res2 = PathAndQuery.parse("/%23?a=b%231");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/#");
        assertThat(res2.query()).isEqualTo("a=b%231");
    }
//  [java]
    void space() {
        final PathAndQuery res = parse("/ ? ");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%20");
        assertThat(res.query()).isEqualTo("+");

        final PathAndQuery res2 = parse("/%20?%20");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/%20");
        assertThat(res2.query()).isEqualTo("+");
    }
//  [java]
    void space() {
        final PathAndQuery res = PathAndQuery.parse("/ ? ");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%20");
        assertThat(res.query()).isEqualTo("+");

        final PathAndQuery res2 = PathAndQuery.parse("/%20?%20");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/%20");
        assertThat(res2.query()).isEqualTo("+");
    }
//  [java]
		public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) {
			newNode.setDisplayOption(CourseNode.DISPLAY_OPTS_TITLE_DESCRIPTION_CONTENT);
			VFSContainer rootContainer = course.getCourseFolderContainer();
			VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
			if (singleFile == null) {
				singleFile = rootContainer.createChildLeaf(filename);
			}

			if(in != null) {
				moduleConfig.set(SPEditController.CONFIG_KEY_FILE, "/" + filename);
				
				OutputStream out = singleFile.getOutputStream(false);
				FileUtils.copy(in, out);
				FileUtils.closeSafely(out);
				FileUtils.closeSafely(in);
			} else {
				if(StringHelper.containsNonWhitespace(path)) {
					if(!path.startsWith("/")) {
						path = "/" + path;
					}
					if(!path.endsWith("/")) {
						path += "/";
					}
				} else {
					path = "/";
				}
				moduleConfig.set(SPEditController.CONFIG_KEY_FILE, path + filename);
			}
			//saved node configuration
		}
//  [java]
		public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) {
			newNode.setDisplayOption(CourseNode.DISPLAY_OPTS_TITLE_DESCRIPTION_CONTENT);
			VFSContainer rootContainer = course.getCourseFolderContainer();
			VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
			if (singleFile == null) {
				singleFile = rootContainer.createChildLeaf("/" + filename);
			}

			if(in != null) {
				moduleConfig.set(SPEditController.CONFIG_KEY_FILE, "/" + filename);
				
				OutputStream out = singleFile.getOutputStream(false);
				FileUtils.copy(in, out);
				FileUtils.closeSafely(out);
				FileUtils.closeSafely(in);
			} else {
				if(StringHelper.containsNonWhitespace(path)) {
					if(!path.startsWith("/")) {
						path = "/" + path;
					}
					if(!path.endsWith("/")) {
						path += "/";
					}
				} else {
					path = "/";
				}
				moduleConfig.set(SPEditController.CONFIG_KEY_FILE, path + filename);
			}
			//saved node configuration
		}
//  [java]
    void shouldNotDecodeSlash() {
        final PathAndQuery res = parse("%2F?%2F");
        // Do not accept a relative path.
        assertThat(res).isNull();
        final PathAndQuery res1 = parse("/%2F?%2F");
        assertThat(res1).isNotNull();
        assertThat(res1.path()).isEqualTo("/%2F");
        assertThat(res1.query()).isEqualTo("%2F");

        final PathAndQuery pathOnly = parse("/foo%2F");
        assertThat(pathOnly).isNotNull();
        assertThat(pathOnly.path()).isEqualTo("/foo%2F");
        assertThat(pathOnly.query()).isNull();

        final PathAndQuery queryOnly = parse("/?%2f=%2F");
        assertThat(queryOnly).isNotNull();
        assertThat(queryOnly.path()).isEqualTo("/");
        assertThat(queryOnly.query()).isEqualTo("%2F=%2F");
    }
//  [java]
    void shouldNotDecodeSlash() {
        final PathAndQuery res = PathAndQuery.parse("%2F?%2F");
        // Do not accept a relative path.
        assertThat(res).isNull();
        final PathAndQuery res1 = PathAndQuery.parse("/%2F?%2F");
        assertThat(res1).isNotNull();
        assertThat(res1.path()).isEqualTo("/%2F");
        assertThat(res1.query()).isEqualTo("%2F");

        final PathAndQuery pathOnly = PathAndQuery.parse("/foo%2F");
        assertThat(pathOnly).isNotNull();
        assertThat(pathOnly.path()).isEqualTo("/foo%2F");
        assertThat(pathOnly.query()).isNull();

        final PathAndQuery queryOnly = PathAndQuery.parse("/?%2f=%2F");
        assertThat(queryOnly).isNotNull();
        assertThat(queryOnly.path()).isEqualTo("/");
        assertThat(queryOnly.query()).isEqualTo("%2F=%2F");
    }
//  [java]
    void hexadecimal() {
        assertThat(parse("/%")).isNull();
        assertThat(parse("/%0")).isNull();
        assertThat(parse("/%0X")).isNull();
        assertThat(parse("/%X0")).isNull();
    }
//  [java]
    void hexadecimal() {
        assertThat(PathAndQuery.parse("/%")).isNull();
        assertThat(PathAndQuery.parse("/%0")).isNull();
        assertThat(PathAndQuery.parse("/%0X")).isNull();
        assertThat(PathAndQuery.parse("/%X0")).isNull();
    }
//  [java]
	public Response attachTaskFile(@PathParam("courseId") Long courseId, @PathParam("nodeId") String nodeId,
			@Context HttpServletRequest request) {
			ICourse course = CoursesWebService.loadCourse(courseId);
		CourseEditorTreeNode parentNode = getParentNode(course, nodeId);
		if(course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		}
		if(parentNode == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if(!(parentNode.getCourseNode() instanceof TACourseNode)) {
			return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
		}
		if (!isAuthorEditor(course, request)) {
			return Response.serverError().status(Status.UNAUTHORIZED).build();
		}

		InputStream in = null;
		MultipartReader reader = null;
		try {
			reader = new MultipartReader(request);
			String filename = reader.getValue("filename", "task");
			String taskFolderPath = TACourseNode.getTaskFolderPathRelToFolderRoot(course, parentNode.getCourseNode());
			VFSContainer taskFolder = VFSManager.olatRootContainer(taskFolderPath, null);
			VFSLeaf singleFile = (VFSLeaf)taskFolder.resolve(filename);
			if (singleFile == null) {
				singleFile = taskFolder.createChildLeaf(filename);
			}
			File file = reader.getFile();
			if(file != null) {
				in = new FileInputStream(file);
				OutputStream out = singleFile.getOutputStream(false);
				IOUtils.copy(in, out);
				IOUtils.closeQuietly(out);
			} else {
				return Response.status(Status.NOT_ACCEPTABLE).build();
			}
		} catch (Exception e) {
			log.error("", e);
			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
		} finally {
			MultipartReader.closeQuietly(reader);
			IOUtils.closeQuietly(in);
		}
		
		return Response.ok().build();
	}
//  [java]
	public Response attachTaskFile(@PathParam("courseId") Long courseId, @PathParam("nodeId") String nodeId,
			@Context HttpServletRequest request) {
			ICourse course = CoursesWebService.loadCourse(courseId);
		CourseEditorTreeNode parentNode = getParentNode(course, nodeId);
		if(course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		}
		if(parentNode == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if(!(parentNode.getCourseNode() instanceof TACourseNode)) {
			return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
		}
		if (!isAuthorEditor(course, request)) {
			return Response.serverError().status(Status.UNAUTHORIZED).build();
		}

		InputStream in = null;
		MultipartReader reader = null;
		try {
			reader = new MultipartReader(request);
			String filename = reader.getValue("filename", "task");
			String taskFolderPath = TACourseNode.getTaskFolderPathRelToFolderRoot(course, parentNode.getCourseNode());
			VFSContainer taskFolder = VFSManager.olatRootContainer(taskFolderPath, null);
			VFSLeaf singleFile = (VFSLeaf) taskFolder.resolve("/" + filename);
			if (singleFile == null) {
				singleFile = taskFolder.createChildLeaf("/" + filename);
			}
			File file = reader.getFile();
			if(file != null) {
				in = new FileInputStream(file);
				OutputStream out = singleFile.getOutputStream(false);
				IOUtils.copy(in, out);
				IOUtils.closeQuietly(out);
			} else {
				return Response.status(Status.NOT_ACCEPTABLE).build();
			}
		} catch (Exception e) {
			log.error("", e);
			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
		} finally {
			MultipartReader.closeQuietly(reader);
			IOUtils.closeQuietly(in);
		}
		
		return Response.ok().build();
	}
//  [java]
	public VFSContainer createChildContainer(String name) {
		File fNewFile = new File(getBasefile(), name);
		if(!isInPath(name)) {
			log.warn("Could not create a new container::{} in container::{} - file out of parent directory", name, getBasefile().getAbsolutePath());
			return null;
		}
		if (!fNewFile.mkdir()) {
			return null;
		}
		LocalFolderImpl locFI =  new LocalFolderImpl(fNewFile, this);
		locFI.setDefaultItemFilter(defaultFilter);
		return locFI;
	}
//  [java]
	public VFSContainer createChildContainer(String name) {
		File fNewFile = new File(getBasefile(), name);
		if (!fNewFile.mkdir()) return null;
		LocalFolderImpl locFI =  new LocalFolderImpl(fNewFile, this);
		locFI.setDefaultItemFilter(defaultFilter);
		return locFI;
	}
//  [java]
		public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) {
			
			if(displayType != null && (STCourseNodeEditController.CONFIG_VALUE_DISPLAY_TOC.equals(displayType)
					|| STCourseNodeEditController.CONFIG_VALUE_DISPLAY_PEEKVIEW.equals(displayType)
					|| STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(displayType))) {
				moduleConfig.setStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, displayType);
			}
			
			if(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(moduleConfig.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE))) {
				if(in != null && StringHelper.containsNonWhitespace(filename)) {
					VFSContainer rootContainer = course.getCourseFolderContainer();
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
					if (singleFile == null) {
						singleFile = rootContainer.createChildLeaf(filename);
					}
	
					moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename);
					OutputStream out = singleFile.getOutputStream(false);
					FileUtils.copy(in, out);
					FileUtils.closeSafely(out);
					FileUtils.closeSafely(in);
				} else if (StringHelper.containsNonWhitespace(filename)) {
					VFSContainer rootContainer = course.getCourseFolderContainer();
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
					if(singleFile != null) {
						moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename);
					}
				}
			}
		}
//  [java]
		public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) {
			
			if(displayType != null && (STCourseNodeEditController.CONFIG_VALUE_DISPLAY_TOC.equals(displayType)
					|| STCourseNodeEditController.CONFIG_VALUE_DISPLAY_PEEKVIEW.equals(displayType)
					|| STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(displayType))) {
				moduleConfig.setStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, displayType);
			}
			
			if(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(moduleConfig.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE))) {
				if(in != null && StringHelper.containsNonWhitespace(filename)) {
					VFSContainer rootContainer = course.getCourseFolderContainer();
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
					if (singleFile == null) {
						singleFile = rootContainer.createChildLeaf("/" + filename);
					}
	
					moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename);
					OutputStream out = singleFile.getOutputStream(false);
					FileUtils.copy(in, out);
					FileUtils.closeSafely(out);
					FileUtils.closeSafely(in);
				} else if (StringHelper.containsNonWhitespace(filename)) {
					VFSContainer rootContainer = course.getCourseFolderContainer();
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
					if(singleFile != null) {
						moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename);
					}
				}
			}
		}
//  [java]
    public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception {
        try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
             ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
            addFolderToZip("", srcFolder, zip, ignore);
            zip.flush();
        }
    }
//  [java]
    public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception {
        try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
             ZipOutputStream zip = new ZipOutputStream(fileWriter)){
            addFolderToZip("", srcFolder, zip, ignore);
            zip.flush();
        }
    }
//  [java]
    public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception {
        try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
             ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
            addFolderToZipAPKTool("", srcFolder, zip);
            zip.flush();
        }
    }
//  [java]
    public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception {
        try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
             ZipOutputStream zip = new ZipOutputStream(fileWriter)){
            addFolderToZipAPKTool("", srcFolder, zip);
            zip.flush();
        }
    }
//  [java]
    public Optional<URL> getResource(String path) {
        if (missingPath) {
            return Optional.empty();
        }

        boolean isDirectory = isDirectory(path);

        if (!isDirectory) {
            URL url = classLoader.getResource(prefixPath(path));
            if (url != null && startsWithBase(url)) {
                return Optional.of(url);
            }
        }
        return Optional.empty();
    }
//  [java]
    public Optional<URL> getResource(String path) {
        boolean isDirectory = isDirectory(path);

        if (!isDirectory) {
            URL url = classLoader.getResource(prefixPath(path));
            return Optional.ofNullable(url);
        }
        return Optional.empty();
    }
//  [java]
    void rawUnicode() {
        // 2- and 3-byte UTF-8
        final PathAndQuery res1 = parse("/\u00A2?\u20AC"); // ¢ and €
        assertThat(res1).isNotNull();
        assertThat(res1.path()).isEqualTo("/%C2%A2");
        assertThat(res1.query()).isEqualTo("%E2%82%AC");

        // 4-byte UTF-8
        final PathAndQuery res2 = parse("/\uD800\uDF48"); // 𐍈
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/%F0%90%8D%88");
        assertThat(res2.query()).isNull();

        // 5- and 6-byte forms are only theoretically possible, so we won't test them here.
    }
//  [java]
    void rawUnicode() {
        // 2- and 3-byte UTF-8
        final PathAndQuery res1 = PathAndQuery.parse("/\u00A2?\u20AC"); // ¢ and €
        assertThat(res1).isNotNull();
        assertThat(res1.path()).isEqualTo("/%C2%A2");
        assertThat(res1.query()).isEqualTo("%E2%82%AC");

        // 4-byte UTF-8
        final PathAndQuery res2 = PathAndQuery.parse("/\uD800\uDF48"); // 𐍈
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/%F0%90%8D%88");
        assertThat(res2.query()).isNull();

        // 5- and 6-byte forms are only theoretically possible, so we won't test them here.
    }
//  [java]
    public Stream<URL> getResources(String path) {
        Enumeration<URL> all;
        try {
            all = classLoader.getResources(prefixPath(path));
        } catch (IOException e) {
            return Stream.empty();
        }
        Stream.Builder<URL> builder = Stream.builder();
        while (all.hasMoreElements()) {
            URL url = all.nextElement();
            if (startsWithBase(url)) {
                builder.accept(url);
            }
        }
        return builder.build();
    }
//  [java]
    public Stream<URL> getResources(String path) {
        Enumeration<URL> all;
        try {
            all = classLoader.getResources(prefixPath(path));
        } catch (IOException e) {
            return Stream.empty();
        }
        Stream.Builder<URL> builder = Stream.builder();
        while (all.hasMoreElements()) {
            URL url = all.nextElement();
            builder.accept(url);
        }
        return builder.build();
    }